@equationalapplications/core-llm-wiki 8.1.0 → 8.3.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.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { M as MemoryBundle, F as FormatContextOptions, G as GraphNeighborhood, a as MemoryDump, b as FormattedMemoryDump, R as ReadOptions, S as SQLiteAdapter, W as WikiOptions, c as WikiMemory } from './testing-CG8Hw5Ph.mjs';
2
- export { C as ChunkFailure, d as ClassifierAnswer, e as ClassifierQuestion, f as ClassifyRequest, g as ClassifyResponse, D as DegradedRecord, h as DraftPage, E as EmbedFactResult, i as EmbedFailureKind, j as EmbeddingMarkerKind, k as EntityMaintenanceReport, l as EntityStatus, m as ExtractedFact, n as ExtractedFactEdge, o as ExtractedFactWithOntology, p as ExtractedTask, q as GraphTraversalOptions, r as GroundingConfig, H as HEAL_BATCH_SIZE, s as HEAL_RECHECK_MS, t as HOOK_TIMEOUT_MARKER, u as HealResult, I as IngestDocumentResult, L as LLMProvider, v as LibrarianConfig, w as LibrarianGateConfig, x as MaintenanceJob, y as MaintenanceStopReason, z as MigrationPolicy, O as ONTOLOGY_BACKFILL_BATCH_SIZE, A as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, B as ONTOLOGY_BACKFILL_RECHECK_MS, J as OntologyBackfillResult, K as OntologyConfig, N as OntologyEdgeType, P as OntologyManifest, Q as OntologyMode, T as OntologyNodeType, U as OntologyPromptContext, V as OntologyUpdates, X as PendingMaintenance, Y as PendingMigrationWork, Z as PendingSourceStatus, _ as PromptOverrides, $ as PromptService, a0 as PrunePartialFailureError, a1 as ReembedResult, a2 as RememberInput, a3 as RunPendingMaintenanceOptions, a4 as RunPendingMaintenanceResult, a5 as SupersedeReplacement, a6 as VectorRanker, a7 as VectorRankerFallback, a8 as VectorRankerRankArgs, a9 as VectorRankerSemanticResult, aa as WikiBusyError, ab as WikiBusyOperation, ac as WikiCheckpoint, ad as WikiConfig, ae as WikiDiagnostic, af as WikiDiagnosticCode, ag as WikiDiagnosticDetail, ah as WikiDiagnosticOperation, ai as WikiDiagnosticSeverity, aj as WikiDiagnosticTrigger, ak as WikiDraftNotFound, al as WikiDuplicateHashError, am as WikiEdge, an as WikiEvent, ao as WikiFact, ap as WikiGraphNodeOwnershipConflict, aq as WikiIngestEmptyError, ar as WikiInstructions, as as WikiInvalidReadOptions, at as WikiLintReport, au as WikiMemoryTestAccess, av as WikiMigrationRequiredError, aw as WikiOutboxEvent, ax as WikiParseError, ay as WikiSearchUnavailableError, az as WikiSourceRefHashCollision, aA as WikiStrictOntologyViolation, aB as WikiSupersedeError, aC as WikiSupersedeReason, aD as WikiTask, aE as WikiTransactionError, aF as isWikiSearchUnavailableError, aG as validateManifest } from './testing-CG8Hw5Ph.mjs';
1
+ import { M as MemoryBundle, F as FormatContextOptions, G as GraphNeighborhood, a as MemoryDump, b as FormattedMemoryDump, R as ReadOptions, S as SQLiteAdapter, W as WikiOptions, c as WikiMemory } from './testing-BT5qSnGB.mjs';
2
+ export { C as ChunkFailure, d as ClassifierAnswer, e as ClassifierQuestion, f as ClassifyRequest, g as ClassifyResponse, D as DegradedRecord, h as DraftPage, E as EmbedFactResult, i as EmbedFailureKind, j as EmbeddingMarkerKind, k as EntityMaintenanceReport, l as EntityStatus, m as ExtractedFact, n as ExtractedFactEdge, o as ExtractedFactWithOntology, p as ExtractedTask, q as ForgetParams, r as ForgetResult, s as GraphTraversalOptions, t as GroundingConfig, H as HEAL_BATCH_SIZE, u as HEAL_RECHECK_MS, v as HOOK_TIMEOUT_MARKER, w as HealResult, I as IngestDocumentResult, L as LLMProvider, x as LibrarianConfig, y as LibrarianGateConfig, z as MaintenanceJob, A as MaintenanceStopReason, B as MigrationPolicy, O as ONTOLOGY_BACKFILL_BATCH_SIZE, J as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, K as ONTOLOGY_BACKFILL_RECHECK_MS, N as OntologyBackfillResult, P as OntologyConfig, Q as OntologyEdgeType, T as OntologyManifest, U as OntologyMode, V as OntologyNodeType, X as OntologyPromptContext, Y as OntologyUpdates, Z as PendingMaintenance, _ as PendingMigrationWork, $ as PendingSourceStatus, a0 as PromptOverrides, a1 as PromptService, a2 as PrunePartialFailureError, a3 as ReembedResult, a4 as RememberInput, a5 as RunPendingMaintenanceOptions, a6 as RunPendingMaintenanceResult, a7 as SupersedeReplacement, a8 as VectorRanker, a9 as VectorRankerFallback, aa as VectorRankerRankArgs, ab as VectorRankerSemanticResult, ac as WikiBusyError, ad as WikiBusyOperation, ae as WikiCheckpoint, af as WikiConfig, ag as WikiDiagnostic, ah as WikiDiagnosticCode, ai as WikiDiagnosticDetail, aj as WikiDiagnosticOperation, ak as WikiDiagnosticSeverity, al as WikiDiagnosticTrigger, am as WikiDraftNotFound, an as WikiDuplicateHashError, ao as WikiEdge, ap as WikiEvent, aq as WikiFact, ar as WikiGraphNodeOwnershipConflict, as as WikiIngestEmptyError, at as WikiInstructions, au as WikiInvalidReadOptions, av as WikiLintReport, aw as WikiMemoryTestAccess, ax as WikiMigrationRequiredError, ay as WikiOutboxEvent, az as WikiParseError, aA as WikiSearchUnavailableError, aB as WikiSourceRefHashCollision, aC as WikiStrictOntologyViolation, aD as WikiSupersedeError, aE as WikiSupersedeReason, aF as WikiTask, aG as WikiTransactionError, aH as isWikiSearchUnavailableError, aI as validateManifest } from './testing-BT5qSnGB.mjs';
3
3
  import { OkfFile } from '@equationalapplications/core-okf';
