@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.
package/dist/index.js CHANGED
@@ -253,6 +253,16 @@ function resolveSystemOneTypeOnWrite(config) {
253
253
  }
254
254
  return typeOnWrite ?? "llm";
255
255
  }
256
+ function resolveSystemOneTypeOnIngest(config) {
257
+ const typeOnIngest = config?.systemOne?.typeOnIngest;
258
+ if (typeOnIngest !== void 0 && !isTypingMode(typeOnIngest)) {
259
+ warnOnce(
260
+ `[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.`
261
+ );
262
+ return "llm";
263
+ }
264
+ return typeOnIngest ?? "llm";
265
+ }
256
266
  function resolveHealScreenMinConfidence(config) {
257
267
  if (resolveSystemOneHealScreen(config) !== "auto") return void 0;
258
268
  const floor = config?.systemOne?.minConfidence?.healScreen;
@@ -417,7 +427,7 @@ var MESSAGE = {
417
427
  guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass.",
418
428
  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).",
419
429
  source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer.",
420
- 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).",
430
+ 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.",
421
431
  derived_events_invalid: "Import met a malformed derived_events value and stored null.",
422
432
  source_store_source_too_large: "A source document exceeded the per-document size cap and was not stored.",
423
433
  source_store_budget_exceeded: "Storing a source document would exceed the store UTF-16 code-unit budget and it was not stored.",
@@ -1807,8 +1817,14 @@ function isManifestRepresentable(manifest) {
1807
1817
  const slugs = manifest.node_types.map((n) => n.type);
1808
1818
  return slugs.length > 0 && slugs.length + 1 <= CLASSIFIER_MAX_CHOICES && !slugs.some((s) => isReservedAbstainSlug(s));
1809
1819
  }
1820
+ function typingEngages(site, provider, mode, manifest) {
1821
+ return site === "auto" && typeof provider.classify === "function" && mode !== "off" && isManifestRepresentable(manifest);
1822
+ }
1810
1823
  function canEngageWriteTyping(config, provider, mode, manifest) {
1811
- return resolveSystemOneTypeOnWrite(config) === "auto" && typeof provider.classify === "function" && mode !== "off" && isManifestRepresentable(manifest);
1824
+ return typingEngages(resolveSystemOneTypeOnWrite(config), provider, mode, manifest);
1825
+ }
1826
+ function canEngageIngestTyping(config, provider, mode, manifest) {
1827
+ return typingEngages(resolveSystemOneTypeOnIngest(config), provider, mode, manifest);
1812
1828
  }
