@equationalapplications/core-llm-wiki 9.15.0 → 9.16.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/testing.js CHANGED
@@ -753,11 +753,14 @@ var SEVERITY = {
753
753
  event_created_at_clamped: "warn",
754
754
  event_created_at_restamped: "info",
755
755
  external_deletion_pending: "warn",
756
+ supersede_scheduled_end_replaced: "info",
756
757
  external_deletion_discarded: "warn",
757
758
  guidance_too_long: "warn",
758
759
  guidance_resolver_failed: "warn",
759
760
  source_pointer_unresolved: "warn",
760
761
  source_pointer_invalid: "warn",
762
+ source_event_gone: "warn",
763
+ derived_events_invalid: "warn",
761
764
  source_store_source_too_large: "warn",
762
765
  source_store_budget_exceeded: "warn",
763
766
  source_store_hash_mismatch: "warn",
@@ -809,12 +812,15 @@ var MESSAGE = {
809
812
  import_tombstone_skipped: "Import skipped live dump rows (facts and tasks) whose ids were forgotten locally. The protection holds while the tombstone is retained; once a prune hard-deletes the row, an old dump can import the fact again \u2014 see the OKF guide\u2019s restore caveat.",
810
813
  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.",
811
814
  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.",
815
+ supersede_scheduled_end_replaced: "A supersede replaced a scheduled end date on the old fact; the prior end is kept in prior_valid_to and reopen() can restore it.",
812
816
  external_deletion_pending: "Removals owed to the external vector index are still pending.",
813
817
  external_deletion_discarded: "Pending external vector removals were discarded because forceDeleteIgnoreRankerHook is set.",
814
818
  guidance_too_long: "The configured guidance exceeded the length cap and was not sent for this pass.",
815
819
  guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass.",
816
- source_pointer_unresolved: "A stored librarian fact carries no source pointer because the model answer could not yield one.",
820
+ 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).",
817
821
  source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer.",
822
+ 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).",
823
+ derived_events_invalid: "Import met a malformed derived_events value and stored null.",
818
824
  source_store_source_too_large: "A source document exceeded the per-document size cap and was not stored.",
819
825
  source_store_budget_exceeded: "Storing a source document would exceed the store UTF-16 code-unit budget and it was not stored.",
820
826
  source_store_hash_mismatch: "A source document text did not match its recorded hash and was not stored.",
@@ -1684,6 +1690,27 @@ function validateSourcePointerValue(v) {
1684
1690
  return normalized;
1685
1691
  }
1686
1692
 
1693
+ // src/utils/derivedEvents.ts
1694
+ function validateDerivedEventsValue(v) {
1695
+ if (v === null) return null;
1696
+ if (!Array.isArray(v)) return void 0;
1697
+ for (const x of v) {
1698
+ if (typeof x !== "string" || x.length === 0) return void 0;
1699
+ }
1700
+ const out = dedupeEventIds(v);
1701
+ return out.length === 0 ? null : out;
1702
+ }
1703
+ function dedupeEventIds(ids) {
1704
+ const seen = /* @__PURE__ */ new Set();
1705
+ const out = [];
1706
+ for (const id of ids) {
1707
+ if (typeof id !== "string" || id.length === 0 || seen.has(id)) continue;
1708
+ seen.add(id);
1709
+ out.push(id);
1710
+ }
1711
+ return out;
1712
+ }
1713
+
1687
1714
  // src/services/legacyWatermark.ts
1688
1715
  async function anchorAtLegacyBoundary(metadataRepo, eventRepo, entityId, checkpoint, total, db) {
1689
1716
  if (checkpoint <= 0 || total <= 0) return null;
@@ -2090,6 +2117,19 @@ var ImportExportService = class {
2090
2117
  });
2091
2118
  }
2092
2119
  const sourcePointer = pointerValidated === void 0 ? null : pointerValidated;
