@equationalapplications/core-llm-wiki 9.16.2 → 9.18.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.
@@ -246,6 +246,16 @@ function resolveSystemOneTypeOnWrite(config) {
246
246
  }
247
247
  return typeOnWrite ?? "llm";
248
248
  }
249
+ function resolveSystemOneTypeOnIngest(config) {
250
+ const typeOnIngest = config?.systemOne?.typeOnIngest;
251
+ if (typeOnIngest !== void 0 && !isTypingMode(typeOnIngest)) {
252
+ warnOnce(
253
+ `[core-llm-wiki] systemOne: \`systemOne.typeOnIngest\` is ${formatConfigValue(typeOnIngest)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
254
+ );
255
+ return "llm";
256
+ }
257
+ return typeOnIngest ?? "llm";
258
+ }
249
259
  function resolveHealScreenMinConfidence(config) {
250
260
  if (resolveSystemOneHealScreen(config) !== "auto") return void 0;
251
261
  const floor = config?.systemOne?.minConfidence?.healScreen;
@@ -365,7 +375,7 @@ var MESSAGE = {
365
375
  guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass.",
366
376
  source_pointer_unresolved: "A stored librarian fact carries no source pointer because the model answer could not yield one, or the librarian merged such an unattributed candidate into this fact in place (its derived_events list was not extended).",
367
377
  source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer.",
368
- source_event_gone: "A librarian candidate was dropped at apply time because the event it came from no longer exists (deleted outside the engine while the pass ran).",
378
+ source_event_gone: "A librarian candidate was dropped at apply time because the event it came from was no longer available: deleted (detail.reason gone) or forgotten with forget({ eventId }) (detail.reason forgotten) outside this instance while the pass ran.",
369
379
  derived_events_invalid: "Import met a malformed derived_events value and stored null.",
370
380
  source_store_source_too_large: "A source document exceeded the per-document size cap and was not stored.",
371
381
  source_store_budget_exceeded: "Storing a source document would exceed the store UTF-16 code-unit budget and it was not stored.",
@@ -1800,8 +1810,14 @@ function isManifestRepresentable(manifest) {
1800
1810
  const slugs = manifest.node_types.map((n) => n.type);
1801
1811
  return slugs.length > 0 && slugs.length + 1 <= CLASSIFIER_MAX_CHOICES && !slugs.some((s) => isReservedAbstainSlug(s));
1802
1812
  }
1813
+ function typingEngages(site, provider, mode, manifest) {
1814
+ return site === "auto" && typeof provider.classify === "function" && mode !== "off" && isManifestRepresentable(manifest);
1815
+ }
1803
1816
  function canEngageWriteTyping(config, provider, mode, manifest) {
1804
- return resolveSystemOneTypeOnWrite(config) === "auto" && typeof provider.classify === "function" && mode !== "off" && isManifestRepresentable(manifest);
1817
+ return typingEngages(resolveSystemOneTypeOnWrite(config), provider, mode, manifest);
1818
+ }
1819
+ function canEngageIngestTyping(config, provider, mode, manifest) {
1820
+ return typingEngages(resolveSystemOneTypeOnIngest(config), provider, mode, manifest);
1805
1821
  }
1806
1822
  function buildTypingQuestion(manifest) {
1807
1823
  return {
@@ -1814,9 +1830,9 @@ function buildTypingQuestion(manifest) {
1814
1830
  function volunteeredTypeResolves(rawOkfType, manifest) {
1815
1831
  return typeof rawOkfType === "string" && resolveNodeTypeMatch(rawOkfType, manifest) !== null;
1816
1832
  }
1817
- async function classifyFactsForWrite(options, ctx, facts, manifest, floor) {
1833
+ async function classifyFactsForWrite(options, ctx, facts, manifest, floor, opts) {
1818
1834
  const question = buildTypingQuestion(manifest);
1819
- const rawConcurrency = options.config?.chunkConcurrency ?? 1;
1835
+ const rawConcurrency = opts?.concurrency ?? options.config?.chunkConcurrency ?? 1;
1820
1836
  const concurrency = Number.isFinite(rawConcurrency) && rawConcurrency >= 1 ? Math.floor(rawConcurrency) : 1;
1821
1837
  let stopped = false;
1822
1838
  return withConcurrency(
@@ -1847,6 +1863,10 @@ async function classifyFactsForWrite(options, ctx, facts, manifest, floor) {
1847
1863
  concurrency
1848
1864
  );
1849
1865
  }
1866
+ function toIngestCounters(c) {
1867
+ const { unattempted: _unattempted, ...rest } = c;
1868
+ return rest;
1869
+ }
1850
1870
  function emptyTypingCounters() {
1851
1871
  return { asked: 0, typed: 0, abstained: 0, lowConfidence: 0, invalid: 0, skipped: 0, unattempted: 0 };
1852
1872
  }
@@ -2128,6 +2148,15 @@ var MetadataRepository = class extends BaseRepository {
2128
2148
  await this.db.execAsync(`VACUUM`);
2129
2149
  await this.checkpointTruncateVerified();
2130
2150
  }
2151
+ /**
2152
+ * True when `table` has `column`. A never-set-up or not-yet-migrated store
2153
+ * (the #316 recovery path) lacks columns later migrations add; callers that
2154
+ * must run there probe first.
2155
+ */
2156
+ async columnExists(table, column, tx) {
2157
+ const cols = await this.getExecutor(tx).getAllAsync(`PRAGMA table_info(${table})`);
2158
+ return cols.some((c) => c.name === column);
2159
+ }
2131
2160
  /**
2132
2161
  * Returns the set of distinct `entity_id` values across entries/tasks/events.
2133
2162
  *
@@ -2138,18 +2167,21 @@ var MetadataRepository = class extends BaseRepository {
2138
2167
  * is `entity_id COLLATE BINARY` for stable, locale-independent ordering.
2139
2168
  *
2140
2169
  * With `opts.softDeletedAtOrBefore` the walk is narrowed to entities holding
2141
- * at least one soft-deleted entry or task with `deleted_at` at or before
2170
+ * at least one soft-deleted entry, task or forgotten event with `deleted_at` at or before
2142
2171
  * that cutoff (erase's hard-delete walk, forget-erasure spec §2). Without
2143
2172
  * the option the host-facing semantics above are unchanged.
2144
2173
  */
2145
2174
  async getDistinctEntityIds(tx, opts) {
2146
2175
  const executor = this.getExecutor(tx);
2176
+ const eventTombstones = (opts?.softDeletedAll || opts?.softDeletedAtOrBefore !== void 0) && await this.columnExists(`${this.prefix}events`, "forgotten_at", tx);
2147
2177
  if (opts?.softDeletedAll) {
2148
2178
  const rows2 = await executor.getAllAsync(
2149
2179
  `SELECT DISTINCT entity_id FROM (
2150
2180
  SELECT entity_id FROM ${this.prefix}entries WHERE deleted_at IS NOT NULL
2151
2181
  UNION
2152
2182
  SELECT entity_id FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL
2183
+ ${eventTombstones ? `UNION
2184
+ SELECT entity_id FROM ${this.prefix}events WHERE forgotten_at IS NOT NULL` : ""}
2153
2185
  ) ORDER BY entity_id COLLATE BINARY`
2154
2186
  );
2155
2187
  return rows2.map((r) => r.entity_id);
@@ -2161,8 +2193,10 @@ var MetadataRepository = class extends BaseRepository {
2161
2193
  SELECT entity_id FROM ${this.prefix}entries WHERE deleted_at IS NOT NULL AND deleted_at <= ?
2162
2194
  UNION
2163
2195
  SELECT entity_id FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL AND deleted_at <= ?
2196
+ ${eventTombstones ? `UNION
2197
+ SELECT entity_id FROM ${this.prefix}events WHERE forgotten_at IS NOT NULL AND forgotten_at <= ?` : ""}
2164
2198
  ) ORDER BY entity_id COLLATE BINARY`,
2165
- [cutoff, cutoff]
2199
+ eventTombstones ? [cutoff, cutoff, cutoff] : [cutoff, cutoff]
2166
2200
  );
2167
2201
  return rows2.map((r) => r.entity_id);
2168
2202
  }
@@ -3815,7 +3849,9 @@ var IngestionService = class {
3815
3849
  }
3816
3850
  const { chunks: chunks2, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
3817
3851
  if (chunks2.length === 0) return zeroChunkResult();
3818
- const ontologyContext = await this.ontologyService?.buildWritePromptContext(entityId, { engaged: false }) ?? null;
3852
+ const hoistedState = await this.ontologyService?.getEffectiveState(entityId) ?? { mode: "off", manifest: { node_types: [], edge_types: [] } };
3853
+ const engaged = this.ontologyService !== void 0 && canEngageIngestTyping(this.options.config, this.options.llmProvider, hoistedState.mode, hoistedState.manifest);
3854
+ const ontologyContext = await this.ontologyService?.buildWritePromptContext(entityId, { engaged }) ?? null;
3819
3855
  const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
3820
3856
  if (diagnostic) {
3821
3857
  emitDiagnostic(this.options, {
@@ -3971,16 +4007,42 @@ var IngestionService = class {
3971
4007
  chunks: chunks2.length
3972
4008
  });
3973
4009
  }
4010
+ const typing = { outcomes: /* @__PURE__ */ new Map(), counters: emptyTypingCounters() };
4011
+ let hashHeldElsewhere = false;
4012
+ if (engaged && failedChunks === 0 && onDuplicateHash === "ingest") {
4013
+ const holder = await this.sourceRefIndexRepo.findActiveByEntityAndHash(entityId, sourceHash);
4014
+ hashHeldElsewhere = holder !== null && holder !== sourceRef;
4015
+ }
4016
+ if (engaged && !hashHeldElsewhere) {
4017
+ const asked = [];
4018
+ for (const slot of orderedChunkFacts) {
4019
+ for (const fact of slot.facts) {
4020
+ if (!volunteeredTypeResolves(fact.okf_type, hoistedState.manifest)) asked.push(fact);
4021
+ }
4022
+ }
4023
+ const outcomes = await classifyFactsForWrite(
4024
+ this.options,
4025
+ { entityId, trigger: "call", operation: "ingest" },
4026
+ asked,
4027
+ hoistedState.manifest,
4028
+ resolveTypingMinConfidence(this.options.config),
4029
+ { concurrency: chunkConcurrency }
4030
+ );
4031
+ asked.forEach((fact, i) => {
4032
+ typing.outcomes.set(fact, outcomes[i]);
4033
+ tallyTypingOutcome(typing.counters, outcomes[i]);
4034
+ });
4035
+ }
3974
4036
  const insertedFacts = [];
3975
4037
  const deletedSourceFactIds = [];
3976
4038
  try {
3977
4039
  if (failedChunks === 0) {
3978
4040
  const fullResult = await this.db.withTransactionAsync(async (tx) => {
3979
- return await this.runFullUpsertGraph(entityId, sourceRef, sourceHash, orderedChunkFacts, tx, diagBuffer, factLedger);
4041
+ return await this.runFullUpsertGraph(entityId, sourceRef, sourceHash, orderedChunkFacts, tx, diagBuffer, factLedger, typing);
3980
4042
  });
3981
4043
  deletedSourceFactIds.push(...fullResult.deletedSourceFactIds);
3982
4044
  insertedFacts.push(...fullResult.insertedFacts);
3983
- if (ontologyContext !== null && insertedFacts.length === 0 && deletedSourceFactIds.length > 0) {
4045
+ if (hoistedState.mode !== "off" && insertedFacts.length === 0 && deletedSourceFactIds.length > 0) {
3984
4046
  diagBuffer.push({
3985
4047
  entityId,
3986
4048
  operation: "ingest",
@@ -3993,7 +4055,7 @@ var IngestionService = class {
3993
4055
  const partialResult = await this.db.withTransactionAsync(async (tx) => {
3994
4056
  const flat = [];
3995
4057
  for (const slot of orderedChunkFacts) flat.push(...slot.facts);
3996
- return await this.appendPartialFacts(entityId, sourceRef, flat, tx, diagBuffer, factLedger);
4058
+ return await this.appendPartialFacts(entityId, sourceRef, flat, tx, diagBuffer, factLedger, typing);
3997
4059
  });
3998
4060
  insertedFacts.push(...partialResult.insertedDescriptors);
3999
4061
  }
@@ -4045,6 +4107,7 @@ var IngestionService = class {
4045
4107
  failedChunks
4046
4108
  };
4047
4109
  if (failedChunks > 0) result.parseFailures = failures;
4110
+ if (engaged) result.typing = toIngestCounters(typing.counters);
4048
4111
  return result;
4049
4112
  } finally {
4050
4113
  releaseIngestLocks();
@@ -4254,10 +4317,11 @@ var IngestionService = class {
4254
4317
  * On the partial path the caller never invokes this method; the empty
4255
4318
  * arrays stay empty.
4256
4319
  */
4257
- async runFullUpsertGraph(entityId, sourceRef, sourceHash, orderedChunkFacts, tx, diagBuffer, factLedger = /* @__PURE__ */ new Map()) {
4320
+ async runFullUpsertGraph(entityId, sourceRef, sourceHash, orderedChunkFacts, tx, diagBuffer, factLedger = /* @__PURE__ */ new Map(), typing) {
4258
4321
  const deletedSourceFactIds = [];
4259
4322
  const insertedFacts = [];
4260
4323
  const nodeTrust = /* @__PURE__ */ new Map();
4324
+ const diagBase = { entityId, operation: "ingest", trigger: "call" };
4261
4325
  deletedSourceFactIds.push(...await this.entryRepo.findIdsBySource(entityId, sourceRef, null, tx, false));
4262
4326
  const titleIndex = /* @__PURE__ */ new Map();
4263
4327
  const existingFacts = await this.entryRepo.findRecentByEntityId(entityId, 500, tx, sourceRef);
@@ -4271,6 +4335,7 @@ var IngestionService = class {
4271
4335
  let { mode, manifest } = ontologyState;
4272
4336
  const hostNodes = [];
4273
4337
  const rawEdgeRequests = [];
4338
+ const typedAtDoor = [];
4274
4339
  const now = Date.now();
4275
4340
  for (const { facts, ontology_updates } of orderedChunkFacts) {
4276
4341
  if (mode === "emergent" && ontology_updates && this.ontologyService) {
@@ -4290,14 +4355,15 @@ var IngestionService = class {
4290
4355
  for (const fact of facts) {
4291
4356
  const ontologyFact = fact;
4292
4357
  const id = generateId("fact_");
4293
- const validationDrops = [];
4294
- const normalized = this.ontologyService?.validateAndNormalizeFact(ontologyFact, manifest, { strict: false, drops: validationDrops }) ?? { okf_type: null, edges: [] };
4295
- for (const drop of validationDrops) {
4358
+ const outcome = typing?.outcomes.get(fact);
4359
+ const slot = normalizeForWrite(this.ontologyService, ontologyFact, manifest, mode, outcome, diagBase, id);
4360
+ const normalized = slot.normalized;
4361
+ for (const drop of slot.drops) {
4296
4362
  diagBuffer.push(edgeDropDiagnostic(drop, { entityId, operation: "ingest", trigger: "call", sourceRef, factId: id }));
4297
4363
  }
4298
- hostNodes.push({
4364
+ const hostNode = {
4299
4365
  id,
4300
- type: ontologyFact.okf_type ?? "",
4366
+ type: "",
4301
4367
  title: fact.title,
4302
4368
  body: fact.body,
4303
4369
  // Forward the LLM-extracted tags/confidence through the
@@ -4309,18 +4375,20 @@ var IngestionService = class {
4309
4375
  // 'certain' as documented.
4310
4376
  tags: fact.tags,
4311
4377
  confidence: fact.confidence
4312
- });
4378
+ };
4379
+ hostNodes.push(hostNode);
4380
+ typedAtDoor.push({ node: hostNode, fact: ontologyFact, id, outcome, slotType: normalized.okf_type });
4313
4381
  const locator = factLedger.get(fact);
4314
4382
  if (locator?.verdict) {
4315
- const outcome = groundingOutcome(locator.verdict, now);
4316
- nodeTrust.set(id, outcome.trust);
4317
- if (outcome.diagnostic) {
4383
+ const outcome2 = groundingOutcome(locator.verdict, now);
4384
+ nodeTrust.set(id, outcome2.trust);
4385
+ if (outcome2.diagnostic) {
4318
4386
  diagBuffer.push({
4319
4387
  entityId,
4320
4388
  operation: "ingest",
4321
4389
  trigger: "call",
4322
- code: outcome.diagnostic.code,
4323
- detail: { factId: id, sourceRef, chunkIndex: locator.chunkIndex, itemIndex: locator.itemIndex, reason: outcome.diagnostic.reason }
4390
+ code: outcome2.diagnostic.code,
4391
+ detail: { factId: id, sourceRef, chunkIndex: locator.chunkIndex, itemIndex: locator.itemIndex, reason: outcome2.diagnostic.reason }
4324
4392
  });
4325
4393
  }
4326
4394
  }
@@ -4331,6 +4399,18 @@ var IngestionService = class {
4331
4399
  }
4332
4400
  }
4333
4401
  }
4402
+ const doorReceipts = [];
4403
+ for (const { node, fact, id, outcome, slotType } of typedAtDoor) {
4404
+ const final = normalizeForWrite(this.ontologyService, fact, manifest, mode, outcome, diagBase, id);
4405
+ for (const receipt of final.receipts) {
4406
+ doorReceipts.push({ ...receipt, detail: { ...receipt.detail, sourceRef } });
4407
+ }
4408
+ node.type = final.normalized.okf_type ?? "";
4409
+ if (final.typedByClassifier && typing) typing.counters.typed++;
4410
+ if (outcome?.kind === "accepted" && final.normalized.okf_type !== slotType) {
4411
+ titleIndex.set(normalizeTitleKey(fact.title), { id, okf_type: final.normalized.okf_type });
4412
+ }
4413
+ }
4334
4414
  const hostEdges = [];
4335
4415
  for (const req of rawEdgeRequests) {
4336
4416
  const resolveDrops = [];
@@ -4351,6 +4431,7 @@ var IngestionService = class {
4351
4431
  hostEdges.push({ type: e.edge_type, sourceId: e.source_id, targetId: e.target_id });
4352
4432
  }
4353
4433
  }
4434
+ for (const receipt of doorReceipts) diagBuffer.push(receipt);
4354
4435
  await this.upsertGraphCore(
4355
4436
  entityId,
4356
4437
  { sourceRef, sourceHash, nodes: hostNodes, edges: hostEdges },
@@ -4379,7 +4460,7 @@ var IngestionService = class {
4379
4460
  * Runs INSIDE the caller's `tx`. Does not open a nested transaction.
4380
4461
  * Returns `{ inserted, skippedDuplicate }` for observability.
4381
4462
  */
4382
- async appendPartialFacts(entityId, sourceRef, dedupedFacts, tx, diagBuffer, factLedger = /* @__PURE__ */ new Map()) {
4463
+ async appendPartialFacts(entityId, sourceRef, dedupedFacts, tx, diagBuffer, factLedger = /* @__PURE__ */ new Map(), typing) {
4383
4464
  const liveIds = await this.entryRepo.findIdsBySource(entityId, sourceRef, null, tx, false);
4384
4465
  const liveFacts = liveIds.length === 0 ? [] : await this.entryRepo.findByIds(liveIds, void 0, tx);
4385
4466
  const liveTitles = new Set(liveFacts.map((f) => normalizeTitleKey(f.title)));
@@ -4390,6 +4471,7 @@ var IngestionService = class {
4390
4471
  for (const f of indexedFacts) {
4391
4472
  titleIndex.set(normalizeTitleKey(f.title), { id: f.id, okf_type: f.okf_type ?? null });
4392
4473
  }
4474
+ const diagBase = { entityId, operation: "ingest", trigger: "call" };
4393
4475
  const pendingEdges = [];
4394
4476
  let inserted = 0;
4395
4477
  let skippedDuplicate = 0;
@@ -4416,22 +4498,22 @@ var IngestionService = class {
4416
4498
  });
4417
4499
  }
4418
4500
  const ontologyFact = fact;
4419
- const validationDrops = [];
4420
- const normalized = this.ontologyService?.validateAndNormalizeFact(ontologyFact, manifest, { strict: false, drops: validationDrops }) ?? { okf_type: null, edges: [] };
4501
+ const { normalized, drops: validationDrops, receipts, typedByClassifier } = normalizeForWrite(
4502
+ this.ontologyService,
4503
+ ontologyFact,
4504
+ manifest,
4505
+ mode,
4506
+ typing?.outcomes.get(fact),
4507
+ diagBase,
4508
+ id
4509
+ );
4421
4510
  for (const drop of validationDrops) {
4422
4511
  diagBuffer.push(edgeDropDiagnostic(drop, { entityId, operation: "ingest", trigger: "call", sourceRef, factId: id }));
4423
4512
  }
4424
- if (shouldEmitOntologyReceipt(mode)) {
4425
- for (const receipt of nodeTypeReceipts(
4426
- { entityId, operation: "ingest", trigger: "call" },
4427
- id,
4428
- ontologyFact.okf_type ?? "",
4429
- normalized.okf_type,
4430
- normalized.match
4431
- )) {
4432
- diagBuffer.push({ ...receipt, detail: { ...receipt.detail, sourceRef } });
4433
- }
4513
+ for (const receipt of receipts) {
4514
+ diagBuffer.push({ ...receipt, detail: { ...receipt.detail, sourceRef } });
4434
4515
  }
4516
+ if (typedByClassifier && typing) typing.counters.typed++;
4435
4517
  if (normalized.edges.length > 0) {
4436
4518
  pendingEdges.push({ sourceId: id, sourceType: normalized.okf_type, edges: normalized.edges });
4437
4519
  }
@@ -5605,7 +5687,8 @@ async function setupDatabase(db, prefix) {
5605
5687
  summary TEXT NOT NULL,
5606
5688
  related_entry_id TEXT,
5607
5689
  created_at INTEGER NOT NULL,
5608
- occurred_at INTEGER
5690
+ occurred_at INTEGER,
5691
+ forgotten_at INTEGER
5609
5692
  );
5610
5693
 
5611
5694
  CREATE INDEX IF NOT EXISTS ${prefix}events_entity_idx ON ${prefix}events(entity_id, created_at DESC);
@@ -6307,8 +6390,27 @@ var MIGRATIONS = [
6307
6390
  await addPriorValidToColumn(db, prefix);
6308
6391
  await addDerivedEventsColumn(db, prefix);
6309
6392
  }
6393
+ },
6394
+ {
6395
+ version: 19,
6396
+ description: "Nullable events.forgotten_at column and partial index marking events the host forgot with forget({ eventId }) (specs/forget-event-exclusion)",
6397
+ run: async (db, prefix) => {
6398
+ await addEventsForgottenAtColumn(db, prefix);
6399
+ await createEventsForgottenIndex(db, prefix);
6400
+ }
6310
6401
  }
6311
6402
  ];
6403
+ async function addEventsForgottenAtColumn(db, prefix) {
6404
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}events)`);
6405
+ if (!cols.some((c) => c.name === "forgotten_at")) {
6406
+ await db.execAsync(`ALTER TABLE ${prefix}events ADD COLUMN forgotten_at INTEGER`);
6407
+ }
6408
+ }
6409
+ async function createEventsForgottenIndex(db, prefix) {
6410
+ await db.execAsync(
6411
+ `CREATE INDEX IF NOT EXISTS ${prefix}events_forgotten_idx ON ${prefix}events(entity_id, forgotten_at) WHERE forgotten_at IS NOT NULL`
6412
+ );
6413
+ }
6312
6414
  async function addPriorValidToColumn(db, prefix) {
6313
6415
  const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
6314
6416
  if (!cols.some((c) => c.name === "prior_valid_to")) {
@@ -6478,6 +6580,9 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
6478
6580
  const { entityId, trigger } = ctx;
6479
6581
  const promptOverride = ctx.promptOverride;
6480
6582
  const events = await deps.eventRepo.getRecent(entityId, 50);
6583
+ if (events.length === 0 && await deps.eventRepo.count(entityId) > 0) {
6584
+ return { processedThrough: null, factsWritten: 0 };
6585
+ }
6481
6586
  const currentFactsRows = await deps.entryRepo.findRecentByEntityId(entityId, 100);
6482
6587
  const currentFacts = currentFactsRows.map((f) => {
6483
6588
  const { embedding: _embedding, embedding_blob: _blob, ...rest } = f;
@@ -7332,12 +7437,18 @@ async function applyOps(deps, ctx, input) {
7332
7437
  return id;
7333
7438
  };
7334
7439
  const sourceIds = [...new Set(input.gated.map((g) => g.candidate.sourceEventId).filter((x) => x !== null))];
7335
- const presentIds = sourceIds.length > 0 ? await deps.eventRepo.findExistingIds(entityId, sourceIds, tx) : /* @__PURE__ */ new Set();
7440
+ const presentIds = sourceIds.length > 0 ? await deps.eventRepo.findLiveIds(entityId, sourceIds, tx) : /* @__PURE__ */ new Set();
7441
+ const failedIds = sourceIds.filter((id) => !presentIds.has(id));
7442
+ const stillExist = failedIds.length > 0 ? await deps.eventRepo.findExistingIds(entityId, failedIds, tx) : /* @__PURE__ */ new Set();
7336
7443
  const gatedLive = [];
7337
7444
  for (const g of input.gated) {
7338
7445
  const ev = g.candidate.sourceEventId;
7339
7446
  if (ev !== null && !presentIds.has(ev)) {
7340
- input.diagnostics.push({ ...diagBase, code: "source_event_gone", detail: { itemIndex: g.candidate.index, sourceRef: ev } });
7447
+ input.diagnostics.push({
7448
+ ...diagBase,
7449
+ code: "source_event_gone",
7450
+ detail: { itemIndex: g.candidate.index, sourceRef: ev, reason: stillExist.has(ev) ? "forgotten" : "gone" }
7451
+ });
7341
7452
  continue;
7342
7453
  }
7343
7454
  gatedLive.push(g);
@@ -7779,6 +7890,21 @@ var _MaintenanceService = class _MaintenanceService {
7779
7890
  }
7780
7891
  }
7781
7892
  deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx, { noCutoff: softDeletedAll });
7893
+ const delOpts = { noCutoff: softDeletedAll };
7894
+ const hasForgottenCol = await this.metadataRepo.columnExists(`${this.prefix}events`, "forgotten_at", tx) && await this.eventRepo.hasDeletableForgotten(entityId, cutoff, tx, delOpts);
7895
+ const cpBefore = hasForgottenCol ? await this.metadataRepo.getCheckpoint(entityId, tx) : null;
7896
+ const memDrop = cpBefore && (cpBefore.memory ?? 0) > 0 ? await this.eventRepo.countForgottenInPrefix(entityId, cpBefore.memory, cutoff, tx, delOpts) : 0;
7897
+ const healDrop = cpBefore && (cpBefore.heal ?? 0) > 0 ? await this.eventRepo.countForgottenInPrefix(entityId, cpBefore.heal, cutoff, tx, delOpts) : 0;
7898
+ const forgottenGone = hasForgottenCol ? (await this.eventRepo.deleteForgotten(entityId, cutoff, tx, delOpts)).changes : 0;
7899
+ if (forgottenGone > 0) {
7900
+ deletedEvents += forgottenGone;
7901
+ const updates = {};
7902
+ if (memDrop > 0) updates.memory = Math.max(0, cpBefore.memory - memDrop);
7903
+ if (healDrop > 0) updates.heal = Math.max(0, cpBefore.heal - healDrop);
7904
+ if (updates.memory !== void 0 || updates.heal !== void 0) {
7905
+ await this.metadataRepo.updateCheckpoint(entityId, updates, tx);
7906
+ }
7907
+ }
7782
7908
  });
7783
7909
  if (hookLedger) {
7784
7910
  const keptSet = new Set(kept);
@@ -7799,18 +7925,20 @@ var _MaintenanceService = class _MaintenanceService {
7799
7925
  const cutoff = now - retainEventsFor * 864e5;
7800
7926
  const guarded = resolveMaintenanceMode(this.options.config) === "deferred" || resolveLibrarianStrategy(this.options.config) === "ops";
7801
7927
  let wm = null;
7928
+ let retentionDeleted = 0;
7802
7929
  await this.db.withTransactionAsync(async (tx) => {
7803
7930
  if (guarded) {
7804
7931
  wm = await this.metadataRepo.getLibrarianWatermark(entityId, tx);
7805
- deletedEvents = (await this.eventRepo.pruneThrough(entityId, cutoff, wm, tx)).changes;
7932
+ retentionDeleted = (await this.eventRepo.pruneThrough(entityId, cutoff, wm, tx)).changes;
7806
7933
  } else {
7807
- deletedEvents = (await this.eventRepo.prune(entityId, cutoff, tx)).changes;
7934
+ retentionDeleted = (await this.eventRepo.prune(entityId, cutoff, tx)).changes;
7808
7935
  }
7809
- if (deletedEvents > 0) {
7936
+ deletedEvents += retentionDeleted;
7937
+ if (retentionDeleted > 0) {
7810
7938
  const cp = await this.metadataRepo.getCheckpoint(entityId, tx);
7811
7939
  const updates = {};
7812
- if ((cp.memory ?? 0) > 0) updates.memory = Math.max(0, cp.memory - deletedEvents);
7813
- if ((cp.heal ?? 0) > 0) updates.heal = Math.max(0, cp.heal - deletedEvents);
7940
+ if ((cp.memory ?? 0) > 0) updates.memory = Math.max(0, cp.memory - retentionDeleted);
7941
+ if ((cp.heal ?? 0) > 0) updates.heal = Math.max(0, cp.heal - retentionDeleted);
7814
7942
  if (updates.memory !== void 0 || updates.heal !== void 0) {
7815
7943
  await this.metadataRepo.updateCheckpoint(entityId, updates, tx);
7816
7944
  }
@@ -8018,9 +8146,11 @@ var _MaintenanceService = class _MaintenanceService {
8018
8146
  if (report.skipped.length === 0 && report.holds.length === 0) {
8019
8147
  let remainingTombstones;
8020
8148
  try {
8149
+ const eventsTracked = await this.metadataRepo.columnExists(`${this.prefix}events`, "forgotten_at");
8021
8150
  const row = await this.db.getFirstAsync(
8022
8151
  `SELECT (SELECT COUNT(*) FROM ${this.prefix}entries WHERE deleted_at IS NOT NULL)
8023
- + (SELECT COUNT(*) FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL) AS n`
8152
+ + (SELECT COUNT(*) FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL)
8153
+ ${eventsTracked ? `+ (SELECT COUNT(*) FROM ${this.prefix}events WHERE forgotten_at IS NOT NULL)` : ""} AS n`
8024
8154
  );
8025
8155
  remainingTombstones = row?.n ?? 0;
8026
8156
  } catch (err) {
@@ -8433,6 +8563,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
8433
8563
  let deletedEntries = 0;
8434
8564
  let deletedTasks = 0;
8435
8565
  let deletedEvents = 0;
8566
+ let eventMarked = 0;
8436
8567
  let chainIds = [];
8437
8568
  let chainTruncated = false;
8438
8569
  const deletedEntryIds = [];
@@ -8513,6 +8644,9 @@ DROP TRIGGER IF EXISTS ${ad};`);
8513
8644
  if (taskResult) deletedTasks++;
8514
8645
  deletedEntries += refResult;
8515
8646
  deletedEntries += pointerResult;
8647
+ if (params.eventId !== void 0) {
8648
+ eventMarked = await this.metadataRepo.columnExists(`${this.prefix}events`, "forgotten_at", tx) ? await this.eventRepo.markForgotten(entityId, params.eventId, now, tx) : 0;
8649
+ }
8516
8650
  }
8517
8651
  if (ledgerOn && this.vectorRemoval?.gate() === "hook" && deletedEntryIds.length > 0) {
8518
8652
  await this.vectorRemovalRepo?.backstopEnqueue(entityId, Array.from(new Set(deletedEntryIds)), now, tx);
@@ -8565,7 +8699,9 @@ DROP TRIGGER IF EXISTS ${ad};`);
8565
8699
  }
8566
8700
  }
8567
8701
  if (!params.clearAll) {
8568
- const base = { deleted: { entries: deletedEntries, tasks: deletedTasks } };
8702
+ const base = {
8703
+ deleted: params.eventId !== void 0 ? { entries: deletedEntries, tasks: deletedTasks, events: eventMarked } : { entries: deletedEntries, tasks: deletedTasks }
8704
+ };
8569
8705
  if (params.includeChain) {
8570
8706
  base.chainEntryIds = chainIds;
8571
8707
  if (chainTruncated) {
@@ -8671,7 +8807,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
8671
8807
  }
8672
8808
  if (params.eventId !== void 0) {
8673
8809
  const entries2 = await this.entryRepo.countLiveByPointerEvent(entityId, params.eventId);
8674
- return { deleted: { entries: entries2, tasks: 0 } };
8810
+ const events = await this.metadataRepo.columnExists(`${this.prefix}events`, "forgotten_at") ? await this.eventRepo.countForgettable(entityId, params.eventId) : 0;
8811
+ return { deleted: { entries: entries2, tasks: 0, events } };
8675
8812
  }
8676
8813
  const sourceRef = params.sourceRef !== void 0 ? normalizeSourceRef(params.sourceRef) : null;
8677
8814
  if (params.sourceRef !== void 0 && !sourceRef) throw new Error("Invalid sourceRef");
@@ -10458,7 +10595,7 @@ var ImportExportService = class {
10458
10595
  const [factsRaw, tasks, events, edges, summaryValue] = await Promise.all([
10459
10596
  opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId, void 0, incl) : this.entryRepo.findAllByEntityId(entityId, void 0, incl),
10460
10597
  this.taskRepo.findAllByEntityId(entityId, void 0, incl),
10461
- this.eventRepo.getByEntityId(entityId, opts?.maxEvents),
10598
+ this.eventRepo.getByEntityId(entityId, opts?.maxEvents, incl),
10462
10599
  this.edgeRepo.getByEntityId(entityId),
10463
10600
  this.metadataRepo.getMeta(entitySummaryMetaKey(entityId))
10464
10601
  ]);
@@ -10789,10 +10926,14 @@ var ImportExportService = class {
10789
10926
  summary: event.summary,
10790
10927
  related_entry_id: event.related_entry_id ?? null,
10791
10928
  created_at: stamp.createdAt,
10792
- occurred_at: stamp.occurredAt
10929
+ occurred_at: stamp.occurredAt,
10930
+ forgotten_at: event.forgotten_at ?? null
10793
10931
  },
10794
10932
  tx
10795
10933
  );
10934
+ if (!inserted && event.forgotten_at != null) {
10935
+ await this.eventRepo.markForgotten(entityId, event.id, event.forgotten_at, tx);
10936
+ }
10796
10937
  if (!inserted || stamp.reason === null) continue;
10797
10938
  if (stamp.reason === "future") clampedEvents++;
10798
10939
  else restamped[stamp.reason]++;
@@ -12436,6 +12577,6 @@ var WriteService = class {
12436
12577
  }
12437
12578
  };
12438
12579
 
12439
- 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, canEngageWriteTyping, chunkText, configureRandomSource, createEntriesDeletedIndex, 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, parseStoredDerivedEvents, parseStoredSourcePointer, passageFtsTablesDdl, passageFtsTriggerNames, passageFtsTriggersDdl, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveContextBudget, resolveContextBudgetOrThrow, resolveDefaultChunkLength, resolveEdgeDefinitions, resolveEdgesMinConfidence, resolveGrounding, resolveHealScreenMinConfidence, resolveLibrarianStrategy, resolveMaxPromptChars, resolveNodeType, resolveNodeTypeMatch, resolveResolveMinConfidence, resolveSystemOneEdges, resolveSystemOneHealScreen, resolveSystemOneResolve, resolveSystemOneTypeOnWrite, resolveSystemOneTyping, resolveTypingMinConfidence, retiredTableName, runSourceRefNormalize, safeSlice, serializeDerivedEvents, serializeSourcePointer, setupDatabase, shouldEmitOntologyReceipt, sweepChunkSql, sweepHiSql, typeSatisfies, validUsage, validateDerivedEventsValue, validateInlineEdges, validateManifest, validateSourcePointerValue, warnChangedDefaultsOnce, warnOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
12440
- //# sourceMappingURL=chunk-64ZKSSY6.mjs.map
12441
- //# sourceMappingURL=chunk-64ZKSSY6.mjs.map
12580
+ 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, canEngageIngestTyping, canEngageWriteTyping, chunkText, configureRandomSource, createEntriesDeletedIndex, createEventsForgottenIndex, 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, parseStoredDerivedEvents, parseStoredSourcePointer, passageFtsTablesDdl, passageFtsTriggerNames, passageFtsTriggersDdl, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveContextBudget, resolveContextBudgetOrThrow, resolveDefaultChunkLength, resolveEdgeDefinitions, resolveEdgesMinConfidence, resolveGrounding, resolveHealScreenMinConfidence, resolveLibrarianStrategy, resolveMaxPromptChars, resolveNodeType, resolveNodeTypeMatch, resolveResolveMinConfidence, resolveSystemOneEdges, resolveSystemOneHealScreen, resolveSystemOneResolve, resolveSystemOneTypeOnIngest, resolveSystemOneTypeOnWrite, resolveSystemOneTyping, resolveTypingMinConfidence, retiredTableName, runSourceRefNormalize, safeSlice, serializeDerivedEvents, serializeSourcePointer, setupDatabase, shouldEmitOntologyReceipt, sweepChunkSql, sweepHiSql, typeSatisfies, validUsage, validateDerivedEventsValue, validateInlineEdges, validateManifest, validateSourcePointerValue, warnChangedDefaultsOnce, warnOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
12581
+ //# sourceMappingURL=chunk-FX4J6MLA.mjs.map
12582
+ //# sourceMappingURL=chunk-FX4J6MLA.mjs.map