dotmem 0.1.7 → 0.1.9

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/cli.cjs CHANGED
@@ -1,21 +1,21 @@
1
1
  'use strict';
2
2
 
3
3
  var memorio = require('memorio');
4
- var fs2 = require('fs');
5
- var path2 = require('path');
4
+ var fs3 = require('fs');
5
+ var fs = require('fs/promises');
6
+ var path3 = require('path');
6
7
  var url = require('url');
7
8
  var crypto2 = require('crypto');
8
9
  var process14 = require('process');
9
- var fs4 = require('fs/promises');
10
10
 
11
11
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
12
12
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
13
13
 
14
- var fs2__default = /*#__PURE__*/_interopDefault(fs2);
15
- var path2__default = /*#__PURE__*/_interopDefault(path2);
14
+ var fs3__default = /*#__PURE__*/_interopDefault(fs3);
15
+ var fs__default = /*#__PURE__*/_interopDefault(fs);
16
+ var path3__default = /*#__PURE__*/_interopDefault(path3);
16
17
  var crypto2__default = /*#__PURE__*/_interopDefault(crypto2);
17
18
  var process14__default = /*#__PURE__*/_interopDefault(process14);
18
- var fs4__default = /*#__PURE__*/_interopDefault(fs4);
19
19
 
20
20
  var __defProp = Object.defineProperty;
21
21
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -44,18 +44,6 @@ var __copyProps = (to, from, except, desc) => {
44
44
  };
45
45
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
46
46
 
47
- // core/suppress-idb-warning.ts
48
- var orig;
49
- var init_suppress_idb_warning = __esm({
50
- "core/suppress-idb-warning.ts"() {
51
- orig = console.warn.bind(console);
52
- console.warn = (...args) => {
53
- if (typeof args[0] === "string" && args[0].includes("IndexedDB is not available")) return;
54
- orig(...args);
55
- };
56
- }
57
- });
58
-
59
47
  // core/env.ts
60
48
  var DEV;