1813
1829
  function buildTypingQuestion(manifest) {
1814
1830
  return {
@@ -1821,9 +1837,9 @@ function buildTypingQuestion(manifest) {
1821
1837
  function volunteeredTypeResolves(rawOkfType, manifest) {
1822
1838
  return typeof rawOkfType === "string" && resolveNodeTypeMatch(rawOkfType, manifest) !== null;
1823
1839
  }
1824
- async function classifyFactsForWrite(options, ctx, facts, manifest, floor) {
1840
+ async function classifyFactsForWrite(options, ctx, facts, manifest, floor, opts) {
1825
1841
  const question = buildTypingQuestion(manifest);
1826
- const rawConcurrency = options.config?.chunkConcurrency ?? 1;
1842
+ const rawConcurrency = opts?.concurrency ?? options.config?.chunkConcurrency ?? 1;
1827
1843
  const concurrency = Number.isFinite(rawConcurrency) && rawConcurrency >= 1 ? Math.floor(rawConcurrency) : 1;
1828
1844
  let stopped = false;
1829
1845
  return withConcurrency(
@@ -1854,6 +1870,10 @@ async function classifyFactsForWrite(options, ctx, facts, manifest, floor) {
1854
1870
  concurrency
1855
1871
  );
1856
1872
  }
1873
+ function toIngestCounters(c) {
1874
+ const { unattempted: _unattempted, ...rest } = c;
1875
+ return rest;
1876
+ }
1857
1877
  function emptyTypingCounters() {
1858
1878
  return { asked: 0, typed: 0, abstained: 0, lowConfidence: 0, invalid: 0, skipped: 0, unattempted: 0 };
1859
1879
  }
@@ -2102,7 +2122,8 @@ async function setupDatabase(db, prefix) {
2102
2122
  summary TEXT NOT NULL,
2103
2123
  related_entry_id TEXT,
2104
2124
  created_at INTEGER NOT NULL,
2105
- occurred_at INTEGER
2125
+ occurred_at INTEGER,
2126
+ forgotten_at INTEGER
2106
2127
  );
2107
2128
 
2108
2129
  CREATE INDEX IF NOT EXISTS ${prefix}events_entity_idx ON ${prefix}events(entity_id, created_at DESC);
@@ -2804,8 +2825,27 @@ var MIGRATIONS = [
2804
2825
  await addPriorValidToColumn(db, prefix);
2805
2826
  await addDerivedEventsColumn(db, prefix);
2806
2827
  }
2828
+ },
2829
+ {
2830
+ version: 19,
2831
+ description: "Nullable events.forgotten_at column and partial index marking events the host forgot with forget({ eventId }) (specs/forget-event-exclusion)",
2832
+ run: async (db, prefix) => {
2833
+ await addEventsForgottenAtColumn(db, prefix);
2834
+ await createEventsForgottenIndex(db, prefix);
2835
+ }
2807
2836
  }
2808
2837
  ];
2838
+ async function addEventsForgottenAtColumn(db, prefix) {
2839
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}events)`);
2840
+ if (!cols.some((c) => c.name === "forgotten_at")) {
2841
+ await db.execAsync(`ALTER TABLE ${prefix}events ADD COLUMN forgotten_at INTEGER`);
2842
+ }
2843
+ }
2844
+ async function createEventsForgottenIndex(db, prefix) {
2845
+ await db.execAsync(
2846
+ `CREATE INDEX IF NOT EXISTS ${prefix}events_forgotten_idx ON ${prefix}events(entity_id, forgotten_at) WHERE forgotten_at IS NOT NULL`
2847
+ );
2848
+ }
2809
2849
  async function addPriorValidToColumn(db, prefix) {
2810
2850
  const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
2811
2851
  if (!cols.some((c) => c.name === "prior_valid_to")) {
@@ -5248,12 +5288,13 @@ function afterArgs(wm) {
5248
5288
  return [wm.at, wm.at, wm.id];
5249
5289
  }
5250
5290
  function mapEvent(row) {
5251
- if (row.occurred_at == null) {
5252
- const rest = { ...row };
5253
- delete rest.occurred_at;
5254
- return rest;
5255
- }
5256
- return row;
5291
+ const dropOccurred = row.occurred_at == null;
5292
+ const dropForgotten = row.forgotten_at == null;
5293
+ if (!dropOccurred && !dropForgotten) return row;
5294
+ const rest = { ...row };
5295
+ if (dropOccurred) delete rest.occurred_at;
5296
+ if (dropForgotten) delete rest.forgotten_at;
5297
+ return rest;
5257
5298
  }
5258
5299
  var EventRepository = class extends BaseRepository {
5259
5300
  /**
@@ -5280,8 +5321,8 @@ var EventRepository = class extends BaseRepository {
5280
5321
  async addIgnoreDuplicate(event, tx) {
5281
5322
  const executor = this.getExecutor(tx);
5282
5323
  const result = await executor.runAsync(
5283
- `INSERT OR IGNORE INTO ${this.prefix}events (id, entity_id, event_type, summary, related_entry_id, created_at, occurred_at)
5284
- VALUES (?, ?, ?, ?, ?, ?, ?)`,
5324
+ `INSERT OR IGNORE INTO ${this.prefix}events (id, entity_id, event_type, summary, related_entry_id, created_at, occurred_at, forgotten_at)
5325
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
5285
5326
  [
5286
5327
  event.id,
5287
5328
  event.entity_id,
@@ -5289,7 +5330,8 @@ var EventRepository = class extends BaseRepository {
5289
5330
  event.summary,
5290
5331
  event.related_entry_id ?? null,
5291
5332
  event.created_at,
5292
- event.occurred_at ?? null
5333
+ event.occurred_at ?? null,
5334
+ event.forgotten_at ?? null
5293
5335
  ]
5294
5336
  );
5295
5337
  return result.changes > 0;
@@ -5298,27 +5340,37 @@ var EventRepository = class extends BaseRepository {
5298
5340
  * The subset of `ids` that exist as events of `entityId` (specs/
5299
5341
  * inplace-update-provenance §3). Chunked so a large batch stays under the
5300
5342
  * bound-variable limit. Pass `tx` to read inside the caller's transaction.
5343
+ * `liveOnly` (default false) also requires `forgotten_at IS NULL`.
5301
5344
  */
5302
- async findExistingIds(entityId, ids, tx) {
5345
+ async findIds(entityId, ids, liveOnly, tx) {
5303
5346
  const executor = this.getExecutor(tx);
5304
5347
  const found = /* @__PURE__ */ new Set();
5348
+ const live = liveOnly ? " AND forgotten_at IS NULL" : "";
5305
5349
  for (let i = 0; i < ids.length; i += 500) {
5306
5350
  const chunk = ids.slice(i, i + 500);
5307
5351
  const rows = await executor.getAllAsync(
5308
- `SELECT id FROM ${this.prefix}events WHERE entity_id = ? AND id IN (${chunk.map(() => "?").join(",")})`,
5352
+ `SELECT id FROM ${this.prefix}events WHERE entity_id = ? AND id IN (${chunk.map(() => "?").join(",")})${live}`,
5309
5353
  [entityId, ...chunk]
5310
5354
  );
5311
5355
  for (const r of rows) found.add(r.id);
5312
5356
  }
5313
5357
  return found;
5314
5358
  }
5359
+ /** Events that exist as rows, forgotten or not (apply re-check's gone-vs-forgotten probe, specs/forget-event-exclusion §4). */
5360
+ async findExistingIds(entityId, ids, tx) {
5361
+ return this.findIds(entityId, ids, false, tx);
5362
+ }
5363
+ /** Events that exist and are not forgotten (specs/forget-event-exclusion §4). */
5364
+ async findLiveIds(entityId, ids, tx) {
5365
+ return this.findIds(entityId, ids, true, tx);
5366
+ }
5315
5367
  /**
5316
5368
  * Return the most recent events for an entity, newest first.
5317
5369
  * Defaults to a limit of 50.
5318
5370
  */
5319
5371
  async getRecent(entityId, limit = 50) {
5320
5372
  const rows = await this.db.getAllAsync(
5321
- `SELECT * FROM ${this.prefix}events WHERE entity_id = ? ORDER BY created_at DESC LIMIT ?`,
5373
+ `SELECT * FROM ${this.prefix}events WHERE entity_id = ? AND forgotten_at IS NULL ORDER BY created_at DESC LIMIT ?`,
5322
5374
  [entityId, limit]
5323
5375
  );
5324
5376
  return rows.map(mapEvent);
@@ -5331,7 +5383,7 @@ var EventRepository = class extends BaseRepository {
5331
5383
  if (entityIds.length === 0) return [];
5332
5384
  const placeholders = entityIds.map(() => "?").join(", ");
5333
5385
  const rows = await this.db.getAllAsync(
5334
- `SELECT * FROM ${this.prefix}events WHERE entity_id IN (${placeholders}) ORDER BY created_at DESC LIMIT ?`,
5386
+ `SELECT * FROM ${this.prefix}events WHERE entity_id IN (${placeholders}) AND forgotten_at IS NULL ORDER BY created_at DESC LIMIT ?`,
5335
5387
  [...entityIds, limit]
5336
5388
  );
5337
5389
  return rows.map(mapEvent);
@@ -5372,7 +5424,7 @@ var EventRepository = class extends BaseRepository {
5372
5424
  async countHeldBack(entityId, cutoff, wm) {
5373
5425
  const where = wm ? ` AND ${AFTER_SQL}` : "";
5374
5426
  const row = await this.db.getFirstAsync(
5375
- `SELECT COUNT(*) AS n FROM ${this.prefix}events WHERE entity_id = ? AND created_at <= ?${where}`,
5427
+ `SELECT COUNT(*) AS n FROM ${this.prefix}events WHERE entity_id = ? AND created_at <= ? AND forgotten_at IS NULL${where}`,
5376
5428
  [entityId, cutoff, ...wm ? afterArgs(wm) : []]
5377
5429
  );
5378
5430
  return Number(row?.n ?? 0);
@@ -5405,16 +5457,17 @@ var EventRepository = class extends BaseRepository {
5405
5457
  * Return all events for an entity in chronological (ASC) order.
5406
5458
  * When limit is provided, fetches newest-first then reverses to preserve chronological order.
5407
5459
  */
5408
- async getByEntityId(entityId, limit) {
5460
+ async getByEntityId(entityId, limit, opts) {
5461
+ const live = opts?.includeDeleted ? "" : " AND forgotten_at IS NULL";
5409
5462
  if (limit != null) {
5410
5463
  const rows2 = await this.db.getAllAsync(
5411
- `SELECT * FROM ${this.prefix}events WHERE entity_id = ? ORDER BY created_at DESC LIMIT ?`,
5464
+ `SELECT * FROM ${this.prefix}events WHERE entity_id = ?${live} ORDER BY created_at DESC LIMIT ?`,
5412
5465
  [entityId, limit]
5413
5466
  );
5414
5467
  return rows2.map(mapEvent).slice().reverse();
5415
5468
  }
5416
5469
  const rows = await this.db.getAllAsync(
5417
- `SELECT * FROM ${this.prefix}events WHERE entity_id = ? ORDER BY created_at ASC`,
5470
+ `SELECT * FROM ${this.prefix}events WHERE entity_id = ?${live} ORDER BY created_at ASC`,
5418
5471
  [entityId]
5419
5472
  );
5420
5473
  return rows.map(mapEvent);
@@ -5429,7 +5482,7 @@ var EventRepository = class extends BaseRepository {
5429
5482
  async getAfter(entityId, wm, limit) {
5430
5483
  const limitClause = limit != null ? ` LIMIT ?` : "";
5431
5484
  const params = wm ? [entityId, wm.at, wm.at, wm.id] : [entityId];
5432
- const where = wm ? `entity_id = ? AND ${AFTER_SQL}` : `entity_id = ?`;
5485
+ const where = wm ? `entity_id = ? AND forgotten_at IS NULL AND ${AFTER_SQL}` : `entity_id = ? AND forgotten_at IS NULL`;
5433
5486
  if (limit != null) params.push(limit);
5434
5487
  const rows = await this.db.getAllAsync(
5435
5488
  `SELECT * FROM ${this.prefix}events WHERE ${where} ORDER BY created_at ASC, id ASC${limitClause}`,
@@ -5445,7 +5498,7 @@ var EventRepository = class extends BaseRepository {
5445
5498
  */
5446
5499
  async countAfter(entityId, wm) {
5447
5500
  const params = wm ? [entityId, wm.at, wm.at, wm.id] : [entityId];
5448
- const where = wm ? `entity_id = ? AND ${AFTER_SQL}` : `entity_id = ?`;
5501
+ const where = wm ? `entity_id = ? AND forgotten_at IS NULL AND ${AFTER_SQL}` : `entity_id = ? AND forgotten_at IS NULL`;
5449
5502
  const row = await this.db.getFirstAsync(
5450
5503
  `SELECT COUNT(*) as count FROM ${this.prefix}events WHERE ${where}`,
5451
5504
  params
@@ -5477,13 +5530,68 @@ var EventRepository = class extends BaseRepository {
5477
5530
  async sumSummaryCharsAfter(entityId, wm, tx) {
5478
5531
  const executor = this.getExecutor(tx);
5479
5532
  const params = wm ? [entityId, wm.at, wm.at, wm.id] : [entityId];
5480
- const where = wm ? `entity_id = ? AND ${AFTER_SQL}` : `entity_id = ?`;
5533
+ const where = wm ? `entity_id = ? AND forgotten_at IS NULL AND ${AFTER_SQL}` : `entity_id = ? AND forgotten_at IS NULL`;
5481
5534
  const row = await executor.getFirstAsync(
5482
5535
  `SELECT SUM(LENGTH(summary)) as total FROM ${this.prefix}events WHERE ${where}`,
5483
5536
  params
5484
5537
  );
5485
5538
  return row?.total ?? 0;
5486
5539
  }
5540
+ /**
5541
+ * Mark one event forgotten (specs/forget-event-exclusion §2). Entity scoped
5542
+ * (rule 3) and idempotent: an unknown id, another entity's id or an already
5543
+ * forgotten row changes nothing and reports 0.
5544
+ */
5545
+ async markForgotten(entityId, eventId, now, tx) {
5546
+ const r = await this.getExecutor(tx).runAsync(
5547
+ `UPDATE ${this.prefix}events SET forgotten_at = ? WHERE entity_id = ? AND id = ? AND forgotten_at IS NULL`,
5548
+ [now, entityId, eventId]
5549
+ );
5550
+ return r.changes > 0 ? 1 : 0;
5551
+ }
5552
+ /** 1 when the event exists for the entity and is not yet forgotten, else 0 (the forget dry run). */
5553
+ async countForgettable(entityId, eventId) {
5554
+ const row = await this.db.getFirstAsync(
5555
+ `SELECT COUNT(*) AS n FROM ${this.prefix}events WHERE entity_id = ? AND id = ? AND forgotten_at IS NULL`,
5556
+ [entityId, eventId]
5557
+ );
5558
+ return Number(row?.n ?? 0) > 0 ? 1 : 0;
5559
+ }
5560
+ /** True when `deleteForgotten` with the same arguments would delete at least one row. */
5561
+ async hasDeletableForgotten(entityId, cutoff, tx, opts) {
5562
+ const row = opts?.noCutoff ? await tx.getFirstAsync(`SELECT 1 AS x FROM ${this.prefix}events WHERE entity_id = ? AND forgotten_at IS NOT NULL LIMIT 1`, [entityId]) : await tx.getFirstAsync(`SELECT 1 AS x FROM ${this.prefix}events WHERE entity_id = ? AND forgotten_at IS NOT NULL AND forgotten_at <= ? LIMIT 1`, [entityId, cutoff]);
5563
+ return !!row;
5564
+ }
5565
+ /**
5566
+ * How many of the entity's first `n` events, in `(created_at, id)` order,
5567
+ * `deleteForgotten` with the same arguments would delete. The memory and
5568
+ * heal checkpoints count rows in that order, so this is exactly how far a
5569
+ * checkpoint must drop (specs/forget-event-exclusion §5). Call before the delete.
5570
+ */
5571
+ async countForgottenInPrefix(entityId, n, cutoff, tx, opts) {
5572
+ if (n <= 0) return 0;
5573
+ const pred = opts?.noCutoff ? "forgotten_at IS NOT NULL" : "forgotten_at IS NOT NULL AND forgotten_at <= ?";
5574
+ const row = await tx.getFirstAsync(
5575
+ `SELECT COUNT(*) AS n FROM (SELECT forgotten_at FROM ${this.prefix}events WHERE entity_id = ? ORDER BY created_at ASC, id ASC LIMIT ?) WHERE ${pred}`,
5576
+ opts?.noCutoff ? [entityId, Math.trunc(n)] : [entityId, Math.trunc(n), cutoff]
5577
+ );
5578
+ return Number(row?.n ?? 0);
5579
+ }
5580
+ /**
5581
+ * Hard-delete the entity's forgotten events (specs/forget-event-exclusion
5582
+ * §5). No watermark guard and no `retainEventsFor`: a forgotten row is never
5583
+ * read. `noCutoff` drops the age predicate (erase) so a non-numeric or
5584
+ * future `forgotten_at` cannot escape.
5585
+ */
5586
+ async deleteForgotten(entityId, cutoff, tx, opts) {
5587
+ if (opts?.noCutoff) {
5588
+ return tx.runAsync(`DELETE FROM ${this.prefix}events WHERE entity_id = ? AND forgotten_at IS NOT NULL`, [entityId]);
5589
+ }
5590
+ return tx.runAsync(
5591
+ `DELETE FROM ${this.prefix}events WHERE entity_id = ? AND forgotten_at IS NOT NULL AND forgotten_at <= ?`,
5592
+ [entityId, cutoff]
5593
+ );
5594
+ }
5487
5595
  };
5488
5596
 
5489
5597
  // src/repositories/EdgeRepository.ts
@@ -5812,6 +5920,15 @@ var MetadataRepository = class extends BaseRepository {
5812
5920
  await this.db.execAsync(`VACUUM`);
5813
5921
  await this.checkpointTruncateVerified();
5814
5922
  }
5923
+ /**
5924
+ * True when `table` has `column`. A never-set-up or not-yet-migrated store
5925
+ * (the #316 recovery path) lacks columns later migrations add; callers that
5926
+ * must run there probe first.
5927
+ */
5928
+ async columnExists(table, column, tx) {
5929
+ const cols = await this.getExecutor(tx).getAllAsync(`PRAGMA table_info(${table})`);
5930
+ return cols.some((c) => c.name === column);
5931
+ }
5815
5932
  /**
5816
5933
  * Returns the set of distinct `entity_id` values across entries/tasks/events.
5817
5934
  *
@@ -5822,18 +5939,21 @@ var MetadataRepository = class extends BaseRepository {
5822
5939
  * is `entity_id COLLATE BINARY` for stable, locale-independent ordering.
5823
5940
  *
5824
5941
  * With `opts.softDeletedAtOrBefore` the walk is narrowed to entities holding
5825
- * at least one soft-deleted entry or task with `deleted_at` at or before
5942
+ * at least one soft-deleted entry, task or forgotten event with `deleted_at` at or before
5826
5943
  * that cutoff (erase's hard-delete walk, forget-erasure spec §2). Without
5827
5944
  * the option the host-facing semantics above are unchanged.
5828
5945
  */
5829
5946
  async getDistinctEntityIds(tx, opts) {
5830
5947
  const executor = this.getExecutor(tx);
5948
+ const eventTombstones = (opts?.softDeletedAll || opts?.softDeletedAtOrBefore !== void 0) && await this.columnExists(`${this.prefix}events`, "forgotten_at", tx);
5831
5949
  if (opts?.softDeletedAll) {
5832
5950
  const rows2 = await executor.getAllAsync(
5833
5951
  `SELECT DISTINCT entity_id FROM (
5834
5952
  SELECT entity_id FROM ${this.prefix}entries WHERE deleted_at IS NOT NULL
5835
5953
  UNION
5836
5954
  SELECT entity_id FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL
5955
+ ${eventTombstones ? `UNION
5956
+ SELECT entity_id FROM ${this.prefix}events WHERE forgotten_at IS NOT NULL` : ""}
5837
5957
  ) ORDER BY entity_id COLLATE BINARY`
5838
5958
  );
5839
5959
  return rows2.map((r) => r.entity_id);
@@ -5845,8 +5965,10 @@ var MetadataRepository = class extends BaseRepository {
5845
5965
  SELECT entity_id FROM ${this.prefix}entries WHERE deleted_at IS NOT NULL AND deleted_at <= ?
5846
5966
  UNION
5847
5967
  SELECT entity_id FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL AND deleted_at <= ?
5968
+ ${eventTombstones ? `UNION
5969
+ SELECT entity_id FROM ${this.prefix}events WHERE forgotten_at IS NOT NULL AND forgotten_at <= ?` : ""}
5848
5970
  ) ORDER BY entity_id COLLATE BINARY`,
5849
- [cutoff, cutoff]
5971
+ eventTombstones ? [cutoff, cutoff, cutoff] : [cutoff, cutoff]
5850
5972
  );
5851
5973
  return rows2.map((r) => r.entity_id);
5852
5974
  }
@@ -8932,7 +9054,9 @@ var IngestionService = class {
8932
9054
  }
8933
9055
  const { chunks: chunks2, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
8934
9056
  if (chunks2.length === 0) return zeroChunkResult();
8935
- const ontologyContext = await this.ontologyService?.buildWritePromptContext(entityId, { engaged: false }) ?? null;
9057
+ const hoistedState = await this.ontologyService?.getEffectiveState(entityId) ?? { mode: "off", manifest: { node_types: [], edge_types: [] } };
9058
+ const engaged = this.ontologyService !== void 0 && canEngageIngestTyping(this.options.config, this.options.llmProvider, hoistedState.mode, hoistedState.manifest);
9059
+ const ontologyContext = await this.ontologyService?.buildWritePromptContext(entityId, { engaged }) ?? null;
8936
9060
  const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
8937
9061
  if (diagnostic) {
8938
9062
  emitDiagnostic(this.options, {
@@ -9088,16 +9212,42 @@ var IngestionService = class {
9088
9212
  chunks: chunks2.length
9089
9213
  });
9090
9214
  }
9215
+ const typing = { outcomes: /* @__PURE__ */ new Map(), counters: emptyTypingCounters() };
9216
+ let hashHeldElsewhere = false;
9217
+ if (engaged && failedChunks === 0 && onDuplicateHash === "ingest") {
9218
+ const holder = await this.sourceRefIndexRepo.findActiveByEntityAndHash(entityId, sourceHash);
9219
+ hashHeldElsewhere = holder !== null && holder !== sourceRef;
9220
+ }
9221
+ if (engaged && !hashHeldElsewhere) {
9222
+ const asked = [];
9223
+ for (const slot of orderedChunkFacts) {
9224
+ for (const fact of slot.facts) {
9225
+ if (!volunteeredTypeResolves(fact.okf_type, hoistedState.manifest)) asked.push(fact);
9226
+ }
9227
+ }
9228
+ const outcomes = await classifyFactsForWrite(
9229
+ this.options,
9230
+ { entityId, trigger: "call", operation: "ingest" },
9231
+ asked,
9232
+ hoistedState.manifest,
9233
+ resolveTypingMinConfidence(this.options.config),
9234
+ { concurrency: chunkConcurrency }
9235
+ );
9236
+ asked.forEach((fact, i) => {
9237
+ typing.outcomes.set(fact, outcomes[i]);
9238
+ tallyTypingOutcome(typing.counters, outcomes[i]);
9239
+ });
9240
+ }
9091
9241
  const insertedFacts = [];
9092
9242
  const deletedSourceFactIds = [];
9093
9243
  try {
9094
9244
  if (failedChunks === 0) {
9095
9245
  const fullResult = await this.db.withTransactionAsync(async (tx) => {
9096
- return await this.runFullUpsertGraph(entityId, sourceRef, sourceHash, orderedChunkFacts, tx, diagBuffer, factLedger);
9246
+ return await this.runFullUpsertGraph(entityId, sourceRef, sourceHash, orderedChunkFacts, tx, diagBuffer, factLedger, typing);
9097
9247
  });
9098
9248
  deletedSourceFactIds.push(...fullResult.deletedSourceFactIds);
9099
9249
  insertedFacts.push(...fullResult.insertedFacts);
9100
- if (ontologyContext !== null && insertedFacts.length === 0 && deletedSourceFactIds.length > 0) {
9250
+ if (hoistedState.mode !== "off" && insertedFacts.length === 0 && deletedSourceFactIds.length > 0) {
9101
9251
  diagBuffer.push({
9102
9252
  entityId,
9103
9253
  operation: "ingest",
@@ -9110,7 +9260,7 @@ var IngestionService = class {
9110
9260
  const partialResult = await this.db.withTransactionAsync(async (tx) => {
9111
9261
  const flat = [];
9112
9262
  for (const slot of orderedChunkFacts) flat.push(...slot.facts);
9113
- return await this.appendPartialFacts(entityId, sourceRef, flat, tx, diagBuffer, factLedger);
9263
+ return await this.appendPartialFacts(entityId, sourceRef, flat, tx, diagBuffer, factLedger, typing);
9114
9264
  });
9115
9265
  insertedFacts.push(...partialResult.insertedDescriptors);
9116
9266
  }
@@ -9162,6 +9312,7 @@ var IngestionService = class {
9162
9312
  failedChunks
9163
9313
  };
9164
9314
  if (failedChunks > 0) result.parseFailures = failures;
9315
+ if (engaged) result.typing = toIngestCounters(typing.counters);
9165
9316
  return result;
9166
9317
  } finally {
9167
9318
  releaseIngestLocks();
@@ -9371,10 +9522,11 @@ var IngestionService = class {
9371
9522
  * On the partial path the caller never invokes this method; the empty
9372
9523
  * arrays stay empty.
9373
9524
  */
9374
- async runFullUpsertGraph(entityId, sourceRef, sourceHash, orderedChunkFacts, tx, diagBuffer, factLedger = /* @__PURE__ */ new Map()) {
9525
+ async runFullUpsertGraph(entityId, sourceRef, sourceHash, orderedChunkFacts, tx, diagBuffer, factLedger = /* @__PURE__ */ new Map(), typing) {
9375
9526
  const deletedSourceFactIds = [];
9376
9527
  const insertedFacts = [];
9377
9528
  const nodeTrust = /* @__PURE__ */ new Map();
9529
+ const diagBase = { entityId, operation: "ingest", trigger: "call" };
9378
9530
  deletedSourceFactIds.push(...await this.entryRepo.findIdsBySource(entityId, sourceRef, null, tx, false));
9379
9531
  const titleIndex = /* @__PURE__ */ new Map();
9380
9532
  const existingFacts = await this.entryRepo.findRecentByEntityId(entityId, 500, tx, sourceRef);
@@ -9388,6 +9540,7 @@ var IngestionService = class {
9388
9540
  let { mode, manifest } = ontologyState;
9389
9541
  const hostNodes = [];
9390
9542
  const rawEdgeRequests = [];
9543
+ const typedAtDoor = [];
9391
9544
  const now = Date.now();
9392
9545
  for (const { facts, ontology_updates } of orderedChunkFacts) {
9393
9546
  if (mode === "emergent" && ontology_updates && this.ontologyService) {
@@ -9407,14 +9560,15 @@ var IngestionService = class {
9407
9560
  for (const fact of facts) {
9408
9561
  const ontologyFact = fact;
9409
9562
  const id = generateId("fact_");
9410
- const validationDrops = [];
9411
- const normalized = this.ontologyService?.validateAndNormalizeFact(ontologyFact, manifest, { strict: false, drops: validationDrops }) ?? { okf_type: null, edges: [] };
9412
- for (const drop of validationDrops) {
9563
+ const outcome = typing?.outcomes.get(fact);
9564
+ const slot = normalizeForWrite(this.ontologyService, ontologyFact, manifest, mode, outcome, diagBase, id);
9565
+ const normalized = slot.normalized;
9566
+ for (const drop of slot.drops) {
9413
9567
  diagBuffer.push(edgeDropDiagnostic(drop, { entityId, operation: "ingest", trigger: "call", sourceRef, factId: id }));
9414
9568
  }
9415
- hostNodes.push({
9569
+ const hostNode = {
9416
9570
  id,
9417
- type: ontologyFact.okf_type ?? "",
9571
+ type: "",
9418
9572
  title: fact.title,
9419
9573
  body: fact.body,
9420
9574
  // Forward the LLM-extracted tags/confidence through the
@@ -9426,18 +9580,20 @@ var IngestionService = class {
9426
9580
  // 'certain' as documented.
9427
9581
  tags: fact.tags,
9428
9582
  confidence: fact.confidence
9429
- });
9583
+ };
9584
+ hostNodes.push(hostNode);
9585
+ typedAtDoor.push({ node: hostNode, fact: ontologyFact, id, outcome, slotType: normalized.okf_type });
9430
9586
  const locator = factLedger.get(fact);
9431
9587
  if (locator?.verdict) {
9432
- const outcome = groundingOutcome(locator.verdict, now);
9433
- nodeTrust.set(id, outcome.trust);
9434
- if (outcome.diagnostic) {
9588
+ const outcome2 = groundingOutcome(locator.verdict, now);
9589
+ nodeTrust.set(id, outcome2.trust);
9590
+ if (outcome2.diagnostic) {
9435
9591
  diagBuffer.push({
9436
9592
  entityId,
9437
9593
  operation: "ingest",
9438
9594
  trigger: "call",
9439
- code: outcome.diagnostic.code,
9440
- detail: { factId: id, sourceRef, chunkIndex: locator.chunkIndex, itemIndex: locator.itemIndex, reason: outcome.diagnostic.reason }
9595
+ code: outcome2.diagnostic.code,
9596
+ detail: { factId: id, sourceRef, chunkIndex: locator.chunkIndex, itemIndex: locator.itemIndex, reason: outcome2.diagnostic.reason }
9441
9597
  });
9442
9598
  }
9443
9599
  }
@@ -9448,6 +9604,18 @@ var IngestionService = class {
9448
9604
  }
9449
9605
  }
9450
9606
  }
9607
+ const doorReceipts = [];
9608
+ for (const { node, fact, id, outcome, slotType } of typedAtDoor) {
9609
+ const final = normalizeForWrite(this.ontologyService, fact, manifest, mode, outcome, diagBase, id);
9610
+ for (const receipt of final.receipts) {
9611
+ doorReceipts.push({ ...receipt, detail: { ...receipt.detail, sourceRef } });
9612
+ }
9613
+ node.type = final.normalized.okf_type ?? "";
9614
+ if (final.typedByClassifier && typing) typing.counters.typed++;
9615
+ if (outcome?.kind === "accepted" && final.normalized.okf_type !== slotType) {
9616
+ titleIndex.set(normalizeTitleKey(fact.title), { id, okf_type: final.normalized.okf_type });
9617
+ }
9618
+ }
9451
9619
  const hostEdges = [];
9452
9620
  for (const req of rawEdgeRequests) {
9453
9621
  const resolveDrops = [];
@@ -9468,6 +9636,7 @@ var IngestionService = class {
9468
9636
  hostEdges.push({ type: e.edge_type, sourceId: e.source_id, targetId: e.target_id });
9469
9637
  }
9470
9638
  }
9639
+ for (const receipt of doorReceipts) diagBuffer.push(receipt);
9471
9640
  await this.upsertGraphCore(
9472
9641
  entityId,
9473
9642
  { sourceRef, sourceHash, nodes: hostNodes, edges: hostEdges },
@@ -9496,7 +9665,7 @@ var IngestionService = class {
9496
9665
  * Runs INSIDE the caller's `tx`. Does not open a nested transaction.
9497
9666
  * Returns `{ inserted, skippedDuplicate }` for observability.
9498
9667
  */
9499
- async appendPartialFacts(entityId, sourceRef, dedupedFacts, tx, diagBuffer, factLedger = /* @__PURE__ */ new Map()) {
9668
+ async appendPartialFacts(entityId, sourceRef, dedupedFacts, tx, diagBuffer, factLedger = /* @__PURE__ */ new Map(), typing) {
9500
9669
  const liveIds = await this.entryRepo.findIdsBySource(entityId, sourceRef, null, tx, false);
9501
9670
  const liveFacts = liveIds.length === 0 ? [] : await this.entryRepo.findByIds(liveIds, void 0, tx);
9502
9671
  const liveTitles = new Set(liveFacts.map((f) => normalizeTitleKey(f.title)));
@@ -9507,6 +9676,7 @@ var IngestionService = class {
9507
9676
  for (const f of indexedFacts) {
9508
9677
  titleIndex.set(normalizeTitleKey(f.title), { id: f.id, okf_type: f.okf_type ?? null });
9509
9678
  }
9679
+ const diagBase = { entityId, operation: "ingest", trigger: "call" };
9510
9680
  const pendingEdges = [];
9511
9681
  let inserted = 0;
9512
9682
  let skippedDuplicate = 0;
@@ -9533,22 +9703,22 @@ var IngestionService = class {
9533
9703
  });
9534
9704
  }
9535
9705
  const ontologyFact = fact;
9536
- const validationDrops = [];
9537
- const normalized = this.ontologyService?.validateAndNormalizeFact(ontologyFact, manifest, { strict: false, drops: validationDrops }) ?? { okf_type: null, edges: [] };
9706
+ const { normalized, drops: validationDrops, receipts, typedByClassifier } = normalizeForWrite(
9707
+ this.ontologyService,
9708
+ ontologyFact,
9709
+ manifest,
9710
+ mode,
9711
+ typing?.outcomes.get(fact),
9712
+ diagBase,
9713
+ id
9714
+ );
9538
9715
  for (const drop of validationDrops) {
9539
9716
  diagBuffer.push(edgeDropDiagnostic(drop, { entityId, operation: "ingest", trigger: "call", sourceRef, factId: id }));
9540
9717
  }
9541
- if (shouldEmitOntologyReceipt(mode)) {
9542
- for (const receipt of nodeTypeReceipts(
9543
- { entityId, operation: "ingest", trigger: "call" },
9544
- id,
9545
- ontologyFact.okf_type ?? "",
9546
- normalized.okf_type,
9547
- normalized.match
9548
- )) {
9549
- diagBuffer.push({ ...receipt, detail: { ...receipt.detail, sourceRef } });
9550
- }
9718
+ for (const receipt of receipts) {
9719
+ diagBuffer.push({ ...receipt, detail: { ...receipt.detail, sourceRef } });
9551
9720
  }
9721
+ if (typedByClassifier && typing) typing.counters.typed++;
9552
9722
  if (normalized.edges.length > 0) {
9553
9723
  pendingEdges.push({ sourceId: id, sourceType: normalized.okf_type, edges: normalized.edges });
9554
9724
  }
@@ -10381,6 +10551,9 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
10381
10551
  const { entityId, trigger } = ctx;
10382
10552
  const promptOverride = ctx.promptOverride;
10383
10553
  const events = await deps.eventRepo.getRecent(entityId, 50);
10554
+ if (events.length === 0 && await deps.eventRepo.count(entityId) > 0) {
10555
+ return { processedThrough: null, factsWritten: 0 };
10556
+ }
10384
10557
  const currentFactsRows = await deps.entryRepo.findRecentByEntityId(entityId, 100);
10385
10558
  const currentFacts = currentFactsRows.map((f) => {
10386
10559
  const { embedding: _embedding, embedding_blob: _blob, ...rest } = f;
@@ -11198,12 +11371,18 @@ async function applyOps(deps, ctx, input) {
11198
11371
  return id;
11199
11372
  };
11200
11373
  const sourceIds = [...new Set(input.gated.map((g) => g.candidate.sourceEventId).filter((x) => x !== null))];
11201
- const presentIds = sourceIds.length > 0 ? await deps.eventRepo.findExistingIds(entityId, sourceIds, tx) : /* @__PURE__ */ new Set();
11374
+ const presentIds = sourceIds.length > 0 ? await deps.eventRepo.findLiveIds(entityId, sourceIds, tx) : /* @__PURE__ */ new Set();
11375
+ const failedIds = sourceIds.filter((id) => !presentIds.has(id));
11376
+ const stillExist = failedIds.length > 0 ? await deps.eventRepo.findExistingIds(entityId, failedIds, tx) : /* @__PURE__ */ new Set();
11202
11377
  const gatedLive = [];
11203
11378
  for (const g of input.gated) {
11204
11379
  const ev = g.candidate.sourceEventId;
11205
11380
  if (ev !== null && !presentIds.has(ev)) {
11206
- input.diagnostics.push({ ...diagBase, code: "source_event_gone", detail: { itemIndex: g.candidate.index, sourceRef: ev } });
11381
+ input.diagnostics.push({
11382
+ ...diagBase,
11383
+ code: "source_event_gone",
11384
+ detail: { itemIndex: g.candidate.index, sourceRef: ev, reason: stillExist.has(ev) ? "forgotten" : "gone" }
11385
+ });
11207
11386
  continue;
11208
11387
  }
11209
11388
  gatedLive.push(g);
@@ -11645,6 +11824,21 @@ var _MaintenanceService = class _MaintenanceService {
11645
11824
  }
11646
11825
  }
11647
11826
  deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx, { noCutoff: softDeletedAll });
11827
+ const delOpts = { noCutoff: softDeletedAll };
11828
+ const hasForgottenCol = await this.metadataRepo.columnExists(`${this.prefix}events`, "forgotten_at", tx) && await this.eventRepo.hasDeletableForgotten(entityId, cutoff, tx, delOpts);
11829
+ const cpBefore = hasForgottenCol ? await this.metadataRepo.getCheckpoint(entityId, tx) : null;
11830
+ const memDrop = cpBefore && (cpBefore.memory ?? 0) > 0 ? await this.eventRepo.countForgottenInPrefix(entityId, cpBefore.memory, cutoff, tx, delOpts) : 0;
11831
+ const healDrop = cpBefore && (cpBefore.heal ?? 0) > 0 ? await this.eventRepo.countForgottenInPrefix(entityId, cpBefore.heal, cutoff, tx, delOpts) : 0;
11832
+ const forgottenGone = hasForgottenCol ? (await this.eventRepo.deleteForgotten(entityId, cutoff, tx, delOpts)).changes : 0;
11833
+ if (forgottenGone > 0) {
11834
+ deletedEvents += forgottenGone;
11835
+ const updates = {};
11836
+ if (memDrop > 0) updates.memory = Math.max(0, cpBefore.memory - memDrop);
11837
+ if (healDrop > 0) updates.heal = Math.max(0, cpBefore.heal - healDrop);
11838
+ if (updates.memory !== void 0 || updates.heal !== void 0) {
11839
+ await this.metadataRepo.updateCheckpoint(entityId, updates, tx);
11840
+ }
11841
+ }
11648
11842
  });
11649
11843
  if (hookLedger) {
11650
11844
  const keptSet = new Set(kept);
@@ -11665,18 +11859,20 @@ var _MaintenanceService = class _MaintenanceService {
11665
11859
  const cutoff = now - retainEventsFor * 864e5;
11666
11860
  const guarded = resolveMaintenanceMode(this.options.config) === "deferred" || resolveLibrarianStrategy(this.options.config) === "ops";
11667
11861
  let wm = null;
11862
+ let retentionDeleted = 0;
11668
11863
  await this.db.withTransactionAsync(async (tx) => {
11669
11864
  if (guarded) {
11670
11865
  wm = await this.metadataRepo.getLibrarianWatermark(entityId, tx);
11671
- deletedEvents = (await this.eventRepo.pruneThrough(entityId, cutoff, wm, tx)).changes;
11866
+ retentionDeleted = (await this.eventRepo.pruneThrough(entityId, cutoff, wm, tx)).changes;
11672
11867
  } else {
11673
- deletedEvents = (await this.eventRepo.prune(entityId, cutoff, tx)).changes;
11868
+ retentionDeleted = (await this.eventRepo.prune(entityId, cutoff, tx)).changes;
11674
11869
  }
11675
- if (deletedEvents > 0) {
11870
+ deletedEvents += retentionDeleted;
11871
+ if (retentionDeleted > 0) {
11676
11872
  const cp = await this.metadataRepo.getCheckpoint(entityId, tx);
11677
11873
  const updates = {};
11678
- if ((cp.memory ?? 0) > 0) updates.memory = Math.max(0, cp.memory - deletedEvents);
11679
- if ((cp.heal ?? 0) > 0) updates.heal = Math.max(0, cp.heal - deletedEvents);
11874
+ if ((cp.memory ?? 0) > 0) updates.memory = Math.max(0, cp.memory - retentionDeleted);
11875
+ if ((cp.heal ?? 0) > 0) updates.heal = Math.max(0, cp.heal - retentionDeleted);
11680
11876
  if (updates.memory !== void 0 || updates.heal !== void 0) {
11681
11877
  await this.metadataRepo.updateCheckpoint(entityId, updates, tx);
11682
11878
  }
@@ -11884,9 +12080,11 @@ var _MaintenanceService = class _MaintenanceService {
11884
12080
  if (report.skipped.length === 0 && report.holds.length === 0) {
11885
12081
  let remainingTombstones;
11886
12082
  try {
12083
+ const eventsTracked = await this.metadataRepo.columnExists(`${this.prefix}events`, "forgotten_at");
11887
12084
  const row = await this.db.getFirstAsync(
11888
12085
  `SELECT (SELECT COUNT(*) FROM ${this.prefix}entries WHERE deleted_at IS NOT NULL)
11889
- + (SELECT COUNT(*) FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL) AS n`
12086
+ + (SELECT COUNT(*) FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL)
12087
+ ${eventsTracked ? `+ (SELECT COUNT(*) FROM ${this.prefix}events WHERE forgotten_at IS NOT NULL)` : ""} AS n`
11890
12088
  );
11891
12089
  remainingTombstones = row?.n ?? 0;
11892
12090
  } catch (err) {
@@ -12299,6 +12497,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
12299
12497
  let deletedEntries = 0;
12300
12498
  let deletedTasks = 0;
12301
12499
  let deletedEvents = 0;
12500
+ let eventMarked = 0;
12302
12501
  let chainIds = [];
12303
12502
  let chainTruncated = false;
12304
12503
  const deletedEntryIds = [];
@@ -12379,6 +12578,9 @@ DROP TRIGGER IF EXISTS ${ad};`);
12379
12578
  if (taskResult) deletedTasks++;
12380
12579
  deletedEntries += refResult;
12381
12580
  deletedEntries += pointerResult;
12581
+ if (params.eventId !== void 0) {
12582
+ eventMarked = await this.metadataRepo.columnExists(`${this.prefix}events`, "forgotten_at", tx) ? await this.eventRepo.markForgotten(entityId, params.eventId, now, tx) : 0;
12583
+ }
12382
12584
  }
12383
12585
  if (ledgerOn && this.vectorRemoval?.gate() === "hook" && deletedEntryIds.length > 0) {
12384
12586
  await this.vectorRemovalRepo?.backstopEnqueue(entityId, Array.from(new Set(deletedEntryIds)), now, tx);
@@ -12431,7 +12633,9 @@ DROP TRIGGER IF EXISTS ${ad};`);
12431
12633
  }
12432
12634
  }
12433
12635
  if (!params.clearAll) {
12434
- const base = { deleted: { entries: deletedEntries, tasks: deletedTasks } };
12636
+ const base = {
12637
+ deleted: params.eventId !== void 0 ? { entries: deletedEntries, tasks: deletedTasks, events: eventMarked } : { entries: deletedEntries, tasks: deletedTasks }
12638
+ };
12435
12639
  if (params.includeChain) {
12436
12640
  base.chainEntryIds = chainIds;
12437
12641
  if (chainTruncated) {
@@ -12537,7 +12741,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
12537
12741
  }
12538
12742
  if (params.eventId !== void 0) {
12539
12743
  const entries2 = await this.entryRepo.countLiveByPointerEvent(entityId, params.eventId);
12540
- return { deleted: { entries: entries2, tasks: 0 } };
12744
+ const events = await this.metadataRepo.columnExists(`${this.prefix}events`, "forgotten_at") ? await this.eventRepo.countForgettable(entityId, params.eventId) : 0;
12745
+ return { deleted: { entries: entries2, tasks: 0, events } };
12541
12746
  }
12542
12747
  const sourceRef = params.sourceRef !== void 0 ? normalizeSourceRef(params.sourceRef) : null;
12543
12748
  if (params.sourceRef !== void 0 && !sourceRef) throw new Error("Invalid sourceRef");
@@ -14222,7 +14427,7 @@ var ImportExportService = class {
14222
14427
  const [factsRaw, tasks, events, edges, summaryValue] = await Promise.all([
14223
14428
  opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId, void 0, incl) : this.entryRepo.findAllByEntityId(entityId, void 0, incl),
14224
14429
  this.taskRepo.findAllByEntityId(entityId, void 0, incl),
14225
- this.eventRepo.getByEntityId(entityId, opts?.maxEvents),
14430
+ this.eventRepo.getByEntityId(entityId, opts?.maxEvents, incl),
14226
14431
  this.edgeRepo.getByEntityId(entityId),
14227
14432
  this.metadataRepo.getMeta(entitySummaryMetaKey(entityId))
14228
14433
  ]);
@@ -14553,10 +14758,14 @@ var ImportExportService = class {
14553
14758
  summary: event.summary,
14554
14759
  related_entry_id: event.related_entry_id ?? null,
14555
14760
  created_at: stamp.createdAt,
14556
- occurred_at: stamp.occurredAt
14761
+ occurred_at: stamp.occurredAt,
14762
+ forgotten_at: event.forgotten_at ?? null
14557
14763
  },
14558
14764
  tx
14559
14765
  );
14766
+ if (!inserted && event.forgotten_at != null) {
14767
+ await this.eventRepo.markForgotten(entityId, event.id, event.forgotten_at, tx);
14768
+ }
14560
14769
  if (!inserted || stamp.reason === null) continue;
14561
14770
  if (stamp.reason === "future") clampedEvents++;
14562
14771
  else restamped[stamp.reason]++;
@@ -17178,6 +17387,7 @@ var WikiMemory = class {
17178
17387
  await this.db.withTransactionAsync(async (tx) => {
17179
17388
  await createLegacySourceTypeIndex(tx, this.prefix);
17180
17389
  await createEntriesDeletedIndex(tx, this.prefix);
17390
+ await createEventsForgottenIndex(tx, this.prefix);
17181
17391
  await writeNormalizeStamp(this.metadataRepo, tx);
17182
17392
  await this.metadataRepo.setMeta("schema_version", String(CURRENT_SCHEMA_VERSION), tx);
17183
17393
  });
@@ -17388,7 +17598,8 @@ var WikiMemory = class {
17388
17598
  const state = await this.ontologyService.getEffectiveState(entityId);
17389
17599
  const engaged = canEngageWriteTyping(this.options.config, this.options.llmProvider, state.mode, state.manifest);
17390
17600
  const writeContext = await this.ontologyService.buildWritePromptContext(entityId, { engaged });
17391
- const ingestContext = engaged ? await this.ontologyService.buildWritePromptContext(entityId, { engaged: false }) : writeContext;
17601
+ const ingestEngaged = canEngageIngestTyping(this.options.config, this.options.llmProvider, state.mode, state.manifest);
17602
+ const ingestContext = ingestEngaged ? null : engaged ? await this.ontologyService.buildWritePromptContext(entityId, { engaged: false }) : writeContext;
17392
17603
  const backfillContext = await this.ontologyService.buildPromptContext(entityId);
17393
17604
  const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
17394
17605
  if (diagnostic) {
@@ -18562,7 +18773,7 @@ function conceptRelativePath(sourceFilePath, targetFilePath) {
18562
18773
  return targetFilePath.replace(/^entities\/[^/]+\//, "");
18563
18774
  }
18564
18775
  function buildEventLogEntries(events, factIdToFilename) {
18565
- return events.map((e) => {
18776
+ return events.filter((e) => e.forgotten_at == null).map((e) => {
18566
18777
  const factFilename = e.related_entry_id ? factIdToFilename.get(e.related_entry_id) : void 0;
18567
18778
  const summary = e.summary.replace(/\\/g, "\\\\").replace(/\[/g, "\\[").replace(/\]/g, "\\]").replace(/\r?\n/g, " ");
18568
18779
  const text = factFilename ? `(${e.event_type}) [${summary}](./facts/${factFilename}.md)` : `(${e.event_type}) ${summary}`;
@@ -19196,6 +19407,7 @@ exports.resolveResolveMinConfidence = resolveResolveMinConfidence;
19196
19407
  exports.resolveSystemOneEdges = resolveSystemOneEdges;
19197
19408
  exports.resolveSystemOneHealScreen = resolveSystemOneHealScreen;
19198
19409
  exports.resolveSystemOneResolve = resolveSystemOneResolve;
19410
+ exports.resolveSystemOneTypeOnIngest = resolveSystemOneTypeOnIngest;
19199
19411
  exports.resolveSystemOneTypeOnWrite = resolveSystemOneTypeOnWrite;
19200
19412
  exports.resolveSystemOneTyping = resolveSystemOneTyping;
19201
19413
  exports.resolveTypingMinConfidence = resolveTypingMinConfidence;