4
4
 
5
5
  /**
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { M as MemoryBundle, F as FormatContextOptions, G as GraphNeighborhood, a as MemoryDump, b as FormattedMemoryDump, R as ReadOptions, S as SQLiteAdapter, W as WikiOptions, c as WikiMemory } from './testing-CG8Hw5Ph.js';
2
- export { C as ChunkFailure, d as ClassifierAnswer, e as ClassifierQuestion, f as ClassifyRequest, g as ClassifyResponse, D as DegradedRecord, h as DraftPage, E as EmbedFactResult, i as EmbedFailureKind, j as EmbeddingMarkerKind, k as EntityMaintenanceReport, l as EntityStatus, m as ExtractedFact, n as ExtractedFactEdge, o as ExtractedFactWithOntology, p as ExtractedTask, q as GraphTraversalOptions, r as GroundingConfig, H as HEAL_BATCH_SIZE, s as HEAL_RECHECK_MS, t as HOOK_TIMEOUT_MARKER, u as HealResult, I as IngestDocumentResult, L as LLMProvider, v as LibrarianConfig, w as LibrarianGateConfig, x as MaintenanceJob, y as MaintenanceStopReason, z as MigrationPolicy, O as ONTOLOGY_BACKFILL_BATCH_SIZE, A as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, B as ONTOLOGY_BACKFILL_RECHECK_MS, J as OntologyBackfillResult, K as OntologyConfig, N as OntologyEdgeType, P as OntologyManifest, Q as OntologyMode, T as OntologyNodeType, U as OntologyPromptContext, V as OntologyUpdates, X as PendingMaintenance, Y as PendingMigrationWork, Z as PendingSourceStatus, _ as PromptOverrides, $ as PromptService, a0 as PrunePartialFailureError, a1 as ReembedResult, a2 as RememberInput, a3 as RunPendingMaintenanceOptions, a4 as RunPendingMaintenanceResult, a5 as SupersedeReplacement, a6 as VectorRanker, a7 as VectorRankerFallback, a8 as VectorRankerRankArgs, a9 as VectorRankerSemanticResult, aa as WikiBusyError, ab as WikiBusyOperation, ac as WikiCheckpoint, ad as WikiConfig, ae as WikiDiagnostic, af as WikiDiagnosticCode, ag as WikiDiagnosticDetail, ah as WikiDiagnosticOperation, ai as WikiDiagnosticSeverity, aj as WikiDiagnosticTrigger, ak as WikiDraftNotFound, al as WikiDuplicateHashError, am as WikiEdge, an as WikiEvent, ao as WikiFact, ap as WikiGraphNodeOwnershipConflict, aq as WikiIngestEmptyError, ar as WikiInstructions, as as WikiInvalidReadOptions, at as WikiLintReport, au as WikiMemoryTestAccess, av as WikiMigrationRequiredError, aw as WikiOutboxEvent, ax as WikiParseError, ay as WikiSearchUnavailableError, az as WikiSourceRefHashCollision, aA as WikiStrictOntologyViolation, aB as WikiSupersedeError, aC as WikiSupersedeReason, aD as WikiTask, aE as WikiTransactionError, aF as isWikiSearchUnavailableError, aG as validateManifest } from './testing-CG8Hw5Ph.js';
1
+ import { M as MemoryBundle, F as FormatContextOptions, G as GraphNeighborhood, a as MemoryDump, b as FormattedMemoryDump, R as ReadOptions, S as SQLiteAdapter, W as WikiOptions, c as WikiMemory } from './testing-BT5qSnGB.js';
2
+ export { C as ChunkFailure, d as ClassifierAnswer, e as ClassifierQuestion, f as ClassifyRequest, g as ClassifyResponse, D as DegradedRecord, h as DraftPage, E as EmbedFactResult, i as EmbedFailureKind, j as EmbeddingMarkerKind, k as EntityMaintenanceReport, l as EntityStatus, m as ExtractedFact, n as ExtractedFactEdge, o as ExtractedFactWithOntology, p as ExtractedTask, q as ForgetParams, r as ForgetResult, s as GraphTraversalOptions, t as GroundingConfig, H as HEAL_BATCH_SIZE, u as HEAL_RECHECK_MS, v as HOOK_TIMEOUT_MARKER, w as HealResult, I as IngestDocumentResult, L as LLMProvider, x as LibrarianConfig, y as LibrarianGateConfig, z as MaintenanceJob, A as MaintenanceStopReason, B as MigrationPolicy, O as ONTOLOGY_BACKFILL_BATCH_SIZE, J as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, K as ONTOLOGY_BACKFILL_RECHECK_MS, N as OntologyBackfillResult, P as OntologyConfig, Q as OntologyEdgeType, T as OntologyManifest, U as OntologyMode, V as OntologyNodeType, X as OntologyPromptContext, Y as OntologyUpdates, Z as PendingMaintenance, _ as PendingMigrationWork, $ as PendingSourceStatus, a0 as PromptOverrides, a1 as PromptService, a2 as PrunePartialFailureError, a3 as ReembedResult, a4 as RememberInput, a5 as RunPendingMaintenanceOptions, a6 as RunPendingMaintenanceResult, a7 as SupersedeReplacement, a8 as VectorRanker, a9 as VectorRankerFallback, aa as VectorRankerRankArgs, ab as VectorRankerSemanticResult, ac as WikiBusyError, ad as WikiBusyOperation, ae as WikiCheckpoint, af as WikiConfig, ag as WikiDiagnostic, ah as WikiDiagnosticCode, ai as WikiDiagnosticDetail, aj as WikiDiagnosticOperation, ak as WikiDiagnosticSeverity, al as WikiDiagnosticTrigger, am as WikiDraftNotFound, an as WikiDuplicateHashError, ao as WikiEdge, ap as WikiEvent, aq as WikiFact, ar as WikiGraphNodeOwnershipConflict, as as WikiIngestEmptyError, at as WikiInstructions, au as WikiInvalidReadOptions, av as WikiLintReport, aw as WikiMemoryTestAccess, ax as WikiMigrationRequiredError, ay as WikiOutboxEvent, az as WikiParseError, aA as WikiSearchUnavailableError, aB as WikiSourceRefHashCollision, aC as WikiStrictOntologyViolation, aD as WikiSupersedeError, aE as WikiSupersedeReason, aF as WikiTask, aG as WikiTransactionError, aH as isWikiSearchUnavailableError, aI as validateManifest } from './testing-BT5qSnGB.js';
3
3
  import { OkfFile } from '@equationalapplications/core-okf';
4
4
 
5
5
  /**
package/dist/index.js CHANGED
@@ -3137,6 +3137,19 @@ var SourceRefIndexRepository = class extends BaseRepository {
3137
3137
  [generateId("sri_"), entityId, sourceHash, sourceRef, Date.now()]
3138
3138
  );
3139
3139
  }
3140
+ /**
3141
+ * Hard-delete every row of the entity, live or soft-deleted (forget clearAll,
3142
+ * spec import-followups §6 rev 4). Nothing reads a soft-deleted row and
3143
+ * runPrune never sweeps this table, so a wipe leaves no tombstones.
3144
+ */
3145
+ async deleteByEntityId(entityId, tx) {
3146
+ const executor = this.getExecutor(tx);
3147
+ const result = await executor.runAsync(
3148
+ `DELETE FROM ${this.prefix}source_ref_index WHERE entity_id = ?`,
3149
+ [entityId]
3150
+ );
3151
+ return result.changes;
3152
+ }
3140
3153
  /**
3141
3154
  * Idempotent soft-delete of the live row for (entity_id, source_ref).
3142
3155
  * Called at the start of every ingestDocument to remove the prior run's
@@ -3579,6 +3592,10 @@ var EventRepository = class extends BaseRepository {
3579
3592
  );
3580
3593
  return rows.map(mapEvent);
3581
3594
  }
3595
+ /** Hard-delete every event of the entity, read or not (requested wipe, spec import-followups §6). */
3596
+ async deleteByEntityId(entityId, tx) {
3597
+ return tx.runAsync(`DELETE FROM ${this.prefix}events WHERE entity_id = ?`, [entityId]);
3598
+ }
3582
3599
  /**
3583
3600
  * Delete events for an entity that were created at or before the given cutoff timestamp.
3584
3601
  * Returns the number of deleted rows.
@@ -5986,7 +6003,8 @@ var SEVERITY = {
5986
6003
  resolve_failed: "warn",
5987
6004
  read_budget: "info",
5988
6005
  event_retention_held: "info",
5989
- event_created_at_clamped: "warn"
6006
+ event_created_at_clamped: "warn",
6007
+ event_created_at_restamped: "info"
5990
6008
  };
5991
6009
  var MESSAGE = {
5992
6010
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -6009,7 +6027,8 @@ var MESSAGE = {
6009
6027
  resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
6010
6028
  read_budget: "A read was packed to a token budget.",
6011
6029
  event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
6012
- event_created_at_clamped: "Imported events dated in the future were re-dated just after the current time, or after the librarian position if that is later, keeping their order."
6030
+ event_created_at_clamped: "Imported events dated in the future were re-dated just after the current time, or after the librarian position if that is later, keeping their order.",
6031
+ event_created_at_restamped: "Imported events that would have sorted behind the librarian position, or had an unusable date, were adjusted: an affected created_at was re-dated just after the current time, or after the librarian position if that is later, keeping their order; an unusable occurred_at was cleared."
6013
6032
  };
6014
6033
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
6015
6034
  function copyDetail(detail) {
@@ -7611,7 +7630,9 @@ async function runExtract(deps, ctx, batch) {
7611
7630
  const base = { entityId, operation: "librarian", trigger };
7612
7631
  const diagnostics = [];
7613
7632
  const byLabel = new Map(batch.map((l) => [l.label, l]));
7614
- const newestAt = batch[batch.length - 1].at;
7633
+ let newestAt = batch[0].at;
7634
+ for (const l of batch) if (l.at > newestAt) newestAt = l.at;
7635
+ const defaultValidFrom = Math.min(newestAt, Date.now());
7615
7636
  const candidates = [];
7616
7637
  (Array.isArray(parsed.facts) ? parsed.facts : []).forEach((raw, index) => {
7617
7638
  const fact = validateFact(raw);
@@ -7621,7 +7642,7 @@ async function runExtract(deps, ctx, batch) {
7621
7642
  }
7622
7643
  const r = raw;
7623
7644
  const sourceLabel = typeof r.source_event === "string" && byLabel.has(r.source_event) ? r.source_event : null;
7624
- const validFrom = parseValidFrom(r.valid_from) ?? (sourceLabel ? byLabel.get(sourceLabel).at : newestAt);
7645
+ const validFrom = parseValidFrom(r.valid_from) ?? (sourceLabel ? byLabel.get(sourceLabel).at : defaultValidFrom);
7625
7646
  candidates.push({ index, fact, sourceLabel, validFrom });
7626
7647
  });
7627
7648
  const tasks = [];
@@ -8191,7 +8212,7 @@ var formatSkipError = (err) => {
8191
8212
  return base;
8192
8213
  };
8193
8214
  var MaintenanceService = class {
8194
- constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService) {
8215
+ constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo) {
8195
8216
  this.db = db;
8196
8217
  this.prefix = prefix;
8197
8218
  this.options = options;
@@ -8205,6 +8226,7 @@ var MaintenanceService = class {
8205
8226
  this.embeddingService = embeddingService;
8206
8227
  this.ontologyService = ontologyService;
8207
8228
  this.promptService = promptService ?? new PromptService(this.options.config?.prompts, resolveGrounding(this.options.config?.grounding));
8229
+ this.edgeRepo = edgeRepo ?? new EdgeRepository(this.db, this.prefix);
8208
8230
  }
8209
8231
  async runPrune(entityId, options) {
8210
8232
  this.jobManager.acquireLock("prune", entityId);
@@ -8435,6 +8457,9 @@ var MaintenanceService = class {
8435
8457
  if (params.clearAll && (params.entryId !== void 0 || params.taskId !== void 0 || params.sourceRef !== void 0 || params.sourceHash !== void 0)) {
8436
8458
  throw new Error("forget() clearAll is mutually exclusive with entryId, taskId, sourceRef, and sourceHash");
8437
8459
  }
8460
+ if (params.includeEvents && !params.clearAll) {
8461
+ throw new Error("forget() includeEvents requires clearAll: true");
8462
+ }
8438
8463
  if (opts?.dryRun === true) {
8439
8464
  return this.forgetDryRun(entityId, params);
8440
8465
  }
@@ -8443,13 +8468,23 @@ var MaintenanceService = class {
8443
8468
  const now = Date.now();
8444
8469
  let deletedEntries = 0;
8445
8470
  let deletedTasks = 0;
8471
+ let deletedEvents = 0;
8446
8472
  const deletedEntryIds = [];
8447
8473
  await this.db.withTransactionAsync(async (tx) => {
8448
8474
  if (params.clearAll) {
8449
- deletedEntryIds.push(...await this.entryRepo.findIdsBySource(entityId, null, null, tx, true));
8475
+ for (const id of await this.entryRepo.findIdsBySource(entityId, null, null, tx, true)) deletedEntryIds.push(id);
8450
8476
  deletedEntries = await this.entryRepo.bulkSoftDeleteByEntityId(entityId, tx);
8451
8477
  deletedTasks = await this.taskRepo.bulkSoftDeleteByEntityId(entityId, tx);
8452
- await this.metadataRepo.updateCheckpoint(entityId, { memory: 0, heal: 0 }, tx);
8478
+ if (await this.sourceRefIndexPresent(tx)) {
8479
+ await this.sourceRefIndexRepo.deleteByEntityId(entityId, tx);
8480
+ }
8481
+ await this.edgeRepo.bulkDeleteByEntityId(entityId, tx);
8482
+ if (params.includeEvents) {
8483
+ deletedEvents = (await this.eventRepo.deleteByEntityId(entityId, tx)).changes;
8484
+ await this.metadataRepo.deleteCheckpoint(entityId, tx);
8485
+ } else {
8486
+ await this.metadataRepo.updateCheckpoint(entityId, { memory: 0, heal: 0 }, tx);
8487
+ }
8453
8488
  await this.metadataRepo.deleteMeta(entitySummaryMetaKey(entityId), tx);
8454
8489
  } else {
8455
8490
  const hasIdSelectors = params.entryId !== void 0 || params.taskId !== void 0;
@@ -8467,7 +8502,7 @@ var MaintenanceService = class {
8467
8502
  if (entryId) deletedEntryIds.push(entryId);
8468
8503
  }
8469
8504
  if (sourceRef || sourceHash) {
8470
- deletedEntryIds.push(...await this.entryRepo.findIdsBySource(entityId, sourceRef, sourceHash, tx, true));
8505
+ for (const id of await this.entryRepo.findIdsBySource(entityId, sourceRef, sourceHash, tx, true)) deletedEntryIds.push(id);
8471
8506
  }
8472
8507
  const entryPromise = params.entryId ? this.entryRepo.softDelete(params.entryId, entityId, tx).then((r) => r.changes > 0) : null;
8473
8508
  const taskDeletedPromise = params.taskId ? this.taskRepo.softDeleteById(params.taskId, entityId, tx).then((r) => r.changes > 0) : null;
@@ -8501,7 +8536,8 @@ var MaintenanceService = class {
8501
8536
  throw new Error(`forget(${entityId}/${factId}) failed: ANN cleanup hook rejected`, { cause: this._sanitizeRankerError(hookErr) });
8502
8537
  }
8503
8538
  }
8504
- return params.clearAll ? { deleted: { entries: deletedEntries, tasks: deletedTasks }, metadataReset: true } : { deleted: { entries: deletedEntries, tasks: deletedTasks } };
8539
+ if (!params.clearAll) return { deleted: { entries: deletedEntries, tasks: deletedTasks } };
8540
+ return params.includeEvents ? { deleted: { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents }, metadataReset: true } : { deleted: { entries: deletedEntries, tasks: deletedTasks }, metadataReset: true };
8505
8541
  } finally {
8506
8542
  this.jobManager.releaseLock("forget", entityId);
8507
8543
  }
@@ -8552,6 +8588,10 @@ var MaintenanceService = class {
8552
8588
  if (params.clearAll) {
8553
8589
  const entries2 = await this.entryRepo.countLiveByEntityId(entityId);
8554
8590
  const tasks = await this.taskRepo.countLiveByEntityId(entityId);
8591
+ if (params.includeEvents) {
8592
+ const events = await this.eventRepo.count(entityId);
8593
+ return { deleted: { entries: entries2, tasks, events }, metadataReset: true };
8594
+ }
8555
8595
  return { deleted: { entries: entries2, tasks }, metadataReset: true };
8556
8596
  }
8557
8597
  const sourceRef = params.sourceRef !== void 0 ? normalizeSourceRef(params.sourceRef) : null;
@@ -9461,22 +9501,68 @@ var MaintenanceScheduler = class {
9461
9501
  };
9462
9502
  }
9463
9503
  };
9464
- var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
9465
- var IMPORT_TITLE_MAX = 500;
9466
- var IMPORT_BODY_MAX = 8e3;
9504
+
9505
+ // src/services/importEventStamps.ts
9506
+ var DATE_MAX = 864e13;
9467
9507
  var DECIMAL_TEXT = /^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*$/;
9468
9508
  function createdAtValue(v) {
9469
9509
  if (typeof v === "number") return v;
9470
9510
  if (typeof v === "string" && DECIMAL_TEXT.test(v)) return Number(v);
9471
9511
  return NaN;
9472
9512
  }
9473
- function clampFutureCreatedAt(events, now, floor) {
9474
- const future = events.map((e) => ({ e, at: createdAtValue(e.created_at) })).filter((x) => x.at > now).sort((x, y) => (x.at === y.at ? 0 : x.at < y.at ? -1 : 1) || (x.e.id < y.e.id ? -1 : x.e.id > y.e.id ? 1 : 0));
9475
- if (future.length > 0 && floor + future.length > Number.MAX_SAFE_INTEGER) {
9476
- throw new RangeError(`importDump: cannot re-date ${future.length} future-dated event(s): the floor (${floor}) is too close to Number.MAX_SAFE_INTEGER to keep them ordered.`);
9477
- }
9478
- return new Map(future.map((x, i) => [x.e, floor + 1 + i]));
9513
+ function isUsableDate(v) {
9514
+ return Number.isFinite(v) && v >= -DATE_MAX && v <= DATE_MAX;
9515
+ }
9516
+ function parseSourceWatermark(raw) {
9517
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null;
9518
+ const { at, id } = raw;
9519
+ if (typeof at !== "number" || !Number.isFinite(at) || typeof id !== "string") return null;
9520
+ return { at, id };
9521
+ }
9522
+ var cmp = (a, b) => a === b ? 0 : a < b ? -1 : 1;
9523
+ function planEventStamps(events, ctx) {
9524
+ const { now, floor, merge, localWm, sourceWm } = ctx;
9525
+ const after = (v, id, wm) => v > wm.at || v === wm.at && id > wm.id;
9526
+ const plan = /* @__PURE__ */ new Map();
9527
+ const restamp = [];
9528
+ for (const e of events) {
9529
+ const v = createdAtValue(e.created_at);
9530
+ const o = createdAtValue(e.occurred_at);
9531
+ let occurredAt = null;
9532
+ let occurredInvalid = false;
9533
+ if (e.occurred_at != null) {
9534
+ if (isUsableDate(o)) occurredAt = Math.trunc(o);
9535
+ else occurredInvalid = true;
9536
+ }
9537
+ let reason = null;
9538
+ const invalidCreated = Number.isNaN(v) || v < -DATE_MAX;
9539
+ if (invalidCreated) reason = "invalid";
9540
+ else if (v > now) reason = "future";
9541
+ else if (merge && localWm !== null && Number.isFinite(localWm.at) && !after(v, e.id, localWm) && (sourceWm === null || after(v, e.id, sourceWm))) {
9542
+ reason = "behind_watermark";
9543
+ }
9544
+ if (reason === "behind_watermark" && occurredAt === null && Number.isFinite(v) && v >= 0) {
9545
+ occurredAt = Math.trunc(v);
9546
+ }
9547
+ const stamp = { createdAt: v, occurredAt, reason };
9548
+ if (reason === null && occurredInvalid) stamp.reason = "invalid";
9549
+ plan.set(e, stamp);
9550
+ if (reason !== null) restamp.push({ e, key: invalidCreated ? -Infinity : v, stamp });
9551
+ }
9552
+ restamp.sort((x, y) => cmp(x.key, y.key) || cmp(x.e.id, y.e.id));
9553
+ if (restamp.length > 0 && floor + restamp.length > Number.MAX_SAFE_INTEGER) {
9554
+ throw new RangeError(`importDump: cannot re-date ${restamp.length} event(s): the floor (${floor}) is too close to Number.MAX_SAFE_INTEGER to keep them ordered.`);
9555
+ }
9556
+ restamp.forEach((x, i) => {
9557
+ x.stamp.createdAt = floor + 1 + i;
9558
+ });
9559
+ return plan;
9479
9560
  }