61
49
  var init_env = __esm({
@@ -90,7 +78,6 @@ function configure(opts) {
90
78
  var g, STORE_PREFIX, INDEX_KEY, journal, journal_default;
91
79
  var init_journal = __esm({
92
80
  "core/memory/journal.ts"() {
93
- init_suppress_idb_warning();
94
81
  init_env();
95
82
  g = globalThis;
96
83
  __name(namespace, "namespace");
@@ -338,6 +325,60 @@ var init_storage_paths = __esm({
338
325
  }
339
326
  });
340
327
 
328
+ // core/knowledge/text-encoding.ts
329
+ function detectBom(bytes) {
330
+ if (bytes.length >= 3 && bytes[0] === BOM_UTF8 && bytes[1] === 187 && bytes[2] === 191) {
331
+ return "utf-8";
332
+ }
333
+ if (bytes.length >= 2 && bytes[0] === BOM_UTF16LE_FIRST && bytes[1] === BOM_UTF16LE_SECOND) {
334
+ return "utf-16le";
335
+ }
336
+ if (bytes.length >= 2 && bytes[0] === BOM_UTF16BE_FIRST && bytes[1] === BOM_UTF16BE_SECOND) {
337
+ return "utf-16be";
338
+ }
339
+ return null;
340
+ }
341
+ function encodeText(value) {
342
+ return encoder.encode(value);
343
+ }
344
+ function decodeText(bytes, options = {}) {
345
+ const bom = detectBom(bytes);
346
+ if (bom === "utf-16le" || bom === "utf-16be") {
347
+ throw new UnsupportedEncodingError(
348
+ `UTF-16 encoded content detected in ${options.source ?? "unknown"}; dotmem persists UTF-8 only. Re-save the file as UTF-8 without BOM.`
349
+ );
350
+ }
351
+ let content = bytes;
352
+ if (bom === "utf-8") {
353
+ content = bytes.subarray(3);
354
+ }
355
+ return strictDecoder.decode(content);
356
+ }
357
+ var encoder, strictDecoder, UnsupportedEncodingError, BOM_UTF8, BOM_UTF16LE_FIRST, BOM_UTF16LE_SECOND, BOM_UTF16BE_FIRST, BOM_UTF16BE_SECOND;
358
+ var init_text_encoding = __esm({
359
+ "core/knowledge/text-encoding.ts"() {
360
+ encoder = new TextEncoder();
361
+ strictDecoder = new TextDecoder("utf-8", { fatal: true });
362
+ UnsupportedEncodingError = class extends Error {
363
+ static {
364
+ __name(this, "UnsupportedEncodingError");
365
+ }
366
+ constructor(message) {
367
+ super(message);
368
+ this.name = "UnsupportedEncodingError";
369
+ }
370
+ };
371
+ BOM_UTF8 = 239;
372
+ BOM_UTF16LE_FIRST = 255;
373
+ BOM_UTF16LE_SECOND = 254;
374
+ BOM_UTF16BE_FIRST = 254;
375
+ BOM_UTF16BE_SECOND = 255;
376
+ __name(detectBom, "detectBom");
377
+ __name(encodeText, "encodeText");
378
+ __name(decodeText, "decodeText");
379
+ }
380
+ });
381
+
341
382
  // core/knowledge/storage-settings.ts
342
383
  exports.DOTMEM_STORAGE_SETTINGS_FILE_NAME = void 0; exports.DOTMEM_STORAGE_SETTINGS_VERSION = void 0; var SETTINGS_MODES, projectRoot, findProjectSettingsFile; exports.resolveProjectSettingsFilePath = void 0; exports.discoverProjectSettingsFilePath = void 0; exports.resolveUserSettingsFilePath = void 0; var invalidSettings, parseSettings, resolveSettingsEntry, readTextFile; exports.readStorageSettings = void 0;
343
384
  var init_storage_settings = __esm({
@@ -351,13 +392,13 @@ var init_storage_settings = __esm({
351
392
  return normalized || normalizeStoragePath(cwd);
352
393
  }, "projectRoot");
353
394
  findProjectSettingsFile = /* @__PURE__ */ __name((cwd) => {
354
- const fs7 = getSyncFs();
355
- if (!fs7) return null;
395
+ const fs9 = getSyncFs();
396
+ if (!fs9) return null;
356
397
  let current = projectRoot(cwd);
357
398
  for (; ; ) {
358
399
  const candidate = joinStoragePath(current, exports.DOTMEM_STORAGE_SETTINGS_FILE_NAME);
359
400
  try {
360
- if (fs7.existsSync(candidate)) return candidate;
401
+ if (fs9.existsSync(candidate)) return candidate;
361
402
  } catch {
362
403
  return null;
363
404
  }
@@ -432,10 +473,10 @@ var init_storage_settings = __esm({
432
473
  }
433
474
  return { tier, file, root: normalizeStoragePath(declared), mode };
434
475
  }, "resolveSettingsEntry");
435
- readTextFile = /* @__PURE__ */ __name((fs7, file) => {
476
+ readTextFile = /* @__PURE__ */ __name((fs9, file) => {
436
477
  let raw;
437
478
  try {
438
- raw = fs7.readFileSync(file, "utf8");
479
+ raw = fs9.readFileSync(file, "utf8");
439
480
  } catch (error) {
440
481
  const code = error?.code;
441
482
  if (code === "ENOENT" || code === "ENOTDIR") return null;
@@ -447,9 +488,9 @@ var init_storage_settings = __esm({
447
488
  return raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw;
448
489
  }, "readTextFile");
449
490
  exports.readStorageSettings = /* @__PURE__ */ __name((file, tier) => {
450
- const fs7 = getSyncFs();
451
- if (!fs7) return null;
452
- const raw = readTextFile(fs7, file);
491
+ const fs9 = getSyncFs();
492
+ if (!fs9) return null;
493
+ const raw = readTextFile(fs9, file);
453
494
  if (raw === null) return null;
454
495
  return resolveSettingsEntry(parseSettings(raw, file), tier, file);
455
496
  }, "readStorageSettings");
@@ -465,21 +506,25 @@ function resolveUserAnchor() {
465
506
  return joinStoragePath(stripTrailingSeparator(home.trim()), DOTMEM_USER_ANCHOR_DIR_NAME);
466
507
  }
467
508
  function readDotMemStorageLocator() {
468
- const fs7 = getSyncFs();
469
- if (!fs7) return null;
509
+ const fs9 = getSyncFs();
510
+ if (!fs9) return null;
470
511
  const anchor = resolveUserAnchor();
471
512
  const locatorFile = resolveLocatorFilePath(anchor);
472
513
  let raw;
473
514
  try {
474
- raw = fs7.readFileSync(locatorFile, "utf8");
515
+ raw = decodeText(fs9.readFileSync(locatorFile), { source: locatorFile });
475
516
  } catch (error) {
517
+ if (error instanceof UnsupportedEncodingError) {
518
+ throw new exports.DotMemStorageLocationError(
519
+ `dotmem storage location cannot be resolved: the user locator file at ${locatorFile} is UTF-16 encoded; dotmem persists UTF-8 only. Re-save the locator as UTF-8 without BOM.`
520
+ );
521
+ }
476
522
  const code = error?.code;
477
523
  if (code === "ENOENT") return null;
478
524
  throw new exports.DotMemStorageLocationError(
479
525
  `dotmem storage location cannot be resolved: the user locator file at ${locatorFile} cannot be read (${describeAccessFailure(error)}). No alternative location was selected automatically.`
480
526
  );
481
527
  }
482
- if (raw.charCodeAt(0) === 65279) raw = raw.slice(1);
483
528
  let parsed;
484
529
  try {
485
530
  parsed = JSON.parse(raw);
@@ -583,8 +628,8 @@ async function probeDotMemStorageCapabilities(root) {
583
628
  multiWriterSafety: "unsupported",
584
629
  notes
585
630
  };
586
- const fs7 = getSyncFs();
587
- if (!fs7) {
631
+ const fs9 = getSyncFs();
632
+ if (!fs9) {
588
633
  notes.push("no filesystem access in this runtime");
589
634
  return report;
590
635
  }
@@ -670,14 +715,14 @@ async function relocateDotMemStorage(targetRoot, options = {}) {
670
715
  `Storage relocation target ${target} and the active storage root ${current.storageRoot} must not contain each other.`
671
716
  );
672
717
  }
673
- const fs7 = getSyncFs();
674
- if (!fs7) {
718
+ const fs9 = getSyncFs();
719
+ if (!fs9) {
675
720
  throw new exports.DotMemStorageLocationError("Storage relocation requires filesystem access, which is unavailable in this runtime.");
676
721
  }
677
722
  const fsPromises = await nodeFsPromises();
678
723
  await fsPromises.mkdir(target, { recursive: true });
679
724
  try {
680
- const access = fs7.statSync(target);
725
+ const access = fs9.statSync(target);
681
726
  if (!access.isDirectory()) throw new Error("not a directory");
682
727
  } catch (error) {
683
728
  if (error instanceof exports.DotMemStorageLocationError) throw error;
@@ -686,7 +731,7 @@ async function relocateDotMemStorage(targetRoot, options = {}) {
686
731
  );
687
732
  }
688
733
  await migrateStorageData(current.storageRoot, target);
689
- if (!verifyMigratedData(fs7, current.storageRoot, target)) {
734
+ if (!verifyMigratedData(fs9, current.storageRoot, target)) {
690
735
  throw new exports.DotMemStorageLocationError(
691
736
  `Storage relocation to ${target} could not be verified: migrated data is incomplete. The locator at ${current.locatorFile} was not updated and the storage root remains ${current.storageRoot}.`
692
737
  );
@@ -731,15 +776,15 @@ async function restoreDefaultDotMemStorage(options = {}) {
731
776
  if (current.source === "default") {
732
777
  return current;
733
778
  }
734
- const fs7 = getSyncFs();
735
- if (!fs7) {
779
+ const fs9 = getSyncFs();
780
+ if (!fs9) {
736
781
  throw new exports.DotMemStorageLocationError("Restoring the default storage location requires filesystem access, which is unavailable in this runtime.");
737
782
  }
738
783
  const fsPromises = await nodeFsPromises();
739
784
  const target = current.anchor;
740
785
  await fsPromises.mkdir(target, { recursive: true });
741
786
  await migrateStorageData(current.storageRoot, target);
742
- if (!verifyMigratedData(fs7, current.storageRoot, target)) {
787
+ if (!verifyMigratedData(fs9, current.storageRoot, target)) {
743
788
  throw new exports.DotMemStorageLocationError(
744
789
  `Restoring the default location ${target} could not be verified: migrated data is incomplete. The locator at ${current.locatorFile} was not removed and still points to ${current.storageRoot}.`
745
790
  );
@@ -765,6 +810,7 @@ var DOTMEM_USER_ANCHOR_DIR_NAME, DOTMEM_STORAGE_LOCATOR_FILE_NAME, DOTMEM_STORAG
765
810
  var init_storage_location = __esm({
766
811
  "core/knowledge/storage-location.ts"() {
767
812
  init_storage_paths();
813
+ init_text_encoding();
768
814
  init_storage_settings();
769
815
  init_storage_paths();
770
816
  DOTMEM_USER_ANCHOR_DIR_NAME = ".dotmem";
@@ -786,9 +832,9 @@ var init_storage_location = __esm({
786
832
  return proc && typeof proc.cwd === "function" ? proc.cwd() : ".";
787
833
  }, "currentWorkingDirectory");
788
834
  packageInstallPathHint = null;
789
- exports.noteDotMemPackageInstallPath = /* @__PURE__ */ __name((path5) => {
790
- if (typeof path5 === "string" && path5.trim()) {
791
- packageInstallPathHint = normalizeStoragePath(path5.trim());
835
+ exports.noteDotMemPackageInstallPath = /* @__PURE__ */ __name((path8) => {
836
+ if (typeof path8 === "string" && path8.trim()) {
837
+ packageInstallPathHint = normalizeStoragePath(path8.trim());
792
838
  }
793
839
  }, "noteDotMemPackageInstallPath");
794
840
  looksLikeDotMemInstallPath = /* @__PURE__ */ __name((value) => {
@@ -837,10 +883,10 @@ var init_storage_location = __esm({
837
883
  cliStorageRootOverride = null;
838
884
  }, "clearDotMemStorageRootOverride");
839
885
  hasRecognizableStore = /* @__PURE__ */ __name((root) => {
840
- const fs7 = getSyncFs();
841
- if (!fs7) return false;
886
+ const fs9 = getSyncFs();
887
+ if (!fs9) return false;
842
888
  try {
843
- const entries2 = fs7.readdirSync(root);
889
+ const entries2 = fs9.readdirSync(root);
844
890
  return entries2.some((name) => name.endsWith(".mem") || name === "policy" || name === "DOTMEM.md" || name === "projects");
845
891
  } catch {
846
892
  return false;
@@ -866,10 +912,10 @@ var init_storage_location = __esm({
866
912
  }
867
913
  const root = normalizeStoragePath(trimmed);
868
914
  assertNotInsidePackageInstall(root, source);
869
- const fs7 = getSyncFs();
870
- if (!fs7) return root;
915
+ const fs9 = getSyncFs();
916
+ if (!fs9) return root;
871
917
  try {
872
- const stats = fs7.statSync(root);
918
+ const stats = fs9.statSync(root);
873
919
  if (!stats.isDirectory()) {
874
920
  throw invalidConfiguredRoot(trimmed, source, "the path exists but is not a directory");
875
921
  }
@@ -883,11 +929,11 @@ var init_storage_location = __esm({
883
929
  __name(describeDotMemStorage, "describeDotMemStorage");
884
930
  __name(resolveDotMemStorageRoot, "resolveDotMemStorageRoot");
885
931
  __name(probeDotMemStorageCapabilities, "probeDotMemStorageCapabilities");
886
- collectRelativeEntries = /* @__PURE__ */ __name((fs7, root, prefix = "") => {
932
+ collectRelativeEntries = /* @__PURE__ */ __name((fs9, root, prefix = "") => {
887
933
  const entries2 = [];
888
934
  let dirents;
889
935
  try {
890
- dirents = fs7.readdirSync(root, { withFileTypes: true });
936
+ dirents = fs9.readdirSync(root, { withFileTypes: true });
891
937
  } catch {
892
938
  return entries2;
893
939
  }
@@ -895,23 +941,23 @@ var init_storage_location = __esm({
895
941
  const relative = prefix ? `${prefix}/${dirent.name}` : dirent.name;
896
942
  if (relative === DOTMEM_STORAGE_LOCATOR_FILE_NAME || relative === `${DOTMEM_STORAGE_LOCATOR_FILE_NAME}.tmp`) continue;
897
943
  if (dirent.isDirectory()) {
898
- entries2.push(...collectRelativeEntries(fs7, joinStoragePath(root, dirent.name), relative));
944
+ entries2.push(...collectRelativeEntries(fs9, joinStoragePath(root, dirent.name), relative));
899
945
  } else {
900
946
  entries2.push(relative);
901
947
  }
902
948
  }
903
949
  return entries2.sort();
904
950
  }, "collectRelativeEntries");
905
- verifyMigratedData = /* @__PURE__ */ __name((fs7, from, to) => {
906
- const expected = collectRelativeEntries(fs7, from);
907
- const migrated = new Set(collectRelativeEntries(fs7, to));
951
+ verifyMigratedData = /* @__PURE__ */ __name((fs9, from, to) => {
952
+ const expected = collectRelativeEntries(fs9, from);
953
+ const migrated = new Set(collectRelativeEntries(fs9, to));
908
954
  return expected.every((relative) => migrated.has(relative));
909
955
  }, "verifyMigratedData");
910
956
  migrateStorageData = /* @__PURE__ */ __name(async (from, to) => {
911
- const fs7 = getSyncFs();
912
- if (!fs7) throw new exports.DotMemStorageLocationError("Storage migration requires filesystem access, which is unavailable in this runtime.");
957
+ const fs9 = getSyncFs();
958
+ if (!fs9) throw new exports.DotMemStorageLocationError("Storage migration requires filesystem access, which is unavailable in this runtime.");
913
959
  const fsPromises = await nodeFsPromises();
914
- for (const relative of collectRelativeEntries(fs7, from)) {
960
+ for (const relative of collectRelativeEntries(fs9, from)) {
915
961
  const source = joinStoragePath(from, ...relative.split("/"));
916
962
  const destination = joinStoragePath(to, ...relative.split("/"));
917
963
  await fsPromises.mkdir(parentStoragePath(destination), { recursive: true });
@@ -932,10 +978,10 @@ var init_storage_location = __esm({
932
978
  await fsPromises.rename(temporary, locatorFile);
933
979
  }, "writeStorageLocator");
934
980
  clearMigratedSource = /* @__PURE__ */ __name(async (root, removeRoot) => {
935
- const fs7 = getSyncFs();
936
- if (!fs7) return;
981
+ const fs9 = getSyncFs();
982
+ if (!fs9) return;
937
983
  const fsPromises = await nodeFsPromises();
938
- for (const relative of collectRelativeEntries(fs7, root)) {
984
+ for (const relative of collectRelativeEntries(fs9, root)) {
939
985
  await fsPromises.rm(joinStoragePath(root, ...relative.split("/")), { recursive: true, force: true }).catch(() => void 0);
940
986
  }
941
987
  if (removeRoot && root !== resolveUserAnchor()) {
@@ -943,11 +989,11 @@ var init_storage_location = __esm({
943
989
  }
944
990
  }, "clearMigratedSource");
945
991
  writeSettingsFile = /* @__PURE__ */ __name(async (file, transform) => {
946
- const fs7 = getSyncFs();
947
- if (!fs7) throw new exports.DotMemStorageLocationError("Writing storage settings requires filesystem access, which is unavailable in this runtime.");
992
+ const fs9 = getSyncFs();
993
+ if (!fs9) throw new exports.DotMemStorageLocationError("Writing storage settings requires filesystem access, which is unavailable in this runtime.");
948
994
  let document = {};
949
995
  try {
950
- const raw = fs7.readFileSync(file, "utf8");
996
+ const raw = fs9.readFileSync(file, "utf8");
951
997
  const parsed = JSON.parse(raw);
952
998
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("not an object");
953
999
  document = parsed;
@@ -1702,8 +1748,8 @@ __export(brain_exports, {
1702
1748
  });
1703
1749
  async function brainLoad(brainPath) {
1704
1750
  try {
1705
- const fs7 = await nodeFs();
1706
- const raw = await fs7.readFile(brainPath, "utf8");
1751
+ const fs9 = await nodeFs();
1752
+ const raw = await fs9.readFile(brainPath, "utf8");
1707
1753
  const doc = JSON.parse(raw);
1708
1754
  if (doc.format !== "dotmem.brain" || doc.version !== 1) return emptyBrain();
1709
1755
  if (!Array.isArray(doc.relationships)) return emptyBrain();
@@ -1713,26 +1759,26 @@ async function brainLoad(brainPath) {
1713
1759
  }
1714
1760
  }
1715
1761
  async function brainSave(brainPath, document) {
1716
- const fs7 = await nodeFs();
1762
+ const fs9 = await nodeFs();
1717
1763
  const dir = brainPath.includes("/") ? brainPath.slice(0, brainPath.lastIndexOf("/")) : brainPath.includes("\\") ? brainPath.slice(0, brainPath.lastIndexOf("\\")) : ".";
1718
- await fs7.mkdir(dir, { recursive: true });
1764
+ await fs9.mkdir(dir, { recursive: true });
1719
1765
  const tmp = `${brainPath}.${process.pid}.${Date.now().toString(36)}.tmp`;
1720
1766
  try {
1721
- await fs7.writeFile(tmp, JSON.stringify(document, null, 2));
1722
- await fs7.rename(tmp, brainPath);
1767
+ await fs9.writeFile(tmp, JSON.stringify(document, null, 2));
1768
+ await fs9.rename(tmp, brainPath);
1723
1769
  } catch (error) {
1724
- await fs7.rm(tmp, { force: true }).catch(() => void 0);
1770
+ await fs9.rm(tmp, { force: true }).catch(() => void 0);
1725
1771
  throw error;
1726
1772
  }
1727
1773
  }
1728
1774
  async function getBrainDocument() {
1729
- const path5 = getBrainPath();
1730
- cachedBrainPath = path5;
1731
- return brainLoad(path5);
1775
+ const path8 = getBrainPath();
1776
+ cachedBrainPath = path8;
1777
+ return brainLoad(path8);
1732
1778
  }
1733
1779
  async function saveBrainDocument(document) {
1734
- const path5 = cachedBrainPath || getBrainPath();
1735
- await brainSave(path5, document);
1780
+ const path8 = cachedBrainPath || getBrainPath();
1781
+ await brainSave(path8, document);
1736
1782
  }
1737
1783
  function resetBrainPathCache() {
1738
1784
  cachedBrainPath = null;
@@ -1888,11 +1934,11 @@ var init_state = __esm({
1888
1934
  }
1889
1935
  for (let index = 0; index < evidence.length; index++) {
1890
1936
  const entry = evidence[index];
1891
- const path5 = `evidence[${index}]`;
1937
+ const path8 = `evidence[${index}]`;
1892
1938
  if (Array.isArray(entry)) {
1893
1939
  throw canonicalEvidenceError({
1894
1940
  claimId: claim.id,
1895
- path: path5,
1941
+ path: path8,
1896
1942
  problem: CANONICAL_EVIDENCE_PROBLEMS.tupleEntry,
1897
1943
  received: entry,
1898
1944
  fix: CANONICAL_EVIDENCE_FIX.tupleEntry
@@ -1901,7 +1947,7 @@ var init_state = __esm({
1901
1947
  if (!entry || typeof entry !== "object") {
1902
1948
  throw canonicalEvidenceError({
1903
1949
  claimId: claim.id,
1904
- path: path5,
1950
+ path: path8,
1905
1951
  problem: CANONICAL_EVIDENCE_PROBLEMS.nonObjectEntry,
1906
1952
  received: entry,
1907
1953
  fix: CANONICAL_EVIDENCE_FIX.nonObjectEntry
@@ -1910,7 +1956,7 @@ var init_state = __esm({
1910
1956
  if (!requiredText(entry.id)) {
1911
1957
  throw canonicalEvidenceError({
1912
1958
  claimId: claim.id,
1913
- path: `${path5}.id`,
1959
+ path: `${path8}.id`,
1914
1960
  problem: CANONICAL_EVIDENCE_PROBLEMS.missingId,
1915
1961
  received: entry,
1916
1962
  fix: CANONICAL_EVIDENCE_FIX.missingId
@@ -1921,7 +1967,7 @@ var init_state = __esm({
1921
1967
  if (fieldValue !== void 0 && !requiredText(fieldValue)) {
1922
1968
  throw canonicalEvidenceError({
1923
1969
  claimId: claim.id,
1924
- path: `${path5}.${field}`,
1970
+ path: `${path8}.${field}`,
1925
1971
  problem: CANONICAL_EVIDENCE_PROBLEMS.invalidOptionalField(field),
1926
1972
  received: fieldValue,
1927
1973
  fix: CANONICAL_EVIDENCE_FIX.invalidOptionalField(field)
@@ -2271,6 +2317,50 @@ var init_scope_eligibility = __esm({
2271
2317
  }
2272
2318
  });
2273
2319
 
2320
+ // core/knowledge/currentness.ts
2321
+ var asRecord, verifiedAtOf, findContestedIds, deriveCurrentness;
2322
+ var init_currentness = __esm({
2323
+ "core/knowledge/currentness.ts"() {
2324
+ asRecord = /* @__PURE__ */ __name((value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0, "asRecord");
2325
+ verifiedAtOf = /* @__PURE__ */ __name((claim) => {
2326
+ const value = asRecord(claim.knowledge)?.verifiedAt;
2327
+ if (typeof value !== "string") return void 0;
2328
+ const parsed = Date.parse(value);
2329
+ return Number.isNaN(parsed) ? void 0 : parsed;
2330
+ }, "verifiedAtOf");
2331
+ findContestedIds = /* @__PURE__ */ __name((claims) => {
2332
+ const retracting = /* @__PURE__ */ new Map();
2333
+ for (const claim of claims) {
2334
+ if (claim.revision?.kind === "retracts" && claim.revision.claimIds.length > 0) {
2335
+ retracting.set(claim.id, new Set(claim.revision.claimIds));
2336
+ }
2337
+ }
2338
+ const contested = /* @__PURE__ */ new Set();
2339
+ for (const [id, targets] of retracting) {
2340
+ for (const target of targets) {
2341
+ if (retracting.get(target)?.has(id)) {
2342
+ contested.add(id);
2343
+ contested.add(target);
2344
+ }
2345
+ }
2346
+ }
2347
+ return contested;
2348
+ }, "findContestedIds");
2349
+ deriveCurrentness = /* @__PURE__ */ __name((claim, context2 = {}) => {
2350
+ const now2 = context2.now ?? Date.now();
2351
+ if (context2.contestedIds?.has(claim.id)) return "contested";
2352
+ if (claim.revision?.kind === "retracts") return "historical";
2353
+ if (context2.retractedIds?.has(claim.id)) return "historical";
2354
+ if (context2.supersededIds?.has(claim.id)) return "superseded";
2355
+ if (claim.expiresAt !== void 0 && now2 >= claim.expiresAt) return "expired";
2356
+ const verifiedAt = verifiedAtOf(claim);
2357
+ if (verifiedAt !== void 0) return "verified";
2358
+ if (claim.epistemicType === "verified") return "unverified";
2359
+ return "unknown-currentness";
2360
+ }, "deriveCurrentness");
2361
+ }
2362
+ });
2363
+
2274
2364
  // core/knowledge/discover.ts
2275
2365
  var diagnostic, DEFAULT_LIMITS, FIELD_ORDER, FIELD_WEIGHT, normalize, discoveryTerms, jsonText, fieldText, acquiredTime, isExpired, rankCandidate, discoverAcquiredExperience;
2276
2366
  var init_discover = __esm({
@@ -2278,6 +2368,7 @@ var init_discover = __esm({
2278
2368
  init_state();
2279
2369
  init_applicability();
2280
2370
  init_scope_eligibility();
2371
+ init_currentness();
2281
2372
  init_env();
2282
2373
  diagnostic = /* @__PURE__ */ __name((message) => {
2283
2374
  if (typeof process !== "undefined" && typeof process.stderr?.write === "function") {
@@ -2390,11 +2481,82 @@ var init_discover = __esm({
2390
2481
  throw new Error("Discovery maxCandidates must be a positive integer");
2391
2482
  }
2392
2483
  const queryTerms = discoveryTerms(situation);
2484
+ const offset = options.cursor?.offset ?? 0;
2485
+ if (!Number.isInteger(offset) || offset < 0) {
2486
+ throw new Error("Discovery cursor offset must be a non-negative integer");
2487
+ }
2488
+ if (options.cursor && options.cursor.knowledgeVersion !== validated.version) {
2489
+ return {
2490
+ knowledgeVersion: validated.version,
2491
+ depth,
2492
+ queryTerms,
2493
+ candidates: [],
2494
+ omissions: [],
2495
+ offset: 0,
2496
+ snapshotChanged: true
2497
+ };
2498
+ }
2393
2499
  const available = activeClaims(validated);
2500
+ const availableIds = new Set(available.map((claim) => claim.id));
2501
+ const retractedIds = /* @__PURE__ */ new Set();
2502
+ const supersededIds = /* @__PURE__ */ new Set();
2503
+ const contestedIds = findContestedIds(validated.claims);
2504
+ for (const claim of validated.claims) {
2505
+ if (claim.revision?.kind === "retracts") {
2506
+ for (const id of claim.revision.claimIds) retractedIds.add(id);
2507
+ }
2508
+ if (claim.revision?.kind === "supersedes") {
2509
+ for (const id of claim.revision.claimIds) supersededIds.add(id);
2510
+ }
2511
+ }
2512
+ const revisionOmissions = validated.claims.filter((claim) => !availableIds.has(claim.id)).map((claim) => {
2513
+ const retracted = retractedIds.has(claim.id);
2514
+ const superseded = supersededIds.has(claim.id);
2515
+ return {
2516
+ id: claim.id,
2517
+ reason: retracted ? "retracted" : superseded ? "superseded" : "retracted",
2518
+ gate: "revision-resolution",
2519
+ ...retracted || superseded ? {} : { detail: "the claim itself retracts prior knowledge and is kept as history" }
2520
+ };
2521
+ }).sort((left, right) => left.id.localeCompare(right.id));
2394
2522
  const scopeEligible = options.currentProjectId === void 0 ? available : available.filter((claim) => isScopeEligible(claim, options.currentProjectId, sources.get(claim.id)));
2395
2523
  const freshEligible = scopeEligible.filter((claim) => !isExpired(claim));
2524
+ const scopeEligibleIds = new Set(scopeEligible.map((claim) => claim.id));
2525
+ const scopeOmissions = available.filter((claim) => !scopeEligibleIds.has(claim.id)).map((claim) => {
2526
+ const owner = claimOwnerProject(claim, sources.get(claim.id));
2527
+ return {
2528
+ id: claim.id,
2529
+ reason: "scope",
2530
+ gate: "scope",
2531
+ detail: owner === void 0 ? "owner project could not be resolved" : `owned by project ${owner}`
2532
+ };
2533
+ }).sort((left, right) => left.id.localeCompare(right.id));
2534
+ const freshIds = new Set(freshEligible.map((claim) => claim.id));
2535
+ const freshnessOmissions = scopeEligible.filter((claim) => !freshIds.has(claim.id)).map((claim) => ({
2536
+ id: claim.id,
2537
+ reason: "expired",
2538
+ gate: "freshness",
2539
+ detail: `expired at ${new Date(claim.expiresAt).toISOString()}`
2540
+ })).sort((left, right) => left.id.localeCompare(right.id));
2396
2541
  const situationApplicability = deriveSituationApplicability(situation, options.facts);
2397
- const eligible = freshEligible.map((claim) => ({ claim, match: isEligibleByApplicability(claim, situationApplicability) })).filter((candidate) => candidate.match.eligible);
2542
+ const applicabilityMatches = new Map(
2543
+ freshEligible.map((claim) => [claim.id, isEligibleByApplicability(claim, situationApplicability)])
2544
+ );
2545
+ const eligible = freshEligible.map((claim) => ({ claim, match: applicabilityMatches.get(claim.id) })).filter((candidate) => candidate.match.eligible);
2546
+ const eligibleForContext = options.includeRules === true ? eligible : eligible.filter((candidate) => {
2547
+ const knowledge = candidate.claim.knowledge;
2548
+ return !(knowledge && typeof knowledge === "object" && !Array.isArray(knowledge) && knowledge.kind === "rule");
2549
+ });
2550
+ const applicabilityOmissions = freshEligible.filter((claim) => !applicabilityMatches.get(claim.id).eligible).map((claim) => {
2551
+ const match = applicabilityMatches.get(claim.id);
2552
+ const mismatched = Object.entries(match.dimensions).filter(([, state3]) => state3 === "MISMATCH").map(([dimension]) => dimension);
2553
+ return {
2554
+ id: claim.id,
2555
+ reason: "applicability-mismatch",
2556
+ gate: "applicability",
2557
+ detail: `mismatching dimensions: ${mismatched.length > 0 ? mismatched.join(", ") : "none recorded"}`
2558
+ };
2559
+ }).sort((left, right) => left.id.localeCompare(right.id));
2398
2560
  if (DEV) {
2399
2561
  diagnostic(
2400
2562
  "[dotmem discovery] ACTIVE=" + JSON.stringify(
@@ -2406,12 +2568,15 @@ var init_discover = __esm({
2406
2568
  )
2407
2569
  );
2408
2570
  }
2571
+ const currentnessOf = /* @__PURE__ */ __name((claim) => deriveCurrentness(claim, { retractedIds, supersededIds, contestedIds }), "currentnessOf");
2409
2572
  if (queryTerms.length === 0) {
2410
- const baseline = eligible.filter((candidate) => candidate.claim.applicability?.baseline === true).map((candidate) => candidate.claim).sort((left, right) => {
2573
+ const baselineAll = eligibleForContext.filter((candidate) => candidate.claim.applicability?.baseline === true).map((candidate) => candidate.claim).sort((left, right) => {
2411
2574
  const leftTime = acquiredTime(left);
2412
2575
  const rightTime = acquiredTime(right);
2413
2576
  return rightTime - leftTime || Number(right.scope === "project") - Number(left.scope === "project") || left.id.localeCompare(right.id);
2414
- }).slice(0, maxCandidates);
2577
+ });
2578
+ const baseline = baselineAll.slice(offset, offset + maxCandidates);
2579
+ const limitOmissions = baselineAll.slice(offset + maxCandidates).map((claim) => ({ id: claim.id, reason: "limit", gate: "ranking" })).sort((left, right) => left.id.localeCompare(right.id));
2415
2580
  const baselineCandidates = baseline.map((claim) => {
2416
2581
  const explanation = {
2417
2582
  matchedTerms: [],
@@ -2424,7 +2589,8 @@ var init_discover = __esm({
2424
2589
  }
2425
2590
  return {
2426
2591
  claim,
2427
- explanation
2592
+ explanation,
2593
+ currentness: currentnessOf(claim)
2428
2594
  };
2429
2595
  });
2430
2596
  if (DEV) {
@@ -2437,10 +2603,18 @@ var init_discover = __esm({
2437
2603
  depth,
2438
2604
  queryTerms,
2439
2605
  situationApplicability,
2440
- candidates: baselineCandidates
2606
+ candidates: baselineCandidates,
2607
+ offset,
2608
+ omissions: [
2609
+ ...revisionOmissions,
2610
+ ...scopeOmissions,
2611
+ ...freshnessOmissions,
2612
+ ...applicabilityOmissions,
2613
+ ...limitOmissions
2614
+ ]
2441
2615
  };
2442
2616
  }
2443
- const candidates = eligible.map(
2617
+ const ranked = eligibleForContext.map(
2444
2618
  (candidate) => rankCandidate(
2445
2619
  candidate.claim,
2446
2620
  situation,
@@ -2452,16 +2626,40 @@ var init_discover = __esm({
2452
2626
  (candidate) => candidate !== null
2453
2627
  ).sort(
2454
2628
  (left, right) => Number(right.directPhrase) - Number(left.directPhrase) || right.matchedTermCount - left.matchedTermCount || right.fieldWeight - left.fieldWeight || Number(right.claim.scope === "project") - Number(left.claim.scope === "project") || right.acquiredTime - left.acquiredTime || left.claim.id.localeCompare(right.claim.id)
2455
- ).slice(0, maxCandidates).map(({ claim, explanation }) => ({
2629
+ );
2630
+ const rankedIds = new Set(ranked.map((candidate) => candidate.claim.id));
2631
+ const rankingOmissions = [
2632
+ ...eligibleForContext.filter((candidate) => !rankedIds.has(candidate.claim.id)).map((candidate) => ({
2633
+ id: candidate.claim.id,
2634
+ reason: "no-term-match",
2635
+ gate: "ranking",
2636
+ detail: "passed every gate but shares no query term"
2637
+ })),
2638
+ ...ranked.slice(offset + maxCandidates).map((candidate) => ({
2639
+ id: candidate.claim.id,
2640
+ reason: "limit",
2641
+ gate: "ranking"
2642
+ }))
2643
+ ].sort((left, right) => left.id.localeCompare(right.id));
2644
+ const candidates = ranked.slice(offset, offset + maxCandidates).map(({ claim, explanation }) => ({
2456
2645
  claim,
2457
- explanation
2646
+ explanation,
2647
+ currentness: currentnessOf(claim)
2458
2648
  }));
2459
2649
  return {
2460
2650
  knowledgeVersion: validated.version,
2461
2651
  depth,
2462
2652
  queryTerms,
2463
2653
  situationApplicability,
2464
- candidates
2654
+ candidates,
2655
+ offset,
2656
+ omissions: [
2657
+ ...revisionOmissions,
2658
+ ...scopeOmissions,
2659
+ ...freshnessOmissions,
2660
+ ...applicabilityOmissions,
2661
+ ...rankingOmissions
2662
+ ]
2465
2663
  };
2466
2664
  }, "discoverAcquiredExperience");
2467
2665
  }
@@ -2730,9 +2928,9 @@ var init_policy_namespace_lock = __esm({
2730
2928
  acquiredAt: (/* @__PURE__ */ new Date()).toISOString(),
2731
2929
  token: `lock-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`
2732
2930
  }), "createOwner");
2733
- readLockOwner = /* @__PURE__ */ __name(async (fs7, lockPath) => {
2931
+ readLockOwner = /* @__PURE__ */ __name(async (fs9, lockPath) => {
2734
2932
  try {
2735
- const raw = await fs7.readFile(lockPath, "utf8");
2933
+ const raw = await fs9.readFile(lockPath, "utf8");
2736
2934
  const parsed = JSON.parse(raw);
2737
2935
  if (!parsed || typeof parsed !== "object") return null;
2738
2936
  return {
@@ -2745,11 +2943,11 @@ var init_policy_namespace_lock = __esm({
2745
2943
  return null;
2746
2944
  }
2747
2945
  }, "readLockOwner");
2748
- acquireLock = /* @__PURE__ */ __name(async (fs7, lockPath, owner) => {
2946
+ acquireLock = /* @__PURE__ */ __name(async (fs9, lockPath, owner) => {
2749
2947
  let brokenOwner = null;
2750
2948
  for (let attempt = 0; attempt <= POLICY_LOCK_RETRY_ATTEMPTS; attempt++) {
2751
2949
  try {
2752
- await fs7.writeFile(lockPath, JSON.stringify(owner), { encoding: "utf8", flag: "wx" });
2950
+ await fs9.writeFile(lockPath, JSON.stringify(owner), { encoding: "utf8", flag: "wx" });
2753
2951
  return brokenOwner;
2754
2952
  } catch (error) {
2755
2953
  const code = error?.code;
@@ -2758,12 +2956,12 @@ var init_policy_namespace_lock = __esm({
2758
2956
  `Policy namespace exclusive creation is not verifiable on this substrate (${String(code)}); policy mutation fails closed`
2759
2957
  );
2760
2958
  }
2761
- const held = await readLockOwner(fs7, lockPath);
2959
+ const held = await readLockOwner(fs9, lockPath);
2762
2960
  const acquiredAt = held ? Date.parse(held.acquiredAt) : Number.NaN;
2763
2961
  const age = Number.isFinite(acquiredAt) ? Date.now() - acquiredAt : Number.POSITIVE_INFINITY;
2764
2962
  if (age > POLICY_LOCK_TTL_MS) {
2765
2963
  const stale = held ?? { pid: 0, host: "unknown", acquiredAt: "", token: "" };
2766
- const outcome = await breakStalePolicyLock(fs7, lockPath, stale);
2964
+ const outcome = await breakStalePolicyLock(fs9, lockPath, stale);
2767
2965
  if (outcome === "broken") {
2768
2966
  brokenOwner = stale;
2769
2967
  }
@@ -2782,21 +2980,21 @@ var init_policy_namespace_lock = __esm({
2782
2980
  `Policy namespace lock could not be acquired after ${POLICY_LOCK_RETRY_ATTEMPTS} bounded retries; policy mutation fails closed`
2783
2981
  );
2784
2982
  }, "acquireLock");
2785
- breakStalePolicyLock = /* @__PURE__ */ __name(async (fs7, lockPath, staleOwner) => {
2983
+ breakStalePolicyLock = /* @__PURE__ */ __name(async (fs9, lockPath, staleOwner) => {
2786
2984
  const candidate = `${lockPath}.breaking-${staleOwner.token || "unknown"}`;
2787
2985
  try {
2788
- await fs7.rename(lockPath, candidate);
2986
+ await fs9.rename(lockPath, candidate);
2789
2987
  } catch (error) {
2790
2988
  if (error.code === "ENOENT") return "lost";
2791
2989
  throw error;
2792
2990
  }
2793
- const moved = await readLockOwner(fs7, candidate);
2991
+ const moved = await readLockOwner(fs9, candidate);
2794
2992
  if (moved && moved.token === staleOwner.token) {
2795
- await fs7.rm(candidate, { force: true }).catch(() => void 0);
2993
+ await fs9.rm(candidate, { force: true }).catch(() => void 0);
2796
2994
  return "broken";
2797
2995
  }
2798
2996
  try {
2799
- await fs7.link(candidate, lockPath);
2997
+ await fs9.link(candidate, lockPath);
2800
2998
  } catch (error) {
2801
2999
  const code = error?.code;
2802
3000
  if (code !== "EEXIST") {
@@ -2805,22 +3003,22 @@ var init_policy_namespace_lock = __esm({
2805
3003
  );
2806
3004
  }
2807
3005
  }
2808
- await fs7.rm(candidate, { force: true }).catch(() => void 0);
3006
+ await fs9.rm(candidate, { force: true }).catch(() => void 0);
2809
3007
  return "lost";
2810
3008
  }, "breakStalePolicyLock");
2811
- releaseLock = /* @__PURE__ */ __name(async (fs7, lockPath, owner) => {
2812
- const held = await readLockOwner(fs7, lockPath);
3009
+ releaseLock = /* @__PURE__ */ __name(async (fs9, lockPath, owner) => {
3010
+ const held = await readLockOwner(fs9, lockPath);
2813
3011
  if (!held || held.token !== owner.token) return;
2814
- await fs7.rm(lockPath, { force: true }).catch(() => void 0);
3012
+ await fs9.rm(lockPath, { force: true }).catch(() => void 0);
2815
3013
  }, "releaseLock");
2816
3014
  withPolicyNamespaceLock = /* @__PURE__ */ __name(async (operation, options = {}) => {
2817
3015
  const directory = options.directory ?? resolveUserPolicyDir();
2818
3016
  const lockPath = resolvePolicyNamespaceLockPath(directory);
2819
3017
  return enqueue(directory, async () => {
2820
- const fs7 = await nodeFs2();
3018
+ const fs9 = await nodeFs2();
2821
3019
  const owner = await createOwner();
2822
- await fs7.mkdir(parentDirectoryOf(lockPath), { recursive: true }).catch(() => void 0);
2823
- const brokenOwner = await acquireLock(fs7, lockPath, owner);
3020
+ await fs9.mkdir(parentDirectoryOf(lockPath), { recursive: true }).catch(() => void 0);
3021
+ const brokenOwner = await acquireLock(fs9, lockPath, owner);
2824
3022
  if (brokenOwner && options.onLockBreak) {
2825
3023
  options.onLockBreak({
2826
3024
  at: (/* @__PURE__ */ new Date()).toISOString(),
@@ -2831,7 +3029,7 @@ var init_policy_namespace_lock = __esm({
2831
3029
  try {
2832
3030
  return await operation({
2833
3031
  assertOwnership: /* @__PURE__ */ __name(async () => {
2834
- const held = await readLockOwner(fs7, lockPath);
3032
+ const held = await readLockOwner(fs9, lockPath);
2835
3033
  if (!held || held.token !== owner.token) {
2836
3034
  throw new PolicyNamespaceLockError(
2837
3035
  "Policy namespace lock ownership was lost before commit; policy mutation fails closed"
@@ -2840,7 +3038,7 @@ var init_policy_namespace_lock = __esm({
2840
3038
  }, "assertOwnership")
2841
3039
  });
2842
3040
  } finally {
2843
- await releaseLock(fs7, lockPath, owner);
3041
+ await releaseLock(fs9, lockPath, owner);
2844
3042
  }
2845
3043
  });
2846
3044
  }, "withPolicyNamespaceLock");
@@ -3168,35 +3366,35 @@ var init_policy_store = __esm({
3168
3366
  }
3169
3367
  /** Read one namespace document: always fresh, always validated. */
3170
3368
  async load(namespace2) {
3171
- const fs7 = await nodeFs3();
3172
- return this.readDocument(fs7, namespace2);
3369
+ const fs9 = await nodeFs3();
3370
+ return this.readDocument(fs9, namespace2);
3173
3371
  }
3174
- async readDocument(fs7, namespace2) {
3372
+ async readDocument(fs9, namespace2) {
3175
3373
  let raw;
3176
3374
  try {
3177
- raw = await fs7.readFile(this.filePath(namespace2), "utf8");
3375
+ raw = await fs9.readFile(this.filePath(namespace2), "utf8");
3178
3376
  } catch (error) {
3179
3377
  if (error.code === "ENOENT") return emptyPolicyDocument();
3180
3378
  throw error;
3181
3379
  }
3182
3380
  return validatePolicyDocument(JSON.parse(raw));
3183
3381
  }
3184
- async writeDocument(fs7, namespace2, document) {
3185
- await fs7.mkdir(this.dir(), { recursive: true });
3382
+ async writeDocument(fs9, namespace2, document) {
3383
+ await fs9.mkdir(this.dir(), { recursive: true });
3186
3384
  const filePath = this.filePath(namespace2);
3187
3385
  const temporary = `${filePath}.${process.pid}.${Date.now().toString(36)}.tmp`;
3188
3386
  try {
3189
- await fs7.writeFile(temporary, `${JSON.stringify(document, null, 2)}
3387
+ await fs9.writeFile(temporary, `${JSON.stringify(document, null, 2)}
3190
3388
  `, "utf8");
3191
- const handle = await fs7.open(temporary, "r+");
3389
+ const handle = await fs9.open(temporary, "r+");
3192
3390
  try {
3193
3391
  await handle.sync();
3194
3392
  } finally {
3195
3393
  await handle.close();
3196
3394
  }
3197
- await fs7.rename(temporary, filePath);
3395
+ await fs9.rename(temporary, filePath);
3198
3396
  } catch (error) {
3199
- await fs7.rm(temporary, { force: true }).catch(() => void 0);
3397
+ await fs9.rm(temporary, { force: true }).catch(() => void 0);
3200
3398
  throw error;
3201
3399
  }
3202
3400
  }
@@ -3215,8 +3413,8 @@ var init_policy_store = __esm({
3215
3413
  const lockBreaks = [];
3216
3414
  try {
3217
3415
  return await withPolicyNamespaceLock(async (session2) => {
3218
- const fs7 = await nodeFs3();
3219
- const document = await this.readDocument(fs7, namespace2);
3416
+ const fs9 = await nodeFs3();
3417
+ const document = await this.readDocument(fs9, namespace2);
3220
3418
  if (options.basedOnRevision !== void 0 && options.basedOnRevision !== document.revision) {
3221
3419
  throw new PolicyStoreError(
3222
3420
  `Stale policy revision: caller expected ${options.basedOnRevision}, current document revision is ${document.revision}`
@@ -3237,7 +3435,7 @@ var init_policy_store = __esm({
3237
3435
  }
3238
3436
  validatePolicyDocument(next);
3239
3437
  await session2.assertOwnership();
3240
- await this.writeDocument(fs7, namespace2, next);
3438
+ await this.writeDocument(fs9, namespace2, next);
3241
3439
  return outcome.result;
3242
3440
  }, { directory, onLockBreak: /* @__PURE__ */ __name((lockBreak) => {
3243
3441
  lockBreaks.push(lockBreak);
@@ -3518,7 +3716,7 @@ var init_policy_store = __esm({
3518
3716
  });
3519
3717
 
3520
3718
  // core/knowledge/acquisition-limits.ts
3521
- var MEMORY_ACQUIRE_LIMITS, MEMORY_ACQUIRE_LIMITS_MCP, MEMORY_STORE_LIMITS, DOTMEM_ACQUIRE_ERROR_CODES, MemoryAcquireLimitError, MemoryAcquireConcurrencyError, MemoryAcquireDuplicateClaimError, encoder, serializedBytes, measureKnowledge, checkAcquireLimits;
3719
+ var MEMORY_ACQUIRE_LIMITS, MEMORY_ACQUIRE_LIMITS_MCP, MEMORY_STORE_LIMITS, DOTMEM_ACQUIRE_ERROR_CODES, MemoryAcquireLimitError, MemoryAcquireConcurrencyError, MemoryAcquireDuplicateClaimError, encoder2, serializedBytes, measureKnowledge, checkAcquireLimits;
3522
3720
  var init_acquisition_limits = __esm({
3523
3721
  "core/knowledge/acquisition-limits.ts"() {
3524
3722
  MEMORY_ACQUIRE_LIMITS = Object.freeze({
@@ -3577,10 +3775,10 @@ var init_acquisition_limits = __esm({
3577
3775
  this.name = "MemoryAcquireDuplicateClaimError";
3578
3776
  }
3579
3777
  };
3580
- encoder = new TextEncoder();
3778
+ encoder2 = new TextEncoder();
3581
3779
  serializedBytes = /* @__PURE__ */ __name((value) => {
3582
3780
  const json = JSON.stringify(value);
3583
- return json === void 0 ? 0 : encoder.encode(json).length;
3781
+ return json === void 0 ? 0 : encoder2.encode(json).length;
3584
3782
  }, "serializedBytes");
3585
3783
  measureKnowledge = /* @__PURE__ */ __name((knowledge) => {
3586
3784
  const claimBytes = serializedBytes(knowledge);
@@ -3611,6 +3809,74 @@ var init_acquisition_limits = __esm({
3611
3809
  }
3612
3810
  });
3613
3811
 
3812
+ // core/knowledge/verification.ts
3813
+ var deriveTrustBasis, buildVerificationRecord, callerInjectedVerificationMetadata, isCallerDeclaredVerified;
3814
+ var init_verification = __esm({
3815
+ "core/knowledge/verification.ts"() {
3816
+ deriveTrustBasis = /* @__PURE__ */ __name((claim, options = {}) => {
3817
+ const { packageAuth, externalAttestation, verificationRecord, resolvedEvidence } = options;
3818
+ const evidenceCount = Array.isArray(claim.evidence) ? claim.evidence.length : 0;
3819
+ const resolvedIds = resolvedEvidence ?? /* @__PURE__ */ new Set();
3820
+ const evidenceResolved = evidenceCount > 0 && resolvedIds.size === evidenceCount;
3821
+ const mechanicallyChecked = verificationRecord !== null && verificationRecord !== void 0 && verificationRecord.verifyStatus === "valid";
3822
+ const externallyAttested = packageAuth !== void 0 && packageAuth.status === "valid" && externalAttestation !== void 0 && externalAttestation.validated === true;
3823
+ if (externallyAttested) {
3824
+ return {
3825
+ basis: "externally-attested",
3826
+ reason: "Package signature is cryptographically valid and an external attestation was validated by a trusted mechanism",
3827
+ evidenceResolved,
3828
+ mechanicallyChecked,
3829
+ externallyAttested: true
3830
+ };
3831
+ }
3832
+ if (mechanicallyChecked) {
3833
+ return {
3834
+ basis: "mechanically-checked",
3835
+ reason: `A ${verificationRecord.check.kind} check executed by ${verificationRecord.verifiedBy} at ${verificationRecord.verifiedAt} succeeded; status bounded to ${verificationRecord.verifyStatus}`,
3836
+ evidenceResolved,
3837
+ mechanicallyChecked: true,
3838
+ externallyAttested: false
3839
+ };
3840
+ }
3841
+ if (evidenceCount > 0) {
3842
+ return {
3843
+ basis: "evidenced",
3844
+ reason: `${evidenceCount} evidence reference(s) present but not independently resolved and validated`,
3845
+ evidenceResolved: false,
3846
+ mechanicallyChecked: false,
3847
+ externallyAttested: false
3848
+ };
3849
+ }
3850
+ const declaredLabel = claim.epistemicType === "verified" ? ` (stored label ${claim.epistemicType})` : "";
3851
+ return {
3852
+ basis: "declared",
3853
+ reason: `Caller/author assertion without independent validation${declaredLabel}. Trust follows provenance, not the label.`,
3854
+ evidenceResolved: false,
3855
+ mechanicallyChecked: false,
3856
+ externallyAttested: false
3857
+ };
3858
+ }, "deriveTrustBasis");
3859
+ buildVerificationRecord = /* @__PURE__ */ __name((claimId, probe) => {
3860
+ if (probe.status !== "valid") return null;
3861
+ return {
3862
+ verifiedAt: (/* @__PURE__ */ new Date()).toISOString(),
3863
+ verifiedBy: "dotmem-verify",
3864
+ verifyStatus: probe.status,
3865
+ check: { kind: probe.kind, target: probe.target }
3866
+ };
3867
+ }, "buildVerificationRecord");
3868
+ callerInjectedVerificationMetadata = /* @__PURE__ */ __name((knowledge) => {
3869
+ if (!knowledge || typeof knowledge !== "object" || Array.isArray(knowledge)) return [];
3870
+ const keys = [];
3871
+ for (const key of ["verifiedAt", "verifiedBy", "verifyStatus"]) {
3872
+ if (key in knowledge) keys.push(key);
3873
+ }
3874
+ return keys;
3875
+ }, "callerInjectedVerificationMetadata");
3876
+ isCallerDeclaredVerified = /* @__PURE__ */ __name((value) => value === "verified", "isCallerDeclaredVerified");
3877
+ }
3878
+ });
3879
+
3614
3880
  // core/knowledge/acquisition-boundary.ts
3615
3881
  exports.MEMORY_ACQUIRE_EVENT = void 0; exports.crossAcquisitionBoundary = void 0;
3616
3882
  var init_acquisition_boundary = __esm({
@@ -3620,6 +3886,7 @@ var init_acquisition_boundary = __esm({
3620
3886
  init_policy_store();
3621
3887
  init_applicability();
3622
3888
  init_acquisition_limits();
3889
+ init_verification();
3623
3890
  exports.MEMORY_ACQUIRE_EVENT = "memory.acquire";
3624
3891
  if (!(exports.MEMORY_ACQUIRE_EVENT in CANONICAL_EVENTS)) {
3625
3892
  throw new Error(
@@ -3629,6 +3896,12 @@ var init_acquisition_boundary = __esm({
3629
3896
  exports.crossAcquisitionBoundary = /* @__PURE__ */ __name(async (opts, dependencies = {}) => {
3630
3897
  const limits = dependencies.limits ?? MEMORY_ACQUIRE_LIMITS;
3631
3898
  checkAcquireLimits(opts.knowledge, limits);
3899
+ const injected = callerInjectedVerificationMetadata(opts.knowledge);
3900
+ if (injected.length > 0) {
3901
+ throw new Error(
3902
+ `Claim ${opts.id} rejected at write time: caller-supplied verification metadata is not accepted: ${injected.join(", ")}`
3903
+ );
3904
+ }
3632
3905
  const sanitized = sanitizeKnowledge(opts.knowledge);
3633
3906
  if (sanitized.disposition === "reject") {
3634
3907
  throw new Error(
@@ -3675,10 +3948,11 @@ var init_context_constants = __esm({
3675
3948
  });
3676
3949
 
3677
3950
  // core/knowledge/project.ts
3678
- var FORMAT, STATUS, NOTICE, DEFAULT_MAX_CANDIDATES, DEFAULT_MAX_CHARACTERS, MIN_MAX_CHARACTERS, projectCandidate, GIST_MAX_LENGTH, GIST_KEYS, deriveIndexTopic, deriveIndexStatus, deriveGist, renderHeader, renderExperience, renderText, projectDiscoveredExperience, renderContextIndex, renderSizeDisclosure, renderProfileDocuments;
3951
+ var FORMAT, STATUS, NOTICE, DEFAULT_MAX_CANDIDATES, DEFAULT_MAX_CHARACTERS, MIN_MAX_CHARACTERS, projectCandidate, GIST_MAX_LENGTH, GIST_KEYS, MANIFEST_ID_LIMIT, deriveIndexTopic, deriveIndexStatus, deriveGist, renderHeader, renderExperience, renderText, byteLength, summarizeOmissions, renderManifestFitting, renderCompactExperience, projectDiscoveredExperience, renderContextIndex, renderExpandedClaim, renderSizeDisclosure, renderProfileDocuments;
3679
3952
  var init_project = __esm({
3680
3953
  "core/knowledge/project.ts"() {
3681
3954
  init_state();
3955
+ init_verification();
3682
3956
  init_user_paths();
3683
3957
  init_discover();
3684
3958
  init_context_constants();
@@ -3690,21 +3964,41 @@ var init_project = __esm({
3690
3964
  MIN_MAX_CHARACTERS = DOTMEM_CONTEXT_DEFAULT_MIN_MAX__CHARACTERS;
3691
3965
  projectCandidate = /* @__PURE__ */ __name((candidate) => {
3692
3966
  const claim = validateClaim(candidate.claim);
3967
+ const verificationRecord = claim.knowledge && typeof claim.knowledge === "object" && !Array.isArray(claim.knowledge) && claim.knowledge.verifiedBy === "dotmem-verify" && claim.knowledge.verifyStatus === "valid" && typeof claim.knowledge.verifiedAt === "string" ? {
3968
+ verifiedAt: String(claim.knowledge.verifiedAt),
3969
+ verifiedBy: "dotmem-verify",
3970
+ verifyStatus: String(claim.knowledge.verifyStatus),
3971
+ check: { kind: "probe", target: claim.id }
3972
+ } : null;
3973
+ const derivation = deriveTrustBasis(claim, {
3974
+ verificationRecord,
3975
+ resolvedEvidence: new Set(claim.evidence.map((evidence) => evidence.id).filter((id) => id.length > 0))
3976
+ });
3977
+ const trustBasis = {
3978
+ trustBasis: derivation.basis,
3979
+ evidenceResolved: derivation.evidenceResolved,
3980
+ mechanicallyChecked: derivation.mechanicallyChecked,
3981
+ externallyAttested: derivation.externallyAttested,
3982
+ evidenceResolution: claim.evidence.map((evidence) => ({ id: evidence.id, resolved: false }))
3983
+ };
3693
3984
  return structuredClone({
3694
3985
  id: claim.id,
3695
3986
  status: "prior-acquired-experience-candidate",
3696
3987
  experience: claim.knowledge,
3697
3988
  applicability: claim.applicability,
3698
- evidence: claim.evidence,
3989
+ evidence: claim.evidence.map((evidence) => ({ ...evidence, resolved: false })),
3699
3990
  ...claim.epistemicType ? { epistemicType: claim.epistemicType } : {},
3700
3991
  ...claim.provenance ? { provenance: claim.provenance } : {},
3701
3992
  ...claim.acquiredAt ? { acquiredAt: claim.acquiredAt } : {},
3702
3993
  ...claim.revision ? { revision: claim.revision } : {},
3703
- ...candidate.explanation.sourceId ? { sourceId: candidate.explanation.sourceId } : {}
3994
+ ...candidate.explanation.sourceId ? { sourceId: candidate.explanation.sourceId } : {},
3995
+ ...candidate.currentness ? { currentness: candidate.currentness } : {},
3996
+ trustBasis
3704
3997
  });
3705
3998
  }, "projectCandidate");
3706
3999
  GIST_MAX_LENGTH = 80;
3707
4000
  GIST_KEYS = ["gist", "summary", "statement", "title", "reason", "principle", "finding", "detail"];
4001
+ MANIFEST_ID_LIMIT = 40;
3708
4002
  deriveIndexTopic = /* @__PURE__ */ __name((applicability) => {
3709
4003
  const topic = applicability.topic;
3710
4004
  if (typeof topic === "string" && topic.length > 0) return topic;
@@ -3754,27 +4048,72 @@ var init_project = __esm({
3754
4048
  evidence.supports ?? null
3755
4049
  ]),
3756
4050
  ...experience.epistemicType ? { epistemic: experience.epistemicType } : {},
4051
+ ...experience.currentness ? { currentness: experience.currentness } : {},
3757
4052
  ...experience.provenance ? { provenance: [experience.provenance.source, experience.provenance.detail ?? null] } : {},
3758
4053
  ...experience.acquiredAt ? { acquiredAt: experience.acquiredAt } : {},
3759
4054
  ...experience.revision ? { revision: experience.revision } : {},
3760
- ...experience.sourceId ? { source: experience.sourceId } : {}
4055
+ ...experience.sourceId ? { source: experience.sourceId } : {},
4056
+ ...experience.trustBasis ? { trustBasis: experience.trustBasis } : {}
3761
4057
  }), "renderExperience");
3762
- renderText = /* @__PURE__ */ __name((header, experiences, omittedCandidates) => `${header}${experiences.length ? `
3763
- ${experiences.map(renderExperience).join("\n")}` : ""}
3764
- OMITTED:${omittedCandidates}`, "renderText");
4058
+ renderText = /* @__PURE__ */ __name((header, experiences, omittedCandidates, manifest, render = renderExperience, currentnessSummary) => {
4059
+ const lines = [header];
4060
+ if (experiences.length > 0) lines.push(...experiences.map(render));
4061
+ lines.push(`OMITTED:${omittedCandidates}`);
4062
+ if (manifest && manifest.byReason.length > 0) {
4063
+ lines.push(`OMITTED_BY_REASON:${manifest.byReason.map((entry) => `${entry.reason}=${entry.count}`).join(",")}`);
4064
+ }
4065
+ if (manifest && manifest.items.length > 0) {
4066
+ lines.push(`OMITTED_IDS:${manifest.items.slice(0, MANIFEST_ID_LIMIT).map((item) => item.id).join(",")}`);
4067
+ if (manifest.items.length > MANIFEST_ID_LIMIT) {
4068
+ lines.push(`OMITTED_IDS_TRUNCATED:${manifest.items.length - MANIFEST_ID_LIMIT}`);
4069
+ }
4070
+ }
4071
+ if (currentnessSummary) {
4072
+ lines.push(`CURRENTNESS:${currentnessSummary}`);
4073
+ }
4074
+ return lines.join("\n");
4075
+ }, "renderText");
4076
+ byteLength = /* @__PURE__ */ __name((value) => new TextEncoder().encode(value).length, "byteLength");
4077
+ summarizeOmissions = /* @__PURE__ */ __name((items) => {
4078
+ const counts = /* @__PURE__ */ new Map();
4079
+ for (const item of items) counts.set(item.reason, (counts.get(item.reason) ?? 0) + 1);
4080
+ return [...counts.entries()].map(([reason, count]) => ({ reason, count })).sort((left, right) => left.reason.localeCompare(right.reason));
4081
+ }, "summarizeOmissions");
4082
+ renderManifestFitting = /* @__PURE__ */ __name((header, experiences, omittedCandidates, manifest, maxCharacters, render, currentnessSummary) => {
4083
+ const full = renderText(header, experiences, omittedCandidates, manifest, render, currentnessSummary);
4084
+ if (byteLength(full) <= maxCharacters) return full;
4085
+ const withoutIds = { ...manifest, items: [] };
4086
+ return renderText(header, experiences, omittedCandidates, withoutIds, render, currentnessSummary);
4087
+ }, "renderManifestFitting");
4088
+ renderCompactExperience = /* @__PURE__ */ __name((experience) => JSON.stringify({
4089
+ id: experience.id,
4090
+ status: "candidate",
4091
+ gist: deriveGist(experience.experience),
4092
+ epistemic: experience.epistemicType ?? null,
4093
+ currentness: experience.currentness ?? null,
4094
+ trustBasis: experience.trustBasis?.trustBasis ?? null,
4095
+ ...experience.revision ? { revision: experience.revision.kind } : {}
4096
+ }), "renderCompactExperience");
3765
4097
  projectDiscoveredExperience = /* @__PURE__ */ __name((discovery, options = {}) => {
3766
4098
  if (!discovery || !Number.isInteger(discovery.knowledgeVersion) || discovery.knowledgeVersion < 0 || !Array.isArray(discovery.candidates)) {
3767
4099
  throw new Error("Valid DiscoveryResult is required for context projection");
3768
4100
  }
3769
4101
  const maxCandidates = options.maxCandidates ?? DEFAULT_MAX_CANDIDATES;
3770
4102
  const maxCharacters = options.maxCharacters ?? DEFAULT_MAX_CHARACTERS;
4103
+ const format = options.format ?? "compact";
4104
+ if (format !== "compact" && format !== "standard" && format !== "full") {
4105
+ throw new Error("Projection format must be compact, standard or full");
4106
+ }
3771
4107
  if (!Number.isInteger(maxCandidates) || maxCandidates < 1) throw new Error("Projection maxCandidates must be a positive integer");
3772
4108
  if (!Number.isInteger(maxCharacters) || maxCharacters < MIN_MAX_CHARACTERS) {
3773
4109
  throw new Error(`Projection maxCharacters must be an integer of at least ${MIN_MAX_CHARACTERS}`);
3774
4110
  }
3775
- const totalCandidates = discovery.candidates.length;
4111
+ const render = /* @__PURE__ */ __name((experience) => format === "compact" ? renderCompactExperience(experience) : renderExperience(experience), "render");
4112
+ const gateOmissions = discovery.omissions ?? [];
4113
+ const totalCandidates = discovery.candidates.length + gateOmissions.length;
3776
4114
  const header = renderHeader(discovery.knowledgeVersion, totalCandidates);
3777
- if (renderText(header, [], totalCandidates).length > maxCharacters) {
4115
+ const emptyManifest = { considered: totalCandidates, included: 0, items: [], byReason: [] };
4116
+ if (byteLength(renderText(header, [], totalCandidates, emptyManifest)) > maxCharacters) {
3778
4117
  throw new Error("Projection maxCharacters is too small for the projection envelope");
3779
4118
  }
3780
4119
  const experiences = [];
@@ -3783,12 +4122,49 @@ OMITTED:${omittedCandidates}`, "renderText");
3783
4122
  const projected = projectCandidate(candidate);
3784
4123
  const possibleExperiences = [...experiences, projected];
3785
4124
  const possibleOmitted = totalCandidates - possibleExperiences.length;
3786
- if (renderText(header, possibleExperiences, possibleOmitted).length <= maxCharacters) {
4125
+ const candidateManifest = {
4126
+ considered: totalCandidates,
4127
+ included: possibleExperiences.length,
4128
+ items: gateOmissions,
4129
+ byReason: summarizeOmissions(gateOmissions)
4130
+ };
4131
+ if (byteLength(renderText(header, possibleExperiences, possibleOmitted, candidateManifest, render)) <= maxCharacters) {
4132
+ experiences.push(projected);
4133
+ continue;
4134
+ }
4135
+ if (byteLength(renderText(header, possibleExperiences, possibleOmitted, void 0, render)) <= maxCharacters) {
3787
4136
  experiences.push(projected);
3788
4137
  }
3789
4138
  }
4139
+ const projectedIds = new Set(experiences.map((experience) => experience.id));
4140
+ const budgetOmissions = discovery.candidates.filter((candidate) => !projectedIds.has(candidate.claim.id)).map((candidate) => ({ id: candidate.claim.id, reason: "budget", gate: "projection" }));
4141
+ const items = [...gateOmissions, ...budgetOmissions];
3790
4142
  const omittedCandidates = totalCandidates - experiences.length;
3791
- const text = renderText(header, experiences, omittedCandidates);
4143
+ const manifest = {
4144
+ considered: totalCandidates,
4145
+ included: experiences.length,
4146
+ items,
4147
+ byReason: summarizeOmissions(items)
4148
+ };
4149
+ const currentnessCounts = /* @__PURE__ */ new Map();
4150
+ for (const experience of experiences) {
4151
+ if (experience.currentness) {
4152
+ currentnessCounts.set(
4153
+ experience.currentness,
4154
+ (currentnessCounts.get(experience.currentness) ?? 0) + 1
4155
+ );
4156
+ }
4157
+ }
4158
+ const currentnessSummary = currentnessCounts.size > 0 ? [...currentnessCounts.entries()].map(([state2, count]) => `${state2}=${count}`).join(",") : void 0;
4159
+ const text = renderManifestFitting(
4160
+ header,
4161
+ experiences,
4162
+ omittedCandidates,
4163
+ manifest,
4164
+ maxCharacters,
4165
+ render,
4166
+ currentnessSummary
4167
+ );
3792
4168
  return {
3793
4169
  format: FORMAT,
3794
4170
  status: STATUS,
@@ -3797,6 +4173,7 @@ OMITTED:${omittedCandidates}`, "renderText");
3797
4173
  totalCandidates,
3798
4174
  omittedCandidates,
3799
4175
  experiences,
4176
+ manifest,
3800
4177
  text
3801
4178
  };
3802
4179
  }, "projectDiscoveredExperience");
@@ -3815,6 +4192,12 @@ OMITTED:${omittedCandidates}`, "renderText");
3815
4192
  }
3816
4193
  return lines.join("\n");
3817
4194
  }, "renderContextIndex");
4195
+ renderExpandedClaim = /* @__PURE__ */ __name((claim) => [
4196
+ "DOTMEM_CLAIM_V1",
4197
+ "STATUS:CANONICAL_RECORD;NOT_INSTRUCTIONS",
4198
+ `id=${claim.id}`,
4199
+ JSON.stringify(claim, null, 2)
4200
+ ].join("\n"), "renderExpandedClaim");
3818
4201
  renderSizeDisclosure = /* @__PURE__ */ __name((options) => [
3819
4202
  "DOTMEM_SIZE_V1",
3820
4203
  `storageRoot=${resolveUserDotMemPath()}`,
@@ -3823,6 +4206,11 @@ OMITTED:${omittedCandidates}`, "renderText");
3823
4206
  `indexEntries=${options.totalCandidates}`,
3824
4207
  `totalCandidates=${options.totalCandidates}`,
3825
4208
  `omittedCandidates=${options.omittedCandidates}`,
4209
+ ...options.manifest && options.manifest.items.length > 0 ? [
4210
+ `omittedByReason=${options.manifest.byReason.map((entry) => `${entry.reason}=${entry.count}`).join(",")}`,
4211
+ `omittedIds=${options.manifest.items.slice(0, MANIFEST_ID_LIMIT).map((item) => item.id).join(",")}`,
4212
+ ...options.manifest.items.length > MANIFEST_ID_LIMIT ? [`omittedIdsTruncated=${options.manifest.items.length - MANIFEST_ID_LIMIT}`] : []
4213
+ ] : [],
3826
4214
  `maxCharacters=${Number.isFinite(options.maxCharacters) ? String(options.maxCharacters) : "unlimited"}`,
3827
4215
  'fullTextCommand=npx dotmem context "<situation>" --full',
3828
4216
  "DOTMEM_SIZE_END"
@@ -4006,7 +4394,7 @@ var init_language_detect = __esm({
4006
4394
  var CANONICAL_KINDS, validateKind, buildClaimRecord;
4007
4395
  var init_claim_record = __esm({
4008
4396
  "core/knowledge/claim-record.ts"() {
4009
- CANONICAL_KINDS = ["experience", "logic", "agent", "relationship", "note"];
4397
+ CANONICAL_KINDS = ["experience", "logic", "agent", "relationship", "note", "rule"];
4010
4398
  validateKind = /* @__PURE__ */ __name((kind) => {
4011
4399
  if (!CANONICAL_KINDS.includes(kind)) {
4012
4400
  throw new Error(
@@ -5412,8 +5800,8 @@ var init_browser = __esm({
5412
5800
  this.p = null;
5413
5801
  }
5414
5802
  };
5415
- Unzip2.prototype.register = function(decoder2) {
5416
- this.o[decoder2.compression] = decoder2;
5803
+ Unzip2.prototype.register = function(decoder) {
5804
+ this.o[decoder.compression] = decoder;
5417
5805
  };
5418
5806
  return Unzip2;
5419
5807
  })();
@@ -5433,6 +5821,15 @@ function encodeMemFile(stateValue, preserved) {
5433
5821
  if (!map.claim.includes("kind")) {
5434
5822
  map.claim.push("kind");
5435
5823
  }
5824
+ if (!map.claim.includes("expires-at")) {
5825
+ map.claim.push("expires-at");
5826
+ }
5827
+ if (!map.claim.includes("bootstrap-priority")) {
5828
+ map.claim.push("bootstrap-priority");
5829
+ }
5830
+ if (!map.claim.includes("check")) {
5831
+ map.claim.push("check");
5832
+ }
5436
5833
  const indexes = Object.fromEntries(Object.keys(expectedFields).map((name) => [name, fieldIndexes(map, name)]));
5437
5834
  validateVocabulary(map.epistemicType, epistemicTypes, "epistemicType");
5438
5835
  validateVocabulary(map.revisionKind, revisionKinds, "revisionKind");
@@ -5482,6 +5879,15 @@ function encodeMemFile(stateValue, preserved) {
5482
5879
  if (indexes.claim.has("kind")) {
5483
5880
  putOptional(record, indexes.claim, "kind", claim.kind ?? void 0, original !== void 0);
5484
5881
  }
5882
+ if (indexes.claim.has("expires-at")) {
5883
+ putOptional(record, indexes.claim, "expires-at", claim.expiresAt, original !== void 0);
5884
+ }
5885
+ if (indexes.claim.has("bootstrap-priority")) {
5886
+ putOptional(record, indexes.claim, "bootstrap-priority", claim.bootstrapPriority, original !== void 0);
5887
+ }
5888
+ if (indexes.claim.has("check")) {
5889
+ putOptional(record, indexes.claim, "check", claim.check, original !== void 0);
5890
+ }
5485
5891
  return original ? record : trimRecord(record);
5486
5892
  }, "encodeClaim");
5487
5893
  const stateRecord = structuredClone(preserved?.data ?? []);
@@ -5550,8 +5956,37 @@ function decodeMemDocument(value) {
5550
5956
  const scope = optionalGet(record, indexes.claim, "scope");
5551
5957
  const sourceProject = optionalGet(record, indexes.claim, "source-project");
5552
5958
  const kindValue = optionalGet(record, indexes.claim, "kind");
5959
+ const expiresAtValue = indexes.claim.has("expires-at") ? optionalGet(record, indexes.claim, "expires-at") : void 0;
5960
+ const bootstrapPriorityValue = indexes.claim.has("bootstrap-priority") ? optionalGet(record, indexes.claim, "bootstrap-priority") : void 0;
5961
+ const checkValue = indexes.claim.has("check") ? optionalGet(record, indexes.claim, "check") : void 0;
5553
5962
  if (epistemicIndex !== void 0 && (!Number.isInteger(epistemicIndex) || epistemicIndex < 0 || epistemicIndex >= epistemic.length)) throw new Error("Invalid .mem epistemic value");
5554
5963
  if (kindIndex !== void 0 && (!Number.isInteger(kindIndex) || kindIndex < 0 || kindIndex >= revisions.length)) throw new Error("Invalid .mem revision value");
5964
+ if (expiresAtValue !== void 0 && (!Number.isInteger(expiresAtValue) || expiresAtValue < 0)) {
5965
+ throw new Error("Invalid .mem expiresAt value");
5966
+ }
5967
+ if (bootstrapPriorityValue !== void 0 && !bootstrapPriorities.includes(bootstrapPriorityValue)) {
5968
+ throw new Error("Invalid .mem bootstrapPriority value");
5969
+ }
5970
+ let check;
5971
+ if (checkValue !== void 0) {
5972
+ if (!checkValue || typeof checkValue !== "object" || Array.isArray(checkValue)) {
5973
+ throw new Error("Invalid .mem check record");
5974
+ }
5975
+ const checkRecord = checkValue;
5976
+ const description = checkRecord.description;
5977
+ if (typeof description !== "undefined" && typeof description !== "string") {
5978
+ throw new Error("Invalid .mem check record");
5979
+ }
5980
+ if (checkRecord.kind !== "regex" || typeof checkRecord.pattern !== "string" || checkRecord.pattern.length === 0 || !checkTargets.includes(checkRecord.on)) {
5981
+ throw new Error("Invalid .mem check record");
5982
+ }
5983
+ check = {
5984
+ kind: "regex",
5985
+ pattern: checkRecord.pattern,
5986
+ on: checkRecord.on,
5987
+ ...typeof description === "string" ? { description } : {}
5988
+ };
5989
+ }
5555
5990
  const understoodEpistemic = typeof epistemicIndex === "number" && epistemicTypes.includes(epistemic[epistemicIndex]) ? epistemic[epistemicIndex] : void 0;
5556
5991
  const understoodRevision = typeof kindIndex === "number" && revisionKinds.includes(revisions[kindIndex]);
5557
5992
  const claim = {
@@ -5576,6 +6011,9 @@ function decodeMemDocument(value) {
5576
6011
  } : {},
5577
6012
  ...scope === void 0 ? {} : { scope },
5578
6013
  ...sourceProject === void 0 ? {} : { sourceProject },
6014
+ ...expiresAtValue === void 0 ? {} : { expiresAt: expiresAtValue },
6015
+ ...bootstrapPriorityValue === void 0 ? {} : { bootstrapPriority: bootstrapPriorityValue },
6016
+ ...check === void 0 ? {} : { check },
5579
6017
  ...claimKinds.includes(kindValue) ? { kind: kindValue } : {}
5580
6018
  };
5581
6019
  return validateClaim(claim);
@@ -5585,7 +6023,7 @@ function decodeMemDocument(value) {
5585
6023
  preserved: { map: structuredClone(map), data: structuredClone(stateRecord) }
5586
6024
  };
5587
6025
  }
5588
- var MEM_FORMAT, MEM_FORMAT_LEGACY, MEM_FORMAT_VERSION, MEM_FORMAT_VERSION_V1, expectedFields, epistemicTypes, revisionKinds, claimKinds, isJsonValue2, createMemInterpretationMap, validateSourceState, trimRecord, fieldIndexes, validateVocabulary, put, get, optionalGet, requireRecord, putOptional;
6026
+ var MEM_FORMAT, MEM_FORMAT_LEGACY, MEM_FORMAT_VERSION, MEM_FORMAT_VERSION_V1, expectedFields, epistemicTypes, revisionKinds, claimKinds, bootstrapPriorities, checkTargets, isJsonValue2, createMemInterpretationMap, validateSourceState, trimRecord, fieldIndexes, validateVocabulary, put, get, optionalGet, requireRecord, putOptional;
5589
6027
  var init_mem_codec = __esm({
5590
6028
  "core/knowledge/mem-codec.ts"() {
5591
6029
  init_state();
@@ -5602,7 +6040,9 @@ var init_mem_codec = __esm({
5602
6040
  };
5603
6041
  epistemicTypes = ["observed", "inferred", "human-stated", "verified"];
5604
6042
  revisionKinds = ["refines", "supersedes", "retracts"];
5605
- claimKinds = ["experience", "agent", "relationship", "logic", "note"];
6043
+ claimKinds = ["experience", "agent", "relationship", "logic", "note", "rule"];
6044
+ bootstrapPriorities = ["P1", "P2", "P3", "P4", "P5", "unclassified"];
6045
+ checkTargets = ["staged", "committed", "working-tree"];
5606
6046
  isJsonValue2 = /* @__PURE__ */ __name((value) => {
5607
6047
  if (value === null || typeof value === "string" || typeof value === "boolean") return true;
5608
6048
  if (typeof value === "number") return Number.isFinite(value);
@@ -5682,8 +6122,8 @@ async function signMemPackage(input, privateKey, publicKey) {
5682
6122
  const artifact = await decodePackage(input);
5683
6123
  const rawPublicKey = new Uint8Array(await crypto.subtle.exportKey("raw", publicKey));
5684
6124
  const keyId = await keyIdentity(rawPublicKey);
5685
- const path5 = signaturePath(keyId);
5686
- const existingSignatures = { ...artifact.package?.signatures, [path5]: jsonBytes({}) };
6125
+ const path8 = signaturePath(keyId);
6126
+ const existingSignatures = { ...artifact.package?.signatures, [path8]: jsonBytes({}) };
5687
6127
  const declaredPackage = await encodePackage(artifact.state, artifact.preserved, artifact.package, existingSignatures);
5688
6128
  const declaredArtifact = await decodePackage(declaredPackage);
5689
6129
  const signature = new Uint8Array(await crypto.subtle.sign(
@@ -5702,18 +6142,18 @@ async function signMemPackage(input, privateKey, publicKey) {
5702
6142
  };
5703
6143
  return encodePackage(artifact.state, artifact.preserved, artifact.package, {
5704
6144
  ...artifact.package?.signatures,
5705
- [path5]: jsonBytes(document)
6145
+ [path8]: jsonBytes(document)
5706
6146
  });
5707
6147
  }
5708
6148
  async function decodeMemArtifact(input) {
5709
- const bytes = typeof input === "string" ? encoder2.encode(input) : input;
6149
+ const bytes = typeof input === "string" ? encoder3.encode(input) : input;
5710
6150
  if (isZip(bytes)) {
5711
6151
  const { parts: _parts, integrity: _integrity, ...artifact } = await decodePackage(bytes);
5712
6152
  return artifact;
5713
6153
  }
5714
6154
  let value;
5715
6155
  try {
5716
- value = JSON.parse(decoder.decode(bytes).replace(/^\uFEFF/, ""));
6156
+ value = JSON.parse(decodeText(bytes));
5717
6157
  } catch (error) {
5718
6158
  throw new MemArtifactError("corrupt", `Unsupported or corrupt MEM artifact: ${error.message}`);
5719
6159
  }
@@ -5728,13 +6168,13 @@ async function decodeMemArtifact(input) {
5728
6168
  }
5729
6169
  async function inspectMem(input) {
5730
6170
  try {
5731
- const bytes = typeof input === "string" ? encoder2.encode(input) : input;
6171
+ const bytes = typeof input === "string" ? encodeText(input) : input;
5732
6172
  if (isZip(bytes)) {
5733
6173
  const artifact2 = await decodePackage(bytes);
5734
6174
  const knownMapKeys = /* @__PURE__ */ new Set(["state", "claim", "evidence", "provenance", "revision", "epistemicType", "revisionKind"]);
5735
6175
  const unknownMapEntries = Object.keys(artifact2.preserved?.map ?? {}).filter((key) => !knownMapKeys.has(key)).length;
5736
6176
  const vocabularyEntries = Math.max(0, (artifact2.preserved?.map.epistemicType.length ?? 4) - 4) + Math.max(0, (artifact2.preserved?.map.revisionKind.length ?? 3) - 3);
5737
- const signatures = await Promise.all(Object.entries(artifact2.package?.signatures ?? {}).sort(([left], [right]) => left.localeCompare(right)).map(([path5, part]) => verifySignature(path5, part, artifact2.integrity.contentId)));
6177
+ const signatures = await Promise.all(Object.entries(artifact2.package?.signatures ?? {}).sort(([left], [right]) => left.localeCompare(right)).map(([path8, part]) => verifySignature(path8, part, artifact2.integrity.contentId)));
5738
6178
  const authenticityStatus = signatures.length === 0 ? "unsigned" : signatures.some((signature) => signature.status === "invalid") ? "invalid" : signatures.some((signature) => signature.status === "unsupported") ? "unsupported" : "valid";
5739
6179
  return {
5740
6180
  status: "valid",
@@ -5743,10 +6183,10 @@ async function inspectMem(input) {
5743
6183
  packageVersion: MEM_PACKAGE_VERSION,
5744
6184
  memoryVersion: MEM_FORMAT_VERSION,
5745
6185
  contentId: artifact2.integrity.contentId,
5746
- parts: Object.entries(artifact2.parts).sort(([a], [b]) => a.localeCompare(b)).map(([path5, part]) => ({
5747
- path: path5,
6186
+ parts: Object.entries(artifact2.parts).sort(([a], [b]) => a.localeCompare(b)).map(([path8, part]) => ({
6187
+ path: path8,
5748
6188
  bytes: part.length,
5749
- protected: path5 !== INTEGRITY_PATH && !path5.startsWith("security/signatures/")
6189
+ protected: path8 !== INTEGRITY_PATH && !path8.startsWith("security/signatures/")
5750
6190
  })),
5751
6191
  knowledge: artifact2.state,
5752
6192
  unknownSemantics: { mapEntries: unknownMapEntries, vocabularyEntries, extensionParts: Object.keys(artifact2.package?.extensions ?? {}).sort() },
@@ -5769,11 +6209,12 @@ async function inspectMem(input) {
5769
6209
  return { status: artifactError.code, representation: "unknown", message: artifactError.message, parts: [] };
5770
6210
  }
5771
6211
  }
5772
- var MEM_PACKAGE_FORMAT, MEM_PACKAGE_FORMAT_LEGACY, MEM_PACKAGE_VERSION, MEM_PACKAGE_LIMITS, MEM_PACKAGE_WRITE_MARGIN_BYTES, MEM_PACKAGE_WRITE_LIMITS, MANIFEST_PATH, MAP_PATH, DATA_PATH, INTEGRITY_PATH, requiredParts, encoder2, decoder, MemArtifactError, stableValue, jsonBytes, sha256, parseJson, validEntryPath, concatenate, readZipParts, createManifest, digestTableIdentity, signaturePayload, base64UrlEncode, base64UrlDecode, keyIdentity, signaturePath, encodePackage, isZip, decodePackage, verifySignature;
6212
+ var MEM_PACKAGE_FORMAT, MEM_PACKAGE_FORMAT_LEGACY, MEM_PACKAGE_VERSION, MEM_PACKAGE_LIMITS, MEM_PACKAGE_WRITE_MARGIN_BYTES, MEM_PACKAGE_WRITE_LIMITS, MANIFEST_PATH, MAP_PATH, DATA_PATH, INTEGRITY_PATH, requiredParts, encoder3, MemArtifactError, stableValue, jsonBytes, sha256, parseJson, validEntryPath, concatenate, readZipParts, createManifest, digestTableIdentity, signaturePayload, base64UrlEncode, base64UrlDecode, keyIdentity, signaturePath, encodePackage, isZip, decodePackage, verifySignature;
5773
6213
  var init_mem_package = __esm({
5774
6214
  "core/knowledge/mem-package.ts"() {
5775
6215
  init_browser();
5776
6216
  init_mem_codec();
6217
+ init_text_encoding();
5777
6218
  MEM_PACKAGE_FORMAT = "dotmem.package";
5778
6219
  MEM_PACKAGE_FORMAT_LEGACY = "memorio.package";
5779
6220
  MEM_PACKAGE_VERSION = 1;
@@ -5797,8 +6238,7 @@ var init_mem_package = __esm({
5797
6238
  DATA_PATH = "memory/data.json";
5798
6239
  INTEGRITY_PATH = "security/integrity.json";
5799
6240
  requiredParts = [MANIFEST_PATH, MAP_PATH, DATA_PATH];
5800
- encoder2 = new TextEncoder();
5801
- decoder = new TextDecoder("utf-8", { fatal: true });
6241
+ encoder3 = new TextEncoder();
5802
6242
  MemArtifactError = class extends Error {
5803
6243
  constructor(code, message) {
5804
6244
  super(message);
@@ -5817,21 +6257,21 @@ var init_mem_package = __esm({
5817
6257
  }
5818
6258
  return value;
5819
6259
  }, "stableValue");
5820
- jsonBytes = /* @__PURE__ */ __name((value) => encoder2.encode(`${JSON.stringify(stableValue(value), null, 2)}
6260
+ jsonBytes = /* @__PURE__ */ __name((value) => encoder3.encode(`${JSON.stringify(stableValue(value), null, 2)}
5821
6261
  `), "jsonBytes");
5822
6262
  sha256 = /* @__PURE__ */ __name(async (data) => {
5823
6263
  if (!globalThis.crypto?.subtle) throw new MemArtifactError("unsupported", "SHA-256 is unavailable in this runtime");
5824
6264
  const digest = await globalThis.crypto.subtle.digest("SHA-256", data);
5825
6265
  return `sha256:${[...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
5826
6266
  }, "sha256");
5827
- parseJson = /* @__PURE__ */ __name((bytes, path5) => {
6267
+ parseJson = /* @__PURE__ */ __name((bytes, path8) => {
5828
6268
  try {
5829
- return JSON.parse(decoder.decode(bytes));
6269
+ return JSON.parse(decodeText(bytes));
5830
6270
  } catch (error) {
5831
- throw new MemArtifactError("invalid", `Invalid UTF-8 JSON in ${path5}: ${error.message}`);
6271
+ throw new MemArtifactError("invalid", `Invalid UTF-8 JSON in ${path8}: ${error.message}`);
5832
6272
  }
5833
6273
  }, "parseJson");
5834
- validEntryPath = /* @__PURE__ */ __name((path5) => path5.length > 0 && path5.length <= 240 && !path5.includes("\\") && !path5.startsWith("/") && !/^[A-Za-z]:/.test(path5) && path5.split("/").every((segment) => segment.length > 0 && segment !== "." && segment !== ".."), "validEntryPath");
6274
+ validEntryPath = /* @__PURE__ */ __name((path8) => path8.length > 0 && path8.length <= 240 && !path8.includes("\\") && !path8.startsWith("/") && !/^[A-Za-z]:/.test(path8) && path8.split("/").every((segment) => segment.length > 0 && segment !== "." && segment !== ".."), "validEntryPath");
5835
6275
  concatenate = /* @__PURE__ */ __name((chunks, size) => {
5836
6276
  const result = new Uint8Array(size);
5837
6277
  let offset = 0;
@@ -5892,7 +6332,7 @@ var init_mem_package = __esm({
5892
6332
  parts: { map: MAP_PATH, data: DATA_PATH, integrity: INTEGRITY_PATH }
5893
6333
  }), "createManifest");
5894
6334
  digestTableIdentity = /* @__PURE__ */ __name((files) => sha256(jsonBytes(files)), "digestTableIdentity");
5895
- signaturePayload = /* @__PURE__ */ __name((contentId) => encoder2.encode(`DOTMEM-PACKAGE-SIGNATURE-V1
6335
+ signaturePayload = /* @__PURE__ */ __name((contentId) => encoder3.encode(`DOTMEM-PACKAGE-SIGNATURE-V1
5896
6336
  ${contentId}
5897
6337
  `), "signaturePayload");
5898
6338
  base64UrlEncode = /* @__PURE__ */ __name((value) => {
@@ -5923,31 +6363,31 @@ ${contentId}
5923
6363
  [DATA_PATH]: jsonBytes(memory2.data),
5924
6364
  ...structuredClone(preservedPackage?.extensions ?? {})
5925
6365
  };
5926
- for (const path5 of Object.keys(protectedParts)) {
5927
- if (!requiredParts.includes(path5) && !path5.startsWith("extensions/")) {
5928
- throw new MemArtifactError("invalid", `Unsupported preserved package part: ${path5}`);
6366
+ for (const path8 of Object.keys(protectedParts)) {
6367
+ if (!requiredParts.includes(path8) && !path8.startsWith("extensions/")) {
6368
+ throw new MemArtifactError("invalid", `Unsupported preserved package part: ${path8}`);
5929
6369
  }
5930
- if (!validEntryPath(path5)) throw new MemArtifactError("invalid", `Unsafe MEM package path: ${path5}`);
6370
+ if (!validEntryPath(path8)) throw new MemArtifactError("invalid", `Unsafe MEM package path: ${path8}`);
5931
6371
  }
5932
- for (const path5 of Object.keys(signatures)) {
5933
- if (!/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path5)) {
5934
- throw new MemArtifactError("invalid", `Invalid MEM signature path: ${path5}`);
6372
+ for (const path8 of Object.keys(signatures)) {
6373
+ if (!/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path8)) {
6374
+ throw new MemArtifactError("invalid", `Invalid MEM signature path: ${path8}`);
5935
6375
  }
5936
6376
  }
5937
6377
  const files = {};
5938
- for (const path5 of Object.keys(protectedParts).sort()) files[path5] = await sha256(protectedParts[path5]);
6378
+ for (const path8 of Object.keys(protectedParts).sort()) files[path8] = await sha256(protectedParts[path8]);
5939
6379
  const integrity = { algorithm: "sha256", files, contentId: await digestTableIdentity(files) };
5940
6380
  const parts = { ...protectedParts, [INTEGRITY_PATH]: jsonBytes(integrity), ...signatures };
5941
- for (const [path5, bytes] of Object.entries(parts)) {
6381
+ for (const [path8, bytes] of Object.entries(parts)) {
5942
6382
  if (bytes.length > MEM_PACKAGE_WRITE_LIMITS.maximumEntryBytes) {
5943
- throw new MemArtifactError("invalid", `MEM package entry exceeds the write limit: ${path5}`);
6383
+ throw new MemArtifactError("invalid", `MEM package entry exceeds the write limit: ${path8}`);
5944
6384
  }
5945
6385
  }
5946
6386
  const uncompressedBytes = Object.values(parts).reduce((total, bytes) => total + bytes.length, 0);
5947
6387
  if (uncompressedBytes > MEM_PACKAGE_WRITE_LIMITS.maximumUncompressedBytes) {
5948
6388
  throw new MemArtifactError("invalid", "MEM package exceeds the write limit for uncompressed content");
5949
6389
  }
5950
- const zippable = Object.fromEntries(Object.keys(parts).sort().map((path5) => [path5, [parts[path5], {
6390
+ const zippable = Object.fromEntries(Object.keys(parts).sort().map((path8) => [path8, [parts[path8], {
5951
6391
  level: 6,
5952
6392
  mtime: /* @__PURE__ */ new Date("1980-01-02T00:00:00.000Z")
5953
6393
  }]]));
@@ -5962,8 +6402,8 @@ ${contentId}
5962
6402
  isZip = /* @__PURE__ */ __name((bytes) => bytes.length >= 4 && bytes[0] === 80 && bytes[1] === 75 && (bytes[2] === 3 && bytes[3] === 4 || bytes[2] === 5 && bytes[3] === 6), "isZip");
5963
6403
  decodePackage = /* @__PURE__ */ __name(async (bytes) => {
5964
6404
  const parts = readZipParts(bytes);
5965
- for (const path5 of [...requiredParts, INTEGRITY_PATH]) {
5966
- if (!parts[path5]) throw new MemArtifactError("invalid", `Missing MEM package part: ${path5}`);
6405
+ for (const path8 of [...requiredParts, INTEGRITY_PATH]) {
6406
+ if (!parts[path8]) throw new MemArtifactError("invalid", `Missing MEM package part: ${path8}`);
5967
6407
  }
5968
6408
  const manifest = parseJson(parts[MANIFEST_PATH], MANIFEST_PATH);
5969
6409
  if (manifest.format !== MEM_PACKAGE_FORMAT && manifest.format !== MEM_PACKAGE_FORMAT_LEGACY || manifest.version !== MEM_PACKAGE_VERSION) {
@@ -5974,8 +6414,8 @@ ${contentId}
5974
6414
  }
5975
6415
  const integrity = parseJson(parts[INTEGRITY_PATH], INTEGRITY_PATH);
5976
6416
  if (integrity.algorithm !== "sha256") throw new MemArtifactError("unsupported", "Unsupported MEM package integrity algorithm");
5977
- const signaturePaths = Object.keys(parts).filter((path5) => path5.startsWith("security/signatures/")).sort();
5978
- if (signaturePaths.some((path5) => !/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path5))) {
6417
+ const signaturePaths = Object.keys(parts).filter((path8) => path8.startsWith("security/signatures/")).sort();
6418
+ if (signaturePaths.some((path8) => !/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path8))) {
5979
6419
  throw new MemArtifactError("invalid", "Invalid MEM signature entry path");
5980
6420
  }
5981
6421
  if (manifest.authenticity !== void 0 && manifest.authenticity.signed !== true) {
@@ -5984,14 +6424,14 @@ ${contentId}
5984
6424
  if (manifest.authenticity?.signed === true !== signaturePaths.length > 0) {
5985
6425
  throw new MemArtifactError("invalid", "Declared MEM signatures do not match package entries");
5986
6426
  }
5987
- const archivePaths = Object.keys(parts).filter((path5) => path5 !== INTEGRITY_PATH && !path5.startsWith("security/signatures/")).sort();
6427
+ const archivePaths = Object.keys(parts).filter((path8) => path8 !== INTEGRITY_PATH && !path8.startsWith("security/signatures/")).sort();
5988
6428
  const protectedPaths = Object.keys(integrity.files ?? {}).sort();
5989
6429
  if (JSON.stringify(archivePaths) !== JSON.stringify(protectedPaths)) {
5990
6430
  throw new MemArtifactError("invalid", "MEM package protected-parts table does not match archive contents");
5991
6431
  }
5992
- for (const path5 of protectedPaths) {
5993
- const actual = await sha256(parts[path5]);
5994
- if (integrity.files[path5] !== actual) throw new MemArtifactError("checksum_mismatch", `Checksum mismatch for ${path5}`);
6432
+ for (const path8 of protectedPaths) {
6433
+ const actual = await sha256(parts[path8]);
6434
+ if (integrity.files[path8] !== actual) throw new MemArtifactError("checksum_mismatch", `Checksum mismatch for ${path8}`);
5995
6435
  }
5996
6436
  if (integrity.contentId !== await digestTableIdentity(integrity.files)) {
5997
6437
  throw new MemArtifactError("checksum_mismatch", "MEM package content identity mismatch");
@@ -6004,14 +6444,14 @@ ${contentId}
6004
6444
  } catch (error) {
6005
6445
  throw new MemArtifactError("invalid", `Invalid packaged MEM semantics: ${error.message}`);
6006
6446
  }
6007
- const extensions = Object.fromEntries(Object.entries(parts).filter(([path5]) => path5.startsWith("extensions/")));
6008
- const signatures = Object.fromEntries(signaturePaths.map((path5) => [path5, parts[path5]]));
6447
+ const extensions = Object.fromEntries(Object.entries(parts).filter(([path8]) => path8.startsWith("extensions/")));
6448
+ const signatures = Object.fromEntries(signaturePaths.map((path8) => [path8, parts[path8]]));
6009
6449
  return { ...decoded, representation: "package-v1", package: { manifest, extensions, signatures }, parts, integrity };
6010
6450
  }, "decodePackage");
6011
- verifySignature = /* @__PURE__ */ __name(async (path5, bytes, contentId) => {
6451
+ verifySignature = /* @__PURE__ */ __name(async (path8, bytes, contentId) => {
6012
6452
  let document;
6013
6453
  try {
6014
- document = parseJson(bytes, path5);
6454
+ document = parseJson(bytes, path8);
6015
6455
  } catch (error) {
6016
6456
  return { status: "invalid", message: error.message };
6017
6457
  }
@@ -6043,7 +6483,7 @@ ${contentId}
6043
6483
  const publicKeyBytes = base64UrlDecode(document.publicKey.value);
6044
6484
  const signatureBytes = base64UrlDecode(document.signature.value);
6045
6485
  const derivedKeyId = await keyIdentity(publicKeyBytes);
6046
- if (derivedKeyId !== document.keyId || signaturePath(derivedKeyId) !== path5) {
6486
+ if (derivedKeyId !== document.keyId || signaturePath(derivedKeyId) !== path8) {
6047
6487
  return {
6048
6488
  status: "invalid",
6049
6489
  algorithm: document.algorithm,
@@ -6082,10 +6522,12 @@ ${contentId}
6082
6522
  });
6083
6523
 
6084
6524
  // core/storage-coordinator/index.ts
6085
- var nodeFs4, withStorageLock, readStorageGeneration, writeStorageGeneration;
6525
+ var nodeFs4, heldLocks, withStorageLock, readStorageGeneration, writeStorageGeneration;
6086
6526
  var init_storage_coordinator = __esm({
6087
6527
  "core/storage-coordinator/index.ts"() {
6528
+ init_text_encoding();
6088
6529
  nodeFs4 = /* @__PURE__ */ __name(async () => import('fs/promises'), "nodeFs");
6530
+ heldLocks = /* @__PURE__ */ new Map();
6089
6531
  withStorageLock = /* @__PURE__ */ __name(async (directoryPath, operationOrOptions, operation, _options = {}) => {
6090
6532
  const opts = typeof operationOrOptions === "function" ? operation ?? {} : operationOrOptions ?? {};
6091
6533
  const op = typeof operationOrOptions === "function" ? operationOrOptions : operation;
@@ -6093,14 +6535,23 @@ var init_storage_coordinator = __esm({
6093
6535
  const staleMs = opts.staleMs ?? 6e4;
6094
6536
  const lockName = opts.lockName ?? ".storage.lock";
6095
6537
  const lockPath = `${directoryPath}/${lockName}`;
6096
- const fs7 = await nodeFs4();
6538
+ const fs9 = await nodeFs4();
6097
6539
  const started = Date.now();
6098
- await fs7.mkdir(directoryPath, { recursive: true });
6540
+ const heldDepth = heldLocks.get(lockPath) ?? 0;
6541
+ if (heldDepth > 0) {
6542
+ heldLocks.set(lockPath, heldDepth + 1);
6543
+ try {
6544
+ return await op();
6545
+ } finally {
6546
+ heldLocks.set(lockPath, heldDepth);
6547
+ }
6548
+ }
6549
+ await fs9.mkdir(directoryPath, { recursive: true });
6099
6550
  while (true) {
6100
6551
  try {
6101
- await fs7.mkdir(lockPath);
6552
+ await fs9.mkdir(lockPath);
6102
6553
  const token2 = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
6103
- await fs7.writeFile(`${lockPath}/owner.json`, JSON.stringify({ token: token2, pid: process.pid, createdAt: Date.now() }), { flag: "wx" });
6554
+ await fs9.writeFile(`${lockPath}/owner.json`, JSON.stringify({ token: token2, pid: process.pid, createdAt: Date.now() }), { flag: "wx" });
6104
6555
  break;
6105
6556
  } catch (error) {
6106
6557
  const code = error.code;
@@ -6108,8 +6559,8 @@ var init_storage_coordinator = __esm({
6108
6559
  let stale = false;
6109
6560
  let processDead = false;
6110
6561
  try {
6111
- const raw = await fs7.readFile(`${lockPath}/owner.json`, "utf8");
6112
- const parsed = JSON.parse(raw);
6562
+ const raw = await fs9.readFile(`${lockPath}/owner.json`);
6563
+ const parsed = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` }));
6113
6564
  const ageStale = typeof parsed.createdAt === "number" && Date.now() - parsed.createdAt > staleMs;
6114
6565
  if (typeof parsed.pid === "number") {
6115
6566
  try {
@@ -6127,13 +6578,13 @@ var init_storage_coordinator = __esm({
6127
6578
  if (stale) {
6128
6579
  if (processDead) {
6129
6580
  try {
6130
- await fs7.rm(lockPath, { recursive: true, force: true });
6581
+ await fs9.rm(lockPath, { recursive: true, force: true });
6131
6582
  continue;
6132
6583
  } catch {
6133
6584
  }
6134
6585
  }
6135
6586
  try {
6136
- await fs7.rmdir(lockPath);
6587
+ await fs9.rmdir(lockPath);
6137
6588
  continue;
6138
6589
  } catch {
6139
6590
  }
@@ -6146,40 +6597,42 @@ var init_storage_coordinator = __esm({
6146
6597
  }
6147
6598
  let token = "";
6148
6599
  try {
6149
- const raw = await fs7.readFile(`${lockPath}/owner.json`, "utf8");
6150
- token = JSON.parse(raw).token ?? "";
6600
+ const raw = await fs9.readFile(`${lockPath}/owner.json`);
6601
+ token = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` })).token ?? "";
6151
6602
  } catch {
6152
6603
  token = "";
6153
6604
  }
6154
6605
  try {
6606
+ heldLocks.set(lockPath, 1);
6155
6607
  return await op();
6156
6608
  } finally {
6609
+ heldLocks.delete(lockPath);
6157
6610
  try {
6158
- const raw = await fs7.readFile(`${lockPath}/owner.json`, "utf8");
6159
- const parsed = JSON.parse(raw);
6611
+ const raw = await fs9.readFile(`${lockPath}/owner.json`);
6612
+ const parsed = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` }));
6160
6613
  if (parsed.token === token && token) {
6161
- await fs7.rm(lockPath, { recursive: true, force: true });
6614
+ await fs9.rm(lockPath, { recursive: true, force: true });
6162
6615
  }
6163
6616
  } catch {
6164
6617
  }
6165
6618
  }
6166
6619
  }, "withStorageLock");
6167
6620
  readStorageGeneration = /* @__PURE__ */ __name(async (directoryPath) => {
6168
- const fs7 = await nodeFs4();
6621
+ const fs9 = await nodeFs4();
6169
6622
  try {
6170
- const raw = await fs7.readFile(`${directoryPath}/.storage.generation`, "utf8");
6171
- const value = Number(raw.trim());
6623
+ const raw = await fs9.readFile(`${directoryPath}/.storage.generation`);
6624
+ const value = Number(decodeText(raw, { source: `${directoryPath}/.storage.generation` }).trim());
6172
6625
  return Number.isFinite(value) && value >= 0 ? value : 0;
6173
6626
  } catch {
6174
6627
  return 0;
6175
6628
  }
6176
6629
  }, "readStorageGeneration");
6177
6630
  writeStorageGeneration = /* @__PURE__ */ __name(async (directoryPath, value) => {
6178
- const fs7 = await nodeFs4();
6179
- await fs7.mkdir(directoryPath, { recursive: true });
6631
+ const fs9 = await nodeFs4();
6632
+ await fs9.mkdir(directoryPath, { recursive: true });
6180
6633
  const temp = `${directoryPath}/.storage.generation.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
6181
- await fs7.writeFile(temp, String(value));
6182
- await fs7.rename(temp, `${directoryPath}/.storage.generation`);
6634
+ await fs9.writeFile(temp, String(value));
6635
+ await fs9.rename(temp, `${directoryPath}/.storage.generation`);
6183
6636
  }, "writeStorageGeneration");
6184
6637
  }
6185
6638
  });
@@ -6692,17 +7145,16 @@ function resolveLanguagePath() {
6692
7145
  function resolveLanguagePreferencePath() {
6693
7146
  return resolveUserLanguagePath();
6694
7147
  }
6695
- function readJsonFile(path5) {
6696
- const fs7 = getSyncFs();
6697
- if (!fs7) return null;
7148
+ function readJsonFile(path8) {
7149
+ const fs9 = getSyncFs();
7150
+ if (!fs9) return null;
6698
7151
  let raw;
6699
7152
  try {
6700
- raw = fs7.readFileSync(path5, "utf8");
7153
+ raw = decodeText(fs9.readFileSync(path8), { source: path8 });
6701
7154
  } catch {
6702
7155
  return null;
6703
7156
  }
6704
7157
  if (typeof raw !== "string") return null;
6705
- if (raw.charCodeAt(0) === 65279) raw = raw.slice(1);
6706
7158
  try {
6707
7159
  return JSON.parse(raw);
6708
7160
  } catch {
@@ -6731,9 +7183,9 @@ function extractLanguage(value) {
6731
7183
  return null;
6732
7184
  }
6733
7185
  function loadUserLanguage() {
6734
- const fs7 = getSyncFs();
7186
+ const fs9 = getSyncFs();
6735
7187
  const anchor = resolveUserDotMemPath();
6736
- if (fs7) {
7188
+ if (fs9) {
6737
7189
  for (const name of LANGUAGE_FILE_NAMES) {
6738
7190
  const candidatePath = joinPath3(anchor, name);
6739
7191
  const parsed = readJsonFile(candidatePath);
@@ -6795,14 +7247,14 @@ function getResponseLanguage() {
6795
7247
  }
6796
7248
  async function setUserLanguage(language2) {
6797
7249
  const fsMod = await import('fs/promises');
6798
- const path5 = resolveUserLanguagePath();
6799
- const dir = parentStoragePath(path5);
7250
+ const path8 = resolveUserLanguagePath();
7251
+ const dir = parentStoragePath(path8);
6800
7252
  await fsMod.mkdir(dir, { recursive: true });
6801
7253
  const payload = { format: "dotmem.language", version: 1, language: String(language2).trim() };
6802
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
7254
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
6803
7255
  await fsMod.writeFile(temporary, `${JSON.stringify(payload, null, 2)}
6804
7256
  `, "utf8");
6805
- await fsMod.rename(temporary, path5);
7257
+ await fsMod.rename(temporary, path8);
6806
7258
  return payload.language;
6807
7259
  }
6808
7260
  async function saveUserLanguage(language2) {
@@ -6826,6 +7278,7 @@ var init_user_language = __esm({
6826
7278
  "core/knowledge/user-language.ts"() {
6827
7279
  init_user_paths();
6828
7280
  init_storage_paths();
7281
+ init_text_encoding();
6829
7282
  USER_LANGUAGE_FILE_NAME = "language.json";
6830
7283
  USER_LANGUAGE_PREFERENCE_FILE_NAME = "user-language.json";
6831
7284
  LANGUAGE_PREFERENCE_FILE_NAME = "language-preference.json";
@@ -10376,11 +10829,11 @@ var init_identity_governance = __esm({
10376
10829
  updatedAt: (/* @__PURE__ */ new Date(0)).toISOString()
10377
10830
  }), "defaultIdentityGovernance");
10378
10831
  loadIdentityGovernance = /* @__PURE__ */ __name((canonicalAgentName) => {
10379
- const fs7 = getSyncFs();
10380
- if (!fs7) return defaultIdentityGovernance(canonicalAgentName);
10832
+ const fs9 = getSyncFs();
10833
+ if (!fs9) return defaultIdentityGovernance(canonicalAgentName);
10381
10834
  let raw;
10382
10835
  try {
10383
- raw = fs7.readFileSync(resolveUserIdentityGovernancePath(), "utf8");
10836
+ raw = fs9.readFileSync(resolveUserIdentityGovernancePath(), "utf8");
10384
10837
  } catch {
10385
10838
  return defaultIdentityGovernance(canonicalAgentName);
10386
10839
  }
@@ -10400,19 +10853,19 @@ var init_identity_governance = __esm({
10400
10853
  authority,
10401
10854
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
10402
10855
  });
10403
- const fs7 = getSyncFs();
10404
- if (!fs7) {
10856
+ const fs9 = getSyncFs();
10857
+ if (!fs9) {
10405
10858
  throw new IdentityGovernanceError("Identity governance write requires filesystem access, unavailable in this runtime");
10406
10859
  }
10407
10860
  const filePath = resolveUserIdentityGovernancePath();
10408
- await fs7.promises.mkdir(parentStoragePath(filePath), { recursive: true });
10861
+ await fs9.promises.mkdir(parentStoragePath(filePath), { recursive: true });
10409
10862
  const temporary = `${filePath}.${process.pid}.${Date.now().toString(36)}.tmp`;
10410
10863
  try {
10411
- await fs7.promises.writeFile(temporary, `${JSON.stringify(document, null, 2)}
10864
+ await fs9.promises.writeFile(temporary, `${JSON.stringify(document, null, 2)}
10412
10865
  `, "utf8");
10413
- await fs7.promises.rename(temporary, filePath);
10866
+ await fs9.promises.rename(temporary, filePath);
10414
10867
  } catch (error) {
10415
- await fs7.promises.rm(temporary, { force: true }).catch(() => void 0);
10868
+ await fs9.promises.rm(temporary, { force: true }).catch(() => void 0);
10416
10869
  throw error;
10417
10870
  }
10418
10871
  return document;
@@ -10609,20 +11062,20 @@ var init_detection_journal = __esm({
10609
11062
  }, "validateDetectionJournalDocument");
10610
11063
  appendDetectionJournal = /* @__PURE__ */ __name(async (events) => {
10611
11064
  if (events.length === 0) return;
10612
- const fs7 = getSyncFs();
10613
- if (!fs7) return;
11065
+ const fs9 = getSyncFs();
11066
+ if (!fs9) return;
10614
11067
  await withPolicyNamespaceLock(async () => {
10615
11068
  await appendDetectionJournalUnlocked(events);
10616
11069
  }, { directory: resolveUserPolicyDir() });
10617
11070
  }, "appendDetectionJournal");
10618
11071
  appendDetectionJournalUnlocked = /* @__PURE__ */ __name(async (events) => {
10619
11072
  if (events.length === 0) return;
10620
- const fs7 = getSyncFs();
10621
- if (!fs7) return;
11073
+ const fs9 = getSyncFs();
11074
+ if (!fs9) return;
10622
11075
  const filePath = resolveUserDetectionJournalPath();
10623
11076
  let document = emptyDetectionJournal();
10624
11077
  try {
10625
- const raw = await fs7.promises.readFile(filePath, "utf8");
11078
+ const raw = await fs9.promises.readFile(filePath, "utf8");
10626
11079
  document = validateDetectionJournalDocument(JSON.parse(raw));
10627
11080
  } catch (error) {
10628
11081
  const code = error?.code;
@@ -10636,22 +11089,22 @@ var init_detection_journal = __esm({
10636
11089
  }
10637
11090
  const merged = [...document.events, ...events].slice(-DETECTION_JOURNAL_RETENTION);
10638
11091
  const dir = filePath.slice(0, Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\")));
10639
- await fs7.promises.mkdir(dir, { recursive: true });
11092
+ await fs9.promises.mkdir(dir, { recursive: true });
10640
11093
  const temporary = `${filePath}.${process.pid}.${Date.now().toString(36)}.tmp`;
10641
11094
  try {
10642
- await fs7.promises.writeFile(temporary, `${JSON.stringify({ ...document, events: merged }, null, 2)}
11095
+ await fs9.promises.writeFile(temporary, `${JSON.stringify({ ...document, events: merged }, null, 2)}
10643
11096
  `, "utf8");
10644
- await fs7.promises.rename(temporary, filePath);
11097
+ await fs9.promises.rename(temporary, filePath);
10645
11098
  } catch (error) {
10646
- await fs7.promises.rm(temporary, { force: true }).catch(() => void 0);
11099
+ await fs9.promises.rm(temporary, { force: true }).catch(() => void 0);
10647
11100
  throw error;
10648
11101
  }
10649
11102
  }, "appendDetectionJournalUnlocked");
10650
11103
  loadDetectionJournal = /* @__PURE__ */ __name(async () => {
10651
- const fs7 = getSyncFs();
10652
- if (!fs7) return emptyDetectionJournal();
11104
+ const fs9 = getSyncFs();
11105
+ if (!fs9) return emptyDetectionJournal();
10653
11106
  try {
10654
- const raw = await fs7.promises.readFile(resolveUserDetectionJournalPath(), "utf8");
11107
+ const raw = await fs9.promises.readFile(resolveUserDetectionJournalPath(), "utf8");
10655
11108
  return validateDetectionJournalDocument(JSON.parse(raw));
10656
11109
  } catch {
10657
11110
  return emptyDetectionJournal();
@@ -10727,11 +11180,11 @@ var init_store_queue = __esm({
10727
11180
  async function resolveProjectIdentity(cwd, hints) {
10728
11181
  const explicit = sanitizeIdentity(process.env.DOTMEM_PROJECT_ID);
10729
11182
  if (explicit) return explicit;
10730
- const fs7 = await import('fs/promises');
11183
+ const fs9 = await import('fs/promises');
10731
11184
  const pkgPath = cwd.endsWith("/") || cwd.endsWith("\\") ? `${cwd}package.json` : `${cwd}/package.json`;
10732
11185
  let pkgJson;
10733
11186
  try {
10734
- const content = await fs7.readFile(pkgPath, "utf8");
11187
+ const content = await fs9.readFile(pkgPath, "utf8");
10735
11188
  pkgJson = JSON.parse(content);
10736
11189
  } catch {
10737
11190
  }
@@ -10876,8 +11329,8 @@ var init_staging = __esm({
10876
11329
  };
10877
11330
  const requestId = generateRequestId();
10878
11331
  const stagePath = stagePathFor(requestId);
10879
- const fs7 = await nodeFs6();
10880
- await fs7.mkdir(resolveStagingDirectory(), { recursive: true });
11332
+ const fs9 = await nodeFs6();
11333
+ await fs9.mkdir(resolveStagingDirectory(), { recursive: true });
10881
11334
  const stageFile = {
10882
11335
  format: DOTMEM_STAGE_FORMAT,
10883
11336
  version: DOTMEM_STAGE_VERSION,
@@ -10886,9 +11339,9 @@ var init_staging = __esm({
10886
11339
  ...sourceProject ? { sourceProject } : {},
10887
11340
  claim: sanitizedClaim
10888
11341
  };
10889
- await fs7.writeFile(stagePath, JSON.stringify(stageFile), { mode: 384 });
11342
+ await fs9.writeFile(stagePath, JSON.stringify(stageFile), { mode: 384 });
10890
11343
  try {
10891
- await fs7.access(stagePath);
11344
+ await fs9.access(stagePath);
10892
11345
  } catch {
10893
11346
  throw new StageFileError(`Stage file write verification failed: ${requestId} does not exist on disk`, requestId);
10894
11347
  }
@@ -10896,9 +11349,9 @@ var init_staging = __esm({
10896
11349
  }, "writeStageFile");
10897
11350
  readStageFile = /* @__PURE__ */ __name(async (requestId) => {
10898
11351
  const stagePath = stagePathFor(requestId);
10899
- const fs7 = await nodeFs6();
11352
+ const fs9 = await nodeFs6();
10900
11353
  try {
10901
- const content = await fs7.readFile(stagePath, "utf8");
11354
+ const content = await fs9.readFile(stagePath, "utf8");
10902
11355
  return JSON.parse(content);
10903
11356
  } catch (error) {
10904
11357
  if (error.code === "ENOENT") {
@@ -10981,10 +11434,13 @@ var init_staging = __esm({
10981
11434
  epistemicType: sanitizedClaim.epistemicType,
10982
11435
  provenance: sanitizedClaim.provenance,
10983
11436
  acquiredAt: sanitizedClaim.acquiredAt,
11437
+ ...sanitizedClaim.expiresAt === void 0 ? {} : { expiresAt: sanitizedClaim.expiresAt },
11438
+ ...sanitizedClaim.bootstrapPriority === void 0 ? {} : { bootstrapPriority: sanitizedClaim.bootstrapPriority },
10984
11439
  revision,
10985
11440
  scope,
10986
11441
  sourceProject,
10987
- kind
11442
+ kind,
11443
+ ...sanitizedClaim.check === void 0 ? {} : { check: sanitizedClaim.check }
10988
11444
  });
10989
11445
  await withStoreQueue(acquisitionStoreKey(kind, scope, sourceProject), async () => {
10990
11446
  const state2 = await target.runtime.select([]);
@@ -11008,9 +11464,9 @@ var init_staging = __esm({
11008
11464
  }, "commitStageFile");
11009
11465
  cleanupStageFile = /* @__PURE__ */ __name(async (requestId) => {
11010
11466
  const stagePath = stagePathFor(requestId);
11011
- const fs7 = await nodeFs6();
11467
+ const fs9 = await nodeFs6();
11012
11468
  try {
11013
- await fs7.unlink(stagePath);
11469
+ await fs9.unlink(stagePath);
11014
11470
  } catch (error) {
11015
11471
  if (error.code !== "ENOENT") {
11016
11472
  throw error;
@@ -11019,19 +11475,19 @@ var init_staging = __esm({
11019
11475
  }, "cleanupStageFile");
11020
11476
  cleanupStaleStages = /* @__PURE__ */ __name(async (maxAgeMs = 24 * 60 * 60 * 1e3) => {
11021
11477
  const stagingDir = resolveStagingDirectory();
11022
- const fs7 = await nodeFs6();
11478
+ const fs9 = await nodeFs6();
11023
11479
  let count = 0;
11024
11480
  try {
11025
- const entries2 = await fs7.readdir(stagingDir, { withFileTypes: true });
11481
+ const entries2 = await fs9.readdir(stagingDir, { withFileTypes: true });
11026
11482
  const now2 = Date.now();
11027
11483
  for (const entry of entries2) {
11028
11484
  if (!entry.isFile() || !entry.name.endsWith(".stage")) continue;
11029
11485
  const filePath = `${stagingDir}/${entry.name}`;
11030
11486
  try {
11031
- const stat = await fs7.stat(filePath);
11487
+ const stat = await fs9.stat(filePath);
11032
11488
  const age = now2 - stat.mtimeMs;
11033
11489
  if (age > maxAgeMs) {
11034
- await fs7.unlink(filePath);
11490
+ await fs9.unlink(filePath);
11035
11491
  count++;
11036
11492
  }
11037
11493
  } catch {
@@ -11055,25 +11511,25 @@ function joinPath4(base, child) {
11055
11511
  function resolveLoopsFilePath() {
11056
11512
  return joinPath4(resolveUserDotMemPath(), LOOPS_FILE_NAME);
11057
11513
  }
11058
- async function readFile(path5) {
11514
+ async function readFile(path8) {
11059
11515
  try {
11060
- const fs7 = await import('fs/promises');
11061
- return await fs7.readFile(path5, "utf8");
11516
+ const fs9 = await import('fs/promises');
11517
+ return await fs9.readFile(path8, "utf8");
11062
11518
  } catch {
11063
11519
  return null;
11064
11520
  }
11065
11521
  }
11066
- async function writeFile(path5, content) {
11067
- const fs7 = await import('fs/promises');
11068
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
11069
- await fs7.mkdir(dir, { recursive: true });
11070
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
11522
+ async function writeFile(path8, content) {
11523
+ const fs9 = await import('fs/promises');
11524
+ const dir = path8.replace(/[\\/][^\\/]+$/, "");
11525
+ await fs9.mkdir(dir, { recursive: true });
11526
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
11071
11527
  try {
11072
- await fs7.writeFile(temporary, content, "utf8");
11073
- await fs7.rename(temporary, path5);
11528
+ await fs9.writeFile(temporary, content, "utf8");
11529
+ await fs9.rename(temporary, path8);
11074
11530
  } catch {
11075
- await fs7.rm(temporary, { force: true }).catch(() => void 0);
11076
- throw new Error(`Failed to write loops file at ${path5}`);
11531
+ await fs9.rm(temporary, { force: true }).catch(() => void 0);
11532
+ throw new Error(`Failed to write loops file at ${path8}`);
11077
11533
  }
11078
11534
  }
11079
11535
  function emptyDocument() {
@@ -11494,9 +11950,9 @@ async function getCommittedFiles() {
11494
11950
  return result.stdout.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
11495
11951
  }
11496
11952
  async function getFileContent(filePath) {
11497
- const fs7 = await import('fs/promises');
11953
+ const fs9 = await import('fs/promises');
11498
11954
  try {
11499
- return await fs7.readFile(filePath, "utf8");
11955
+ return await fs9.readFile(filePath, "utf8");
11500
11956
  } catch {
11501
11957
  return null;
11502
11958
  }
@@ -11612,25 +12068,25 @@ function joinPath5(base, child) {
11612
12068
  function resolveVaultFilePath() {
11613
12069
  return joinPath5(resolveUserDotMemPath(), VAULT_FILE_NAME);
11614
12070
  }
11615
- async function readFile2(path5) {
12071
+ async function readFile2(path8) {
11616
12072
  try {
11617
- const fs7 = await import('fs/promises');
11618
- return await fs7.readFile(path5, "utf8");
12073
+ const fs9 = await import('fs/promises');
12074
+ return await fs9.readFile(path8, "utf8");
11619
12075
  } catch {
11620
12076
  return null;
11621
12077
  }
11622
12078
  }
11623
- async function writeFile2(path5, content) {
11624
- const fs7 = await import('fs/promises');
11625
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
11626
- await fs7.mkdir(dir, { recursive: true });
11627
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
12079
+ async function writeFile2(path8, content) {
12080
+ const fs9 = await import('fs/promises');
12081
+ const dir = path8.replace(/[\\/][^\\/]+$/, "");
12082
+ await fs9.mkdir(dir, { recursive: true });
12083
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
11628
12084
  try {
11629
- await fs7.writeFile(temporary, content, "utf8");
11630
- await fs7.rename(temporary, path5);
12085
+ await fs9.writeFile(temporary, content, "utf8");
12086
+ await fs9.rename(temporary, path8);
11631
12087
  } catch {
11632
- await fs7.rm(temporary, { force: true }).catch(() => void 0);
11633
- throw new Error(`Failed to write vault file at ${path5}`);
12088
+ await fs9.rm(temporary, { force: true }).catch(() => void 0);
12089
+ throw new Error(`Failed to write vault file at ${path8}`);
11634
12090
  }
11635
12091
  }
11636
12092
  function emptyDocument2() {
@@ -11748,9 +12204,9 @@ function joinPath6(base, child) {
11748
12204
  return `${base.replace(/[\\/]+/g, separator3)}${separator3}${child}`;
11749
12205
  }
11750
12206
  async function readJsonFile2(filePath, pointer) {
11751
- const fs7 = await import('fs/promises');
12207
+ const fs9 = await import('fs/promises');
11752
12208
  try {
11753
- const content = await fs7.readFile(filePath, "utf8");
12209
+ const content = await fs9.readFile(filePath, "utf8");
11754
12210
  const data = JSON.parse(content);
11755
12211
  const pathParts = pointer.replace(/^\//, "").split("/").filter((p) => p.length > 0);
11756
12212
  let current = data;
@@ -11813,6 +12269,39 @@ async function evaluateClaim(claim) {
11813
12269
  detail: `Value is ${result.valueStr}, expected ${expected}`
11814
12270
  };
11815
12271
  }
12272
+ if (kind === "regex") {
12273
+ const pattern = check.pattern;
12274
+ const target = String(check.expect ?? "");
12275
+ let regex;
12276
+ try {
12277
+ regex = new RegExp(pattern);
12278
+ } catch {
12279
+ return {
12280
+ claimId: claim.id,
12281
+ probe,
12282
+ status: "error",
12283
+ detail: `Invalid regex pattern: ${pattern}`
12284
+ };
12285
+ }
12286
+ if (regex.test(target)) {
12287
+ return {
12288
+ claimId: claim.id,
12289
+ probe,
12290
+ status: "valid",
12291
+ currentValue: target,
12292
+ expectedValue: pattern,
12293
+ detail: `Value matches regex: ${pattern}`
12294
+ };
12295
+ }
12296
+ return {
12297
+ claimId: claim.id,
12298
+ probe,
12299
+ status: "stale",
12300
+ currentValue: target,
12301
+ expectedValue: pattern,
12302
+ detail: `Value does not match regex: ${pattern}`
12303
+ };
12304
+ }
11816
12305
  return {
11817
12306
  claimId: claim.id,
11818
12307
  probe,
@@ -11898,144 +12387,678 @@ function formatVerifyResult(result) {
11898
12387
  }
11899
12388
  return lines.join("\n");
11900
12389
  }
12390
+ function applyVerification(state2, claimId, record) {
12391
+ const validated = validateKnowledgeState(state2);
12392
+ const claimIndex = validated.claims.findIndex((candidate) => candidate.id === claimId);
12393
+ if (claimIndex === -1) {
12394
+ throw new Error(`Cannot verify unknown claim: ${claimId}`);
12395
+ }
12396
+ const claim = validated.claims[claimIndex];
12397
+ const knowledge = claim.knowledge;
12398
+ const existing = knowledge?.verifiedAt;
12399
+ if (typeof existing === "string") {
12400
+ const existingTime = Date.parse(existing);
12401
+ const newTime = Date.parse(record.verifiedAt);
12402
+ if (Number.isFinite(existingTime) && Number.isFinite(newTime) && existingTime >= newTime) {
12403
+ return structuredClone(validated);
12404
+ }
12405
+ }
12406
+ const nextKnowledge = knowledge ? { ...knowledge } : {};
12407
+ nextKnowledge.verifiedAt = record.verifiedAt;
12408
+ nextKnowledge.verifiedBy = record.verifiedBy;
12409
+ nextKnowledge.verifyStatus = record.verifyStatus;
12410
+ const nextClaims = validated.claims.map(
12411
+ (candidate, index) => index === claimIndex ? { ...candidate, knowledge: nextKnowledge } : candidate
12412
+ );
12413
+ return structuredClone({ ...validated, version: validated.version + 1, claims: nextClaims });
12414
+ }
12415
+ async function verifyAndPersistClaims(state2, save) {
12416
+ const validated = validateKnowledgeState(state2);
12417
+ const result = await verifyDueClaims(validated);
12418
+ const persisted = [];
12419
+ let current = validated;
12420
+ for (const probe of result.results) {
12421
+ if (probe.status !== "valid") continue;
12422
+ const record = buildVerificationRecord(probe.claimId, {
12423
+ kind: probe.probe.split(":")[0],
12424
+ target: probe.probe.split(":").slice(1).join(":"),
12425
+ status: probe.status
12426
+ });
12427
+ if (!record) continue;
12428
+ current = applyVerification(current, probe.claimId, record);
12429
+ await save(current, current.version);
12430
+ persisted.push(probe.claimId);
12431
+ }
12432
+ return { result, persisted };
12433
+ }
11901
12434
  var init_verify = __esm({
11902
12435
  "core/knowledge/verify.ts"() {
11903
12436
  init_state();
12437
+ init_verification();
11904
12438
  __name(joinPath6, "joinPath");
11905
12439
  __name(readJsonFile2, "readJsonFile");
11906
12440
  __name(evaluateClaim, "evaluateClaim");
11907
12441
  __name(isDue, "isDue");
11908
12442
  __name(verifyDueClaims, "verifyDueClaims");
11909
12443
  __name(formatVerifyResult, "formatVerifyResult");
12444
+ __name(applyVerification, "applyVerification");
12445
+ __name(verifyAndPersistClaims, "verifyAndPersistClaims");
11910
12446
  }
11911
12447
  });
11912
12448
 
11913
- // core/knowledge/context-budget.ts
11914
- function estimateTokens(text) {
11915
- return Math.ceil(text.length / 4);
11916
- }
11917
- function estimateClaimSize(claim) {
11918
- const serialized = JSON.stringify(claim.knowledge ?? {});
11919
- const characters = serialized.length;
11920
- return { tokens: estimateTokens(serialized), characters };
11921
- }
11922
- function calculateBudgetUsage(claims, budget) {
11923
- let totalChars = 0;
11924
- for (const claim of claims) {
11925
- totalChars += estimateClaimSize(claim).characters;
11926
- }
11927
- const tokens = estimateTokens(String(totalChars));
11928
- const utilization = budget === "unlimited" || budget === 0 ? 1 : Math.min(totalChars / (budget * 4), 1);
11929
- return {
11930
- tokens,
11931
- characters: totalChars,
11932
- claimCount: claims.length,
11933
- budget,
11934
- utilization
11935
- };
11936
- }
11937
- function explainBudgetAllocation(included, excluded, budget) {
11938
- const result = {
11939
- included: included.map((claim) => {
11940
- const size = estimateClaimSize(claim);
11941
- return {
11942
- claimId: claim.id,
11943
- reason: "matched discovery",
11944
- estimatedTokens: size.tokens,
11945
- estimatedCharacters: size.characters
11946
- };
11947
- }),
11948
- excluded: excluded.map((item) => ({
11949
- claimId: item.id,
11950
- reason: item.reason
11951
- })),
11952
- total: calculateBudgetUsage(included, budget)
11953
- };
11954
- if (result.total.utilization >= 0.9 && budget !== "unlimited") {
11955
- result.excluded.push({
11956
- claimId: "__budget__",
11957
- reason: `Budget at ${Math.round(result.total.utilization * 100)}% utilization (${result.total.tokens} tokens of ${budget})`
11958
- });
11959
- }
11960
- return result;
11961
- }
11962
- function formatBudgetExplanation(explanation) {
11963
- const lines = [
11964
- "Context Budget Report",
11965
- "",
11966
- `Total claims included: ${explanation.total.claimCount}`,
11967
- `Estimated tokens: ${explanation.total.tokens}`,
11968
- `Budget: ${explanation.total.budget === "unlimited" ? "unlimited" : explanation.total.budget}`,
11969
- `Utilization: ${Math.round(explanation.total.utilization * 100)}%`,
11970
- ""
11971
- ];
11972
- if (explanation.included.length > 0) {
11973
- lines.push("Included claims:");
11974
- for (const item of explanation.included) {
11975
- lines.push(` [${item.claimId}] ${item.estimatedTokens} tokens \u2014 ${item.reason}`);
11976
- }
11977
- lines.push("");
11978
- }
11979
- if (explanation.excluded.length > 0) {
11980
- lines.push("Excluded claims:");
11981
- for (const item of explanation.excluded) {
11982
- lines.push(` [${item.claimId}] ${item.reason}`);
11983
- }
11984
- lines.push("");
11985
- }
11986
- return lines.join("\n");
11987
- }
11988
- var init_context_budget = __esm({
11989
- "core/knowledge/context-budget.ts"() {
11990
- __name(estimateTokens, "estimateTokens");
11991
- __name(estimateClaimSize, "estimateClaimSize");
11992
- __name(calculateBudgetUsage, "calculateBudgetUsage");
11993
- __name(explainBudgetAllocation, "explainBudgetAllocation");
11994
- __name(formatBudgetExplanation, "formatBudgetExplanation");
11995
- }
11996
- });
11997
-
11998
- // core/knowledge/feedback.ts
12449
+ // core/knowledge/violations.ts
11999
12450
  function joinPath7(base, child) {
12000
12451
  const separator3 = process.platform === "win32" ? "\\" : "/";
12001
12452
  return `${base.replace(/[\\/]+/g, separator3)}${separator3}${child}`;
12002
12453
  }
12003
- function resolveFeedbackFilePath() {
12004
- return joinPath7(resolveUserDotMemPath(), FEEDBACK_FILE_NAME);
12454
+ function resolveViolationFilePath() {
12455
+ return joinPath7(resolveUserDotMemPath(), VIOLATION_FILE_NAME);
12005
12456
  }
12006
- async function readFile3(path5) {
12457
+ async function readFile3(path8) {
12007
12458
  try {
12008
- const fs7 = await import('fs/promises');
12009
- return await fs7.readFile(path5, "utf8");
12459
+ const fs9 = await import('fs/promises');
12460
+ return await fs9.readFile(path8, "utf8");
12010
12461
  } catch {
12011
12462
  return null;
12012
12463
  }
12013
12464
  }
12014
- async function writeFile3(path5, content) {
12015
- const fs7 = await import('fs/promises');
12016
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
12017
- await fs7.mkdir(dir, { recursive: true });
12018
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
12019
- await fs7.writeFile(temporary, content, "utf8");
12020
- await fs7.rename(temporary, path5);
12465
+ async function writeFile3(path8, content) {
12466
+ const fs9 = await import('fs/promises');
12467
+ const dir = path8.replace(/[\\/][^\\/]+$/, "");
12468
+ await fs9.mkdir(dir, { recursive: true });
12469
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
12470
+ await fs9.writeFile(temporary, content, "utf8");
12471
+ await fs9.rename(temporary, path8);
12021
12472
  }
12022
- async function loadFeedback() {
12023
- const raw = await readFile3(resolveFeedbackFilePath());
12024
- if (!raw) return { version: FEEDBACK_FORMAT_VERSION, entries: [] };
12473
+ async function loadViolations() {
12474
+ const raw = await readFile3(resolveViolationFilePath());
12475
+ if (!raw) return { version: VIOLATION_FORMAT_VERSION, entries: [] };
12025
12476
  try {
12026
12477
  const parsed = JSON.parse(raw);
12027
- if (parsed.version === FEEDBACK_FORMAT_VERSION && Array.isArray(parsed.entries)) {
12028
- return { version: FEEDBACK_FORMAT_VERSION, entries: parsed.entries };
12478
+ if (parsed.version === VIOLATION_FORMAT_VERSION && Array.isArray(parsed.entries)) {
12479
+ return { version: VIOLATION_FORMAT_VERSION, entries: parsed.entries };
12029
12480
  }
12030
12481
  } catch {
12031
12482
  }
12032
- return { version: FEEDBACK_FORMAT_VERSION, entries: [] };
12483
+ return { version: VIOLATION_FORMAT_VERSION, entries: [] };
12033
12484
  }
12034
- async function saveFeedback(document) {
12035
- await writeFile3(resolveFeedbackFilePath(), JSON.stringify(document, null, 2) + "\n");
12485
+ async function saveViolations(document) {
12486
+ await writeFile3(resolveViolationFilePath(), JSON.stringify(document, null, 2) + "\n");
12036
12487
  }
12037
- function validateFeedbackEntry(entry) {
12038
- if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
12488
+ async function logViolation(ruleId, situation, description = "") {
12489
+ const document = await loadViolations();
12490
+ const record = {
12491
+ ruleId,
12492
+ violatedAt: (/* @__PURE__ */ new Date()).toISOString(),
12493
+ description,
12494
+ situation
12495
+ };
12496
+ document.entries.push(record);
12497
+ await saveViolations(document);
12498
+ return record;
12499
+ }
12500
+ async function countViolations(ruleId) {
12501
+ const document = await loadViolations();
12502
+ return document.entries.filter((e) => e.ruleId === ruleId).length;
12503
+ }
12504
+ async function lastViolation(ruleId) {
12505
+ const document = await loadViolations();
12506
+ const entries2 = document.entries.filter((e) => e.ruleId === ruleId).sort((a, b) => b.violatedAt.localeCompare(a.violatedAt));
12507
+ return entries2[0]?.violatedAt;
12508
+ }
12509
+ async function listViolations(ruleId) {
12510
+ const document = await loadViolations();
12511
+ if (!ruleId) return document.entries;
12512
+ return document.entries.filter((e) => e.ruleId === ruleId);
12513
+ }
12514
+ async function clearViolations(ruleId) {
12515
+ const document = await loadViolations();
12516
+ const beforeCount = document.entries.length;
12517
+ if (ruleId) {
12518
+ document.entries = document.entries.filter((e) => e.ruleId !== ruleId);
12519
+ } else {
12520
+ document.entries = [];
12521
+ }
12522
+ await saveViolations(document);
12523
+ return beforeCount - document.entries.length;
12524
+ }
12525
+ var VIOLATION_FILE_NAME, VIOLATION_FORMAT_VERSION;
12526
+ var init_violations = __esm({
12527
+ "core/knowledge/violations.ts"() {
12528
+ init_user_paths();
12529
+ VIOLATION_FILE_NAME = "violations.json";
12530
+ VIOLATION_FORMAT_VERSION = 1;
12531
+ __name(joinPath7, "joinPath");
12532
+ __name(resolveViolationFilePath, "resolveViolationFilePath");
12533
+ __name(readFile3, "readFile");
12534
+ __name(writeFile3, "writeFile");
12535
+ __name(loadViolations, "loadViolations");
12536
+ __name(saveViolations, "saveViolations");
12537
+ __name(logViolation, "logViolation");
12538
+ __name(countViolations, "countViolations");
12539
+ __name(lastViolation, "lastViolation");
12540
+ __name(listViolations, "listViolations");
12541
+ __name(clearViolations, "clearViolations");
12542
+ }
12543
+ });
12544
+ function isRuleClaim(claim) {
12545
+ const knowledge = claim.knowledge;
12546
+ return knowledge?.kind === "rule";
12547
+ }
12548
+ function isIronRule(claim) {
12549
+ return claim.epistemicType === "human-stated" && isRuleClaim(claim);
12550
+ }
12551
+ function extractIronRules(state2, violations = {}) {
12552
+ const validated = validateKnowledgeState(state2);
12553
+ const claims = activeClaims(validated);
12554
+ const rules = [];
12555
+ for (const claim of claims) {
12556
+ if (!isIronRule(claim)) continue;
12557
+ const knowledge = claim.knowledge;
12558
+ const applicability = claim.applicability;
12559
+ const iron = applicability.iron === true || applicability.priority === "iron";
12560
+ if (!iron) continue;
12561
+ rules.push({
12562
+ id: claim.id,
12563
+ text: String(knowledge.text ?? knowledge.rule ?? claim.id),
12564
+ why: String(knowledge.why ?? knowledge.reason ?? ""),
12565
+ appliesWhen: String(knowledge.appliesWhen ?? knowledge.when ?? ""),
12566
+ violatedOn: Array.isArray(knowledge.violatedOn) ? knowledge.violatedOn : void 0,
12567
+ lastViolation: typeof knowledge.lastViolation === "string" ? knowledge.lastViolation : void 0,
12568
+ frequency: typeof knowledge.frequency === "number" ? knowledge.frequency : violations[claim.id] ?? 0
12569
+ });
12570
+ }
12571
+ return rules;
12572
+ }
12573
+ function sortRulesByViolationFrequency(rules) {
12574
+ return [...rules].sort((a, b) => {
12575
+ if (b.frequency !== a.frequency) return b.frequency - a.frequency;
12576
+ if (a.lastViolation && b.lastViolation) {
12577
+ return b.lastViolation.localeCompare(a.lastViolation);
12578
+ }
12579
+ return 0;
12580
+ });
12581
+ }
12582
+ function loadIronRules(state2) {
12583
+ const rules = sortRulesByViolationFrequency(
12584
+ extractIronRules(state2, readViolationCounts(`${resolveUserDotMemPath()}/${VIOLATION_FILE_NAME}`))
12585
+ );
12586
+ return {
12587
+ rules,
12588
+ count: rules.length,
12589
+ sortedBy: "violation-frequency"
12590
+ };
12591
+ }
12592
+ function formatRulesForSessionStart(rules) {
12593
+ if (rules.length === 0) {
12594
+ return "";
12595
+ }
12596
+ const lines = ["---", "IRON RULES (must always arrive)", "---"];
12597
+ for (const rule of rules) {
12598
+ lines.push(`${rule.id}: ${rule.text}`);
12599
+ }
12600
+ return lines.join("\n");
12601
+ }
12602
+ function formatRuleWithExplanation(rule) {
12603
+ const parts = [];
12604
+ parts.push(`[${rule.id}] ${rule.text}`);
12605
+ if (rule.why) parts.push(` WHY: ${rule.why}`);
12606
+ if (rule.appliesWhen) parts.push(` APPLIES WHEN: ${rule.appliesWhen}`);
12607
+ if (rule.violatedOn && rule.violatedOn.length > 0) {
12608
+ parts.push(` VIOLATED ${rule.violatedOn.length} TIME(S)`);
12609
+ if (rule.lastViolation) parts.push(` Last: ${rule.lastViolation}`);
12610
+ }
12611
+ return parts.join("\n");
12612
+ }
12613
+ var readViolationCounts, ruleSetSignature, formatRulesReference;
12614
+ var init_rules_loader = __esm({
12615
+ "core/knowledge/rules-loader.ts"() {
12616
+ init_state();
12617
+ init_user_paths();
12618
+ init_violations();
12619
+ __name(isRuleClaim, "isRuleClaim");
12620
+ __name(isIronRule, "isIronRule");
12621
+ __name(extractIronRules, "extractIronRules");
12622
+ readViolationCounts = /* @__PURE__ */ __name((file) => {
12623
+ try {
12624
+ const parsed = JSON.parse(fs3.readFileSync(file, "utf8"));
12625
+ const counts = {};
12626
+ for (const violation of Array.isArray(parsed.violations) ? parsed.violations : []) {
12627
+ const ruleId = typeof violation?.ruleId === "string" ? violation.ruleId : "";
12628
+ if (!ruleId) continue;
12629
+ counts[ruleId] = (counts[ruleId] ?? 0) + 1;
12630
+ }
12631
+ return counts;
12632
+ } catch {
12633
+ return {};
12634
+ }
12635
+ }, "readViolationCounts");
12636
+ __name(sortRulesByViolationFrequency, "sortRulesByViolationFrequency");
12637
+ __name(loadIronRules, "loadIronRules");
12638
+ ruleSetSignature = /* @__PURE__ */ __name((rules) => {
12639
+ const material = rules.map((rule) => `${rule.id}\0${rule.text}`).join("");
12640
+ let hash = 2166136261;
12641
+ for (let index = 0; index < material.length; index += 1) {
12642
+ hash ^= material.charCodeAt(index);
12643
+ hash = Math.imul(hash, 16777619) >>> 0;
12644
+ }
12645
+ return hash.toString(16).padStart(8, "0");
12646
+ }, "ruleSetSignature");
12647
+ formatRulesReference = /* @__PURE__ */ __name((rules) => {
12648
+ if (rules.length === 0) return "DOTMEM_IRON_RULES_V1\ncount=0";
12649
+ return [
12650
+ "DOTMEM_IRON_RULES_V1",
12651
+ `count=${rules.length}`,
12652
+ `signature=${ruleSetSignature(rules)}`,
12653
+ `ids=${rules.map((rule) => rule.id).join(",")}`
12654
+ ].join("\n");
12655
+ }, "formatRulesReference");
12656
+ __name(formatRulesForSessionStart, "formatRulesForSessionStart");
12657
+ __name(formatRuleWithExplanation, "formatRuleWithExplanation");
12658
+ }
12659
+ });
12660
+
12661
+ // core/knowledge/bootstrap.ts
12662
+ var unchangedResponse, composeBootstrap;
12663
+ var init_bootstrap = __esm({
12664
+ "core/knowledge/bootstrap.ts"() {
12665
+ init_discover();
12666
+ init_project();
12667
+ init_rules_loader();
12668
+ init_user_paths();
12669
+ init_context_constants();
12670
+ unchangedResponse = /* @__PURE__ */ __name((knowledgeVersion, sinceVersion) => {
12671
+ const text = [
12672
+ "DOTMEM_BOOTSTRAP_V1",
12673
+ `storage=${resolveUserDotMemPath()}`,
12674
+ `knowledgeVersion=${knowledgeVersion}`,
12675
+ `rules=DOTMEM_IRON_RULES_V1 count=0 signature=00000000 ids=`,
12676
+ `UNCHANGED:true`,
12677
+ `sinceVersion=${sinceVersion}`,
12678
+ `assertedVersion=${knowledgeVersion}`
12679
+ ].join("\n");
12680
+ return {
12681
+ format: "dotmem-bootstrap-v1",
12682
+ storage: resolveUserDotMemPath(),
12683
+ knowledgeVersion,
12684
+ rules: { count: 0, signature: "00000000", ids: [] },
12685
+ context: null,
12686
+ unchanged: true,
12687
+ sinceVersion,
12688
+ text
12689
+ };
12690
+ }, "unchangedResponse");
12691
+ composeBootstrap = /* @__PURE__ */ __name(async (options = {}) => {
12692
+ const { sinceVersion, situation } = options;
12693
+ const { loadCombinedKnowledgeState: loadCombinedKnowledgeState2 } = await Promise.resolve().then(() => (init_memory(), memory_exports));
12694
+ const state2 = await loadCombinedKnowledgeState2();
12695
+ const knowledgeVersion = state2.version;
12696
+ if (Number.isInteger(sinceVersion) && sinceVersion >= 0 && sinceVersion === knowledgeVersion) {
12697
+ return unchangedResponse(knowledgeVersion, sinceVersion);
12698
+ }
12699
+ const discovery = await discoverAcquiredExperience(
12700
+ state2,
12701
+ situation ?? "",
12702
+ { maxCandidates: DOTMEM_CONTEXT_DEFAULT_MAX_CANDIDATES }
12703
+ );
12704
+ const context2 = projectDiscoveredExperience(discovery, {
12705
+ maxCandidates: DOTMEM_CONTEXT_DEFAULT_MAX_CANDIDATES,
12706
+ maxCharacters: DOTMEM_CONTEXT_DEFAULT_MAX_CHARACTERS
12707
+ });
12708
+ let rules = [];
12709
+ try {
12710
+ rules = loadIronRules(state2).rules;
12711
+ } catch {
12712
+ rules = [];
12713
+ }
12714
+ const rulesReference = {
12715
+ count: rules.length,
12716
+ signature: ruleSetSignature(rules),
12717
+ ids: rules.map((rule) => rule.id)
12718
+ };
12719
+ const text = [
12720
+ "DOTMEM_BOOTSTRAP_V1",
12721
+ `storage=${resolveUserDotMemPath()}`,
12722
+ `knowledgeVersion=${knowledgeVersion}`,
12723
+ `rules=DOTMEM_IRON_RULES_V1 count=${rulesReference.count} signature=${rulesReference.signature} ids=${rulesReference.ids.join(",")}`,
12724
+ "UNCHANGED:false",
12725
+ "",
12726
+ context2.text
12727
+ ].join("\n");
12728
+ return {
12729
+ format: "dotmem-bootstrap-v1",
12730
+ storage: resolveUserDotMemPath(),
12731
+ knowledgeVersion,
12732
+ rules: rulesReference,
12733
+ context: context2,
12734
+ unchanged: false,
12735
+ text
12736
+ };
12737
+ }, "composeBootstrap");
12738
+ }
12739
+ });
12740
+
12741
+ // core/knowledge/inspect-report.ts
12742
+ var redactValue, redactKnowledge, statusProse, formatParts, redactKnowledgeInInspection, renderInspectReport;
12743
+ var init_inspect_report = __esm({
12744
+ "core/knowledge/inspect-report.ts"() {
12745
+ init_sanitizer();
12746
+ redactValue = /* @__PURE__ */ __name((value) => {
12747
+ if (typeof value === "string" && looksLikeSecretValue(value)) {
12748
+ return "[redacted]";
12749
+ }
12750
+ return value;
12751
+ }, "redactValue");
12752
+ redactKnowledge = /* @__PURE__ */ __name((knowledge, redact) => {
12753
+ if (knowledge === null || typeof knowledge !== "object") {
12754
+ return redactValue(knowledge);
12755
+ }
12756
+ if (Array.isArray(knowledge)) {
12757
+ return knowledge.map((item) => redactKnowledge(item, redact));
12758
+ }
12759
+ const obj = knowledge;
12760
+ const result = {};
12761
+ for (const [key, value] of Object.entries(obj)) {
12762
+ if (redact && (isSecretKey(key) || looksLikeSecretValue(value))) {
12763
+ result[key] = { requiresSecret: true, secretStorage: "external" };
12764
+ continue;
12765
+ }
12766
+ result[key] = redactKnowledge(value, redact);
12767
+ }
12768
+ return result;
12769
+ }, "redactKnowledge");
12770
+ statusProse = /* @__PURE__ */ __name((status) => {
12771
+ switch (status) {
12772
+ case "valid":
12773
+ return "The MEM artifact is valid and intact.";
12774
+ case "invalid":
12775
+ return "The MEM artifact is invalid: its structure or semantics do not conform to the MEM format.";
12776
+ case "checksum_mismatch":
12777
+ return "The MEM artifact failed integrity verification: one or more parts do not match their recorded checksums.";
12778
+ case "unsupported":
12779
+ return "The MEM artifact uses an unsupported format or version.";
12780
+ case "corrupt":
12781
+ return "The MEM artifact is corrupt and could not be decoded.";
12782
+ default:
12783
+ return `The MEM artifact status is ${status}.`;
12784
+ }
12785
+ }, "statusProse");
12786
+ formatParts = /* @__PURE__ */ __name((parts) => {
12787
+ const list2 = parts ?? [];
12788
+ const lines = [` total: ${list2.length}`];
12789
+ for (const part of list2) {
12790
+ lines.push(` - ${part.path} (${part.bytes} bytes, protected=${part.protected})`);
12791
+ }
12792
+ return lines;
12793
+ }, "formatParts");
12794
+ redactKnowledgeInInspection = /* @__PURE__ */ __name((inspection, redact) => {
12795
+ if (!redact || !inspection.knowledge) return inspection;
12796
+ return {
12797
+ ...inspection,
12798
+ knowledge: redactKnowledge(inspection.knowledge, redact)
12799
+ };
12800
+ }, "redactKnowledgeInInspection");
12801
+ renderInspectReport = /* @__PURE__ */ __name((inspection, options = {}) => {
12802
+ const { redact = true, includeKnowledge = false, limit = 50 } = options;
12803
+ const report = redactKnowledgeInInspection(inspection, redact);
12804
+ const lines = [];
12805
+ lines.push("# Dotmem MEM Inspection Report");
12806
+ lines.push("");
12807
+ lines.push(`- **Status:** ${report.status}`);
12808
+ lines.push(`- **Message:** ${statusProse(report.status)}`);
12809
+ lines.push(`- **Representation:** ${report.representation}`);
12810
+ if (report.packageVersion !== void 0) lines.push(`- **Package version:** ${report.packageVersion}`);
12811
+ if (report.memoryVersion !== void 0) lines.push(`- **Memory version:** ${report.memoryVersion}`);
12812
+ if (report.contentId) lines.push(`- **Content ID:** ${report.contentId}`);
12813
+ lines.push("");
12814
+ lines.push("## Integrity");
12815
+ if (report.integrity) {
12816
+ lines.push(`- **Status:** ${report.integrity.status}`);
12817
+ lines.push(`- **Algorithm:** ${report.integrity.algorithm}`);
12818
+ lines.push(`- **Content ID:** ${report.integrity.contentId}`);
12819
+ } else {
12820
+ lines.push("- **Status:** not available");
12821
+ }
12822
+ lines.push("");
12823
+ lines.push("## Authenticity");
12824
+ if (report.authenticity) {
12825
+ lines.push(`- **Status:** ${report.authenticity.status}`);
12826
+ lines.push(`- **Trust:** ${report.authenticity.trust}`);
12827
+ lines.push(`- **Signatures:** ${report.authenticity.signatures.length}`);
12828
+ if (report.authenticity.signatures.length > 0) {
12829
+ lines.push("");
12830
+ lines.push("### Signatures");
12831
+ for (const signature of report.authenticity.signatures) {
12832
+ lines.push(`- ${signature.algorithm ?? "unknown"} / ${signature.keyId ?? "unknown-key"}: **${signature.status}**`);
12833
+ if (signature.message) lines.push(` - ${signature.message}`);
12834
+ }
12835
+ }
12836
+ lines.push("");
12837
+ lines.push("> Unsigned does not mean corrupt: the package has integrity but no cryptographic signature.");
12838
+ } else {
12839
+ lines.push("- **Status:** not available");
12840
+ }
12841
+ lines.push("");
12842
+ lines.push("## Parts");
12843
+ lines.push(...formatParts(report.parts));
12844
+ lines.push("");
12845
+ lines.push("## Claims");
12846
+ const claims = report.knowledge?.claims;
12847
+ if (Array.isArray(claims)) {
12848
+ lines.push(`- **Total:** ${claims.length}`);
12849
+ lines.push(`- **Shown:** ${Math.min(claims.length, limit)}`);
12850
+ lines.push("");
12851
+ for (const claim of claims.slice(0, limit)) {
12852
+ lines.push(`- \`${claim.id}\``);
12853
+ if (claim.epistemicType) lines.push(` - epistemicType: ${claim.epistemicType}`);
12854
+ if (claim.evidence?.length) {
12855
+ lines.push(` - evidence: ${claim.evidence.map((e) => e.id).join(", ")}`);
12856
+ }
12857
+ if (claim.revision) lines.push(` - revision: ${claim.revision.kind}`);
12858
+ }
12859
+ } else {
12860
+ lines.push("- **Total:** not available (knowledge payload not present)");
12861
+ }
12862
+ lines.push("");
12863
+ lines.push("## Redaction");
12864
+ lines.push(`- **Redacted:** ${redact ? "yes" : "no"}`);
12865
+ lines.push("- Secret-shaped values are replaced with placeholders by default. Use --no-redact (CLI only) to disable.");
12866
+ const markdown = lines.join("\n");
12867
+ const json = {
12868
+ status: report.status,
12869
+ representation: report.representation,
12870
+ message: statusProse(report.status),
12871
+ ...report.packageVersion !== void 0 ? { packageVersion: report.packageVersion } : {},
12872
+ ...report.memoryVersion !== void 0 ? { memoryVersion: report.memoryVersion } : {},
12873
+ ...report.contentId ? { contentId: report.contentId } : {},
12874
+ integrity: report.integrity ?? null,
12875
+ authenticity: report.authenticity ?? null,
12876
+ parts: report.parts,
12877
+ claims: includeKnowledge && Array.isArray(report.knowledge?.claims) ? report.knowledge.claims.slice(0, limit).map((claim) => ({
12878
+ id: claim.id,
12879
+ epistemicType: claim.epistemicType,
12880
+ evidence: claim.evidence,
12881
+ revision: claim.revision
12882
+ })) : void 0,
12883
+ claimCount: Array.isArray(report.knowledge?.claims) ? report.knowledge.claims.length : null,
12884
+ redacted: redact,
12885
+ ...includeKnowledge && report.knowledge ? { knowledge: redactKnowledge(report.knowledge, redact) } : {}
12886
+ };
12887
+ return { markdown, json };
12888
+ }, "renderInspectReport");
12889
+ }
12890
+ });
12891
+ var readPackage, listStore;
12892
+ var init_read_only = __esm({
12893
+ "core/knowledge/read-only.ts"() {
12894
+ init_mem_package();
12895
+ init_user_paths();
12896
+ readPackage = /* @__PURE__ */ __name(async (file) => {
12897
+ const resolved = path3__default.default.resolve(file);
12898
+ const bytes = await fs__default.default.readFile(resolved);
12899
+ const inspection = await inspectMem(bytes);
12900
+ return { ...inspection, file: resolved };
12901
+ }, "readPackage");
12902
+ listStore = /* @__PURE__ */ __name(async (root) => {
12903
+ const storageRoot = root ?? resolveUserDotMemPath();
12904
+ const packages = [];
12905
+ let dirents;
12906
+ try {
12907
+ dirents = await fs__default.default.readdir(storageRoot, { withFileTypes: true });
12908
+ } catch {
12909
+ return { root: storageRoot, packages: [] };
12910
+ }
12911
+ for (const entry of dirents) {
12912
+ if (!entry.isFile() || !entry.name.endsWith(".mem") || entry.name === "@brain.mem") continue;
12913
+ const filePath = path3__default.default.join(storageRoot, entry.name);
12914
+ try {
12915
+ const inspection = await readPackage(filePath);
12916
+ packages.push({ file: inspection.file, path: entry.name, inspection });
12917
+ } catch (error) {
12918
+ packages.push({
12919
+ file: filePath,
12920
+ path: entry.name,
12921
+ inspection: {
12922
+ status: "corrupt",
12923
+ representation: "unknown",
12924
+ message: `Unable to inspect: ${error instanceof Error ? error.message : String(error)}`,
12925
+ parts: []
12926
+ }
12927
+ });
12928
+ }
12929
+ }
12930
+ packages.sort((left, right) => left.path.localeCompare(right.path));
12931
+ return { root: storageRoot, packages };
12932
+ }, "listStore");
12933
+ }
12934
+ });
12935
+
12936
+ // core/knowledge/context-budget.ts
12937
+ function estimateTokens(text) {
12938
+ return Math.ceil(text.length / 4);
12939
+ }
12940
+ function estimateClaimSize(claim) {
12941
+ const serialized = JSON.stringify(claim.knowledge ?? {});
12942
+ const characters = serialized.length;
12943
+ return { tokens: estimateTokens(serialized), characters };
12944
+ }
12945
+ function calculateBudgetUsage(claims, budget) {
12946
+ let totalChars = 0;
12947
+ for (const claim of claims) {
12948
+ totalChars += estimateClaimSize(claim).characters;
12949
+ }
12950
+ const tokens = estimateTokens(String(totalChars));
12951
+ const utilization = budget === "unlimited" || budget === 0 ? 1 : Math.min(totalChars / (budget * 4), 1);
12952
+ return {
12953
+ tokens,
12954
+ characters: totalChars,
12955
+ claimCount: claims.length,
12956
+ budget,
12957
+ utilization
12958
+ };
12959
+ }
12960
+ function explainBudgetAllocation(included, excluded, budget) {
12961
+ const result = {
12962
+ included: included.map((claim) => {
12963
+ const size = estimateClaimSize(claim);
12964
+ return {
12965
+ claimId: claim.id,
12966
+ reason: "matched discovery",
12967
+ estimatedTokens: size.tokens,
12968
+ estimatedCharacters: size.characters
12969
+ };
12970
+ }),
12971
+ excluded: excluded.map((item) => ({
12972
+ claimId: item.id,
12973
+ reason: item.reason
12974
+ })),
12975
+ total: calculateBudgetUsage(included, budget)
12976
+ };
12977
+ if (result.total.utilization >= 0.9 && budget !== "unlimited") {
12978
+ result.excluded.push({
12979
+ claimId: "__budget__",
12980
+ reason: `Budget at ${Math.round(result.total.utilization * 100)}% utilization (${result.total.tokens} tokens of ${budget})`
12981
+ });
12982
+ }
12983
+ return result;
12984
+ }
12985
+ function formatBudgetExplanation(explanation) {
12986
+ const lines = [
12987
+ "Context Budget Report",
12988
+ "",
12989
+ `Total claims included: ${explanation.total.claimCount}`,
12990
+ `Estimated tokens: ${explanation.total.tokens}`,
12991
+ `Budget: ${explanation.total.budget === "unlimited" ? "unlimited" : explanation.total.budget}`,
12992
+ `Utilization: ${Math.round(explanation.total.utilization * 100)}%`,
12993
+ ""
12994
+ ];
12995
+ if (explanation.included.length > 0) {
12996
+ lines.push("Included claims:");
12997
+ for (const item of explanation.included) {
12998
+ lines.push(` [${item.claimId}] ${item.estimatedTokens} tokens \u2014 ${item.reason}`);
12999
+ }
13000
+ lines.push("");
13001
+ }
13002
+ if (explanation.excluded.length > 0) {
13003
+ lines.push("Excluded claims:");
13004
+ for (const item of explanation.excluded) {
13005
+ lines.push(` [${item.claimId}] ${item.reason}`);
13006
+ }
13007
+ lines.push("");
13008
+ }
13009
+ return lines.join("\n");
13010
+ }
13011
+ var init_context_budget = __esm({
13012
+ "core/knowledge/context-budget.ts"() {
13013
+ __name(estimateTokens, "estimateTokens");
13014
+ __name(estimateClaimSize, "estimateClaimSize");
13015
+ __name(calculateBudgetUsage, "calculateBudgetUsage");
13016
+ __name(explainBudgetAllocation, "explainBudgetAllocation");
13017
+ __name(formatBudgetExplanation, "formatBudgetExplanation");
13018
+ }
13019
+ });
13020
+
13021
+ // core/knowledge/feedback.ts
13022
+ function joinPath8(base, child) {
13023
+ const separator3 = process.platform === "win32" ? "\\" : "/";
13024
+ return `${base.replace(/[\\/]+/g, separator3)}${separator3}${child}`;
13025
+ }
13026
+ function resolveFeedbackFilePath() {
13027
+ return joinPath8(resolveUserDotMemPath(), FEEDBACK_FILE_NAME);
13028
+ }
13029
+ async function readFile4(path8) {
13030
+ try {
13031
+ const fs9 = await import('fs/promises');
13032
+ return await fs9.readFile(path8, "utf8");
13033
+ } catch {
13034
+ return null;
13035
+ }
13036
+ }
13037
+ async function writeFile4(path8, content) {
13038
+ const fs9 = await import('fs/promises');
13039
+ const dir = path8.replace(/[\\/][^\\/]+$/, "");
13040
+ await fs9.mkdir(dir, { recursive: true });
13041
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
13042
+ await fs9.writeFile(temporary, content, "utf8");
13043
+ await fs9.rename(temporary, path8);
13044
+ }
13045
+ async function loadFeedback() {
13046
+ const raw = await readFile4(resolveFeedbackFilePath());
13047
+ if (!raw) return { version: FEEDBACK_FORMAT_VERSION, entries: [] };
13048
+ try {
13049
+ const parsed = JSON.parse(raw);
13050
+ if (parsed.version === FEEDBACK_FORMAT_VERSION && Array.isArray(parsed.entries)) {
13051
+ return { version: FEEDBACK_FORMAT_VERSION, entries: parsed.entries };
13052
+ }
13053
+ } catch {
13054
+ }
13055
+ return { version: FEEDBACK_FORMAT_VERSION, entries: [] };
13056
+ }
13057
+ async function saveFeedback(document) {
13058
+ await writeFile4(resolveFeedbackFilePath(), JSON.stringify(document, null, 2) + "\n");
13059
+ }
13060
+ function validateFeedbackEntry(entry) {
13061
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
12039
13062
  throw new Error("Feedback entry must be an object");
12040
13063
  }
12041
13064
  const feedback = entry;
@@ -12095,10 +13118,10 @@ var init_feedback = __esm({
12095
13118
  init_user_paths();
12096
13119
  FEEDBACK_FILE_NAME = "feedback.json";
12097
13120
  FEEDBACK_FORMAT_VERSION = 1;
12098
- __name(joinPath7, "joinPath");
13121
+ __name(joinPath8, "joinPath");
12099
13122
  __name(resolveFeedbackFilePath, "resolveFeedbackFilePath");
12100
- __name(readFile3, "readFile");
12101
- __name(writeFile3, "writeFile");
13123
+ __name(readFile4, "readFile");
13124
+ __name(writeFile4, "writeFile");
12102
13125
  VALID_KINDS = /* @__PURE__ */ new Set(["helped", "misled", "ignored"]);
12103
13126
  __name(loadFeedback, "loadFeedback");
12104
13127
  __name(saveFeedback, "saveFeedback");
@@ -12156,302 +13179,125 @@ var init_correction = __esm({
12156
13179
  __name(saveCorrectionDrafts, "saveCorrectionDrafts");
12157
13180
  }
12158
13181
  });
12159
-
12160
- // core/knowledge/incidents.ts
12161
- function findIncidentById(id) {
12162
- return INCIDENT_EVAL_TEST_SET.find((incident) => incident.id === id);
12163
- }
12164
- function listIncidents() {
12165
- return [...INCIDENT_EVAL_TEST_SET];
12166
- }
12167
- function buildIncidentState(overrides = {}) {
12168
- const baseClaims = [
12169
- {
12170
- id: "behavior:watch-files",
12171
- epistemicType: "observed",
12172
- applicability: { verified: true },
12173
- evidence: [{ id: "ev-watch-1", observedAt: "2026-01-01T00:00:00Z" }],
12174
- knowledge: { trigger: "file watching", rule: "watch files with watch tool" },
12175
- acquiredAt: "2026-01-01T00:00:00Z"
12176
- },
12177
- {
12178
- id: "behavior:state-engine",
12179
- epistemicType: "observed",
12180
- applicability: { verified: true },
12181
- evidence: [{ id: "ev-state-1", observedAt: "2026-01-01T00:00:00Z" }],
12182
- knowledge: { trigger: "state engine", rule: "state is foundation" },
12183
- acquiredAt: "2026-01-01T00:00:00Z"
12184
- },
12185
- {
12186
- id: "behavior:git-push-guard",
12187
- epistemicType: "observed",
12188
- applicability: { verified: true },
12189
- evidence: [{ id: "ev-push-1", observedAt: "2026-01-01T00:00:00Z" }],
12190
- knowledge: { trigger: "git push", rule: "guard git operations" },
12191
- acquiredAt: "2026-01-01T00:00:00Z"
12192
- },
12193
- {
12194
- id: "behavior:memory-layer",
12195
- epistemicType: "observed",
12196
- applicability: { verified: true },
12197
- evidence: [{ id: "ev-mem-1", observedAt: "2026-01-01T00:00:00Z" }],
12198
- knowledge: { trigger: "memory", rule: "memory is state plus store" },
12199
- acquiredAt: "2026-01-01T00:00:00Z"
12200
- },
12201
- {
12202
- id: "project:current-project",
12203
- epistemicType: "observed",
12204
- applicability: { scope: "project", verified: true },
12205
- evidence: [{ id: "ev-proj-1", observedAt: "2026-01-01T00:00:00Z" }],
12206
- knowledge: { trigger: "current project", anchor: "project root" },
12207
- acquiredAt: "2026-01-01T00:00:00Z"
12208
- }
12209
- ];
12210
- return {
12211
- version: 1,
12212
- claims: [...baseClaims, ...overrides.claims ?? []]
12213
- };
12214
- }
12215
- function evaluateIncident(incident, matchedClaims) {
12216
- const got = matchedClaims;
12217
- const missing = incident.expectedClaimIds.filter((id) => !got.includes(id));
12218
- const unexpected = got.filter((id) => !incident.expectedClaimIds.includes(id));
12219
- return {
12220
- incidentId: incident.id,
12221
- passed: missing.length === 0 && unexpected.length === 0,
12222
- expected: incident.expectedClaimIds,
12223
- got,
12224
- missing,
12225
- unexpected
12226
- };
12227
- }
12228
- function formatIncidentReport(report) {
12229
- const lines = [
12230
- `Incident Eval Report: ${report.passed}/${report.total} passed`,
12231
- ""
12232
- ];
12233
- for (const result of report.results) {
12234
- const status = result.passed ? "PASS" : "FAIL";
12235
- lines.push(`[${status}] ${result.incidentId}`);
12236
- if (!result.passed) {
12237
- if (result.missing.length > 0) {
12238
- lines.push(` Missing: ${result.missing.join(", ")}`);
12239
- }
12240
- if (result.unexpected.length > 0) {
12241
- lines.push(` Unexpected: ${result.unexpected.join(", ")}`);
12242
- }
12243
- }
12244
- }
12245
- return lines.join("\n");
12246
- }
12247
- var INCIDENT_EVAL_TEST_SET;
12248
- var init_incidents = __esm({
12249
- "core/knowledge/incidents.ts"() {
12250
- INCIDENT_EVAL_TEST_SET = [
12251
- {
12252
- id: "incident-001",
12253
- situation: "user asks about file watching",
12254
- expectedClaimIds: ["behavior:watch-files"],
12255
- excludedIds: ["behavior:state-engine"],
12256
- description: "File watching should pull the watch-files rule, not the state engine rule"
12257
- },
12258
- {
12259
- id: "incident-002",
12260
- situation: "user asks about git push",
12261
- expectedClaimIds: ["behavior:git-push-guard"],
12262
- excludedIds: ["behavior:memory-layer"],
12263
- description: "Git push should trigger the push guard, not the memory layer"
12264
- },
12265
- {
12266
- id: "incident-003",
12267
- situation: "current project context",
12268
- expectedClaimIds: ["project:current-project"],
12269
- excludedIds: ["behavior:state-engine"],
12270
- description: "Current project situation should surface the project anchor claim"
12271
- }
12272
- ];
12273
- __name(findIncidentById, "findIncidentById");
12274
- __name(listIncidents, "listIncidents");
12275
- __name(buildIncidentState, "buildIncidentState");
12276
- __name(evaluateIncident, "evaluateIncident");
12277
- __name(formatIncidentReport, "formatIncidentReport");
12278
- }
12279
- });
12280
-
12281
- // core/knowledge/rules-loader.ts
12282
- function isRuleClaim(claim) {
12283
- const knowledge = claim.knowledge;
12284
- return knowledge?.kind === "rule";
12285
- }
12286
- function isIronRule(claim) {
12287
- return claim.epistemicType === "human-stated" && isRuleClaim(claim);
12288
- }
12289
- function extractIronRules(state2) {
12290
- const validated = validateKnowledgeState(state2);
12291
- const claims = activeClaims(validated);
12292
- const rules = [];
12293
- for (const claim of claims) {
12294
- if (!isIronRule(claim)) continue;
12295
- const knowledge = claim.knowledge;
12296
- const applicability = claim.applicability;
12297
- const iron = applicability.iron === true || applicability.priority === "iron";
12298
- if (!iron) continue;
12299
- rules.push({
12300
- id: claim.id,
12301
- text: String(knowledge.text ?? knowledge.rule ?? claim.id),
12302
- why: String(knowledge.why ?? knowledge.reason ?? ""),
12303
- appliesWhen: String(knowledge.appliesWhen ?? knowledge.when ?? ""),
12304
- violatedOn: Array.isArray(knowledge.violatedOn) ? knowledge.violatedOn : void 0,
12305
- lastViolation: typeof knowledge.lastViolation === "string" ? knowledge.lastViolation : void 0,
12306
- frequency: typeof knowledge.frequency === "number" ? knowledge.frequency : 0
12307
- });
12308
- }
12309
- return rules;
12310
- }
12311
- function sortRulesByViolationFrequency(rules) {
12312
- return [...rules].sort((a, b) => {
12313
- if (b.frequency !== a.frequency) return b.frequency - a.frequency;
12314
- if (a.lastViolation && b.lastViolation) {
12315
- return b.lastViolation.localeCompare(a.lastViolation);
12316
- }
12317
- return 0;
12318
- });
12319
- }
12320
- function loadIronRules(state2) {
12321
- const rules = sortRulesByViolationFrequency(extractIronRules(state2));
12322
- return {
12323
- rules,
12324
- count: rules.length,
12325
- sortedBy: "violation-frequency"
12326
- };
12327
- }
12328
- function formatRulesForSessionStart(rules) {
12329
- if (rules.length === 0) {
12330
- return "";
12331
- }
12332
- const lines = ["---", "IRON RULES (must always arrive)", "---"];
12333
- for (const rule of rules) {
12334
- lines.push(`${rule.id}: ${rule.text}`);
12335
- }
12336
- return lines.join("\n");
12337
- }
12338
- function formatRuleWithExplanation(rule) {
12339
- const parts = [];
12340
- parts.push(`[${rule.id}] ${rule.text}`);
12341
- if (rule.why) parts.push(` WHY: ${rule.why}`);
12342
- if (rule.appliesWhen) parts.push(` APPLIES WHEN: ${rule.appliesWhen}`);
12343
- if (rule.violatedOn && rule.violatedOn.length > 0) {
12344
- parts.push(` VIOLATED ${rule.violatedOn.length} TIME(S)`);
12345
- if (rule.lastViolation) parts.push(` Last: ${rule.lastViolation}`);
12346
- }
12347
- return parts.join("\n");
12348
- }
12349
- var init_rules_loader = __esm({
12350
- "core/knowledge/rules-loader.ts"() {
12351
- init_state();
12352
- __name(isRuleClaim, "isRuleClaim");
12353
- __name(isIronRule, "isIronRule");
12354
- __name(extractIronRules, "extractIronRules");
12355
- __name(sortRulesByViolationFrequency, "sortRulesByViolationFrequency");
12356
- __name(loadIronRules, "loadIronRules");
12357
- __name(formatRulesForSessionStart, "formatRulesForSessionStart");
12358
- __name(formatRuleWithExplanation, "formatRuleWithExplanation");
12359
- }
12360
- });
12361
-
12362
- // core/knowledge/violations.ts
12363
- function joinPath8(base, child) {
12364
- const separator3 = process.platform === "win32" ? "\\" : "/";
12365
- return `${base.replace(/[\\/]+/g, separator3)}${separator3}${child}`;
12366
- }
12367
- function resolveViolationFilePath() {
12368
- return joinPath8(resolveUserDotMemPath(), VIOLATION_FILE_NAME);
12369
- }
12370
- async function readFile4(path5) {
12371
- try {
12372
- const fs7 = await import('fs/promises');
12373
- return await fs7.readFile(path5, "utf8");
12374
- } catch {
12375
- return null;
12376
- }
12377
- }
12378
- async function writeFile4(path5, content) {
12379
- const fs7 = await import('fs/promises');
12380
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
12381
- await fs7.mkdir(dir, { recursive: true });
12382
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
12383
- await fs7.writeFile(temporary, content, "utf8");
12384
- await fs7.rename(temporary, path5);
12385
- }
12386
- async function loadViolations() {
12387
- const raw = await readFile4(resolveViolationFilePath());
12388
- if (!raw) return { version: VIOLATION_FORMAT_VERSION, entries: [] };
12389
- try {
12390
- const parsed = JSON.parse(raw);
12391
- if (parsed.version === VIOLATION_FORMAT_VERSION && Array.isArray(parsed.entries)) {
12392
- return { version: VIOLATION_FORMAT_VERSION, entries: parsed.entries };
12393
- }
12394
- } catch {
12395
- }
12396
- return { version: VIOLATION_FORMAT_VERSION, entries: [] };
12397
- }
12398
- async function saveViolations(document) {
12399
- await writeFile4(resolveViolationFilePath(), JSON.stringify(document, null, 2) + "\n");
12400
- }
12401
- async function logViolation(ruleId, situation, description = "") {
12402
- const document = await loadViolations();
12403
- const record = {
12404
- ruleId,
12405
- violatedAt: (/* @__PURE__ */ new Date()).toISOString(),
12406
- description,
12407
- situation
12408
- };
12409
- document.entries.push(record);
12410
- await saveViolations(document);
12411
- return record;
13182
+
13183
+ // core/knowledge/incidents.ts
13184
+ function findIncidentById(id) {
13185
+ return INCIDENT_EVAL_TEST_SET.find((incident) => incident.id === id);
12412
13186
  }
12413
- async function countViolations(ruleId) {
12414
- const document = await loadViolations();
12415
- return document.entries.filter((e) => e.ruleId === ruleId).length;
13187
+ function listIncidents() {
13188
+ return [...INCIDENT_EVAL_TEST_SET];
12416
13189
  }
12417
- async function lastViolation(ruleId) {
12418
- const document = await loadViolations();
12419
- const entries2 = document.entries.filter((e) => e.ruleId === ruleId).sort((a, b) => b.violatedAt.localeCompare(a.violatedAt));
12420
- return entries2[0]?.violatedAt;
13190
+ function buildIncidentState(overrides = {}) {
13191
+ const baseClaims = [
13192
+ {
13193
+ id: "behavior:watch-files",
13194
+ epistemicType: "observed",
13195
+ applicability: { verified: true },
13196
+ evidence: [{ id: "ev-watch-1", observedAt: "2026-01-01T00:00:00Z" }],
13197
+ knowledge: { trigger: "file watching", rule: "watch files with watch tool" },
13198
+ acquiredAt: "2026-01-01T00:00:00Z"
13199
+ },
13200
+ {
13201
+ id: "behavior:state-engine",
13202
+ epistemicType: "observed",
13203
+ applicability: { verified: true },
13204
+ evidence: [{ id: "ev-state-1", observedAt: "2026-01-01T00:00:00Z" }],
13205
+ knowledge: { trigger: "state engine", rule: "state is foundation" },
13206
+ acquiredAt: "2026-01-01T00:00:00Z"
13207
+ },
13208
+ {
13209
+ id: "behavior:git-push-guard",
13210
+ epistemicType: "observed",
13211
+ applicability: { verified: true },
13212
+ evidence: [{ id: "ev-push-1", observedAt: "2026-01-01T00:00:00Z" }],
13213
+ knowledge: { trigger: "git push", rule: "guard git operations" },
13214
+ acquiredAt: "2026-01-01T00:00:00Z"
13215
+ },
13216
+ {
13217
+ id: "behavior:memory-layer",
13218
+ epistemicType: "observed",
13219
+ applicability: { verified: true },
13220
+ evidence: [{ id: "ev-mem-1", observedAt: "2026-01-01T00:00:00Z" }],
13221
+ knowledge: { trigger: "memory", rule: "memory is state plus store" },
13222
+ acquiredAt: "2026-01-01T00:00:00Z"
13223
+ },
13224
+ {
13225
+ id: "project:current-project",
13226
+ epistemicType: "observed",
13227
+ applicability: { scope: "project", verified: true },
13228
+ evidence: [{ id: "ev-proj-1", observedAt: "2026-01-01T00:00:00Z" }],
13229
+ knowledge: { trigger: "current project", anchor: "project root" },
13230
+ acquiredAt: "2026-01-01T00:00:00Z"
13231
+ }
13232
+ ];
13233
+ return {
13234
+ version: 1,
13235
+ claims: [...baseClaims, ...overrides.claims ?? []]
13236
+ };
12421
13237
  }
12422
- async function listViolations(ruleId) {
12423
- const document = await loadViolations();
12424
- if (!ruleId) return document.entries;
12425
- return document.entries.filter((e) => e.ruleId === ruleId);
13238
+ function evaluateIncident(incident, matchedClaims) {
13239
+ const got = matchedClaims;
13240
+ const missing = incident.expectedClaimIds.filter((id) => !got.includes(id));
13241
+ const unexpected = got.filter((id) => !incident.expectedClaimIds.includes(id));
13242
+ return {
13243
+ incidentId: incident.id,
13244
+ passed: missing.length === 0 && unexpected.length === 0,
13245
+ expected: incident.expectedClaimIds,
13246
+ got,
13247
+ missing,
13248
+ unexpected
13249
+ };
12426
13250
  }
12427
- async function clearViolations(ruleId) {
12428
- const document = await loadViolations();
12429
- const beforeCount = document.entries.length;
12430
- if (ruleId) {
12431
- document.entries = document.entries.filter((e) => e.ruleId !== ruleId);
12432
- } else {
12433
- document.entries = [];
13251
+ function formatIncidentReport(report) {
13252
+ const lines = [
13253
+ `Incident Eval Report: ${report.passed}/${report.total} passed`,
13254
+ ""
13255
+ ];
13256
+ for (const result of report.results) {
13257
+ const status = result.passed ? "PASS" : "FAIL";
13258
+ lines.push(`[${status}] ${result.incidentId}`);
13259
+ if (!result.passed) {
13260
+ if (result.missing.length > 0) {
13261
+ lines.push(` Missing: ${result.missing.join(", ")}`);
13262
+ }
13263
+ if (result.unexpected.length > 0) {
13264
+ lines.push(` Unexpected: ${result.unexpected.join(", ")}`);
13265
+ }
13266
+ }
12434
13267
  }
12435
- await saveViolations(document);
12436
- return beforeCount - document.entries.length;
13268
+ return lines.join("\n");
12437
13269
  }
12438
- var VIOLATION_FILE_NAME, VIOLATION_FORMAT_VERSION;
12439
- var init_violations = __esm({
12440
- "core/knowledge/violations.ts"() {
12441
- init_user_paths();
12442
- VIOLATION_FILE_NAME = "violations.json";
12443
- VIOLATION_FORMAT_VERSION = 1;
12444
- __name(joinPath8, "joinPath");
12445
- __name(resolveViolationFilePath, "resolveViolationFilePath");
12446
- __name(readFile4, "readFile");
12447
- __name(writeFile4, "writeFile");
12448
- __name(loadViolations, "loadViolations");
12449
- __name(saveViolations, "saveViolations");
12450
- __name(logViolation, "logViolation");
12451
- __name(countViolations, "countViolations");
12452
- __name(lastViolation, "lastViolation");
12453
- __name(listViolations, "listViolations");
12454
- __name(clearViolations, "clearViolations");
13270
+ var INCIDENT_EVAL_TEST_SET;
13271
+ var init_incidents = __esm({
13272
+ "core/knowledge/incidents.ts"() {
13273
+ INCIDENT_EVAL_TEST_SET = [
13274
+ {
13275
+ id: "incident-001",
13276
+ situation: "user asks about file watching",
13277
+ expectedClaimIds: ["behavior:watch-files"],
13278
+ excludedIds: ["behavior:state-engine"],
13279
+ description: "File watching should pull the watch-files rule, not the state engine rule"
13280
+ },
13281
+ {
13282
+ id: "incident-002",
13283
+ situation: "user asks about git push",
13284
+ expectedClaimIds: ["behavior:git-push-guard"],
13285
+ excludedIds: ["behavior:memory-layer"],
13286
+ description: "Git push should trigger the push guard, not the memory layer"
13287
+ },
13288
+ {
13289
+ id: "incident-003",
13290
+ situation: "current project context",
13291
+ expectedClaimIds: ["project:current-project"],
13292
+ excludedIds: ["behavior:state-engine"],
13293
+ description: "Current project situation should surface the project anchor claim"
13294
+ }
13295
+ ];
13296
+ __name(findIncidentById, "findIncidentById");
13297
+ __name(listIncidents, "listIncidents");
13298
+ __name(buildIncidentState, "buildIncidentState");
13299
+ __name(evaluateIncident, "evaluateIncident");
13300
+ __name(formatIncidentReport, "formatIncidentReport");
12455
13301
  }
12456
13302
  });
12457
13303
 
@@ -12463,21 +13309,21 @@ function joinPath9(base, child) {
12463
13309
  function resolveSessionFilePath() {
12464
13310
  return joinPath9(resolveUserDotMemPath(), SESSION_FILE_NAME);
12465
13311
  }
12466
- async function readFile5(path5) {
13312
+ async function readFile5(path8) {
12467
13313
  try {
12468
- const fs7 = await import('fs/promises');
12469
- return await fs7.readFile(path5, "utf8");
13314
+ const fs9 = await import('fs/promises');
13315
+ return await fs9.readFile(path8, "utf8");
12470
13316
  } catch {
12471
13317
  return null;
12472
13318
  }
12473
13319
  }
12474
- async function writeFile5(path5, content) {
12475
- const fs7 = await import('fs/promises');
12476
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
12477
- await fs7.mkdir(dir, { recursive: true });
12478
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
12479
- await fs7.writeFile(temporary, content, "utf8");
12480
- await fs7.rename(temporary, path5);
13320
+ async function writeFile5(path8, content) {
13321
+ const fs9 = await import('fs/promises');
13322
+ const dir = path8.replace(/[\\/][^\\/]+$/, "");
13323
+ await fs9.mkdir(dir, { recursive: true });
13324
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
13325
+ await fs9.writeFile(temporary, content, "utf8");
13326
+ await fs9.rename(temporary, path8);
12481
13327
  }
12482
13328
  async function loadSession() {
12483
13329
  const raw = await readFile5(resolveSessionFilePath());
@@ -12579,25 +13425,25 @@ function joinPath10(base, child) {
12579
13425
  function resolveExemplarsPath() {
12580
13426
  return joinPath10(resolveUserDotMemPath(), EXEMPLARS_FILE_NAME);
12581
13427
  }
12582
- async function readFile6(path5) {
13428
+ async function readFile6(path8) {
12583
13429
  try {
12584
- const fs7 = await import('fs/promises');
12585
- return await fs7.readFile(path5, "utf8");
13430
+ const fs9 = await import('fs/promises');
13431
+ return await fs9.readFile(path8, "utf8");
12586
13432
  } catch {
12587
13433
  return null;
12588
13434
  }
12589
13435
  }
12590
- async function writeFile6(path5, content) {
12591
- const fs7 = await import('fs/promises');
12592
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
12593
- await fs7.mkdir(dir, { recursive: true });
12594
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
13436
+ async function writeFile6(path8, content) {
13437
+ const fs9 = await import('fs/promises');
13438
+ const dir = path8.replace(/[\\/][^\\/]+$/, "");
13439
+ await fs9.mkdir(dir, { recursive: true });
13440
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
12595
13441
  try {
12596
- await fs7.writeFile(temporary, content, "utf8");
12597
- await fs7.rename(temporary, path5);
13442
+ await fs9.writeFile(temporary, content, "utf8");
13443
+ await fs9.rename(temporary, path8);
12598
13444
  } catch {
12599
- await fs7.rm(temporary, { force: true }).catch(() => void 0);
12600
- throw new Error(`Failed to write exemplars file at ${path5}`);
13445
+ await fs9.rm(temporary, { force: true }).catch(() => void 0);
13446
+ throw new Error(`Failed to write exemplars file at ${path8}`);
12601
13447
  }
12602
13448
  }
12603
13449
  function emptyStore() {
@@ -12811,25 +13657,25 @@ function joinPath11(base, child) {
12811
13657
  function resolvePersonalityAnchorPath() {
12812
13658
  return joinPath11(resolveUserDotMemPath(), PERSONALITY_ANCHOR_FILE_NAME);
12813
13659
  }
12814
- async function readFile7(path5) {
13660
+ async function readFile7(path8) {
12815
13661
  try {
12816
- const fs7 = await import('fs/promises');
12817
- return await fs7.readFile(path5, "utf8");
13662
+ const fs9 = await import('fs/promises');
13663
+ return await fs9.readFile(path8, "utf8");
12818
13664
  } catch {
12819
13665
  return null;
12820
13666
  }
12821
13667
  }
12822
- async function writeFile7(path5, content) {
12823
- const fs7 = await import('fs/promises');
12824
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
12825
- await fs7.mkdir(dir, { recursive: true });
12826
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
13668
+ async function writeFile7(path8, content) {
13669
+ const fs9 = await import('fs/promises');
13670
+ const dir = path8.replace(/[\\/][^\\/]+$/, "");
13671
+ await fs9.mkdir(dir, { recursive: true });
13672
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
12827
13673
  try {
12828
- await fs7.writeFile(temporary, content, "utf8");
12829
- await fs7.rename(temporary, path5);
13674
+ await fs9.writeFile(temporary, content, "utf8");
13675
+ await fs9.rename(temporary, path8);
12830
13676
  } catch {
12831
- await fs7.rm(temporary, { force: true }).catch(() => void 0);
12832
- throw new Error(`Failed to write personality anchor at ${path5}`);
13677
+ await fs9.rm(temporary, { force: true }).catch(() => void 0);
13678
+ throw new Error(`Failed to write personality anchor at ${path8}`);
12833
13679
  }
12834
13680
  }
12835
13681
  function emptyAnchor() {
@@ -12967,8 +13813,8 @@ async function loadPersonalityAnchor() {
12967
13813
  async function savePersonalityAnchor(anchor) {
12968
13814
  const validated = validateAnchor(anchor);
12969
13815
  const dirPath = resolveUserDotMemPath();
12970
- const fs7 = await import('fs/promises');
12971
- await fs7.mkdir(dirPath, { recursive: true });
13816
+ const fs9 = await import('fs/promises');
13817
+ await fs9.mkdir(dirPath, { recursive: true });
12972
13818
  await writeFile7(resolvePersonalityAnchorPath(), JSON.stringify(validated, null, 2));
12973
13819
  }
12974
13820
  async function updatePersonalityAnchor(updates) {
@@ -13070,7 +13916,7 @@ function pkgDirname() {
13070
13916
  return __dirname;
13071
13917
  }
13072
13918
  try {
13073
- return path2__default.default.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli.cjs', document.baseURI).href))));
13919
+ return path3__default.default.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli.cjs', document.baseURI).href))));
13074
13920
  } catch {
13075
13921
  return process.cwd();
13076
13922
  }
@@ -13078,7 +13924,7 @@ function pkgDirname() {
13078
13924
  function candidatePaths() {
13079
13925
  const paths = [];
13080
13926
  try {
13081
- paths.push(path2__default.default.join(pkgDirname(), "built-in-context.json"));
13927
+ paths.push(path3__default.default.join(pkgDirname(), "built-in-context.json"));
13082
13928
  } catch {
13083
13929
  }
13084
13930
  return paths;
@@ -13147,10 +13993,10 @@ function loadBuiltInContext() {
13147
13993
  let lastError = "Built-in context artifact not found";
13148
13994
  const candidates = _artifactPathOverride ? [_artifactPathOverride] : candidatePaths();
13149
13995
  for (const candidate of candidates) {
13150
- if (!fs2__default.default.existsSync(candidate)) continue;
13996
+ if (!fs3__default.default.existsSync(candidate)) continue;
13151
13997
  try {
13152
- const raw = fs2__default.default.readFileSync(candidate, "utf8");
13153
- const parsed = JSON.parse(raw);
13998
+ const raw = fs3__default.default.readFileSync(candidate);
13999
+ const parsed = JSON.parse(decodeText(raw, { source: candidate }));
13154
14000
  const artifact = validateArtifact(parsed);
13155
14001
  cached = artifact;
13156
14002
  cachedStatus = {
@@ -13180,14 +14026,14 @@ function loadBuiltInContext() {
13180
14026
  }
13181
14027
  let attemptedPath = "";
13182
14028
  try {
13183
- attemptedPath = path2__default.default.join(pkgDirname(), "built-in-context.json");
14029
+ attemptedPath = path3__default.default.join(pkgDirname(), "built-in-context.json");
13184
14030
  } catch {
13185
14031
  }
13186
14032
  let packageVersion = "unknown";
13187
14033
  try {
13188
- const pkgPath = path2__default.default.join(pkgDirname(), "package.json");
13189
- if (fs2__default.default.existsSync(pkgPath)) {
13190
- const pkg = JSON.parse(fs2__default.default.readFileSync(pkgPath, "utf8"));
14034
+ const pkgPath = path3__default.default.join(pkgDirname(), "package.json");
14035
+ if (fs3__default.default.existsSync(pkgPath)) {
14036
+ const pkg = JSON.parse(fs3__default.default.readFileSync(pkgPath, "utf8"));
13191
14037
  packageVersion = typeof pkg.version === "string" ? pkg.version : "unknown";
13192
14038
  }
13193
14039
  } catch {
@@ -13233,6 +14079,7 @@ function resetBuiltInContextCache() {
13233
14079
  var BUILT_IN_CONTEXT_FORMAT, BUILT_IN_CONTEXT_FORMAT_VERSION, cached, cachedStatus, _artifactPathOverride;
13234
14080
  var init_built_in_context = __esm({
13235
14081
  "core/knowledge/built-in-context.ts"() {
14082
+ init_text_encoding();
13236
14083
  BUILT_IN_CONTEXT_FORMAT = "dotmem.built-in-context";
13237
14084
  BUILT_IN_CONTEXT_FORMAT_VERSION = 1;
13238
14085
  cached = null;
@@ -13399,14 +14246,17 @@ __export(knowledge_exports, {
13399
14246
  addLoop: () => addLoop,
13400
14247
  addWaitingForUser: () => addWaitingForUser,
13401
14248
  appendDetectionJournal: () => appendDetectionJournal,
14249
+ applyVerification: () => applyVerification,
13402
14250
  assertBuiltInContextAvailable: () => assertBuiltInContextAvailable,
13403
14251
  assertNoConversationalOverride: () => assertNoConversationalOverride,
13404
14252
  authorityRelaxationPermitted: () => authorityRelaxationPermitted,
13405
14253
  authorityRevocationPermitted: () => authorityRevocationPermitted,
13406
14254
  buildIncidentState: () => buildIncidentState,
14255
+ buildVerificationRecord: () => buildVerificationRecord,
13407
14256
  builtInContextRulesMapped: () => builtInContextRulesMapped,
13408
14257
  calculateAnchorBudget: () => calculateAnchorBudget,
13409
14258
  calculateBudgetUsage: () => calculateBudgetUsage,
14259
+ callerInjectedVerificationMetadata: () => callerInjectedVerificationMetadata,
13410
14260
  canonicalApplicabilityValue: () => canonicalApplicabilityValue,
13411
14261
  canonicalEvent: () => canonicalEvent,
13412
14262
  canonicalEvidenceError: () => canonicalEvidenceError,
@@ -13425,6 +14275,7 @@ __export(knowledge_exports, {
13425
14275
  clearViolations: () => clearViolations,
13426
14276
  closeLoop: () => closeLoop,
13427
14277
  commitStageFile: () => commitStageFile,
14278
+ composeBootstrap: () => composeBootstrap,
13428
14279
  constructEffectiveAgentContract: () => constructEffectiveAgentContract,
13429
14280
  countViolations: () => countViolations,
13430
14281
  crossAcquisitionBoundary: () => exports.crossAcquisitionBoundary,
@@ -13432,7 +14283,9 @@ __export(knowledge_exports, {
13432
14283
  defaultIdentityGovernance: () => defaultIdentityGovernance,
13433
14284
  defaultOverrideId: () => defaultOverrideId,
13434
14285
  defaultPolicyId: () => defaultPolicyId,
14286
+ deriveCurrentness: () => deriveCurrentness,
13435
14287
  deriveSituationApplicability: () => deriveSituationApplicability,
14288
+ deriveTrustBasis: () => deriveTrustBasis,
13436
14289
  describeDotMemStorage: () => describeDotMemStorage,
13437
14290
  detectAuthorityEscalationAttempt: () => detectAuthorityEscalationAttempt,
13438
14291
  detectBehaviorCoreMutationAttempt: () => detectBehaviorCoreMutationAttempt,
@@ -13458,6 +14311,7 @@ __export(knowledge_exports, {
13458
14311
  explainDiscovery: () => explainDiscovery,
13459
14312
  explainIdentityResolution: () => explainIdentityResolution,
13460
14313
  extractIronRules: () => extractIronRules,
14314
+ findContestedIds: () => findContestedIds,
13461
14315
  findExemplar: () => findExemplar,
13462
14316
  findIncidentById: () => findIncidentById,
13463
14317
  fingerprintFromState: () => fingerprintFromState,
@@ -13484,6 +14338,7 @@ __export(knowledge_exports, {
13484
14338
  inspectMem: () => inspectMem,
13485
14339
  isBaselineClaim: () => isBaselineClaim,
13486
14340
  isBuiltInContextAvailable: () => isBuiltInContextAvailable,
14341
+ isCallerDeclaredVerified: () => isCallerDeclaredVerified,
13487
14342
  isEligibleByApplicability: () => isEligibleByApplicability,
13488
14343
  isIronRule: () => isIronRule,
13489
14344
  isItalian: () => isItalian,
@@ -13495,6 +14350,7 @@ __export(knowledge_exports, {
13495
14350
  listExemplars: () => listExemplars,
13496
14351
  listIncidents: () => listIncidents,
13497
14352
  listLoops: () => listLoops,
14353
+ listStore: () => listStore,
13498
14354
  listViews: () => listViews,
13499
14355
  listViolations: () => listViolations,
13500
14356
  loadBuiltInContext: () => loadBuiltInContext,
@@ -13524,6 +14380,7 @@ __export(knowledge_exports, {
13524
14380
  projectExemplarContext: () => projectExemplarContext,
13525
14381
  projectPersonalityAnchor: () => projectPersonalityAnchor,
13526
14382
  readDotMemStorageLocator: () => readDotMemStorageLocator,
14383
+ readPackage: () => readPackage,
13527
14384
  readStageFile: () => readStageFile,
13528
14385
  readStorageSettings: () => exports.readStorageSettings,
13529
14386
  readUserLanguage: () => readUserLanguage,
@@ -13533,7 +14390,9 @@ __export(knowledge_exports, {
13533
14390
  relocateDotMemStorage: () => relocateDotMemStorage,
13534
14391
  removeExemplar: () => removeExemplar,
13535
14392
  renderAgentRules: () => renderAgentRules,
14393
+ renderExpandedClaim: () => renderExpandedClaim,
13536
14394
  renderExplanation: () => renderExplanation,
14395
+ renderInspectReport: () => renderInspectReport,
13537
14396
  renderMarkdownIndex: () => renderMarkdownIndex,
13538
14397
  renderOperatorContract: () => renderOperatorContract,
13539
14398
  renderView: () => renderView,
@@ -13621,6 +14480,7 @@ __export(knowledge_exports, {
13621
14480
  vaultList: () => vaultList,
13622
14481
  vaultPut: () => vaultPut,
13623
14482
  vaultResolve: () => vaultResolve,
14483
+ verifyAndPersistClaims: () => verifyAndPersistClaims,
13624
14484
  verifyDueClaims: () => verifyDueClaims,
13625
14485
  withPolicyNamespaceLock: () => withPolicyNamespaceLock,
13626
14486
  withoutOverlays: () => withoutOverlays,
@@ -13636,6 +14496,7 @@ var init_knowledge = __esm({
13636
14496
  init_state();
13637
14497
  init_select();
13638
14498
  init_discover();
14499
+ init_currentness();
13639
14500
  init_project();
13640
14501
  init_applicability();
13641
14502
  init_policy();
@@ -13669,6 +14530,10 @@ var init_knowledge = __esm({
13669
14530
  init_rule_checker();
13670
14531
  init_vault();
13671
14532
  init_verify();
14533
+ init_verification();
14534
+ init_bootstrap();
14535
+ init_inspect_report();
14536
+ init_read_only();
13672
14537
  init_context_budget();
13673
14538
  init_feedback();
13674
14539
  init_correction();
@@ -13743,7 +14608,6 @@ function _inferConfidence(claim) {
13743
14608
  var LOGIC_MEM_FILE, nodeCwd2, cachedRuntime, LogicEngine, logic, logic_default;
13744
14609
  var init_logic = __esm({
13745
14610
  "core/logic/index.ts"() {
13746
- init_suppress_idb_warning();
13747
14611
  init_knowledge();
13748
14612
  init_mem_repository();
13749
14613
  init_acquisition_boundary();
@@ -13898,16 +14762,16 @@ function detectLineEnding(content) {
13898
14762
  return content.includes("\r\n") ? "\r\n" : "\n";
13899
14763
  }
13900
14764
  async function ensureDotMemReadme(_projectRoot, readmeSource) {
13901
- const fs7 = await import('fs/promises');
14765
+ const fs9 = await import('fs/promises');
13902
14766
  const dotmemDir = resolveUserDotMemPath();
13903
14767
  try {
13904
- await fs7.mkdir(dotmemDir, { recursive: true });
14768
+ await fs9.mkdir(dotmemDir, { recursive: true });
13905
14769
  } catch {
13906
14770
  }
13907
14771
  const contractDestination = resolveUserContractPath();
13908
14772
  const readmeDestination = resolveUserReadmePath();
13909
14773
  try {
13910
- await fs7.access(contractDestination);
14774
+ await fs9.access(contractDestination);
13911
14775
  } catch {
13912
14776
  let source = readmeSource;
13913
14777
  if (!source) {
@@ -13925,7 +14789,7 @@ async function ensureDotMemReadme(_projectRoot, readmeSource) {
13925
14789
  return pathname.startsWith("/") && pathname.length > 3 && pathname[2] === ":" ? pathname.slice(1) : pathname;
13926
14790
  });
13927
14791
  for (const candidate of sourceCandidates) {
13928
- if (await fs7.access(candidate).then(() => true).catch(() => false)) {
14792
+ if (await fs9.access(candidate).then(() => true).catch(() => false)) {
13929
14793
  source = candidate;
13930
14794
  break;
13931
14795
  }
@@ -13933,22 +14797,22 @@ async function ensureDotMemReadme(_projectRoot, readmeSource) {
13933
14797
  source ??= sourceCandidates.at(-1);
13934
14798
  }
13935
14799
  try {
13936
- const contractContent = await fs7.readFile(source, "utf8");
14800
+ const contractContent = await fs9.readFile(source, "utf8");
13937
14801
  if (!contractContent.trim()) {
13938
14802
  throw new Error(`Refusing to install ${source} as the dotmem contract: the file is empty`);
13939
14803
  }
13940
- await fs7.writeFile(contractDestination, contractContent, "utf8");
14804
+ await fs9.writeFile(contractDestination, contractContent, "utf8");
13941
14805
  } catch (error) {
13942
14806
  throw new Error(`Failed to install dotmem contract from ${source} to ${contractDestination}: ${error instanceof Error ? error.message : String(error)}`);
13943
14807
  }
13944
14808
  }
13945
14809
  try {
13946
- await fs7.access(readmeDestination);
14810
+ await fs9.access(readmeDestination);
13947
14811
  return { action: "already-present", path: readmeDestination };
13948
14812
  } catch {
13949
14813
  }
13950
14814
  try {
13951
- await fs7.writeFile(readmeDestination, DEFAULT_README_CONTENT, "utf8");
14815
+ await fs9.writeFile(readmeDestination, DEFAULT_README_CONTENT, "utf8");
13952
14816
  return { action: "created", path: readmeDestination };
13953
14817
  } catch (error) {
13954
14818
  throw new Error(`Failed to write dotmem README at ${readmeDestination}: ${error instanceof Error ? error.message : String(error)}`);
@@ -14131,7 +14995,6 @@ async function loadCombinedKnowledgeState() {
14131
14995
  var EmptyLogicRepository, KNOWLEDGE_STATE_KEY, knowledgeSaveQueue, StoreKnowledgeRepository, RuntimeSlot, projectSlot, userSlot, installDotMemReadme;
14132
14996
  var init_knowledge_runtime = __esm({
14133
14997
  "core/memory/knowledge-runtime.ts"() {
14134
- init_suppress_idb_warning();
14135
14998
  init_knowledge();
14136
14999
  init_project_identity();
14137
15000
  init_user_paths();
@@ -14485,11 +15348,11 @@ function denoFs() {
14485
15348
  writeFile: writeFile8,
14486
15349
  rename,
14487
15350
  copyFile,
14488
- rm: /* @__PURE__ */ __name((path5, opts) => rm(path5, opts), "rm"),
15351
+ rm: /* @__PURE__ */ __name((path8, opts) => rm(path8, opts), "rm"),
14489
15352
  mkdir,
14490
- open: /* @__PURE__ */ __name(async (path5, flags) => {
15353
+ open: /* @__PURE__ */ __name(async (path8, flags) => {
14491
15354
  if (!Deno.open) throw new Error("Deno.open is unavailable");
14492
- const file = await Deno.open(path5, flags);
15355
+ const file = await Deno.open(path8, flags);
14493
15356
  return {
14494
15357
  writeFile: /* @__PURE__ */ __name(async (data) => {
14495
15358
  const written = await file.write(data);
@@ -14512,6 +15375,7 @@ var init_durable_store = __esm({
14512
15375
  "core/memory/durable-store.ts"() {
14513
15376
  init_storage_coordinator();
14514
15377
  init_store_queue();
15378
+ init_text_encoding();
14515
15379
  DurableStorageUnavailableError = class extends Error {
14516
15380
  static {
14517
15381
  __name(this, "DurableStorageUnavailableError");
@@ -14540,8 +15404,8 @@ var init_durable_store = __esm({
14540
15404
  }
14541
15405
  /** Load all entries from disk. Throws on unreadable/corrupt store. */
14542
15406
  async load() {
14543
- const fs7 = await resolveFs();
14544
- if (!fs7) {
15407
+ const fs9 = await resolveFs();
15408
+ if (!fs9) {
14545
15409
  throw new DurableStorageUnavailableError(
14546
15410
  "Durable memory storage is unavailable in this runtime: no filesystem backend could be resolved."
14547
15411
  );
@@ -14551,7 +15415,7 @@ var init_durable_store = __esm({
14551
15415
  async () => {
14552
15416
  let raw;
14553
15417
  try {
14554
- raw = await fs7.readFile(this.filePath);
15418
+ raw = await fs9.readFile(this.filePath);
14555
15419
  } catch (error) {
14556
15420
  const code = error?.code;
14557
15421
  if (code === "ENOENT") {
@@ -14566,11 +15430,11 @@ var init_durable_store = __esm({
14566
15430
  }
14567
15431
  let parsed;
14568
15432
  try {
14569
- parsed = JSON.parse(new TextDecoder().decode(raw));
15433
+ parsed = JSON.parse(decodeText(raw, { source: this.filePath }));
14570
15434
  } catch {
14571
15435
  try {
14572
- const bakRaw = await fs7.readFile(`${this.filePath}.bak`);
14573
- parsed = JSON.parse(new TextDecoder().decode(bakRaw));
15436
+ const bakRaw = await fs9.readFile(`${this.filePath}.bak`);
15437
+ parsed = JSON.parse(decodeText(bakRaw, { source: `${this.filePath}.bak` }));
14574
15438
  } catch {
14575
15439
  throw new DurableStorageUnavailableError(
14576
15440
  "Durable memory store is corrupt and no backup is available."
@@ -14643,8 +15507,8 @@ var init_durable_store = __esm({
14643
15507
  await this.load();
14644
15508
  }
14645
15509
  async persist(entries2, nextVersion) {
14646
- const fs7 = await resolveFs();
14647
- if (!fs7) {
15510
+ const fs9 = await resolveFs();
15511
+ if (!fs9) {
14648
15512
  throw new DurableStorageUnavailableError(
14649
15513
  "Durable memory storage is unavailable: no filesystem backend could be resolved."
14650
15514
  );
@@ -14653,10 +15517,10 @@ var init_durable_store = __esm({
14653
15517
  version: nextVersion,
14654
15518
  entries: [...entries2.values()]
14655
15519
  };
14656
- await fs7.mkdir(parentDir(this.filePath), { recursive: true });
15520
+ await fs9.mkdir(parentDir(this.filePath), { recursive: true });
14657
15521
  const temporary = `${this.filePath}.${pidSuffix()}.${uniqueSuffix2()}.tmp`;
14658
15522
  try {
14659
- const handle = await fs7.open(temporary, "wx");
15523
+ const handle = await fs9.open(temporary, "wx");
14660
15524
  try {
14661
15525
  const bytes = new TextEncoder().encode(JSON.stringify(state2, null, 2) + "\n");
14662
15526
  await handle.writeFile(bytes);
@@ -14664,26 +15528,26 @@ var init_durable_store = __esm({
14664
15528
  } finally {
14665
15529
  await handle.close();
14666
15530
  }
14667
- await fs7.readFile(temporary);
14668
- await this.keepLastValidVersion(fs7);
14669
- await fs7.rename(temporary, this.filePath);
15531
+ await fs9.readFile(temporary);
15532
+ await this.keepLastValidVersion(fs9);
15533
+ await fs9.rename(temporary, this.filePath);
14670
15534
  await this.syncDirectory(parentDir(this.filePath));
14671
15535
  } catch (error) {
14672
- await fs7.rm(temporary, { force: true }).catch(() => void 0);
15536
+ await fs9.rm(temporary, { force: true }).catch(() => void 0);
14673
15537
  throw error;
14674
15538
  }
14675
15539
  }
14676
- async keepLastValidVersion(fs7) {
15540
+ async keepLastValidVersion(fs9) {
14677
15541
  try {
14678
- await fs7.copyFile(this.filePath, `${this.filePath}.bak`);
15542
+ await fs9.copyFile(this.filePath, `${this.filePath}.bak`);
14679
15543
  } catch {
14680
15544
  }
14681
15545
  }
14682
15546
  async syncDirectory(directoryPath) {
14683
- const fs7 = await resolveFs();
14684
- if (!fs7) return;
15547
+ const fs9 = await resolveFs();
15548
+ if (!fs9) return;
14685
15549
  try {
14686
- const handle = await fs7.open(directoryPath, "r");
15550
+ const handle = await fs9.open(directoryPath, "r");
14687
15551
  try {
14688
15552
  await handle.sync();
14689
15553
  } finally {
@@ -14794,9 +15658,9 @@ function computeRelevance(entry) {
14794
15658
  };
14795
15659
  return recencyScore * confidenceScore * accessScore * typeBoost[entry.type] * scopeBoost[entry.scope];
14796
15660
  }
14797
- function getNestedPath(obj, path5) {
14798
- if (!path5 || typeof path5 !== "string") return void 0;
14799
- const parts = path5.replace(/^state\./, "").split(".");
15661
+ function getNestedPath(obj, path8) {
15662
+ if (!path8 || typeof path8 !== "string") return void 0;
15663
+ const parts = path8.replace(/^state\./, "").split(".");
14800
15664
  let current = obj;
14801
15665
  for (const part of parts) {
14802
15666
  if (current === null || current === void 0) return void 0;
@@ -14804,9 +15668,9 @@ function getNestedPath(obj, path5) {
14804
15668
  }
14805
15669
  return current;
14806
15670
  }
14807
- function setNestedPath(obj, path5, value) {
14808
- if (!path5 || typeof path5 !== "string") return;
14809
- const parts = path5.replace(/^state\./, "").split(".");
15671
+ function setNestedPath(obj, path8, value) {
15672
+ if (!path8 || typeof path8 !== "string") return;
15673
+ const parts = path8.replace(/^state\./, "").split(".");
14810
15674
  let current = obj;
14811
15675
  for (let i2 = 0; i2 < parts.length - 1; i2++) {
14812
15676
  const part = parts[i2];
@@ -14817,9 +15681,9 @@ function setNestedPath(obj, path5, value) {
14817
15681
  }
14818
15682
  current[parts[parts.length - 1]] = value;
14819
15683
  }
14820
- function deleteNestedPath(obj, path5) {
14821
- if (!path5 || typeof path5 !== "string") return;
14822
- const parts = path5.replace(/^state\./, "").split(".");
15684
+ function deleteNestedPath(obj, path8) {
15685
+ if (!path8 || typeof path8 !== "string") return;
15686
+ const parts = path8.replace(/^state\./, "").split(".");
14823
15687
  let current = obj;
14824
15688
  for (let i2 = 0; i2 < parts.length - 1; i2++) {
14825
15689
  const part = parts[i2];
@@ -14987,7 +15851,6 @@ async function getEntry(key) {
14987
15851
  var MEMORY_INDEX_KEY, SUPERSEDED_PREFIX, durableStoreInstance, entries;
14988
15852
  var init_entries = __esm({
14989
15853
  "core/memory/entries.ts"() {
14990
- init_suppress_idb_warning();
14991
15854
  init_env();
14992
15855
  init_journal();
14993
15856
  init_durable_store();
@@ -15322,13 +16185,13 @@ async function findClaimAcrossAllSources(claimId, scope, sourceProject) {
15322
16185
  const matches2 = [];
15323
16186
  const scanDirectory = /* @__PURE__ */ __name(async (dir) => {
15324
16187
  try {
15325
- const fs7 = await import('fs/promises');
15326
- const entries2 = await fs7.readdir(dir, { withFileTypes: true });
16188
+ const fs9 = await import('fs/promises');
16189
+ const entries2 = await fs9.readdir(dir, { withFileTypes: true });
15327
16190
  for (const e of entries2) {
15328
16191
  if (e.isFile() && e.name.endsWith(".mem") && e.name !== "@brain.mem") {
15329
16192
  const filePath = `${dir}/${e.name}`;
15330
16193
  try {
15331
- const bytes = await fs7.readFile(filePath);
16194
+ const bytes = await fs9.readFile(filePath);
15332
16195
  const artifact = await decodeMemArtifact(bytes);
15333
16196
  const state2 = artifact.state;
15334
16197
  if (!state2) continue;
@@ -15365,7 +16228,6 @@ async function findClaimAcrossAllSources(claimId, scope, sourceProject) {
15365
16228
  var acquire;
15366
16229
  var init_acquire = __esm({
15367
16230
  "core/memory/acquire.ts"() {
15368
- init_suppress_idb_warning();
15369
16231
  init_env();
15370
16232
  init_built_in_context();
15371
16233
  init_project_identity();
@@ -15486,15 +16348,15 @@ var init_profile2 = __esm({
15486
16348
 
15487
16349
  // core/knowledge/note-types.ts
15488
16350
  async function sha256HexOfText(text) {
15489
- const encoder3 = new TextEncoder();
15490
- const bytes = encoder3.encode(text);
16351
+ const encoder4 = new TextEncoder();
16352
+ const bytes = encoder4.encode(text);
15491
16353
  const hashArray = await crypto.subtle.digest("SHA-256", bytes);
15492
16354
  return Array.from(new Uint8Array(hashArray)).map((b) => b.toString(16).padStart(2, "0")).join("");
15493
16355
  }
15494
16356
  async function buildNoteKnowledge(title, content, origin, tag) {
15495
16357
  const sha2563 = await sha256HexOfText(content);
15496
- const encoder3 = new TextEncoder();
15497
- const size = encoder3.encode(content).byteLength;
16358
+ const encoder4 = new TextEncoder();
16359
+ const size = encoder4.encode(content).byteLength;
15498
16360
  return {
15499
16361
  title,
15500
16362
  content,
@@ -16036,11 +16898,11 @@ var init_handshake_session = __esm({
16036
16898
  SESSION_FILE_NAME2 = "handshake-session.json";
16037
16899
  resolveHandshakeSessionPath = /* @__PURE__ */ __name(() => joinStoragePath(joinStoragePath(resolveUserDotMemPath(), RUNTIME_NAMESPACE_DIR), SESSION_FILE_NAME2), "resolveHandshakeSessionPath");
16038
16900
  loadHandshakeSessionRecord = /* @__PURE__ */ __name(() => {
16039
- const fs7 = getSyncFs();
16040
- if (!fs7) return null;
16901
+ const fs9 = getSyncFs();
16902
+ if (!fs9) return null;
16041
16903
  let raw;
16042
16904
  try {
16043
- raw = fs7.readFileSync(resolveHandshakeSessionPath(), "utf8");
16905
+ raw = fs9.readFileSync(resolveHandshakeSessionPath(), "utf8");
16044
16906
  } catch {
16045
16907
  return null;
16046
16908
  }
@@ -16052,26 +16914,26 @@ var init_handshake_session = __esm({
16052
16914
  }
16053
16915
  }, "loadHandshakeSessionRecord");
16054
16916
  saveHandshakeSessionRecord = /* @__PURE__ */ __name(async (record) => {
16055
- const fs7 = getSyncFs();
16056
- if (!fs7) {
16917
+ const fs9 = getSyncFs();
16918
+ if (!fs9) {
16057
16919
  throw new Error("Persisting the handshake session record requires filesystem access, unavailable in this runtime");
16058
16920
  }
16059
16921
  const filePath = resolveHandshakeSessionPath();
16060
- await fs7.promises.mkdir(parentStoragePath(filePath), { recursive: true });
16922
+ await fs9.promises.mkdir(parentStoragePath(filePath), { recursive: true });
16061
16923
  const temporary = `${filePath}.${process.pid}.${Date.now().toString(36)}.tmp`;
16062
16924
  try {
16063
- await fs7.promises.writeFile(temporary, `${JSON.stringify(record, null, 2)}
16925
+ await fs9.promises.writeFile(temporary, `${JSON.stringify(record, null, 2)}
16064
16926
  `, "utf8");
16065
- await fs7.promises.rename(temporary, filePath);
16927
+ await fs9.promises.rename(temporary, filePath);
16066
16928
  } catch (error) {
16067
- await fs7.promises.rm(temporary, { force: true }).catch(() => void 0);
16929
+ await fs9.promises.rm(temporary, { force: true }).catch(() => void 0);
16068
16930
  throw error;
16069
16931
  }
16070
16932
  }, "saveHandshakeSessionRecord");
16071
16933
  clearHandshakeSessionRecord = /* @__PURE__ */ __name(async () => {
16072
- const fs7 = getSyncFs();
16073
- if (!fs7) return;
16074
- await fs7.promises.rm(resolveHandshakeSessionPath(), { force: true }).catch(() => void 0);
16934
+ const fs9 = getSyncFs();
16935
+ if (!fs9) return;
16936
+ await fs9.promises.rm(resolveHandshakeSessionPath(), { force: true }).catch(() => void 0);
16075
16937
  }, "clearHandshakeSessionRecord");
16076
16938
  computeCurrentRuntimeId = /* @__PURE__ */ __name(() => computeRuntimeId({
16077
16939
  platform: process.platform,
@@ -16972,7 +17834,6 @@ async function bootstrapProject() {
16972
17834
  var pendingDetectionEvents, detectionFlushScheduled, flushDetectionEvents; exports.memory = void 0;
16973
17835
  var init_memory = __esm({
16974
17836
  "core/memory/index.ts"() {
16975
- init_suppress_idb_warning();
16976
17837
  init_journal();
16977
17838
  init_brain();
16978
17839
  init_knowledge_runtime();
@@ -17096,7 +17957,7 @@ var init_memory = __esm({
17096
17957
  resetPolicyStoreCache();
17097
17958
  },
17098
17959
  // ----- namespaced surfaces -----
17099
- /** Local operation journal (namespaced). No-op substrate when sqlite/idb unavailable. */
17960
+ /** Local operation journal (namespaced). Persisted on `store`. */
17100
17961
  journal: journal_default,
17101
17962
  /** Configure the optional cloud-sync layer (namespace + provider). Chainable. */
17102
17963
  configure(opts) {
@@ -17231,7 +18092,7 @@ function readStdin() {
17231
18092
  });
17232
18093
  }
17233
18094
  function parseContextArgs(args) {
17234
- const options = { explain: false, json: false, full: false, claimsOnly: false };
18095
+ const options = { explain: false, json: false, full: false, claimsOnly: false, manifest: false };
17235
18096
  const positional = [];
17236
18097
  let i2 = 0;
17237
18098
  while (i2 < args.length) {
@@ -17240,7 +18101,16 @@ function parseContextArgs(args) {
17240
18101
  else if (arg === "--json") options.json = true;
17241
18102
  else if (arg === "--full") options.full = true;
17242
18103
  else if (arg === "--claims-only") options.claimsOnly = true;
17243
- else if (arg === "--limit") {
18104
+ else if (arg === "--manifest") options.manifest = true;
18105
+ else if (arg === "--claim") {
18106
+ i2++;
18107
+ const value = args[i2];
18108
+ if (!value) {
18109
+ console.error("Missing value for --claim");
18110
+ process14__default.default.exit(1);
18111
+ }
18112
+ options.claimId = value;
18113
+ } else if (arg === "--limit") {
17244
18114
  const value = args[i2 + 1];
17245
18115
  if (value === void 0 || value.startsWith("--")) {
17246
18116
  console.error("Missing value for --limit");
@@ -17255,6 +18125,21 @@ function parseContextArgs(args) {
17255
18125
  }
17256
18126
  options.limit = parsed;
17257
18127
  i2++;
18128
+ } else if (arg === "--offset") {
18129
+ const value = args[i2 + 1];
18130
+ if (value === void 0 || value.startsWith("--")) {
18131
+ console.error("Missing value for --offset");
18132
+ process14__default.default.exitCode = 1;
18133
+ process14__default.default.exit(1);
18134
+ }
18135
+ const parsed = parseInt(value, 10);
18136
+ if (Number.isNaN(parsed) || parsed < 0) {
18137
+ console.error(`Invalid --offset value: ${value}. Must be a non-negative integer.`);
18138
+ process14__default.default.exitCode = 1;
18139
+ process14__default.default.exit(1);
18140
+ }
18141
+ options.offset = parsed;
18142
+ i2++;
17258
18143
  } else if (arg === "--format") {
17259
18144
  const value = args[i2 + 1];
17260
18145
  if (value === void 0 || value.startsWith("--")) {
@@ -17272,7 +18157,7 @@ function parseContextArgs(args) {
17272
18157
  i2++;
17273
18158
  } else if (arg.startsWith("--")) {
17274
18159
  console.error(`Unknown context option: ${arg}`);
17275
- console.error('Usage: npx dotmem context "<situation>" [--explain] [--json] [--full] [--claims-only] [--limit <N>] [--format brief]');
18160
+ console.error('Usage: npx dotmem context "<situation>" [--explain] [--json] [--full] [--claims-only] [--limit <N>] [--offset <N>] [--format brief] [--manifest] [--claim <id>]');
17276
18161
  process14__default.default.exit(1);
17277
18162
  } else positional.push(arg);
17278
18163
  i2++;
@@ -17887,7 +18772,6 @@ var init_policy3 = __esm({
17887
18772
  });
17888
18773
 
17889
18774
  // core/cli/index.ts
17890
- init_suppress_idb_warning();
17891
18775
  init_memory();
17892
18776
 
17893
18777
  // core/continuity/freshness.ts
@@ -18089,33 +18973,33 @@ var validateContinuityDocument = /* @__PURE__ */ __name((value) => {
18089
18973
  snapshots: document.snapshots
18090
18974
  };
18091
18975
  }, "validateContinuityDocument");
18092
- var deleteContinuityArtifact = /* @__PURE__ */ __name(async (path5) => {
18093
- const fs7 = getSyncFs();
18094
- if (!fs7) return;
18095
- await fs7.promises.rm(path5, { force: true });
18976
+ var deleteContinuityArtifact = /* @__PURE__ */ __name(async (path8) => {
18977
+ const fs9 = getSyncFs();
18978
+ if (!fs9) return;
18979
+ await fs9.promises.rm(path8, { force: true });
18096
18980
  }, "deleteContinuityArtifact");
18097
- var loadContinuityDocument = /* @__PURE__ */ __name(async (path5) => {
18098
- const fs7 = getSyncFs();
18099
- if (!fs7) return emptyContinuityDocument();
18981
+ var loadContinuityDocument = /* @__PURE__ */ __name(async (path8) => {
18982
+ const fs9 = getSyncFs();
18983
+ if (!fs9) return emptyContinuityDocument();
18100
18984
  try {
18101
- const raw = await fs7.promises.readFile(path5, "utf8");
18985
+ const raw = await fs9.promises.readFile(path8, "utf8");
18102
18986
  return validateContinuityDocument(JSON.parse(raw));
18103
18987
  } catch {
18104
18988
  return emptyContinuityDocument();
18105
18989
  }
18106
18990
  }, "loadContinuityDocument");
18107
- var saveContinuityDocument = /* @__PURE__ */ __name(async (path5, document) => {
18108
- const fs7 = getSyncFs();
18109
- if (!fs7) return;
18991
+ var saveContinuityDocument = /* @__PURE__ */ __name(async (path8, document) => {
18992
+ const fs9 = getSyncFs();
18993
+ if (!fs9) return;
18110
18994
  const validated = validateContinuityDocument(document);
18111
- await fs7.promises.mkdir(resolveUserContinuityDir(), { recursive: true });
18112
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
18995
+ await fs9.promises.mkdir(resolveUserContinuityDir(), { recursive: true });
18996
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
18113
18997
  try {
18114
- await fs7.promises.writeFile(temporary, `${JSON.stringify(validated, null, 2)}
18998
+ await fs9.promises.writeFile(temporary, `${JSON.stringify(validated, null, 2)}
18115
18999
  `, "utf8");
18116
- await fs7.promises.rename(temporary, path5);
19000
+ await fs9.promises.rename(temporary, path8);
18117
19001
  } catch (error) {
18118
- await fs7.promises.rm(temporary, { force: true }).catch(() => void 0);
19002
+ await fs9.promises.rm(temporary, { force: true }).catch(() => void 0);
18119
19003
  throw error;
18120
19004
  }
18121
19005
  }, "saveContinuityDocument");
@@ -18749,48 +19633,48 @@ var HardRulesRegistry = class {
18749
19633
  return resolveRegistryFilePath(this.directory);
18750
19634
  }
18751
19635
  async load() {
18752
- const fs7 = await import('fs/promises');
19636
+ const fs9 = await import('fs/promises');
18753
19637
  try {
18754
- const raw = await fs7.readFile(this.filePath(), "utf8");
19638
+ const raw = await fs9.readFile(this.filePath(), "utf8");
18755
19639
  return validateDocument4(JSON.parse(raw));
18756
19640
  } catch (err2) {
18757
19641
  if (err2.code === "ENOENT") return emptyDocument3();
18758
19642
  throw err2;
18759
19643
  }
18760
19644
  }
18761
- async readDoc(fs7) {
19645
+ async readDoc(fs9) {
18762
19646
  try {
18763
- const raw = await fs7.readFile(this.filePath(), "utf8");
19647
+ const raw = await fs9.readFile(this.filePath(), "utf8");
18764
19648
  return validateDocument4(JSON.parse(raw));
18765
19649
  } catch (err2) {
18766
19650
  if (err2.code === "ENOENT") return emptyDocument3();
18767
19651
  throw err2;
18768
19652
  }
18769
19653
  }
18770
- async writeDoc(fs7, doc) {
18771
- await fs7.mkdir(this.dir(), { recursive: true });
19654
+ async writeDoc(fs9, doc) {
19655
+ await fs9.mkdir(this.dir(), { recursive: true });
18772
19656
  const fp = this.filePath();
18773
19657
  const tmp = `${fp}.${process.pid}.${Date.now().toString(36)}.tmp`;
18774
19658
  try {
18775
- await fs7.writeFile(tmp, `${JSON.stringify(doc, null, 2)}
19659
+ await fs9.writeFile(tmp, `${JSON.stringify(doc, null, 2)}
18776
19660
  `, "utf8");
18777
- const handle = await fs7.open(tmp, "r+");
19661
+ const handle = await fs9.open(tmp, "r+");
18778
19662
  try {
18779
19663
  await handle.sync();
18780
19664
  } finally {
18781
19665
  await handle.close();
18782
19666
  }
18783
- await fs7.rename(tmp, fp);
19667
+ await fs9.rename(tmp, fp);
18784
19668
  } catch (err2) {
18785
- await fs7.rm(tmp, { force: true }).catch(() => void 0);
19669
+ await fs9.rm(tmp, { force: true }).catch(() => void 0);
18786
19670
  throw err2;
18787
19671
  }
18788
19672
  }
18789
19673
  async mutate(operation, options = {}) {
18790
19674
  const directory = this.dir();
18791
19675
  return withPolicyNamespaceLock(async (session2) => {
18792
- const fs7 = await import('fs/promises');
18793
- const doc = await this.readDoc(fs7);
19676
+ const fs9 = await import('fs/promises');
19677
+ const doc = await this.readDoc(fs9);
18794
19678
  if (options.basedOnRevision !== void 0 && options.basedOnRevision !== doc.revision) {
18795
19679
  throw new HardRulesRegistryError(`Stale hard-rules revision: expected ${options.basedOnRevision}, current ${doc.revision}`);
18796
19680
  }
@@ -18798,7 +19682,7 @@ var HardRulesRegistry = class {
18798
19682
  let next = outcome.document;
18799
19683
  validateDocument4(next);
18800
19684
  await session2.assertOwnership();
18801
- await this.writeDoc(fs7, next);
19685
+ await this.writeDoc(fs9, next);
18802
19686
  return outcome.result;
18803
19687
  }, { directory });
18804
19688
  }
@@ -18958,15 +19842,15 @@ var HardRulesRegistry = class {
18958
19842
  // core/functions/bootstrap.ts
18959
19843
  async function checkProjectState(_cwd) {
18960
19844
  const userDotMemDir = resolveUserDotMemPath();
18961
- const userLogicMemPath = path2__default.default.join(userDotMemDir, "logic.mem");
19845
+ const userLogicMemPath = path3__default.default.join(userDotMemDir, "logic.mem");
18962
19846
  let logicMemValid = false;
18963
- if (fs2__default.default.existsSync(userLogicMemPath)) {
19847
+ if (fs3__default.default.existsSync(userLogicMemPath)) {
18964
19848
  logicMemValid = true;
18965
19849
  }
18966
19850
  const projectId = await resolveProjectIdentity(process.cwd());
18967
19851
  const projectAnchorPath = resolveUserProjectMemoryPath(projectId);
18968
- const projectAnchorPresent = fs2__default.default.existsSync(projectAnchorPath);
18969
- const initialized = fs2__default.default.existsSync(userDotMemDir) && logicMemValid && projectAnchorPresent;
19852
+ const projectAnchorPresent = fs3__default.default.existsSync(projectAnchorPath);
19853
+ const initialized = fs3__default.default.existsSync(userDotMemDir) && logicMemValid && projectAnchorPresent;
18970
19854
  return {
18971
19855
  initialized,
18972
19856
  dotmemDir: userDotMemDir,
@@ -18980,8 +19864,8 @@ async function checkProjectState(_cwd) {
18980
19864
  __name(checkProjectState, "checkProjectState");
18981
19865
  async function getMemoryReadiness(_cwd) {
18982
19866
  const userDotMemDir = resolveUserDotMemPath();
18983
- const userProjectsDir = path2__default.default.join(userDotMemDir, "projects");
18984
- if (!fs2__default.default.existsSync(userProjectsDir)) {
19867
+ const userProjectsDir = path3__default.default.join(userDotMemDir, "projects");
19868
+ if (!fs3__default.default.existsSync(userProjectsDir)) {
18985
19869
  return { ready: false, totalSources: 0, totalClaims: 0, sources: [] };
18986
19870
  }
18987
19871
  try {
@@ -19029,12 +19913,12 @@ async function detectAiEnvironment() {
19029
19913
  }
19030
19914
  if (process.platform !== "win32") {
19031
19915
  try {
19032
- const status = fs2__default.default.readFileSync("/proc/self/status", "utf8");
19916
+ const status = fs3__default.default.readFileSync("/proc/self/status", "utf8");
19033
19917
  const ppidMatch = status.match(/^PPid:\s*(\d+)$/m);
19034
19918
  if (ppidMatch) {
19035
19919
  const ppid = parseInt(ppidMatch[1], 10);
19036
19920
  try {
19037
- const comm = fs2__default.default.readFileSync(`/proc/${ppid}/comm`, "utf8").trim();
19921
+ const comm = fs3__default.default.readFileSync(`/proc/${ppid}/comm`, "utf8").trim();
19038
19922
  const knownAiParents = ["codex", "kilo", "claude", "aider", "continue", "cursor"];
19039
19923
  const matchedParent = knownAiParents.find((ai) => comm.toLowerCase().includes(ai));
19040
19924
  if (matchedParent) {
@@ -19063,33 +19947,33 @@ async function detectAiEnvironment() {
19063
19947
  __name(detectAiEnvironment, "detectAiEnvironment");
19064
19948
  async function ensureUserDotMemInitialized() {
19065
19949
  const userDotMemDir = resolveUserDotMemPath();
19066
- const userProjectsDir = path2__default.default.join(userDotMemDir, "projects");
19067
- const userLogicMemPath = path2__default.default.join(userDotMemDir, "logic.mem");
19950
+ const userProjectsDir = path3__default.default.join(userDotMemDir, "projects");
19951
+ const userLogicMemPath = path3__default.default.join(userDotMemDir, "logic.mem");
19068
19952
  const userContractPath = resolveUserContractPath();
19069
19953
  const userBrainPath = resolveUserBrainPath();
19070
19954
  try {
19071
- fs2__default.default.mkdirSync(userDotMemDir, { recursive: true });
19072
- fs2__default.default.mkdirSync(userProjectsDir, { recursive: true });
19955
+ fs3__default.default.mkdirSync(userDotMemDir, { recursive: true });
19956
+ fs3__default.default.mkdirSync(userProjectsDir, { recursive: true });
19073
19957
  } catch {
19074
19958
  }
19075
- if (!fs2__default.default.existsSync(userLogicMemPath)) {
19959
+ if (!fs3__default.default.existsSync(userLogicMemPath)) {
19076
19960
  const seedBytes = await encodeLogicSeed();
19077
- fs2__default.default.writeFileSync(userLogicMemPath, seedBytes);
19961
+ fs3__default.default.writeFileSync(userLogicMemPath, seedBytes);
19078
19962
  }
19079
- if (!fs2__default.default.existsSync(userContractPath)) {
19963
+ if (!fs3__default.default.existsSync(userContractPath)) {
19080
19964
  await ensureDotMemReadme();
19081
19965
  }
19082
- if (!fs2__default.default.existsSync(userBrainPath)) {
19966
+ if (!fs3__default.default.existsSync(userBrainPath)) {
19083
19967
  const emptyBrainDoc = {
19084
19968
  format: "dotmem.brain",
19085
19969
  version: 1,
19086
19970
  relationships: []
19087
19971
  };
19088
- fs2__default.default.writeFileSync(userBrainPath, JSON.stringify(emptyBrainDoc, null, 2));
19972
+ fs3__default.default.writeFileSync(userBrainPath, JSON.stringify(emptyBrainDoc, null, 2));
19089
19973
  }
19090
- const userLanguagePath = path2__default.default.join(userDotMemDir, "language.json");
19091
- if (!fs2__default.default.existsSync(userLanguagePath)) {
19092
- fs2__default.default.writeFileSync(userLanguagePath, JSON.stringify({ format: "dotmem.language", version: 1, language: "it-IT" }, null, 2));
19974
+ const userLanguagePath = path3__default.default.join(userDotMemDir, "language.json");
19975
+ if (!fs3__default.default.existsSync(userLanguagePath)) {
19976
+ fs3__default.default.writeFileSync(userLanguagePath, JSON.stringify({ format: "dotmem.language", version: 1, language: "it-IT" }, null, 2));
19093
19977
  }
19094
19978
  }
19095
19979
  __name(ensureUserDotMemInitialized, "ensureUserDotMemInitialized");
@@ -19498,7 +20382,8 @@ async function runContext(situation, _cwd, options = {}) {
19498
20382
  await getBrainDocument();
19499
20383
  const discovery = discoverAcquiredExperience(combined, situation, {
19500
20384
  currentProjectId: await resolveProjectIdentity(process.cwd()),
19501
- ...options.limit !== void 0 ? { maxCandidates: options.limit } : {}
20385
+ ...options.limit !== void 0 ? { maxCandidates: options.limit } : {},
20386
+ ...options.offset !== void 0 ? { cursor: { knowledgeVersion: combined.version, offset: options.offset } } : {}
19502
20387
  }, sources);
19503
20388
  if (options.explain) {
19504
20389
  const report = explainDiscovery(combined, discovery, situation);
@@ -19627,6 +20512,20 @@ async function runContext(situation, _cwd, options = {}) {
19627
20512
  claims: projection
19628
20513
  }, null, 2);
19629
20514
  }
20515
+ if (options.manifest) {
20516
+ return JSON.stringify({
20517
+ knowledgeVersion: projection.knowledgeVersion,
20518
+ totalCandidates: projection.totalCandidates,
20519
+ included: projection.experiences.length,
20520
+ omittedCandidates: projection.omittedCandidates,
20521
+ manifest: projection.manifest ?? {
20522
+ considered: projection.totalCandidates,
20523
+ included: projection.experiences.length,
20524
+ items: [],
20525
+ byReason: []
20526
+ }
20527
+ }, null, 2);
20528
+ }
19630
20529
  if (options.format === "brief") {
19631
20530
  const header = options.claimsOnly ? renderBriefClaimsHeader() : `${identityChannel.text}
19632
20531
  ${profileText}
@@ -19657,9 +20556,10 @@ ${projection.text}`;
19657
20556
  const sizeText = renderSizeDisclosure({
19658
20557
  totalCandidates: projection.totalCandidates,
19659
20558
  omittedCandidates: projection.omittedCandidates,
19660
- projectedBytes: projectedBody.length,
19661
- maxCharacters: options.full ? Infinity : DOTMEM_CONTEXT_DEFAULT_MAX_CHARACTERS,
19662
- hostCeilingBytes: DOTMEM_HOST_TRUNCATION_CEILING_BYTES
20559
+ projectedBytes: new TextEncoder().encode(projectedBody).length,
20560
+ maxCharacters: options.full ? Number.MAX_SAFE_INTEGER : DOTMEM_CONTEXT_DEFAULT_MAX_CHARACTERS,
20561
+ hostCeilingBytes: DOTMEM_HOST_TRUNCATION_CEILING_BYTES,
20562
+ manifest: projection.manifest
19663
20563
  });
19664
20564
  return `${identityChannel.text}
19665
20565
  ${profileText}
@@ -19757,6 +20657,8 @@ __name(topLevelUsage, "topLevelUsage");
19757
20657
 
19758
20658
  // core/cli/commands/context.ts
19759
20659
  init_memory();
20660
+ init_memory();
20661
+ init_project();
19760
20662
 
19761
20663
  // core/functions/profile-request.ts
19762
20664
  init_profile();
@@ -19819,6 +20721,17 @@ async function runContextCli(situation, options = {}) {
19819
20721
  console.info(gate.text);
19820
20722
  return;
19821
20723
  }
20724
+ if (options.claimId) {
20725
+ const state2 = await loadCombinedKnowledgeState();
20726
+ const claim = state2.claims.find((candidate) => candidate.id === options.claimId);
20727
+ if (!claim) {
20728
+ console.error(`No claim with id ${options.claimId} is present in the loaded stores.`);
20729
+ process.exitCode = 1;
20730
+ return;
20731
+ }
20732
+ console.info(renderExpandedClaim(claim));
20733
+ return;
20734
+ }
19822
20735
  const text = await runContext(situation ?? "", void 0, {
19823
20736
  ...options,
19824
20737
  handshake: gate.record ?? void 0,
@@ -20056,17 +20969,38 @@ __name(runStorageCli, "runStorageCli");
20056
20969
 
20057
20970
  // core/cli/commands/inspect.ts
20058
20971
  init_mem_package();
20059
- function runInspectCli(file) {
20972
+ init_inspect_report();
20973
+ var redactDefault = true;
20974
+ function runInspectCli(file, args) {
20060
20975
  if (!file) {
20061
- console.error("Usage: npx dotmem inspect FILE.mem");
20976
+ console.error("Usage: npx dotmem inspect FILE.mem [--format md|json] [--redact|--no-redact] [--limit N] [--offset N] [--claims]");
20062
20977
  process.exitCode = 1;
20063
20978
  return;
20064
20979
  }
20980
+ const format = args.includes("--format=json") || args.includes("--format json") ? "json" : "md";
20981
+ const redactArg = args.find((a) => a === "--no-redact" || a === "--redact");
20982
+ const redact = redactArg === "--no-redact" ? false : redactDefault;
20983
+ const limitIndex = args.findIndex((a) => a === "--limit");
20984
+ const limit = limitIndex >= 0 ? Number(args[limitIndex + 1]) : 50;
20985
+ const includeClaims = args.includes("--claims");
20065
20986
  void (async () => {
20066
20987
  try {
20067
- const bytes = await fs2__default.default.promises.readFile(path2__default.default.resolve(file));
20988
+ const bytes = await fs3__default.default.promises.readFile(path3__default.default.resolve(file));
20068
20989
  const result = await inspectMem(bytes);
20069
- console.info(JSON.stringify(result, null, 2));
20990
+ const report = renderInspectReport(result, {
20991
+ redact,
20992
+ includeKnowledge: includeClaims,
20993
+ limit: Number.isFinite(limit) && limit > 0 ? limit : 50
20994
+ });
20995
+ if (format === "json") {
20996
+ console.info(JSON.stringify(report.json, null, 2));
20997
+ } else {
20998
+ console.info(report.markdown);
20999
+ if (redact) {
21000
+ console.info("");
21001
+ console.info("Note: secret-shaped values are redacted. Use --no-redact for full local inspection.");
21002
+ }
21003
+ }
20070
21004
  if (result.status !== "valid") process.exitCode = 2;
20071
21005
  } catch (error) {
20072
21006
  console.error(`Unable to inspect ${file}: ${error instanceof Error ? error.message : String(error)}`);
@@ -20132,6 +21066,148 @@ async function runContinuityCli(args) {
20132
21066
  }
20133
21067
  }
20134
21068
  __name(runContinuityCli, "runContinuityCli");
21069
+
21070
+ // core/cli/commands/dump.ts
21071
+ init_read_only();
21072
+ init_inspect_report();
21073
+ async function runDumpCli(args) {
21074
+ const target = args[0];
21075
+ const format = args.includes("--format=json") || args.includes("--format json") ? "json" : "ndjson";
21076
+ const redactArg = args.find((a) => a === "--no-redact" || a === "--redact");
21077
+ const redact = redactArg === "--no-redact" ? false : true;
21078
+ const sinceIndex = args.findIndex((a) => a === "--since");
21079
+ const since = sinceIndex >= 0 ? Number(args[sinceIndex + 1]) : void 0;
21080
+ const root = target ? path3__default.default.resolve(target) : void 0;
21081
+ const listing = await listStore(root);
21082
+ const entries2 = listing.packages.filter((pkg) => since === void 0 || (pkg.inspection.memoryVersion ?? 0) >= since).map((pkg) => renderInspectReport(pkg.inspection, { redact, includeKnowledge: false, limit: 20 }));
21083
+ if (format === "json") {
21084
+ console.info(JSON.stringify({
21085
+ root: listing.root,
21086
+ redacted: redact,
21087
+ count: entries2.length,
21088
+ packages: entries2.map((e) => e.json)
21089
+ }, null, 2));
21090
+ return;
21091
+ }
21092
+ for (const entry of entries2) {
21093
+ const report = entry.json;
21094
+ console.info(`=== ${report.status === "valid" ? "" : "[corrupt] "}${report.packageVersion ? "package-v1" : report.representation}`);
21095
+ console.info(entry.markdown);
21096
+ }
21097
+ }
21098
+ __name(runDumpCli, "runDumpCli");
21099
+
21100
+ // core/cli/commands/diff.ts
21101
+ init_mem_package();
21102
+ var extractClaims = /* @__PURE__ */ __name((inspection) => {
21103
+ if (inspection.status !== "valid" || !inspection.knowledge) return [];
21104
+ const state2 = inspection.knowledge;
21105
+ if (!Array.isArray(state2.claims)) return [];
21106
+ return state2.claims.map((claim) => {
21107
+ const c = claim;
21108
+ return { id: String(c.id ?? ""), knowledge: c.knowledge, epistemicType: c.epistemicType };
21109
+ }).filter((c) => c.id.length > 0);
21110
+ }, "extractClaims");
21111
+ var knowledgeEqual = /* @__PURE__ */ __name((left, right) => JSON.stringify(stableValue2(left)) === JSON.stringify(stableValue2(right)), "knowledgeEqual");
21112
+ var stableValue2 = /* @__PURE__ */ __name((value) => {
21113
+ if (Array.isArray(value)) return value.map(stableValue2);
21114
+ if (value && typeof value === "object") {
21115
+ return Object.fromEntries(
21116
+ Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => [k, stableValue2(v)])
21117
+ );
21118
+ }
21119
+ return value;
21120
+ }, "stableValue");
21121
+ async function runDiffCli(args) {
21122
+ const [fileA, fileB] = args;
21123
+ if (!fileA || !fileB) {
21124
+ console.error("Usage: npx dotmem diff FILE_A.mem FILE_B.mem");
21125
+ process.exitCode = 1;
21126
+ return;
21127
+ }
21128
+ let inspectionA;
21129
+ let inspectionB;
21130
+ try {
21131
+ inspectionA = await inspectMem(await fs__default.default.readFile(path3__default.default.resolve(fileA)));
21132
+ } catch (error) {
21133
+ console.error(`Unable to read ${fileA}: ${error instanceof Error ? error.message : String(error)}`);
21134
+ process.exitCode = 1;
21135
+ return;
21136
+ }
21137
+ try {
21138
+ inspectionB = await inspectMem(await fs__default.default.readFile(path3__default.default.resolve(fileB)));
21139
+ } catch (error) {
21140
+ console.error(`Unable to read ${fileB}: ${error instanceof Error ? error.message : String(error)}`);
21141
+ process.exitCode = 1;
21142
+ return;
21143
+ }
21144
+ if (inspectionA.status !== "valid") {
21145
+ console.error(`Invalid input ${fileA}: ${inspectionA.status}`);
21146
+ process.exitCode = 1;
21147
+ return;
21148
+ }
21149
+ if (inspectionB.status !== "valid") {
21150
+ console.error(`Invalid input ${fileB}: ${inspectionB.status}`);
21151
+ process.exitCode = 1;
21152
+ return;
21153
+ }
21154
+ const claimsA = extractClaims(inspectionA);
21155
+ const claimsB = extractClaims(inspectionB);
21156
+ const mapA = new Map(claimsA.map((c) => [c.id, c]));
21157
+ const mapB = new Map(claimsB.map((c) => [c.id, c]));
21158
+ const added = [];
21159
+ const removed = [];
21160
+ const changed = [];
21161
+ for (const id of [...mapA.keys()].sort()) {
21162
+ if (!mapB.has(id)) removed.push(mapA.get(id));
21163
+ }
21164
+ for (const id of [...mapB.keys()].sort()) {
21165
+ if (!mapA.has(id)) added.push(mapB.get(id));
21166
+ else {
21167
+ const before = mapA.get(id);
21168
+ const after = mapB.get(id);
21169
+ if (!knowledgeEqual(before.knowledge, after.knowledge) || before.epistemicType !== after.epistemicType) {
21170
+ changed.push({ id, before, after });
21171
+ }
21172
+ }
21173
+ }
21174
+ const report = {
21175
+ fileA: path3__default.default.resolve(fileA),
21176
+ fileB: path3__default.default.resolve(fileB),
21177
+ countA: claimsA.length,
21178
+ countB: claimsB.length,
21179
+ added: added.map((c) => c.id),
21180
+ removed: removed.map((c) => c.id),
21181
+ changed: changed.map((c) => c.id),
21182
+ addedClaims: added,
21183
+ removedClaims: removed,
21184
+ changedClaims: changed,
21185
+ identical: added.length === 0 && removed.length === 0 && changed.length === 0
21186
+ };
21187
+ console.info(JSON.stringify(report, null, 2));
21188
+ }
21189
+ __name(runDiffCli, "runDiffCli");
21190
+
21191
+ // core/cli/commands/bootstrap.ts
21192
+ init_bootstrap();
21193
+ async function runBootstrapCli(args) {
21194
+ const sinceIndex = args.findIndex((a) => a === "--since");
21195
+ const since = sinceIndex >= 0 ? Number(args[sinceIndex + 1]) : void 0;
21196
+ const situationIndex = args.findIndex((a) => a === "--situation");
21197
+ const situation = situationIndex >= 0 ? args[situationIndex + 1] : void 0;
21198
+ try {
21199
+ const response = await composeBootstrap({
21200
+ sinceVersion: since,
21201
+ situation
21202
+ });
21203
+ console.info(response.text);
21204
+ if (response.unchanged) process.exitCode = 0;
21205
+ } catch (error) {
21206
+ console.error(`Bootstrap failed: ${error instanceof Error ? error.message : String(error)}`);
21207
+ process.exitCode = 1;
21208
+ }
21209
+ }
21210
+ __name(runBootstrapCli, "runBootstrapCli");
20135
21211
  async function runHandshakeCli(args) {
20136
21212
  const reset = args.includes("--reset");
20137
21213
  const status = args.includes("--status");
@@ -20378,8 +21454,8 @@ async function runRenderCli(args) {
20378
21454
  return;
20379
21455
  }
20380
21456
  if (outFile) {
20381
- const fs7 = await import('fs/promises');
20382
- await fs7.writeFile(outFile, result.markdown, "utf8");
21457
+ const fs9 = await import('fs/promises');
21458
+ await fs9.writeFile(outFile, result.markdown, "utf8");
20383
21459
  console.info(`Rendered ${view} view to ${outFile}: ${result.claimsWritten} claims`);
20384
21460
  } else {
20385
21461
  console.info(result.markdown);
@@ -20417,8 +21493,8 @@ async function runNoteCli(args) {
20417
21493
  content = await readStdin();
20418
21494
  origin = "stdin";
20419
21495
  } else {
20420
- const fs7 = await import('fs/promises');
20421
- content = await fs7.readFile(fileArg, "utf8");
21496
+ const fs9 = await import('fs/promises');
21497
+ content = await fs9.readFile(fileArg, "utf8");
20422
21498
  origin = fileArg.split(/[\\/]/).pop() ?? fileArg;
20423
21499
  }
20424
21500
  const titleIndex = args.indexOf("--title");
@@ -20502,8 +21578,8 @@ async function runNoteCli(args) {
20502
21578
  process14__default.default.exitCode = 1;
20503
21579
  return;
20504
21580
  }
20505
- const fs7 = await import('fs/promises');
20506
- await fs7.writeFile(outFile, content, "utf8");
21581
+ const fs9 = await import('fs/promises');
21582
+ await fs9.writeFile(outFile, content, "utf8");
20507
21583
  console.info(`Exported note ${id} to ${outFile}`);
20508
21584
  break;
20509
21585
  }
@@ -20600,9 +21676,9 @@ async function runSeedCli(args) {
20600
21676
  content = await readStdin();
20601
21677
  origin = "stdin";
20602
21678
  } else {
20603
- const fs7 = await import('fs/promises');
21679
+ const fs9 = await import('fs/promises');
20604
21680
  try {
20605
- content = await fs7.readFile(input, "utf8");
21681
+ content = await fs9.readFile(input, "utf8");
20606
21682
  } catch (error) {
20607
21683
  console.error(`Unable to read seed file: ${error instanceof Error ? error.message : String(error)}`);
20608
21684
  process14__default.default.exitCode = 1;
@@ -20731,12 +21807,34 @@ __name(runVaultCli, "runVaultCli");
20731
21807
 
20732
21808
  // core/cli/commands/verify.ts
20733
21809
  init_memory();
21810
+ init_memory();
20734
21811
  init_verify();
20735
21812
  async function runVerifyCli(args) {
20736
21813
  const json = args.includes("--json");
21814
+ const persist = args.includes("--persist");
20737
21815
  try {
20738
21816
  const state2 = await loadCombinedKnowledgeState();
20739
21817
  const result = await verifyDueClaims(state2);
21818
+ if (persist) {
21819
+ const { repository } = await getUserKnowledgeRuntime();
21820
+ const current = await repository.load();
21821
+ const { result: persistedResult, persisted } = await verifyAndPersistClaims(
21822
+ current,
21823
+ (next, expectedVersion) => repository.save(next, expectedVersion)
21824
+ );
21825
+ if (json) {
21826
+ console.info(JSON.stringify({ ...persistedResult, persisted }, null, 2));
21827
+ } else {
21828
+ console.info(formatVerifyResult(persistedResult));
21829
+ if (persisted.length > 0) {
21830
+ console.info(`Persisted verification metadata for: ${persisted.join(", ")}`);
21831
+ }
21832
+ }
21833
+ if (persistedResult.stale > 0) {
21834
+ process.exitCode = 2;
21835
+ }
21836
+ return;
21837
+ }
20740
21838
  if (json) {
20741
21839
  console.info(JSON.stringify(result, null, 2));
20742
21840
  return;
@@ -20830,6 +21928,7 @@ init_memory();
20830
21928
  init_rules_loader();
20831
21929
  async function runRulesCli(args) {
20832
21930
  const json = args.includes("--json");
21931
+ const expand = args.includes("--expand");
20833
21932
  try {
20834
21933
  const state2 = await loadCombinedKnowledgeState();
20835
21934
  const report = loadIronRules(state2);
@@ -20841,7 +21940,7 @@ async function runRulesCli(args) {
20841
21940
  console.info("No iron rules found.");
20842
21941
  return;
20843
21942
  }
20844
- console.info(formatRulesForSessionStart(report.rules));
21943
+ console.info(expand ? formatRulesForSessionStart(report.rules) : formatRulesReference(report.rules));
20845
21944
  } catch (error) {
20846
21945
  console.error(`Rules loading failed: ${error instanceof Error ? error.message : String(error)}`);
20847
21946
  process.exitCode = 1;
@@ -20940,7 +22039,7 @@ var collectStores = /* @__PURE__ */ __name(async () => {
20940
22039
  const files = [];
20941
22040
  for (const dir of sourceDirs) {
20942
22041
  try {
20943
- const entries2 = await fs4__default.default.readdir(dir, { withFileTypes: true });
22042
+ const entries2 = await fs__default.default.readdir(dir, { withFileTypes: true });
20944
22043
  for (const e of entries2) {
20945
22044
  if (e.isFile() && e.name.endsWith(".mem") && e.name !== "@brain.mem") {
20946
22045
  files.push({ sourceId: e.name, filePath: `${dir}/${e.name}` });
@@ -20952,7 +22051,7 @@ var collectStores = /* @__PURE__ */ __name(async () => {
20952
22051
  const stores = [];
20953
22052
  for (const { sourceId, filePath } of files) {
20954
22053
  try {
20955
- const bytes = await fs4__default.default.readFile(filePath);
22054
+ const bytes = await fs__default.default.readFile(filePath);
20956
22055
  const artifact = await decodeMemArtifact(bytes);
20957
22056
  stores.push({ sourceId, filePath, state: artifact.state, artifact });
20958
22057
  } catch (error) {
@@ -21175,7 +22274,7 @@ async function runDoctorCli(args) {
21175
22274
  }
21176
22275
  const filePath = store5.filePath;
21177
22276
  const expectedVersion = store5.state.version;
21178
- await withStorageLock(path2__default.default.dirname(filePath), async () => {
22277
+ await withStorageLock(path3__default.default.dirname(filePath), async () => {
21179
22278
  const fsMod = await import('fs/promises');
21180
22279
  let currentBytes;
21181
22280
  try {
@@ -21196,7 +22295,7 @@ async function runDoctorCli(args) {
21196
22295
  }
21197
22296
  const tmp = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
21198
22297
  try {
21199
- await fsMod.mkdir(path2__default.default.dirname(filePath), { recursive: true });
22298
+ await fsMod.mkdir(path3__default.default.dirname(filePath), { recursive: true });
21200
22299
  const encoded = await encodeMemPackage(newState, currentArtifact.preserved, currentArtifact.package);
21201
22300
  await fsMod.writeFile(tmp, encoded);
21202
22301
  await decodeMemArtifact(await fsMod.readFile(tmp));
@@ -21310,7 +22409,7 @@ Verify the AGENTS.md scintilla block matches SCINTILLA_SIGNAL_HASH.
21310
22409
  const agentsMd = fileIdx !== -1 && args[fileIdx + 1] !== void 0 ? args[fileIdx + 1] : "AGENTS.md";
21311
22410
  let content;
21312
22411
  try {
21313
- content = fs2__default.default.readFileSync(agentsMd, "utf8");
22412
+ content = fs3__default.default.readFileSync(agentsMd, "utf8");
21314
22413
  } catch {
21315
22414
  console.info(`scintilla block not found: ${agentsMd} does not exist (nothing to verify)`);
21316
22415
  return;
@@ -21397,7 +22496,7 @@ function dispatch4(command, args) {
21397
22496
  return;
21398
22497
  }
21399
22498
  if (command === "--version" || command === "-v") {
21400
- const pkg = JSON.parse(fs2__default.default.readFileSync(new URL("package.json", (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli.cjs', document.baseURI).href))), "utf8"));
22499
+ const pkg = JSON.parse(fs3__default.default.readFileSync(new URL("package.json", (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli.cjs', document.baseURI).href))), "utf8"));
21401
22500
  console.info(pkg.version);
21402
22501
  process14__default.default.exit(0);
21403
22502
  return;
@@ -21512,11 +22611,66 @@ Report or relocate the canonical dotmem storage location.
21512
22611
  }
21513
22612
  if (command === "inspect") {
21514
22613
  if (args[0] === "--help" || args[0] === "-h") {
21515
- console.info("Usage: npx dotmem inspect FILE.mem");
22614
+ console.info(`Usage: npx dotmem inspect FILE.mem [--format md|json] [--redact|--no-redact] [--limit N] [--offset N] [--claims]
22615
+
22616
+ Read-only inspection of a .mem package. Secret-shaped values are redacted by default.
22617
+
22618
+ FILE.mem the package to inspect
22619
+ --format md human-readable Markdown report (default)
22620
+ --format json structured JSON report
22621
+ --redact redact secret-shaped values (default)
22622
+ --no-redact disable redaction (local CLI inspection only)
22623
+ --limit N max claims to list (default 50)
22624
+ --offset N claims offset
22625
+ --claims include claim summaries in the report`);
22626
+ process14__default.default.exit(0);
22627
+ return;
22628
+ }
22629
+ void runInspectCli(args[0], args.slice(1));
22630
+ return;
22631
+ }
22632
+ if (command === "dump") {
22633
+ if (args[0] === "--help" || args[0] === "-h") {
22634
+ console.info(`Usage: npx dotmem dump [root|file] [--format json|ndjson] [--redact|--no-redact] [--since <version>]
22635
+
22636
+ Bounded, deterministic, read-only store-wide dump. Redacted by default.
22637
+
22638
+ (no target) dump the default storage root
22639
+ root|file dump a specific directory or package
22640
+ --format ndjson newline-delimited JSON (default)
22641
+ --format json single JSON document
22642
+ --redact redact secret-shaped values (default)
22643
+ --no-redact disable redaction (local CLI inspection only)
22644
+ --since <v> only packages at or above memory version`);
22645
+ process14__default.default.exit(0);
22646
+ return;
22647
+ }
22648
+ void runDumpCli(args);
22649
+ return;
22650
+ }
22651
+ if (command === "diff") {
22652
+ if (args[0] === "--help" || args[0] === "-h") {
22653
+ console.info(`Usage: npx dotmem diff FILE_A.mem FILE_B.mem
22654
+
22655
+ Deterministic, read-only diff between two MEM packages. Reports added,
22656
+ removed, and changed claims. Never mutates anything.`);
22657
+ process14__default.default.exit(0);
22658
+ return;
22659
+ }
22660
+ void runDiffCli(args);
22661
+ return;
22662
+ }
22663
+ if (command === "bootstrap") {
22664
+ if (args[0] === "--help" || args[0] === "-h") {
22665
+ console.info(`Usage: npx dotmem bootstrap [--since <version>] [--situation "<text>"]
22666
+
22667
+ Unified bootstrap: one call returns the initial context plus the rules
22668
+ reference. Pass --since to receive a small deterministic UNCHANGED response
22669
+ when the store has not changed since that version. Read-only; never mutates anything.`);
21516
22670
  process14__default.default.exit(0);
21517
22671
  return;
21518
22672
  }
21519
- void runInspectCli(args[0]);
22673
+ void runBootstrapCli(args);
21520
22674
  return;
21521
22675
  }
21522
22676
  if (command === "continuity") {
@@ -21663,9 +22817,12 @@ Record operator feedback about how an acquired claim performed.
21663
22817
  }
21664
22818
  if (command === "rules") {
21665
22819
  if (args[0] === "--help" || args[0] === "-h") {
21666
- console.info(`Usage: npx dotmem rules [--json]
22820
+ console.info(`Usage: npx dotmem rules [--json] [--expand]
22821
+
22822
+ Print iron rules (human-stated, kind: 'rule') sorted by violation frequency.
21667
22823
 
21668
- Print iron rules (human-stated, kind: 'rule') sorted by violation frequency.`);
22824
+ --json output structured report (count, signature, ids, rules)
22825
+ --expand print full rule bodies instead of the compact reference`);
21669
22826
  process14__default.default.exit(0);
21670
22827
  return;
21671
22828
  }