@equationalapplications/core-llm-wiki 9.20.2 → 9.21.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
@@ -763,6 +763,8 @@ var SEVERITY = {
763
763
  source_pointer_invalid: "warn",
764
764
  source_event_gone: "warn",
765
765
  derived_events_invalid: "warn",
766
+ okf_extra_invalid: "warn",
767
+ okf_bundle_metadata_invalid: "warn",
766
768
  source_store_source_too_large: "warn",
767
769
  source_store_budget_exceeded: "warn",
768
770
  source_store_hash_mismatch: "warn",
@@ -825,6 +827,8 @@ var MESSAGE = {
825
827
  source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer.",
826
828
  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.",
827
829
  derived_events_invalid: "Import met a malformed derived_events value and stored null.",
830
+ okf_extra_invalid: "Import met a malformed or oversized okf_extra value and stored null, or dropped a raw-block entry no parse could have produced.",
831
+ okf_bundle_metadata_invalid: "Import met a malformed or oversized bundle metadata record and treated it as absent, or dropped a raw-block entry no parse could have produced.",
828
832
  source_store_source_too_large: "A source document exceeded the per-document size cap and was not stored.",
829
833
  source_store_budget_exceeded: "Storing a source document would exceed the store UTF-16 code-unit budget and it was not stored.",
830
834
  source_store_hash_mismatch: "A source document text did not match its recorded hash and was not stored.",
@@ -1380,6 +1384,9 @@ function typeSatisfies(declaredType, concreteType, manifest) {
1380
1384
  function entitySummaryMetaKey(entityId) {
1381
1385
  return `entity_summary:${entityId}`;
1382
1386
  }
1387
+ function bundleMetadataMetaKey(entityId) {
1388
+ return `okf_bundle_metadata:${entityId}`;
1389
+ }
1383
1390
  var START_OF_LOG_WATERMARK = Object.freeze({ at: Number.MIN_SAFE_INTEGER, id: "" });
1384
1391
  var CheckpointIncompleteError = class extends Error {
1385
1392
  constructor() {
@@ -1387,6 +1394,65 @@ var CheckpointIncompleteError = class extends Error {
1387
1394
  this.code = "erase_checkpoint_incomplete";
1388
1395
  }
1389
1396
  };
1397
+
1398
+ // src/utils/sourcePointer.ts
1399
+ var POINTER_SLOTS = ["event_id", "ref", "quote", "position"];
1400
+ function isStringOrNull(v) {
1401
+ return v === null || typeof v === "string";
1402
+ }
1403
+ function isValidPosition(v) {
1404
+ if (v === null) return true;
1405
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return false;
1406
+ const o = v;
1407
+ const keys = Object.keys(o);
1408
+ if (keys.length !== 2 || !("start" in o) || !("length" in o)) return false;
1409
+ const { start, length } = o;
1410
+ return typeof start === "number" && Number.isInteger(start) && start >= 0 && typeof length === "number" && Number.isInteger(length) && length >= 0;
1411
+ }
1412
+ function validateSourcePointerValue(v) {
1413
+ if (v === null) return null;
1414
+ if (typeof v !== "object" || Array.isArray(v)) return void 0;
1415
+ const o = v;
1416
+ const keys = Object.keys(o);
1417
+ for (const k of keys) {
1418
+ if (!POINTER_SLOTS.includes(k)) return void 0;
1419
+ }
1420
+ if (!isStringOrNull(o["event_id"] === void 0 ? null : o["event_id"]) || !isStringOrNull(o["ref"] === void 0 ? null : o["ref"]) || !isStringOrNull(o["quote"] === void 0 ? null : o["quote"])) {
1421
+ return void 0;
1422
+ }
1423
+ if (!isValidPosition(o["position"] === void 0 ? null : o["position"])) return void 0;
1424
+ const normalized = {
1425
+ event_id: o["event_id"] ?? null,
1426
+ ref: o["ref"] ?? null,
1427
+ quote: o["quote"] ?? null,
1428
+ position: o["position"] ?? null
1429
+ };
1430
+ if (normalized.event_id === null && normalized.ref === null && normalized.quote === null && normalized.position === null) {
1431
+ return null;
1432
+ }
1433
+ return normalized;
1434
+ }
1435
+
1436
+ // src/utils/derivedEvents.ts
1437
+ function validateDerivedEventsValue(v) {
1438
+ if (v === null) return null;
1439
+ if (!Array.isArray(v)) return void 0;
1440
+ for (const x of v) {
1441
+ if (typeof x !== "string" || x.length === 0) return void 0;
1442
+ }
1443
+ const out = dedupeEventIds(v);
1444
+ return out.length === 0 ? null : out;
1445
+ }
1446
+ function dedupeEventIds(ids) {
1447
+ const seen = /* @__PURE__ */ new Set();
1448
+ const out = [];
1449
+ for (const id of ids) {
1450
+ if (typeof id !== "string" || id.length === 0 || seen.has(id)) continue;
1451
+ seen.add(id);
1452
+ out.push(id);
1453
+ }
1454
+ return out;
1455
+ }
1390
1456
  function generateId(prefix = "") {
1391
1457
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
1392
1458
  return prefix + crypto.randomUUID().replace(/-/g, "").substring(0, 24);
@@ -1401,6 +1467,60 @@ function generateId(prefix = "") {
1401
1467
  );
1402
1468
  }
1403
1469
 
1470
+ // src/utils/parseOkfBundle.ts
1471
+ var FACT_MAPPED_KEYS = [
1472
+ "type",
1473
+ "title",
1474
+ "tags",
1475
+ "timestamp",
1476
+ "resource",
1477
+ "id",
1478
+ "entity_id",
1479
+ "confidence",
1480
+ "source_type",
1481
+ "source_hash",
1482
+ "created_at",
1483
+ "updated_at",
1484
+ "access_count",
1485
+ "last_accessed_at",
1486
+ "deleted_at",
1487
+ "status",
1488
+ "stale_after",
1489
+ "generated",
1490
+ "verified",
1491
+ "sources",
1492
+ "usage_window",
1493
+ "valid_from",
1494
+ "valid_to",
1495
+ "superseded_by",
1496
+ "superseded_at",
1497
+ "prior_valid_to",
1498
+ "source_pointer",
1499
+ "derived_events",
1500
+ "x-llm-wiki-lifecycle"
1501
+ ];
1502
+ var TASK_MAPPED_KEYS = [
1503
+ "type",
1504
+ "title",
1505
+ "timestamp",
1506
+ "id",
1507
+ "entity_id",
1508
+ "status",
1509
+ "execution_status",
1510
+ "priority",
1511
+ "created_at",
1512
+ "updated_at",
1513
+ "resolved_at",
1514
+ "deleted_at",
1515
+ "stale_after",
1516
+ "generated",
1517
+ "verified",
1518
+ "sources",
1519
+ "usage_window"
1520
+ ];
1521
+ new Set(FACT_MAPPED_KEYS);
1522
+ new Set(TASK_MAPPED_KEYS);
1523
+
1404
1524
  // src/utils/passageCutter.ts
1405
1525
  var MAX_PASSAGE_UNITS = 12e3;
1406
1526
  var WHITESPACE = /\s/;
@@ -1655,64 +1775,46 @@ async function upsertStoredSource(tx, prefix, entityId, src, limits, onRefusal,
1655
1775
  // src/services/SourceStoreService.ts
1656
1776
  var DEFAULT_MAX_CHARS_PER_SOURCE = 2e5;
1657
1777
  var DEFAULT_MAX_TOTAL_CHARS = 5e6;
1658
-
1659
- // src/utils/sourcePointer.ts
1660
- var POINTER_SLOTS = ["event_id", "ref", "quote", "position"];
1661
- function isStringOrNull(v) {
1662
- return v === null || typeof v === "string";
1663
- }
1664
- function isValidPosition(v) {
1665
- if (v === null) return true;
1666
- if (typeof v !== "object" || v === null || Array.isArray(v)) return false;
1667
- const o = v;
1668
- const keys = Object.keys(o);
1669
- if (keys.length !== 2 || !("start" in o) || !("length" in o)) return false;
1670
- const { start, length } = o;
1671
- return typeof start === "number" && Number.isInteger(start) && start >= 0 && typeof length === "number" && Number.isInteger(length) && length >= 0;
1672
- }
1673
- function validateSourcePointerValue(v) {
1674
- if (v === null) return null;
1675
- if (typeof v !== "object" || Array.isArray(v)) return void 0;
1676
- const o = v;
1677
- const keys = Object.keys(o);
1678
- for (const k of keys) {
1679
- if (!POINTER_SLOTS.includes(k)) return void 0;
1680
- }
1681
- if (!isStringOrNull(o["event_id"] === void 0 ? null : o["event_id"]) || !isStringOrNull(o["ref"] === void 0 ? null : o["ref"]) || !isStringOrNull(o["quote"] === void 0 ? null : o["quote"])) {
1682
- return void 0;
1778
+ var OKF_RAW_SLOT = "x-llm-wiki-raw";
1779
+ function matchRawBlockKeyText(line) {
1780
+ const keyMatch = /^(?:"(?:\\.|[^"\\])*"|'(?:''|[^'])*'|[^:]+)/.exec(line);
1781
+ if (!keyMatch || keyMatch[0].length === 0 || line[keyMatch[0].length] !== ":") return null;
1782
+ return keyMatch[0];
1783
+ }
1784
+ function probeParseKey(keyText) {
1785
+ const parsed = coreOkf.parseFrontmatter(`---
1786
+ ${keyText}: __probe__
1787
+ ---`);
1788
+ const keys = Object.keys(parsed.frontmatter);
1789
+ if (keys[0] !== "type") return keys[0] ?? null;
1790
+ return parsed.frontmatter["type"] === "__probe__" ? "type" : null;
1791
+ }
1792
+ function isValidRawBlockEntry(key, lines, mappedKeys) {
1793
+ if (mappedKeys.has(key) || key === OKF_RAW_SLOT) return false;
1794
+ if (lines.includes("\r")) return false;
1795
+ const allLines = lines.split(/\r?\n/);
1796
+ const first = allLines[0] ?? "";
1797
+ const keyText = matchRawBlockKeyText(first);
1798
+ if (keyText === null || probeParseKey(keyText) !== key) return false;
1799
+ const afterColon = first.slice(keyText.length + 1);
1800
+ const trimmedAfter = afterColon.trim();
1801
+ const blockOpening = trimmedAfter === "" || /^[ \t]/.test(afterColon) && trimmedAfter.startsWith("#");
1802
+ for (const line of allLines.slice(1)) {
1803
+ const trimmed = line.trim();
1804
+ if (trimmed === "---") return false;
1805
+ if (/^[ \t]*#/.test(line)) continue;
1806
+ if (line.trim() === "" || /^[ \t]/.test(line)) continue;
1807
+ if (blockOpening && /^-\s/.test(line)) continue;
1808
+ return false;
1683
1809
  }
1684
- if (!isValidPosition(o["position"] === void 0 ? null : o["position"])) return void 0;
1685
- const normalized = {
1686
- event_id: o["event_id"] ?? null,
1687
- ref: o["ref"] ?? null,
1688
- quote: o["quote"] ?? null,
1689
- position: o["position"] ?? null
1690
- };
1691
- if (normalized.event_id === null && normalized.ref === null && normalized.quote === null && normalized.position === null) {
1692
- return null;
1810
+ try {
1811
+ const { issues } = coreOkf.parseFrontmatter(`---
1812
+ ${lines}
1813
+ ---`);
1814
+ return !issues.some((issue) => issue.reason === "anchor_or_alias");
1815
+ } catch {
1816
+ return false;
1693
1817
  }
1694
- return normalized;
1695
- }
1696
-
1697
- // src/utils/derivedEvents.ts
1698
- function validateDerivedEventsValue(v) {
1699
- if (v === null) return null;
1700
- if (!Array.isArray(v)) return void 0;
1701
- for (const x of v) {
1702
- if (typeof x !== "string" || x.length === 0) return void 0;
1703
- }
1704
- const out = dedupeEventIds(v);
1705
- return out.length === 0 ? null : out;
1706
- }
1707
- function dedupeEventIds(ids) {
1708
- const seen = /* @__PURE__ */ new Set();
1709
- const out = [];
1710
- for (const id of ids) {
1711
- if (typeof id !== "string" || id.length === 0 || seen.has(id)) continue;
1712
- seen.add(id);
1713
- out.push(id);
1714
- }
1715
- return out;
1716
1818
  }
1717
1819
 
1718
1820
  // src/services/legacyWatermark.ts
@@ -1798,6 +1900,224 @@ function planEventStamps(events, ctx) {
1798
1900
  var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
1799
1901
  var IMPORT_TITLE_MAX = 500;
1800
1902
  var IMPORT_BODY_MAX = 8e3;
1903
+ var OKF_EXTRA_MAX_CHARS = 2 * IMPORT_BODY_MAX;
1904
+ var OKF_GENERATED_SLOT = "generated";
1905
+ var BUNDLE_METADATA_OWNED_KEYS = ["okf_version", "profile"];
1906
+ function isStorableScalar(value) {
1907
+ return typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value) || value === null;
1908
+ }
1909
+ function isSerializableWithinBound(value, depth) {
1910
+ if (isStorableScalar(value)) return true;
1911
+ if (Array.isArray(value)) {
1912
+ for (const item of value) {
1913
+ if (isStorableScalar(item)) continue;
1914
+ if (Array.isArray(item)) {
1915
+ if (depth >= 1) return false;
1916
+ if (!isSerializableWithinBound(item, depth + 1)) return false;
1917
+ } else if (typeof item === "object") {
1918
+ if (!isSerializableWithinBound(item, depth)) return false;
1919
+ } else {
1920
+ return false;
1921
+ }
1922
+ }
1923
+ return true;
1924
+ }
1925
+ if (value !== null && typeof value === "object") {
1926
+ for (const member of Object.values(value)) {
1927
+ if (member === void 0) continue;
1928
+ if (isStorableScalar(member)) continue;
1929
+ if (Array.isArray(member) || typeof member === "object") {
1930
+ if (depth >= 1) return false;
1931
+ if (!isSerializableWithinBound(member, depth + 1)) return false;
1932
+ } else {
1933
+ return false;
1934
+ }
1935
+ }
1936
+ return true;
1937
+ }
1938
+ return false;
1939
+ }
1940
+ function plainObjectOrNull(value) {
1941
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return null;
1942
+ return value;
1943
+ }
1944
+ function sanitizeRawSlot(value, mappedKeys, reasons) {
1945
+ const slot = plainObjectOrNull(value);
1946
+ if (slot === null) {
1947
+ reasons.push("not_object");
1948
+ return { ok: false };
1949
+ }
1950
+ const clean = {};
1951
+ for (const [entryKey, entryLines] of Object.entries(slot)) {
1952
+ if (entryKey === "__proto__") {
1953
+ reasons.push("raw_block_invalid");
1954
+ continue;
1955
+ }
1956
+ if (typeof entryLines !== "string") {
1957
+ reasons.push("not_object");
1958
+ return { ok: false };
1959
+ }
1960
+ if (entryLines.length > OKF_EXTRA_MAX_CHARS) {
1961
+ reasons.push("raw_block_invalid");
1962
+ continue;
1963
+ }
1964
+ if (isValidRawBlockEntry(entryKey, entryLines, mappedKeys)) clean[entryKey] = entryLines;
1965
+ else reasons.push("raw_block_invalid");
1966
+ }
1967
+ return { ok: true, slot: clean };
1968
+ }
1969
+ function validateOkfExtra(raw, mappedKeys) {
1970
+ if (raw === void 0) return { value: null, reasons: [] };
1971
+ const input = plainObjectOrNull(raw);
1972
+ if (input === null) return { value: null, reasons: ["not_object"] };
1973
+ const mapped = new Set(mappedKeys);
1974
+ const out = {};
1975
+ const reasons = [];
1976
+ for (const [key, value] of Object.entries(input)) {
1977
+ if (key === OKF_RAW_SLOT) {
1978
+ const slot = sanitizeRawSlot(value, mapped, reasons);
1979
+ if (!slot.ok) return { value: null, reasons };
1980
+ if (slot.slot && Object.keys(slot.slot).length > 0) out[OKF_RAW_SLOT] = slot.slot;
1981
+ continue;
1982
+ }
1983
+ if (key === OKF_GENERATED_SLOT) {
1984
+ const plain = plainObjectOrNull(value);
1985
+ if (plain === null || Object.prototype.hasOwnProperty.call(plain, "__proto__")) {
1986
+ reasons.push("not_object");
1987
+ return { value: null, reasons };
1988
+ }
1989
+ out[key] = value;
1990
+ continue;
1991
+ }
1992
+ if (mapped.has(key)) continue;
1993
+ if (key === "__proto__") {
1994
+ reasons.push("raw_block_invalid");
1995
+ continue;
1996
+ }
1997
+ out[key] = value;
1998
+ }
1999
+ if (Object.keys(out).length === 0) return { value: null, reasons };
2000
+ const slotRecord = out[OKF_RAW_SLOT];
2001
+ if (slotRecord) {
2002
+ for (const rk of Object.keys(slotRecord)) {
2003
+ if (rk !== OKF_RAW_SLOT && Object.prototype.hasOwnProperty.call(out, rk)) {
2004
+ delete slotRecord[rk];
2005
+ reasons.push("raw_block_invalid");
2006
+ }
2007
+ }
2008
+ if (Object.keys(slotRecord).length === 0) delete out[OKF_RAW_SLOT];
2009
+ }
2010
+ if (!Object.values(out).every((value) => isSerializableWithinBound(value, 0))) {
2011
+ return { value: null, reasons: [...reasons, "not_serializable"] };
2012
+ }
2013
+ let serialized;
2014
+ try {
2015
+ serialized = JSON.stringify(out) ?? "";
2016
+ } catch {
2017
+ return { value: null, reasons: [...reasons, "not_serializable"] };
2018
+ }
2019
+ if (serialized.length > OKF_EXTRA_MAX_CHARS) return { value: null, reasons: [...reasons, "too_large"] };
2020
+ return { value: out, reasons };
2021
+ }
2022
+ function validateBundleMetadata(raw) {
2023
+ if (raw === void 0) return { value: void 0, reasons: [] };
2024
+ const input = plainObjectOrNull(raw);
2025
+ if (input === null) return { value: void 0, reasons: ["not_object"] };
2026
+ const owned = new Set(BUNDLE_METADATA_OWNED_KEYS);
2027
+ const out = {};
2028
+ const reasons = [];
2029
+ for (const [key, value] of Object.entries(input)) {
2030
+ if (owned.has(key) || key === "__proto__") continue;
2031
+ if (key === OKF_RAW_SLOT) {
2032
+ const slot = sanitizeRawSlot(value, owned, reasons);
2033
+ if (!slot.ok) return { value: void 0, reasons };
2034
+ if (slot.slot && Object.keys(slot.slot).length > 0) out[OKF_RAW_SLOT] = slot.slot;
2035
+ continue;
2036
+ }
2037
+ out[key] = value;
2038
+ }
2039
+ const metaSlot = out[OKF_RAW_SLOT];
2040
+ if (metaSlot) {
2041
+ for (const rk of Object.keys(metaSlot)) {
2042
+ if (rk !== OKF_RAW_SLOT && Object.prototype.hasOwnProperty.call(out, rk)) {
2043
+ delete metaSlot[rk];
2044
+ reasons.push("raw_block_invalid");
2045
+ }
2046
+ }
2047
+ if (Object.keys(metaSlot).length === 0) delete out[OKF_RAW_SLOT];
2048
+ }
2049
+ if (!Object.values(out).every((value) => isSerializableWithinBound(value, 0))) {
2050
+ return { value: void 0, reasons: [...reasons, "not_serializable"] };
2051
+ }
2052
+ let serialized;
2053
+ try {
2054
+ serialized = JSON.stringify(out) ?? "";
2055
+ } catch {
2056
+ return { value: void 0, reasons: [...reasons, "not_serializable"] };
2057
+ }
2058
+ if (serialized.length > OKF_EXTRA_MAX_CHARS) return { value: void 0, reasons: [...reasons, "too_large"] };
2059
+ return { value: out, reasons };
2060
+ }
2061
+ function sanitizeStaleAfterRaw(raw, staleAfter) {
2062
+ if (raw === void 0 || raw === null) return null;
2063
+ if (typeof raw === "string" && raw.trim() === "") return null;
2064
+ if (typeof staleAfter === "number" && Number.isFinite(staleAfter)) return null;
2065
+ let text;
2066
+ if (typeof raw === "string") {
2067
+ text = raw;
2068
+ } else if (typeof raw === "number" || typeof raw === "boolean" || typeof raw === "bigint") {
2069
+ text = String(raw);
2070
+ } else {
2071
+ try {
2072
+ const json = JSON.stringify(raw);
2073
+ text = json === void 0 ? String(raw) : json;
2074
+ } catch {
2075
+ text = String(raw);
2076
+ }
2077
+ }
2078
+ let out = text;
2079
+ if (text.length > IMPORT_TITLE_MAX) {
2080
+ out = text.slice(0, IMPORT_TITLE_MAX);
2081
+ while (out.length > 0 && coreOkf.parseOkfTimestamp(out) !== null) out = out.slice(0, -1);
2082
+ }
2083
+ return out;
2084
+ }
2085
+ function sanitizeStaleAfterPair(raw, staleAfter) {
2086
+ if (typeof staleAfter === "number" && Number.isFinite(staleAfter)) {
2087
+ return { stale_after: staleAfter, stale_after_raw: null };
2088
+ }
2089
+ if (typeof staleAfter === "string") {
2090
+ const parsed = coreOkf.parseOkfTimestamp(staleAfter);
2091
+ if (parsed !== null) return { stale_after: parsed, stale_after_raw: null };
2092
+ const rawText = sanitizeStaleAfterRaw(raw, void 0);
2093
+ if (rawText !== null) return { stale_after: null, stale_after_raw: rawText };
2094
+ return { stale_after: null, stale_after_raw: sanitizeStaleAfterRaw(staleAfter, void 0) };
2095
+ }
2096
+ if (typeof raw === "string" && raw.trim() !== "") {
2097
+ const parsed = coreOkf.parseOkfTimestamp(raw);
2098
+ if (parsed !== null) return { stale_after: parsed, stale_after_raw: null };
2099
+ }
2100
+ if (Array.isArray(staleAfter) && staleAfter.length === 0) {
2101
+ return { stale_after: null, stale_after_raw: sanitizeStaleAfterRaw(raw, staleAfter) };
2102
+ }
2103
+ if (staleAfter !== void 0 && staleAfter !== null) {
2104
+ const fallback = sanitizeStaleAfterRaw(staleAfter, void 0);
2105
+ if (fallback !== null) return { stale_after: null, stale_after_raw: fallback };
2106
+ }
2107
+ return { stale_after: null, stale_after_raw: sanitizeStaleAfterRaw(raw, staleAfter) };
2108
+ }
2109
+ function sanitizeLifecycleStatus(raw) {
2110
+ const clipToBound = (s) => s.length > IMPORT_TITLE_MAX ? s.slice(0, IMPORT_TITLE_MAX) : s;
2111
+ if (raw === void 0 || raw === null || typeof raw === "string" && raw.trim() === "") return "stable";
2112
+ if (typeof raw === "string") return clipToBound(raw);
2113
+ if (typeof raw === "number" || typeof raw === "boolean" || typeof raw === "bigint") return clipToBound(String(raw));
2114
+ try {
2115
+ const json = JSON.stringify(raw);
2116
+ if (json !== void 0) return clipToBound(json);
2117
+ } catch {
2118
+ }
2119
+ return clipToBound(String(raw));
2120
+ }
1801
2121
  var ImportExportService = class {
1802
2122
  constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}, vectorRemoval, prefix) {
1803
2123
  this.db = db;
@@ -1943,12 +2263,15 @@ var ImportExportService = class {
1943
2263
  async getFullBundle(entityId, opts) {
1944
2264
  const incl = opts?.includeForgotten ? { includeDeleted: true } : void 0;
1945
2265
  const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
1946
- const [factsRaw, tasks, events, edges, summaryValue] = await Promise.all([
2266
+ const [factsRaw, tasks, events, edges, summaryValue, bundleMetadataValue] = await Promise.all([
1947
2267
  opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId, void 0, incl) : this.entryRepo.findAllByEntityId(entityId, void 0, incl),
1948
2268
  this.taskRepo.findAllByEntityId(entityId, void 0, incl),
1949
2269
  this.eventRepo.getByEntityId(entityId, opts?.maxEvents, incl),
1950
2270
  this.edgeRepo.getByEntityId(entityId),
1951
- this.metadataRepo.getMeta(entitySummaryMetaKey(entityId))
2271
+ this.metadataRepo.getMeta(entitySummaryMetaKey(entityId)),
2272
+ // §B7: the stored bundle-metadata record rides the entity object back
2273
+ // out, beside the summary.
2274
+ this.metadataRepo.getMeta(bundleMetadataMetaKey(entityId))
1952
2275
  ]);
1953
2276
  const facts = factsRaw.map((f) => {
1954
2277
  const {
@@ -1967,12 +2290,38 @@ var ImportExportService = class {
1967
2290
  tags: typeof factBase.tags === "string" ? JSON.parse(factBase.tags) : factBase.tags
1968
2291
  };
1969
2292
  });
2293
+ let bundleMetadata;
2294
+ if (bundleMetadataValue != null) {
2295
+ try {
2296
+ const parsed = JSON.parse(bundleMetadataValue);
2297
+ bundleMetadata = parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
2298
+ if (bundleMetadata === void 0) {
2299
+ emitDiagnostic(this.options, {
2300
+ code: "okf_bundle_metadata_invalid",
2301
+ operation: "exportDump",
2302
+ trigger: "call",
2303
+ entityId,
2304
+ detail: {}
2305
+ });
2306
+ }
2307
+ } catch {
2308
+ bundleMetadata = void 0;
2309
+ emitDiagnostic(this.options, {
2310
+ code: "okf_bundle_metadata_invalid",
2311
+ operation: "exportDump",
2312
+ trigger: "call",
2313
+ entityId,
2314
+ detail: {}
2315
+ });
2316
+ }
2317
+ }
1970
2318
  return {
1971
2319
  facts,
1972
2320
  tasks,
1973
2321
  events,
1974
2322
  edges,
1975
2323
  ...summaryValue != null ? { summary: summaryValue } : {},
2324
+ ...bundleMetadata != null ? { bundleMetadata } : {},
1976
2325
  ...wm ? { librarian_watermark: wm } : {}
1977
2326
  };
1978
2327
  }
@@ -1980,6 +2329,21 @@ var ImportExportService = class {
1980
2329
  async doImportEntity(entityId, bundle, merge) {
1981
2330
  const skippedSources = [];
1982
2331
  const refusalDiagnostics = [];
2332
+ let carriedBundleMetadata;
2333
+ const rawBundleMetadata = bundle.bundleMetadata;
2334
+ if (rawBundleMetadata !== void 0) {
2335
+ const meta = validateBundleMetadata(rawBundleMetadata);
2336
+ for (const reason of meta.reasons) {
2337
+ refusalDiagnostics.push({
2338
+ code: "okf_bundle_metadata_invalid",
2339
+ operation: "importDump",
2340
+ trigger: "call",
2341
+ entityId,
2342
+ detail: { reason }
2343
+ });
2344
+ }
2345
+ carriedBundleMetadata = meta.value;
2346
+ }
1983
2347
  const upsertedFactIds = /* @__PURE__ */ new Set();
1984
2348
  const liveEmbedFactIds = /* @__PURE__ */ new Set();
1985
2349
  const upsertedDeletedFactIds = /* @__PURE__ */ new Set();
@@ -2012,6 +2376,15 @@ var ImportExportService = class {
2012
2376
  } else if (!merge) {
2013
2377
  await this.metadataRepo.deleteMeta(entitySummaryMetaKey(entityId), tx);
2014
2378
  }
2379
+ if (carriedBundleMetadata !== void 0) {
2380
+ await this.metadataRepo.setMeta(
2381
+ bundleMetadataMetaKey(entityId),
2382
+ JSON.stringify(carriedBundleMetadata),
2383
+ tx
2384
+ );
2385
+ } else if (!merge) {
2386
+ await this.metadataRepo.deleteMeta(bundleMetadataMetaKey(entityId), tx);
2387
+ }
2015
2388
  const wipedByThisImport = new Set(softDeletedFactIds);
2016
2389
  const wipedTasksByThisImport = new Set(softDeletedTaskIds);
2017
2390
  const factIds = bundle.facts.map((fact) => fact.id);
@@ -2134,6 +2507,17 @@ var ImportExportService = class {
2134
2507
  });
2135
2508
  }
2136
2509
  const derivedEvents = derivedValidated ?? null;
2510
+ const factExtra = validateOkfExtra(fact.okf_extra, FACT_MAPPED_KEYS);
2511
+ for (const reason of factExtra.reasons) {
2512
+ refusalDiagnostics.push({
2513
+ code: "okf_extra_invalid",
2514
+ operation: "importDump",
2515
+ trigger: "call",
2516
+ entityId,
2517
+ detail: { factId: fact.id, reason }
2518
+ });
2519
+ }
2520
+ const stalePair = sanitizeStaleAfterPair(fact.stale_after_raw, fact.stale_after);
2137
2521
  const factObj = {
2138
2522
  id: fact.id,
2139
2523
  entity_id: entityId,
@@ -2153,14 +2537,20 @@ var ImportExportService = class {
2153
2537
  okf_type: fact.okf_type ?? null,
2154
2538
  source_pointer: sourcePointer,
2155
2539
  ...derivedEvents ? { derived_events: derivedEvents } : {},
2156
- // OKF v0.2 — forwarded as-is; parseOkfBundle / the caller is responsible for
2157
- // populating these per spec, importDump does not derive or validate them.
2158
- lifecycle_status: fact.lifecycle_status ?? "stable",
2159
- stale_after: fact.stale_after ?? null,
2540
+ // OKF v0.2 — lifecycle follows §B4 (empty or null is `stable`; a
2541
+ // non-string scalar stores its string form, a list or mapping its
2542
+ // compact JSON text). The other v0.2 fields are forwarded as-is;
2543
+ // parseOkfBundle / the caller is responsible for populating those
2544
+ // per spec.
2545
+ lifecycle_status: sanitizeLifecycleStatus(fact.lifecycle_status),
2546
+ stale_after: stalePair.stale_after,
2160
2547
  generated_by: fact.generated_by ?? null,
2161
2548
  okf_sources: fact.okf_sources ?? [],
2162
2549
  okf_verified: fact.okf_verified ?? [],
2163
2550
  okf_usage_window: fact.okf_usage_window ?? null,
2551
+ // OKF v0.3 (§B12) — forwarded through the checks above.
2552
+ okf_extra: factExtra.value,
2553
+ stale_after_raw: stalePair.stale_after_raw,
2164
2554
  // last_verified_at/_by are DERIVED mirrors of `okf_verified` per spec
2165
2555
  // §5.3. Recomputing here (instead of trusting the payload field) closes
2166
2556
  // the invariant that a raw importDump cannot carry a
@@ -2227,6 +2617,17 @@ var ImportExportService = class {
2227
2617
  }
2228
2618
  if (merge && safeUpdatedAt <= existing.updated_at && task.deleted_at == null) continue;
2229
2619
  }
2620
+ const taskExtra = validateOkfExtra(task.okf_extra, TASK_MAPPED_KEYS);
2621
+ for (const reason of taskExtra.reasons) {
2622
+ refusalDiagnostics.push({
2623
+ code: "okf_extra_invalid",
2624
+ operation: "importDump",
2625
+ trigger: "call",
2626
+ entityId,
2627
+ detail: { taskId: task.id, reason }
2628
+ });
2629
+ }
2630
+ const taskStalePair = sanitizeStaleAfterPair(task.stale_after_raw, task.stale_after);
2230
2631
  await this.taskRepo.upsertForImport(
2231
2632
  {
2232
2633
  id: task.id,
@@ -2239,13 +2640,16 @@ var ImportExportService = class {
2239
2640
  resolved_at: task.resolved_at,
2240
2641
  deleted_at: task.deleted_at,
2241
2642
  okf_type: task.okf_type ?? null,
2242
- // OKF v0.2
2243
- lifecycle_status: task.lifecycle_status ?? "stable",
2244
- stale_after: task.stale_after ?? null,
2643
+ // OKF v0.2 — lifecycle follows §B4, as on the fact branch.
2644
+ lifecycle_status: sanitizeLifecycleStatus(task.lifecycle_status),
2645
+ stale_after: taskStalePair.stale_after,
2245
2646
  generated_by: task.generated_by ?? null,
2246
2647
  okf_sources: task.okf_sources ?? [],
2247
2648
  okf_verified: task.okf_verified ?? [],
2248
2649
  okf_usage_window: task.okf_usage_window ?? null,
2650
+ // OKF v0.3 (§B12) — forwarded through the checks above.
2651
+ okf_extra: taskExtra.value,
2652
+ stale_after_raw: taskStalePair.stale_after_raw,
2249
2653
  // Derived mirrors — see fact branch above; same invariant.
2250
2654
  ...(() => {
2251
2655
  const latest = coreOkf.latestVerified(task.okf_verified ?? [], Date.now());
@@ -2892,7 +3296,7 @@ ${JSON.stringify(currentFacts, null, 2)}`,
2892
3296
  const anchorsShown = !usesPlaceholders || hasDocumentAnchors;
2893
3297
  const groundingCorpus = healGrounding ? buildGroundingCorpus([
2894
3298
  ...eventsShown ? effectiveEvents.map(summaryOf) : [],
2895
- ...anchorsShown ? effectiveAnchors.map((a, i) => ({ status: a?.lifecycle_status, shown: promptAnchors[i] })).filter((x) => x.status !== "draft").map((x) => x.shown?.body) : []
3299
+ ...anchorsShown ? effectiveAnchors.map((a, i) => ({ status: a?.lifecycle_status, shown: promptAnchors[i] })).filter((x) => x.status === void 0 || x.status === "stable" || x.status === "deprecated").map((x) => x.shown?.body) : []
2896
3300
  ]) : null;
2897
3301
  const { shapedCandidates, degraded } = applyBodyTruncation(
2898
3302
  healCandidates,
@@ -3249,6 +3653,7 @@ async function callClassify(options, ctx, request) {
3249
3653
  // src/utils/engineDefaults.ts
3250
3654
  var DEFAULT_LIBRARIAN_STRATEGY = "ops";
3251
3655
  var DEFAULT_MAINTENANCE_MODE = "deferred";
3656
+ var ENGINE_ACTOR = "process:llm-wiki";
3252
3657
  function resolveLibrarianStrategy(config) {
3253
3658
  return config?.librarian?.strategy ?? DEFAULT_LIBRARIAN_STRATEGY;
3254
3659
  }
@@ -4158,7 +4563,7 @@ var IngestionService = class {
4158
4563
  if (!sourceRef) throw new Error("Invalid sourceRef");
4159
4564
  params = { ...params, sourceRef };
4160
4565
  await this.assertGraphNodeOwnership(entityId, params.nodes, tx);
4161
- const now = Date.now();
4566
+ const now = opts?.at !== void 0 && Number.isFinite(opts.at) ? opts.at : Date.now();
4162
4567
  const ontologyState = await this.ontologyService?.getEffectiveState(entityId, tx) ?? { mode: "off", manifest: { node_types: [], edge_types: [] } };
4163
4568
  let { mode, manifest } = ontologyState;
4164
4569
  const strictEffective = opts?.strict === false ? false : opts?.strict === true || mode === "strict";
@@ -4205,6 +4610,9 @@ var IngestionService = class {
4205
4610
  access_count: 0,
4206
4611
  deleted_at: null,
4207
4612
  okf_type: normalized.okf_type,
4613
+ // §C1: only the engine-authored path stamps; the host path passes no
4614
+ // flag and binds NULL (the COALESCE still protects any stored actor).
4615
+ ...opts?.authoredByEngine ? { generated_by: ENGINE_ACTOR } : {},
4208
4616
  ...opts?.nodeTrust?.get(node.id)
4209
4617
  };
4210
4618
  wikiFacts.push(wikiFact);
@@ -4273,7 +4681,7 @@ var IngestionService = class {
4273
4681
  await this.sourceRefIndexRepo.softDeleteByEntityAndSourceRef(entityId, params.sourceRef, tx);
4274
4682
  await this.sourceRefIndexRepo.upsert(entityId, params.sourceHash, params.sourceRef, tx);
4275
4683
  for (const wikiFact of wikiFacts) {
4276
- await this.entryRepo.upsert(wikiFact, tx);
4684
+ await this.entryRepo.upsert(wikiFact, tx, now);
4277
4685
  }
4278
4686
  let edgesInsertedCount = 0;
4279
4687
  for (const edge of validEdges) {
@@ -4416,7 +4824,10 @@ var IngestionService = class {
4416
4824
  entityId,
4417
4825
  { sourceRef, sourceHash, nodes: hostNodes, edges: hostEdges },
4418
4826
  tx,
4419
- { strict: false, diag: { buffer: diagBuffer, operation: "ingest" }, ...nodeTrust.size > 0 ? { nodeTrust } : {} }
4827
+ // §C1: the engine authored every node here. §C5: `at` shares this pass's
4828
+ // clock read (used for the grounding events above) with the row writes,
4829
+ // so a grounded fact's verification stays current.
4830
+ { strict: false, diag: { buffer: diagBuffer, operation: "ingest" }, authoredByEngine: true, at: now, ...nodeTrust.size > 0 ? { nodeTrust } : {} }
4420
4831
  );
4421
4832
  return { deletedSourceFactIds, insertedFacts };
4422
4833
  }
@@ -4516,9 +4927,11 @@ var IngestionService = class {
4516
4927
  access_count: 0,
4517
4928
  deleted_at: null,
4518
4929
  okf_type: normalized.okf_type,
4930
+ // §C1: the engine extracted this fact from the document.
4931
+ generated_by: ENGINE_ACTOR,
4519
4932
  ...outcome?.trust
4520
4933
  };
4521
- await this.entryRepo.upsert(wikiFact, tx);
4934
+ await this.entryRepo.upsert(wikiFact, tx, now);
4522
4935
  titleIndex.set(normalizeTitleKey(fact.title), { id, okf_type: normalized.okf_type });
4523
4936
  insertedDescriptors.push({
4524
4937
  id,
@@ -4929,7 +5342,7 @@ var EdgeRepository = class extends BaseRepository {
4929
5342
  END
4930
5343
  ) >= ?
4931
5344
  AND n.source_type NOT IN (${excludeSourceTypesPlaceholders})
4932
- AND (? = 0 OR n.lifecycle_status != 'draft')
5345
+ AND (? = 0 OR n.lifecycle_status IN ('stable','deprecated'))
4933
5346
  AND ${liveAtSql(opts.live.mode, "n.")}
4934
5347
  WHERE w.depth < ?
4935
5348
  AND instr(w.visited, ',' || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ',') = 0
@@ -5431,6 +5844,25 @@ var MIGRATIONS = [
5431
5844
  await addEventsForgottenAtColumn(db, prefix);
5432
5845
  await createEventsForgottenIndex(db, prefix);
5433
5846
  }
5847
+ },
5848
+ {
5849
+ version: 20,
5850
+ description: "OKF v0.3: nullable stale_after_raw (unparseable wire stale_after, verbatim) and okf_extra (unmapped frontmatter keys, JSON) on entries and tasks (specs/okf-v03 \xA7F)",
5851
+ run: async (db, prefix) => {
5852
+ for (const table of ["entries", "tasks"]) {
5853
+ const cols = await db.getAllAsync(
5854
+ `PRAGMA table_info(${prefix}${table})`
5855
+ );
5856
+ const existing = new Set(cols.map((c) => c.name));
5857
+ const adds = [
5858
+ ["stale_after_raw", `ALTER TABLE ${prefix}${table} ADD COLUMN stale_after_raw TEXT`],
5859
+ ["okf_extra", `ALTER TABLE ${prefix}${table} ADD COLUMN okf_extra TEXT`]
5860
+ ];
5861
+ for (const [name, sql] of adds) {
5862
+ if (!existing.has(name)) await db.execAsync(sql);
5863
+ }
5864
+ }
5865
+ }
5434
5866
  }
5435
5867
  ];
5436
5868
  async function addEventsForgottenAtColumn(db, prefix) {
@@ -5663,9 +6095,15 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
5663
6095
  // Legacy writes no pointer (spec §Legacy path): the column stays null
5664
6096
  // on every legacy fact, and the legacy prompt keeps its exact text.
5665
6097
  source_pointer: null,
6098
+ // §C1 (specs/okf-v03): the engine authored this fact, so a NULL row
6099
+ // actor is stamped; the upsert's COALESCE never overwrites a stored
6100
+ // (explicit or imported foreign) actor. §C5: the pass's clock read
6101
+ // is shared with the grounding event, so the verification is current
6102
+ // by the `>=` currency test.
6103
+ generated_by: ENGINE_ACTOR,
5666
6104
  ...grounding?.trust
5667
6105
  };
5668
- await deps.entryRepo.upsert(factObj, tx);
6106
+ await deps.entryRepo.upsert(factObj, tx, now);
5669
6107
  const volunteeredSourceEvent = facts[validFactItemIndexes[k]]?.source_event;
5670
6108
  if (volunteeredSourceEvent !== void 0 && volunteeredSourceEvent !== null) {
5671
6109
  diagBuffer.push({
@@ -5707,7 +6145,8 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
5707
6145
  created_at: now,
5708
6146
  updated_at: now,
5709
6147
  resolved_at: null,
5710
- deleted_at: null
6148
+ deleted_at: null,
6149
+ generated_by: ENGINE_ACTOR
5711
6150
  };
5712
6151
  await deps.taskRepo.upsert(taskObj, tx);
5713
6152
  }
@@ -6318,13 +6757,19 @@ async function applyOps(deps, ctx, input) {
6318
6757
  deleted_at: null,
6319
6758
  okf_type: normalized.okf_type,
6320
6759
  source_pointer: pointer,
6760
+ // §C1 (specs/okf-v03): the engine authored this text (ADD, the
6761
+ // supersede replacement and the contradicts draft all land here), so a
6762
+ // NULL row actor is stamped; the upsert's COALESCE never overwrites a
6763
+ // stored actor. §C5: the pass's clock read is shared with the
6764
+ // grounding event (§C5 currency, `>=`).
6765
+ generated_by: ENGINE_ACTOR,
6321
6766
  // §2: only an UPDATE converted to SUPERSEDE inherits (the merged text
6322
6767
  // rests on the target); ADD and plain SUPERSEDE carry no list.
6323
6768
  ...inheritedDerivedEvents(inheritFrom, pointer?.event_id ?? null),
6324
6769
  ...g2?.trust,
6325
6770
  ...draft ? { lifecycle_status: "draft" } : {}
6326
6771
  };
6327
- await deps.entryRepo.upsert(row, tx);
6772
+ await deps.entryRepo.upsert(row, tx, now);
6328
6773
  await deps.entryRepo.setTemporal(id, entityId, { valid_from: validFrom }, tx);
6329
6774
  if (g.candidate.pointerUnresolved !== null) {
6330
6775
  input.diagnostics.push({
@@ -6399,7 +6844,18 @@ async function applyOps(deps, ctx, input) {
6399
6844
  title: newTitle,
6400
6845
  body: op.body ?? g.candidate.fact.body,
6401
6846
  updated_at: now,
6847
+ // §C1: the engine authored the merged text, so a NULL stored actor
6848
+ // is filled; the upsert's COALESCE keeps a stored (foreign)
6849
+ // actor. The §C2 gate stamps only on a real content change.
6850
+ generated_by: existing.generated_by ?? ENGINE_ACTOR,
6402
6851
  ...derived ? { derived_events: derived } : {}
6852
+ // No shared `at`: this in-place rewrite carries no same-pass
6853
+ // verification, so §C5's shared-instant rationale does not apply —
6854
+ // the repo stamps its own instant inside the transaction (the heal
6855
+ // writeNow discipline). The pass-start read could predate a
6856
+ // concurrent verification commit (the rewritten row would then
6857
+ // out-stay its own replacement, §5.3) or move updated_at backwards
6858
+ // (review 2026-12-04).
6403
6859
  }, tx);
6404
6860
  titleIndex.delete(normalizeTitleKey(existing.title));
6405
6861
  titleIndex.set(normalizeTitleKey(newTitle), { id: existing.id, okf_type: existing.okf_type ?? null });
@@ -6463,7 +6919,8 @@ async function applyOps(deps, ctx, input) {
6463
6919
  created_at: now,
6464
6920
  updated_at: now,
6465
6921
  resolved_at: null,
6466
- deleted_at: null
6922
+ deleted_at: null,
6923
+ generated_by: ENGINE_ACTOR
6467
6924
  };
6468
6925
  await deps.taskRepo.upsert(taskObj, tx);
6469
6926
  }
@@ -7521,6 +7978,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
7521
7978
  await this.metadataRepo.updateCheckpoint(entityId, { memory: 0, heal: 0 }, tx);
7522
7979
  }
7523
7980
  await this.metadataRepo.deleteMeta(entitySummaryMetaKey(entityId), tx);
7981
+ await this.metadataRepo.deleteMeta(bundleMetadataMetaKey(entityId), tx);
7524
7982
  } else {
7525
7983
  const hasIdSelectors = params.entryId !== void 0 || params.taskId !== void 0;
7526
7984
  const hasSourceSelectors = params.sourceRef !== void 0 || params.sourceHash !== void 0;
@@ -7870,8 +8328,10 @@ DROP TRIGGER IF EXISTS ${ad};`);
7870
8328
  * model-directed move emits a `heal_deleted` / `heal_downgraded` receipt
7871
8329
  * after commit (`applied`, `applied_unscreened`, or `below_floor`), in every
7872
8330
  * mode. An `applied` receipt records that the model VERDICT was applied
7873
- * (`downgradeByIds` runs unconditionally): a fact that was already at
7874
- * reduced confidence still gets an `applied` receipt. A withheld delete paired with a restating `newFact` leaves the fact
8331
+ * (`downgradeByIds` runs for every applied id): a fact that was already at
8332
+ * reduced confidence still gets an `applied` receipt even though the row
8333
+ * write and its outbox UPDATE are skipped for an already-'tentative' fact
8334
+ * (specs/okf-v03 §C4). A withheld delete paired with a restating `newFact` leaves the fact
7875
8335
  * live and the restatement is skipped as `fact_deduplicated`.
7876
8336
  */
7877
8337
  async doRunHeal(entityId, options) {
@@ -7936,11 +8396,14 @@ DROP TRIGGER IF EXISTS ${ad};`);
7936
8396
  ...keywordUnavailable ? { searchUnavailable: true } : {}
7937
8397
  };
7938
8398
  }
7939
- const allTasks = await this.taskRepo.findAllPending([entityId], HEAL_MAX_TASKS);
8399
+ const allTasks = (await this.taskRepo.findAllPending([entityId], HEAL_MAX_TASKS)).map((t) => {
8400
+ const { okf_extra: _extra, stale_after_raw: _sraw, ...rest } = t;
8401
+ return rest;
8402
+ });
7940
8403
  const recentEvents = await this.eventRepo.getRecent(entityId, 20);
7941
8404
  const healGrounding = this.promptService.groundingFor("heal");
7942
8405
  const toPromptShape = (f) => {
7943
- const { embedding: _embedding, embedding_blob: _blob, ...rest } = f;
8406
+ const { embedding: _embedding, embedding_blob: _blob, okf_extra: _extra, stale_after_raw: _sraw, ...rest } = f;
7944
8407
  const shown = healGrounding ? (({ lifecycle_status: _l, okf_verified: _v, last_verified_at: _a, last_verified_by: _b, ...r }) => r)(rest) : rest;
7945
8408
  return { ...shown, tags: typeof shown.tags === "string" ? JSON.parse(shown.tags) : shown.tags };
7946
8409
  };
@@ -8116,7 +8579,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
8116
8579
  continue;
8117
8580
  }
8118
8581
  const id = generateId("fact_");
8119
- const grounding = healGrounding ? groundingOutcome(checkGrounding(fact.evidence, validNewFactCorpora[k] ?? [], healGrounding), now) : null;
8582
+ const writeNow = Date.now();
8583
+ const grounding = healGrounding ? groundingOutcome(checkGrounding(fact.evidence, validNewFactCorpora[k] ?? [], healGrounding), writeNow) : null;
8120
8584
  if (grounding?.diagnostic) {
8121
8585
  diagBuffer.push({ ...diagBase, code: grounding.diagnostic.code, detail: { factId: id, itemIndex: validNewFactItemIndexes[k], reason: grounding.diagnostic.reason } });
8122
8586
  }
@@ -8131,14 +8595,17 @@ DROP TRIGGER IF EXISTS ${ad};`);
8131
8595
  source_hash: null,
8132
8596
  source_ref: null,
8133
8597
  source_pointer: null,
8134
- created_at: now,
8135
- updated_at: now,
8598
+ created_at: writeNow,
8599
+ updated_at: writeNow,
8136
8600
  last_accessed_at: null,
8137
8601
  access_count: 0,
8138
8602
  deleted_at: null,
8603
+ // §C1: the engine authored this restatement, so a NULL row actor is
8604
+ // stamped; the upsert's COALESCE never overwrites a stored actor.
8605
+ generated_by: ENGINE_ACTOR,
8139
8606
  ...grounding?.trust
8140
8607
  };
8141
- await this.entryRepo.upsert(factObj, tx);
8608
+ await this.entryRepo.upsert(factObj, tx, writeNow);
8142
8609
  insertedFacts.push({ id, entity_id: entityId, title: fact.title, body: fact.body, tags: JSON.stringify(fact.tags) });
8143
8610
  healFactsForDedupe.push({ id, title: fact.title });
8144
8611
  }
@@ -9171,9 +9638,9 @@ var RetrievalService = class {
9171
9638
  if (maxResults === 0) ; else if (trimmedQuery) {
9172
9639
  let usedEmbed = false;
9173
9640
  const scoredEntityIds = this._filterScoredEntities(entityIds, sanitizedTierWeights, options?.includeZeroWeightEntities);
9174
- const draftIds = excludeDrafts && scoredEntityIds.length > 0 ? await this.entryRepo.findDraftIdsByEntityIds(scoredEntityIds) : EMPTY_ID_SET;
9641
+ const notCurrentIds = excludeDrafts && scoredEntityIds.length > 0 ? await this.entryRepo.findNotCurrentIdsByEntityIds(scoredEntityIds) : EMPTY_ID_SET;
9175
9642
  const nonLiveIds = scoredEntityIds.length > 0 ? await this.entryRepo.findNonLiveIdsByEntityIds(scoredEntityIds, liveMode, liveAt) : EMPTY_ID_SET;
9176
- const excludedIds = draftIds.size === 0 ? nonLiveIds : nonLiveIds.size === 0 ? draftIds : /* @__PURE__ */ new Set([...draftIds, ...nonLiveIds]);
9643
+ const excludedIds = notCurrentIds.size === 0 ? nonLiveIds : nonLiveIds.size === 0 ? notCurrentIds : /* @__PURE__ */ new Set([...notCurrentIds, ...nonLiveIds]);
9177
9644
  const excludedPad = excludedIds.size;
9178
9645
  const padLimit = (n) => n >= Number.MAX_SAFE_INTEGER ? n : n + excludedPad;
9179
9646
  if (scoredEntityIds.length === 0) {