9561
+
9562
+ // src/services/ImportExportService.ts
9563
+ var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
9564
+ var IMPORT_TITLE_MAX = 500;
9565
+ var IMPORT_BODY_MAX = 8e3;
9480
9566
  var ImportExportService = class {
9481
9567
  constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}) {
9482
9568
  this.db = db;
@@ -9529,6 +9615,7 @@ var ImportExportService = class {
9529
9615
  }
9530
9616
  }
9531
9617
  async getFullBundle(entityId, opts) {
9618
+ const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
9532
9619
  const [factsRaw, tasks, events, edges, summaryValue] = await Promise.all([
9533
9620
  opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId) : this.entryRepo.findAllByEntityId(entityId),
9534
9621
  this.taskRepo.findAllByEntityId(entityId),
@@ -9558,7 +9645,8 @@ var ImportExportService = class {
9558
9645
  tasks,
9559
9646
  events,
9560
9647
  edges,
9561
- ...summaryValue != null ? { summary: summaryValue } : {}
9648
+ ...summaryValue != null ? { summary: summaryValue } : {},
9649
+ ...wm ? { librarian_watermark: wm } : {}
9562
9650
  };
9563
9651
  }
9564
9652
  /** Single-entity import transaction + post-processing; package-internal hook for tests. */
@@ -9570,6 +9658,7 @@ var ImportExportService = class {
9570
9658
  const softDeletedFactIds = [];
9571
9659
  const clippedTextByFactId = /* @__PURE__ */ new Map();
9572
9660
  let clampedEvents = 0;
9661
+ const restamped = { behind_watermark: 0, invalid: 0 };
9573
9662
  await this.db.withTransactionAsync(async (tx) => {
9574
9663
  if (!merge) {
9575
9664
  const deletedLiveFactIds = await this.entryRepo.findIdsBySource(
@@ -9793,9 +9882,9 @@ var ImportExportService = class {
9793
9882
  const now = Date.now();
9794
9883
  const wm = bundle.events.length > 0 ? await seedLegacyWatermark(this.metadataRepo, this.eventRepo, entityId, tx) : await this.metadataRepo.getLibrarianWatermark(entityId, tx);
9795
9884
  const floor = wm && Number.isFinite(wm.at) && wm.at > now ? wm.at : now;
9796
- const clampedAt = clampFutureCreatedAt(bundle.events, now, floor);
9885
+ const planned = planEventStamps(bundle.events, { now, floor, merge, localWm: wm, sourceWm: parseSourceWatermark(bundle.librarian_watermark) });
9797
9886
  for (const event of bundle.events) {
9798
- const stamped = clampedAt.get(event);
9887
+ const stamp = planned.get(event);
9799
9888
  const inserted = await this.eventRepo.addIgnoreDuplicate(
9800
9889
  {
9801
9890
  id: event.id,
@@ -9803,12 +9892,14 @@ var ImportExportService = class {
9803
9892
  event_type: event.event_type,
9804
9893
  summary: event.summary,
9805
9894
  related_entry_id: event.related_entry_id ?? null,
9806
- created_at: stamped ?? event.created_at,
9807
- occurred_at: event.occurred_at ?? null
9895
+ created_at: stamp.createdAt,
9896
+ occurred_at: stamp.occurredAt
9808
9897
  },
9809
9898
  tx
9810
9899
  );
9811
- if (inserted && stamped !== void 0) clampedEvents++;
9900
+ if (!inserted || stamp.reason === null) continue;
9901
+ if (stamp.reason === "future") clampedEvents++;
9902
+ else restamped[stamp.reason]++;
9812
9903
  }
9813
9904
  for (const edge of bundle.edges ?? []) {
9814
9905
  await this.edgeRepo.addIgnoreDuplicate(
@@ -9833,6 +9924,17 @@ var ImportExportService = class {
9833
9924
  detail: { count: clampedEvents }
9834
9925
  });
9835
9926
  }
9927
+ for (const reason of ["behind_watermark", "invalid"]) {
9928
+ if (restamped[reason] > 0) {
9929
+ emitDiagnostic(this.options, {
9930
+ code: "event_created_at_restamped",
9931
+ operation: "importDump",
9932
+ trigger: "call",
9933
+ entityId,
9934
+ detail: { count: restamped[reason], reason }
9935
+ });
9936
+ }
9937
+ }
9836
9938
  if (merge) {
9837
9939
  await this.searchService.syncEntries(entityId, [...upsertedFactIds]);
9838
9940
  } else {
@@ -9849,7 +9951,19 @@ var ImportExportService = class {
9849
9951
  tags: Array.isArray(fact.tags) || typeof fact.tags === "string" ? fact.tags : []
9850
9952
  }, { operation: "importDump", trigger: "call" });
9851
9953
  if (!embedded) {
9852
- await this.embeddingService.notifyEmbeddingPersisted(entityId, fact.id, null);
9954
+ try {
9955
+ await this.embeddingService.notifyEmbeddingPersisted(entityId, fact.id, null);
9956
+ } catch (hookErr) {
9957
+ console.warn(
9958
+ `[WikiMemory] onEmbeddingPersisted hook failed for unembedded fact ${fact.id}:`,
9959
+ hookErr
9960
+ );
9961
+ this.embeddingService.reportHookFailed(
9962
+ { operation: "importDump", trigger: "call" },
9963
+ entityId,
9964
+ fact.id
9965
+ );
9966
+ }
9853
9967
  }
9854
9968
  }
9855
9969
  }
@@ -10609,7 +10723,7 @@ var RetrievalService = class {
10609
10723
  if (topK.length < maxBackfill) {
10610
10724
  let insertIdx = topK.length;
10611
10725
  for (let i = 0; i < topK.length; i++) {
10612
- const cmp = this._compareScoredRows(
10726
+ const cmp2 = this._compareScoredRows(
10613
10727
  {
10614
10728
  id: candidate.row.id,
10615
10729
  score: candidate.kwScore,
@@ -10623,7 +10737,7 @@ var RetrievalService = class {
10623
10737
  access_count: topK[i].row.access_count
10624
10738
  }
10625
10739
  );
10626
- if (cmp < 0) {
10740
+ if (cmp2 < 0) {
10627
10741
  insertIdx = i;
10628
10742
  break;
10629
10743
  }
@@ -10647,7 +10761,7 @@ var RetrievalService = class {
10647
10761
  if (cmpWorst < 0) {
10648
10762
  let insertIdx = maxBackfill - 1;
10649
10763
  for (let i = 0; i < topK.length; i++) {
10650
- const cmp = this._compareScoredRows(
10764
+ const cmp2 = this._compareScoredRows(
10651
10765
  {
10652
10766
  id: candidate.row.id,
10653
10767
  score: candidate.kwScore,
@@ -10661,7 +10775,7 @@ var RetrievalService = class {
10661
10775
  access_count: topK[i].row.access_count
10662
10776
  }
10663
10777
  );
10664
- if (cmp < 0) {
10778
+ if (cmp2 < 0) {
10665
10779
  insertIdx = i;
10666
10780
  break;
10667
10781
  }
@@ -11857,7 +11971,8 @@ var WikiMemory = class {
11857
11971
  this.jobManager,
11858
11972
  this.embeddingService,
11859
11973
  this.promptService,
11860
- this.ontologyService
11974
+ this.ontologyService,
11975
+ this.edgeRepo
11861
11976
  );
11862
11977
  this.maintenanceScheduler = new MaintenanceScheduler(
11863
11978
  this.db,
@@ -12370,6 +12485,16 @@ var WikiMemory = class {
12370
12485
  async importDump(dump, opts) {
12371
12486
  return this.importExportService.importDump(dump, opts);
12372
12487
  }
12488
+ /**
12489
+ * Soft-delete facts and tasks by id, by source, or all of them (`clearAll`).
12490
+ * `clearAll` also deletes the entity's edges and its source-ref index rows.
12491
+ * Add `includeEvents: true` to `clearAll` to hard-delete every event too,
12492
+ * read or not, and reset the librarian's position: without it a later
12493
+ * maintenance run can read the events into facts again. `runPrune()` then
12494
+ * hard-deletes the soft-deleted rows once they are older than
12495
+ * `retainSoftDeletedFor` (7 days by default; pass 0 to remove them now).
12496
+ * `dryRun` previews the counts.
12497
+ */
12373
12498
  async forget(entityId, params, opts) {
12374
12499
  return this.maintenanceService.forget(entityId, params, opts);
12375
12500
  }
@@ -13106,9 +13231,13 @@ function buildEventLogEntries(events, factIdToFilename) {
13106
13231
  const factFilename = e.related_entry_id ? factIdToFilename.get(e.related_entry_id) : void 0;
13107
13232
  const summary = e.summary.replace(/\\/g, "\\\\").replace(/\[/g, "\\[").replace(/\]/g, "\\]").replace(/\r?\n/g, " ");
13108
13233
  const text = factFilename ? `(${e.event_type}) [${summary}](./facts/${factFilename}.md)` : `(${e.event_type}) ${summary}`;
13109
- return { date: formatLogDate(e.created_at), text: coreOkf.appendEventIdComment(text, e.id) };
13234
+ const occurred = createdAtValue(e.occurred_at);
13235
+ const logTime = e.occurred_at != null && isUsableDate(occurred) && occurred >= OKF_DATE_MIN && occurred <= OKF_DATE_MAX && occurred <= e.created_at ? occurred : e.created_at;
13236
+ return { date: formatLogDate(logTime), text: coreOkf.appendEventIdComment(text, e.id) };
13110
13237
  });
13111
13238
  }
13239
+ var OKF_DATE_MIN = -621672192e5;
13240
+ var OKF_DATE_MAX = 253402300799999;
13112
13241
  function formatOkfBundle(dump, options) {
13113
13242
  const profile = options?.profile ?? DEFAULT_PROFILE;
13114
13243
  const okfVersion = profile === "llm-wiki/2" ? "0.2" : "0.1";
@@ -13292,6 +13421,24 @@ function parseStaleAfterRaw(raw) {
13292
13421
  }
13293
13422
  return ms;
13294
13423
  }
13424
+ function replaceLoneSurrogates(s) {
13425
+ let out = "";
13426
+ for (let i = 0; i < s.length; i++) {
13427
+ const c = s.charCodeAt(i);
13428
+ if (c >= 55296 && c <= 56319) {
13429
+ const n = i + 1 < s.length ? s.charCodeAt(i + 1) : 0;
13430
+ if (n >= 56320 && n <= 57343) {
13431
+ out += s[i] + s[i + 1];
13432
+ i++;
13433
+ } else out += "\uFFFD";
13434
+ } else if (c >= 56320 && c <= 57343) {
13435
+ out += "\uFFFD";
13436
+ } else {
13437
+ out += s[i];
13438
+ }
13439
+ }
13440
+ return out;
13441
+ }
13295
13442
  function unescapeLogSummary(summary) {
13296
13443
  return summary.replace(/\\\]/g, "]").replace(/\\\[/g, "[").replace(/\\\\/g, "\\");
13297
13444
  }
@@ -13304,7 +13451,7 @@ function parseLogEntryText(text) {
13304
13451
  if (linkPath) {
13305
13452
  return { event_type, summary: unescapeLogSummary(linkedSummary), linkPath };
13306
13453
  }
13307
- return { event_type, summary: (plainSummary ?? "").trim() };
13454
+ return { event_type, summary: unescapeLogSummary((plainSummary ?? "").trim()) };
13308
13455
  }
13309
13456
  function frontmatterToFact(entityId, id, frontmatter, body, now) {
13310
13457
  const created_at = parseFrontmatterTimestamp(frontmatter.created_at, now);
@@ -13516,6 +13663,7 @@ function parseOkfBundle(entityId, files, options) {
13516
13663
  }
13517
13664
  const events = [];
13518
13665
  if (logContent != null) {
13666
+ const pending = [];
13519
13667
  const logPath = logMdPath ?? `entities/${entityId}/log.md`;
13520
13668
  for (const entry of coreOkf.parseLogMd(logContent)) {
13521
13669
  const { text, eventId } = coreOkf.parseEventIdComment(entry.text);
@@ -13533,8 +13681,9 @@ function parseOkfBundle(entityId, files, options) {
13533
13681
  }
13534
13682
  const created_at = (/* @__PURE__ */ new Date(`${entry.date}T00:00:00.000Z`)).getTime();
13535
13683
  if (!Number.isFinite(created_at)) continue;
13684
+ if (eventId === void 0) pending.push({ index: events.length, date: entry.date });
13536
13685
  events.push({
13537
- id: eventId ?? generateId("evt_"),
13686
+ id: eventId ?? "",
13538
13687
  entity_id: entityId,
13539
13688
  event_type: parsed.event_type,
13540
13689
  summary: parsed.summary,
@@ -13542,6 +13691,22 @@ function parseOkfBundle(entityId, files, options) {
13542
13691
  created_at
13543
13692
  });
13544
13693
  }
13694
+ const taken = new Set(events.map((e) => e.id).filter((id) => id !== ""));
13695
+ const nextOccurrence = /* @__PURE__ */ new Map();
13696
+ for (const { index, date } of pending) {
13697
+ const e = events[index];
13698
+ const key = JSON.stringify([date, e.event_type, replaceLoneSurrogates(e.summary)]);
13699
+ let occurrence = nextOccurrence.get(key) ?? 0;
13700
+ const derive = coreOkf.createEventIdDeriver({ entityId, date, eventType: e.event_type, summary: e.summary });
13701
+ let id = derive(occurrence);
13702
+ while (taken.has(id)) {
13703
+ occurrence += 1;
13704
+ id = derive(occurrence);
13705
+ }
13706
+ taken.add(id);
13707
+ nextOccurrence.set(key, occurrence + 1);
13708
+ e.id = id;
13709
+ }
13545
13710
  }
13546
13711
  return {
13547
13712
  generatedAt: now,