2120
+ const rawDerived = fact["derived_events"];
2121
+ const hasDerivedEventsKey = rawDerived !== void 0;
2122
+ const derivedValidated = hasDerivedEventsKey ? validateDerivedEventsValue(rawDerived) : null;
2123
+ if (derivedValidated === void 0) {
2124
+ refusalDiagnostics.push({
2125
+ code: "derived_events_invalid",
2126
+ operation: "importDump",
2127
+ trigger: "call",
2128
+ entityId,
2129
+ detail: { factId: fact.id }
2130
+ });
2131
+ }
2132
+ const derivedEvents = derivedValidated ?? null;
2093
2133
  const factObj = {
2094
2134
  id: fact.id,
2095
2135
  entity_id: entityId,
@@ -2108,6 +2148,7 @@ var ImportExportService = class {
2108
2148
  embedding_blob: blobData ?? void 0,
2109
2149
  okf_type: fact.okf_type ?? null,
2110
2150
  source_pointer: sourcePointer,
2151
+ ...derivedEvents ? { derived_events: derivedEvents } : {},
2111
2152
  // OKF v0.2 — forwarded as-is; parseOkfBundle / the caller is responsible for
2112
2153
  // populating these per spec, importDump does not derive or validate them.
2113
2154
  lifecycle_status: fact.lifecycle_status ?? "stable",
@@ -2125,12 +2166,15 @@ var ImportExportService = class {
2125
2166
  return { last_verified_at: latest?.at ?? null, last_verified_by: latest?.by ?? null };
2126
2167
  })()
2127
2168
  };
2128
- await this.entryRepo.upsertForImport(factObj, tx, hasSourcePointerKey);
2169
+ await this.entryRepo.upsertForImport(factObj, tx, hasSourcePointerKey, hasDerivedEventsKey);
2129
2170
  await this.entryRepo.setTemporal(fact.id, entityId, {
2130
2171
  valid_from: fact.valid_from ?? null,
2131
2172
  valid_to: fact.valid_to ?? null,
2132
2173
  superseded_by: fact.superseded_by ?? null,
2133
- superseded_at: fact.superseded_at ?? null
2174
+ superseded_at: fact.superseded_at ?? null,
2175
+ // prior_valid_to (spec D5): replace semantics like the four siblings;
2176
+ // null whenever the row is not superseded (the column's invariant).
2177
+ prior_valid_to: fact.superseded_by == null ? null : fact.prior_valid_to ?? null
2134
2178
  }, tx, { outbox: false });
2135
2179
  if (blobData != null) {
2136
2180
  factsWithPreservedBlob.set(fact.id, blobData);
@@ -4029,10 +4073,17 @@ var TemporalService = class {
4029
4073
  if (predecessors.some((r) => r.id === newId)) throw new WikiSupersedeError("cycle");
4030
4074
  const start = old.valid_from ?? old.created_at;
4031
4075
  if (t <= start) throw new WikiSupersedeError("invalid_interval");
4032
- await this.entryRepo.setTemporal(oldId, entityId, { valid_to: t, superseded_by: newId, superseded_at: now }, tx);
4076
+ const replacedScheduledEnd = old.valid_to;
4077
+ await this.entryRepo.setTemporal(oldId, entityId, {
4078
+ valid_to: t,
4079
+ superseded_by: newId,
4080
+ superseded_at: now,
4081
+ prior_valid_to: replacedScheduledEnd
4082
+ }, tx);
4033
4083
  if (repl.valid_from == null) {
4034
4084
  await this.entryRepo.setTemporal(newId, entityId, { valid_from: t }, tx);
4035
4085
  }
4086
+ return { replacedScheduledEnd };
4036
4087
  }
4037
4088
  async supersede(entityId, oldId, replacement, options) {
4038
4089
  const now = Date.now();
@@ -4061,6 +4112,7 @@ var TemporalService = class {
4061
4112
  }
4062
4113
  const newId = typeof replacement === "string" ? replacement : created.id;
4063
4114
  const newValidFrom = typeof replacement !== "string" && replacement.valid_from !== void 0 ? assertEpochMs("replacement.valid_from", replacement.valid_from) : void 0;
4115
+ let replacedScheduledEnd = null;
4064
4116
  await this.db.withTransactionAsync(async (tx) => {
4065
4117
  if (created) {
4066
4118
  await this.entryRepo.upsert(created, tx);
@@ -4068,8 +4120,17 @@ var TemporalService = class {
4068
4120
  await this.entryRepo.setTemporal(created.id, entityId, { valid_from: newValidFrom }, tx);
4069
4121
  }
4070
4122
  }
4071
- await this.supersedeInTx(tx, entityId, oldId, newId, t, now);
4123
+ ({ replacedScheduledEnd } = await this.supersedeInTx(tx, entityId, oldId, newId, t, now));
4072
4124
  });
4125
+ if (replacedScheduledEnd != null) {
4126
+ emitDiagnostic(this.options, {
4127
+ code: "supersede_scheduled_end_replaced",
4128
+ operation: "supersede",
4129
+ trigger: "call",
4130
+ entityId,
4131
+ detail: { factId: oldId, priorValidTo: replacedScheduledEnd }
4132
+ });
4133
+ }
4073
4134
  await this.searchService.syncEntries(entityId, [oldId, newId]);
4074
4135
  if (created) {
4075
4136
  await this.embeddingService.embedFact(
@@ -4101,6 +4162,35 @@ var TemporalService = class {
4101
4162
  await this.searchService.syncEntries(entityId, [factId]);
4102
4163
  this.searchService.evictCache(entityId);
4103
4164
  }
4165
+ /**
4166
+ * Return a superseded fact to live once its replacement is forgotten or gone
4167
+ * (INTENT rule 12, specs/supersede-future-valid-to D4). Restores `valid_to`
4168
+ * to `prior_valid_to` (null when none was recorded).
4169
+ */
4170
+ async reopen(entityId, factId) {
4171
+ let restored = null;
4172
+ await this.db.withTransactionAsync(async (tx) => {
4173
+ const row = await this.entryRepo.findTemporalRow(factId, tx);
4174
+ if (!row || row.deleted_at != null) throw new WikiSupersedeError("not_found", "reopen()");
4175
+ if (row.entity_id !== entityId) throw new WikiSupersedeError("cross_entity", "reopen()");
4176
+ if (row.superseded_by == null) throw new WikiSupersedeError("not_superseded", "reopen()");
4177
+ if (row.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target", "reopen()");
4178
+ const successor = await this.entryRepo.findTemporalRow(row.superseded_by, tx);
4179
+ if (successor && successor.deleted_at == null) throw new WikiSupersedeError("successor_live", "reopen()");
4180
+ const p = row.prior_valid_to;
4181
+ restored = p != null && Number.isInteger(p) && p > (row.valid_from ?? row.created_at) ? p : null;
4182
+ const changes = await this.entryRepo.setTemporal(factId, entityId, {
4183
+ valid_to: restored,
4184
+ superseded_by: null,
4185
+ superseded_at: null,
4186
+ prior_valid_to: null
4187
+ }, tx);
4188
+ if (changes === 0) throw new WikiSupersedeError("cross_entity", "reopen()");
4189
+ });
4190
+ await this.searchService.syncEntries(entityId, [factId]);
4191
+ this.searchService.evictCache(entityId);
4192
+ return { valid_to: restored };
4193
+ }
4104
4194
  async history(entityId, factId) {
4105
4195
  const start = await this.entryRepo.findTemporalRow(factId);
4106
4196
  if (!start || start.entity_id !== entityId || start.deleted_at != null) return [];
@@ -5059,8 +5149,34 @@ var MIGRATIONS = [
5059
5149
  );`
5060
5150
  );
5061
5151
  }
5152
+ },
5153
+ {
5154
+ version: 18,
5155
+ description: "Partial index on entries(entity_id, deleted_at) for prune and tombstone probes; nullable prior_valid_to column recording the scheduled end a supersede overwrote; nullable derived_events column listing the events an in-place librarian merge drew on",
5156
+ run: async (db, prefix) => {
5157
+ await createEntriesDeletedIndex(db, prefix);
5158
+ await addPriorValidToColumn(db, prefix);
5159
+ await addDerivedEventsColumn(db, prefix);
5160
+ }
5062
5161
  }
5063
5162
  ];
5163
+ async function addPriorValidToColumn(db, prefix) {
5164
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
5165
+ if (!cols.some((c) => c.name === "prior_valid_to")) {
5166
+ await db.execAsync(`ALTER TABLE ${prefix}entries ADD COLUMN prior_valid_to INTEGER`);
5167
+ }
5168
+ }
5169
+ async function createEntriesDeletedIndex(db, prefix) {
5170
+ await db.execAsync(
5171
+ `CREATE INDEX IF NOT EXISTS ${prefix}entries_deleted_idx ON ${prefix}entries(entity_id, deleted_at) WHERE deleted_at IS NOT NULL`
5172
+ );
5173
+ }
5174
+ async function addDerivedEventsColumn(db, prefix) {
5175
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
5176
+ if (!cols.some((c) => c.name === "derived_events")) {
5177
+ await db.execAsync(`ALTER TABLE ${prefix}entries ADD COLUMN derived_events TEXT`);
5178
+ }
5179
+ }
5064
5180
  async function createLegacySourceTypeIndex(db, prefix) {
5065
5181
  await db.execAsync(
5066
5182
  `CREATE INDEX IF NOT EXISTS ${prefix}entries_legacy_source_type_idx ON ${prefix}entries(source_type) WHERE source_type IN ('user_document', 'agent_inferred')`
@@ -5976,6 +6092,17 @@ function buildSourcePointer(candidate, verdict, groundingOn, groundingCorpus) {
5976
6092
  }
5977
6093
  return { event_id: candidate.sourceEventId, ref: null, quote, position: null };
5978
6094
  }
6095
+ function mergeDerivedEvents(existing, contributing) {
6096
+ if (contributing === null || contributing === existing.source_pointer?.event_id) return void 0;
6097
+ const prior = existing.derived_events ?? [];
6098
+ if (prior.includes(contributing)) return void 0;
6099
+ return dedupeEventIds([...prior, contributing]);
6100
+ }
6101
+ function inheritedDerivedEvents(target, ownEventId) {
6102
+ if (!target) return {};
6103
+ const list = dedupeEventIds([target.source_pointer?.event_id, ...target.derived_events ?? []]).filter((id) => id !== ownEventId);
6104
+ return list.length > 0 ? { derived_events: list } : {};
6105
+ }
5979
6106
  async function applyOps(deps, ctx, input) {
5980
6107
  const { entityId, trigger } = ctx;
5981
6108
  const diagBase = { entityId, operation: "librarian", trigger };
@@ -6006,7 +6133,7 @@ async function applyOps(deps, ctx, input) {
6006
6133
  titleIndex.set(normalizeTitleKey(f.title), { id: f.id, okf_type: f.okf_type ?? null });
6007
6134
  }
6008
6135
  const pendingEdges = [];
6009
- const insert = async (g, draft, validFrom, overrides) => {
6136
+ const insert = async (g, draft, validFrom, overrides, inheritFrom) => {
6010
6137
  const fact = g.candidate.fact;
6011
6138
  const title = overrides?.title ?? fact.title;
6012
6139
  const body = overrides?.body ?? fact.body;
@@ -6050,6 +6177,9 @@ async function applyOps(deps, ctx, input) {
6050
6177
  deleted_at: null,
6051
6178
  okf_type: normalized.okf_type,
6052
6179
  source_pointer: pointer,
6180
+ // §2: only an UPDATE converted to SUPERSEDE inherits (the merged text
6181
+ // rests on the target); ADD and plain SUPERSEDE carry no list.
6182
+ ...inheritedDerivedEvents(inheritFrom, pointer?.event_id ?? null),
6053
6183
  ...g2?.trust,
6054
6184
  ...draft ? { lifecycle_status: "draft" } : {}
6055
6185
  };
@@ -6068,7 +6198,18 @@ async function applyOps(deps, ctx, input) {
6068
6198
  written.push({ id, vector: textChanged ? null : g.vector, fact: { id, entity_id: entityId, title, body, tags: fact.tags } });
6069
6199
  return id;
6070
6200
  };
6201
+ const sourceIds = [...new Set(input.gated.map((g) => g.candidate.sourceEventId).filter((x) => x !== null))];
6202
+ const presentIds = sourceIds.length > 0 ? await deps.eventRepo.findExistingIds(entityId, sourceIds, tx) : /* @__PURE__ */ new Set();
6203
+ const gatedLive = [];
6071
6204
  for (const g of input.gated) {
6205
+ const ev = g.candidate.sourceEventId;
6206
+ if (ev !== null && !presentIds.has(ev)) {
6207
+ input.diagnostics.push({ ...diagBase, code: "source_event_gone", detail: { itemIndex: g.candidate.index, sourceRef: ev } });
6208
+ continue;
6209
+ }
6210
+ gatedLive.push(g);
6211
+ }
6212
+ for (const g of gatedLive) {
6072
6213
  const idx = g.candidate.index;
6073
6214
  const vf = g.candidate.validFrom;
6074
6215
  if (g.decision.kind === "noop") continue;
@@ -6097,11 +6238,21 @@ async function applyOps(deps, ctx, input) {
6097
6238
  const [existing] = await deps.entryRepo.findByIds([op.targetId], [entityId], tx);
6098
6239
  if (existing) {
6099
6240
  const newTitle = op.title ?? g.candidate.fact.title;
6241
+ const contributing = g.candidate.sourceEventId;
6242
+ if (contributing === null && g.candidate.pointerUnresolved !== null) {
6243
+ input.diagnostics.push({
6244
+ ...diagBase,
6245
+ code: "source_pointer_unresolved",
6246
+ detail: { factId: existing.id, itemIndex: idx, reason: g.candidate.pointerUnresolved }
6247
+ });
6248
+ }
6249
+ const derived = mergeDerivedEvents(existing, contributing);
6100
6250
  await deps.entryRepo.upsert({
6101
6251
  ...existing,
6102
6252
  title: newTitle,
6103
6253
  body: op.body ?? g.candidate.fact.body,
6104
- updated_at: now
6254
+ updated_at: now,
6255
+ ...derived ? { derived_events: derived } : {}
6105
6256
  }, tx);
6106
6257
  titleIndex.delete(normalizeTitleKey(existing.title));
6107
6258
  titleIndex.set(normalizeTitleKey(newTitle), { id: existing.id, okf_type: existing.okf_type ?? null });
@@ -6113,15 +6264,24 @@ async function applyOps(deps, ctx, input) {
6113
6264
  const supersedeFrom = op.op === "SUPERSEDE" && op.validFrom !== void 0 ? op.validFrom : vf;
6114
6265
  const overrides = op.op === "UPDATE" ? { title: op.title, body: op.body } : void 0;
6115
6266
  if (target.source_type === "immutable_document") {
6116
- const id = await insert(g, true, supersedeFrom, overrides);
6267
+ const docTarget = op.op === "UPDATE" ? (await deps.entryRepo.findByIds([op.targetId], [entityId], tx))[0] : void 0;
6268
+ const id = await insert(g, true, supersedeFrom, overrides, docTarget);
6117
6269
  input.diagnostics.push({ ...diagBase, code: "contradicts_document", detail: { factId: id, itemIndex: idx } });
6118
6270
  continue;
6119
6271
  }
6120
- const newId = await insert(g, false, supersedeFrom, overrides);
6272
+ const inheritFrom = op.op === "UPDATE" ? (await deps.entryRepo.findByIds([op.targetId], [entityId], tx))[0] : void 0;
6273
+ const newId = await insert(g, false, supersedeFrom, overrides, inheritFrom);
6121
6274
  try {
6122
- await temporal.supersedeInTx(tx, entityId, op.targetId, newId, supersedeFrom, now);
6275
+ const { replacedScheduledEnd } = await temporal.supersedeInTx(tx, entityId, op.targetId, newId, supersedeFrom, now);
6123
6276
  supersededIds.push(op.targetId);
6124
6277
  input.diagnostics.push({ ...diagBase, code: "librarian_superseded", detail: { factId: op.targetId, replacementId: newId } });
6278
+ if (replacedScheduledEnd != null) {
6279
+ input.diagnostics.push({
6280
+ ...diagBase,
6281
+ code: "supersede_scheduled_end_replaced",
6282
+ detail: { factId: op.targetId, priorValidTo: replacedScheduledEnd }
6283
+ });
6284
+ }
6125
6285
  } catch (err) {
6126
6286
  if (!(err instanceof WikiSupersedeError)) throw err;
6127
6287
  input.diagnostics.push({