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.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import { store as store$1, hlc, dispatch, session, state, temporal } from 'memorio';
2
- import fs2 from 'fs';
3
- import path2 from 'path';
2
+ import fs3, { readFileSync } from 'fs';
3
+ import fs from 'fs/promises';
4
+ import path3 from 'path';
4
5
  import { fileURLToPath } from 'url';
5
6
  import crypto2 from 'crypto';
6
7
  import process14 from 'process';
7
- import fs4 from 'fs/promises';
8
8
 
9
9
  var __defProp = Object.defineProperty;
10
10
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -33,18 +33,6 @@ var __copyProps = (to, from, except, desc) => {
33
33
  };
34
34
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
35
35
 
36
- // core/suppress-idb-warning.ts
37
- var orig;
38
- var init_suppress_idb_warning = __esm({
39
- "core/suppress-idb-warning.ts"() {
40
- orig = console.warn.bind(console);
41
- console.warn = (...args) => {
42
- if (typeof args[0] === "string" && args[0].includes("IndexedDB is not available")) return;
43
- orig(...args);
44
- };
45
- }
46
- });
47
-
48
36
  // core/env.ts
49
37
  var DEV;
50
38
  var init_env = __esm({
@@ -79,7 +67,6 @@ function configure(opts) {
79
67
  var g, STORE_PREFIX, INDEX_KEY, journal, journal_default;
80
68
  var init_journal = __esm({
81
69
  "core/memory/journal.ts"() {
82
- init_suppress_idb_warning();
83
70
  init_env();
84
71
  g = globalThis;
85
72
  __name(namespace, "namespace");
@@ -327,6 +314,60 @@ var init_storage_paths = __esm({
327
314
  }
328
315
  });
329
316
 
317
+ // core/knowledge/text-encoding.ts
318
+ function detectBom(bytes) {
319
+ if (bytes.length >= 3 && bytes[0] === BOM_UTF8 && bytes[1] === 187 && bytes[2] === 191) {
320
+ return "utf-8";
321
+ }
322
+ if (bytes.length >= 2 && bytes[0] === BOM_UTF16LE_FIRST && bytes[1] === BOM_UTF16LE_SECOND) {
323
+ return "utf-16le";
324
+ }
325
+ if (bytes.length >= 2 && bytes[0] === BOM_UTF16BE_FIRST && bytes[1] === BOM_UTF16BE_SECOND) {
326
+ return "utf-16be";
327
+ }
328
+ return null;
329
+ }
330
+ function encodeText(value) {
331
+ return encoder.encode(value);
332
+ }
333
+ function decodeText(bytes, options = {}) {
334
+ const bom = detectBom(bytes);
335
+ if (bom === "utf-16le" || bom === "utf-16be") {
336
+ throw new UnsupportedEncodingError(
337
+ `UTF-16 encoded content detected in ${options.source ?? "unknown"}; dotmem persists UTF-8 only. Re-save the file as UTF-8 without BOM.`
338
+ );
339
+ }
340
+ let content = bytes;
341
+ if (bom === "utf-8") {
342
+ content = bytes.subarray(3);
343
+ }
344
+ return strictDecoder.decode(content);
345
+ }
346
+ var encoder, strictDecoder, UnsupportedEncodingError, BOM_UTF8, BOM_UTF16LE_FIRST, BOM_UTF16LE_SECOND, BOM_UTF16BE_FIRST, BOM_UTF16BE_SECOND;
347
+ var init_text_encoding = __esm({
348
+ "core/knowledge/text-encoding.ts"() {
349
+ encoder = new TextEncoder();
350
+ strictDecoder = new TextDecoder("utf-8", { fatal: true });
351
+ UnsupportedEncodingError = class extends Error {
352
+ static {
353
+ __name(this, "UnsupportedEncodingError");
354
+ }
355
+ constructor(message) {
356
+ super(message);
357
+ this.name = "UnsupportedEncodingError";
358
+ }
359
+ };
360
+ BOM_UTF8 = 239;
361
+ BOM_UTF16LE_FIRST = 255;
362
+ BOM_UTF16LE_SECOND = 254;
363
+ BOM_UTF16BE_FIRST = 254;
364
+ BOM_UTF16BE_SECOND = 255;
365
+ __name(detectBom, "detectBom");
366
+ __name(encodeText, "encodeText");
367
+ __name(decodeText, "decodeText");
368
+ }
369
+ });
370
+
330
371
  // core/knowledge/storage-settings.ts
331
372
  var DOTMEM_STORAGE_SETTINGS_FILE_NAME, DOTMEM_STORAGE_SETTINGS_VERSION, SETTINGS_MODES, projectRoot, findProjectSettingsFile, resolveProjectSettingsFilePath, discoverProjectSettingsFilePath, resolveUserSettingsFilePath, invalidSettings, parseSettings, resolveSettingsEntry, readTextFile, readStorageSettings;
332
373
  var init_storage_settings = __esm({
@@ -340,13 +381,13 @@ var init_storage_settings = __esm({
340
381
  return normalized || normalizeStoragePath(cwd);
341
382
  }, "projectRoot");
342
383
  findProjectSettingsFile = /* @__PURE__ */ __name((cwd) => {
343
- const fs7 = getSyncFs();
344
- if (!fs7) return null;
384
+ const fs9 = getSyncFs();
385
+ if (!fs9) return null;
345
386
  let current = projectRoot(cwd);
346
387
  for (; ; ) {
347
388
  const candidate = joinStoragePath(current, DOTMEM_STORAGE_SETTINGS_FILE_NAME);
348
389
  try {
349
- if (fs7.existsSync(candidate)) return candidate;
390
+ if (fs9.existsSync(candidate)) return candidate;
350
391
  } catch {
351
392
  return null;
352
393
  }
@@ -421,10 +462,10 @@ var init_storage_settings = __esm({
421
462
  }
422
463
  return { tier, file, root: normalizeStoragePath(declared), mode };
423
464
  }, "resolveSettingsEntry");
424
- readTextFile = /* @__PURE__ */ __name((fs7, file) => {
465
+ readTextFile = /* @__PURE__ */ __name((fs9, file) => {
425
466
  let raw;
426
467
  try {
427
- raw = fs7.readFileSync(file, "utf8");
468
+ raw = fs9.readFileSync(file, "utf8");
428
469
  } catch (error) {
429
470
  const code = error?.code;
430
471
  if (code === "ENOENT" || code === "ENOTDIR") return null;
@@ -436,9 +477,9 @@ var init_storage_settings = __esm({
436
477
  return raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw;
437
478
  }, "readTextFile");
438
479
  readStorageSettings = /* @__PURE__ */ __name((file, tier) => {
439
- const fs7 = getSyncFs();
440
- if (!fs7) return null;
441
- const raw = readTextFile(fs7, file);
480
+ const fs9 = getSyncFs();
481
+ if (!fs9) return null;
482
+ const raw = readTextFile(fs9, file);
442
483
  if (raw === null) return null;
443
484
  return resolveSettingsEntry(parseSettings(raw, file), tier, file);
444
485
  }, "readStorageSettings");
@@ -454,21 +495,25 @@ function resolveUserAnchor() {
454
495
  return joinStoragePath(stripTrailingSeparator(home.trim()), DOTMEM_USER_ANCHOR_DIR_NAME);
455
496
  }
456
497
  function readDotMemStorageLocator() {
457
- const fs7 = getSyncFs();
458
- if (!fs7) return null;
498
+ const fs9 = getSyncFs();
499
+ if (!fs9) return null;
459
500
  const anchor = resolveUserAnchor();
460
501
  const locatorFile = resolveLocatorFilePath(anchor);
461
502
  let raw;
462
503
  try {
463
- raw = fs7.readFileSync(locatorFile, "utf8");
504
+ raw = decodeText(fs9.readFileSync(locatorFile), { source: locatorFile });
464
505
  } catch (error) {
506
+ if (error instanceof UnsupportedEncodingError) {
507
+ throw new DotMemStorageLocationError(
508
+ `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.`
509
+ );
510
+ }
465
511
  const code = error?.code;
466
512
  if (code === "ENOENT") return null;
467
513
  throw new DotMemStorageLocationError(
468
514
  `dotmem storage location cannot be resolved: the user locator file at ${locatorFile} cannot be read (${describeAccessFailure(error)}). No alternative location was selected automatically.`
469
515
  );
470
516
  }
471
- if (raw.charCodeAt(0) === 65279) raw = raw.slice(1);
472
517
  let parsed;
473
518
  try {
474
519
  parsed = JSON.parse(raw);
@@ -572,8 +617,8 @@ async function probeDotMemStorageCapabilities(root) {
572
617
  multiWriterSafety: "unsupported",
573
618
  notes
574
619
  };
575
- const fs7 = getSyncFs();
576
- if (!fs7) {
620
+ const fs9 = getSyncFs();
621
+ if (!fs9) {
577
622
  notes.push("no filesystem access in this runtime");
578
623
  return report;
579
624
  }
@@ -659,14 +704,14 @@ async function relocateDotMemStorage(targetRoot, options = {}) {
659
704
  `Storage relocation target ${target} and the active storage root ${current.storageRoot} must not contain each other.`
660
705
  );
661
706
  }
662
- const fs7 = getSyncFs();
663
- if (!fs7) {
707
+ const fs9 = getSyncFs();
708
+ if (!fs9) {
664
709
  throw new DotMemStorageLocationError("Storage relocation requires filesystem access, which is unavailable in this runtime.");
665
710
  }
666
711
  const fsPromises = await nodeFsPromises();
667
712
  await fsPromises.mkdir(target, { recursive: true });
668
713
  try {
669
- const access = fs7.statSync(target);
714
+ const access = fs9.statSync(target);
670
715
  if (!access.isDirectory()) throw new Error("not a directory");
671
716
  } catch (error) {
672
717
  if (error instanceof DotMemStorageLocationError) throw error;
@@ -675,7 +720,7 @@ async function relocateDotMemStorage(targetRoot, options = {}) {
675
720
  );
676
721
  }
677
722
  await migrateStorageData(current.storageRoot, target);
678
- if (!verifyMigratedData(fs7, current.storageRoot, target)) {
723
+ if (!verifyMigratedData(fs9, current.storageRoot, target)) {
679
724
  throw new DotMemStorageLocationError(
680
725
  `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}.`
681
726
  );
@@ -720,15 +765,15 @@ async function restoreDefaultDotMemStorage(options = {}) {
720
765
  if (current.source === "default") {
721
766
  return current;
722
767
  }
723
- const fs7 = getSyncFs();
724
- if (!fs7) {
768
+ const fs9 = getSyncFs();
769
+ if (!fs9) {
725
770
  throw new DotMemStorageLocationError("Restoring the default storage location requires filesystem access, which is unavailable in this runtime.");
726
771
  }
727
772
  const fsPromises = await nodeFsPromises();
728
773
  const target = current.anchor;
729
774
  await fsPromises.mkdir(target, { recursive: true });
730
775
  await migrateStorageData(current.storageRoot, target);
731
- if (!verifyMigratedData(fs7, current.storageRoot, target)) {
776
+ if (!verifyMigratedData(fs9, current.storageRoot, target)) {
732
777
  throw new DotMemStorageLocationError(
733
778
  `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}.`
734
779
  );
@@ -754,6 +799,7 @@ var DOTMEM_USER_ANCHOR_DIR_NAME, DOTMEM_STORAGE_LOCATOR_FILE_NAME, DOTMEM_STORAG
754
799
  var init_storage_location = __esm({
755
800
  "core/knowledge/storage-location.ts"() {
756
801
  init_storage_paths();
802
+ init_text_encoding();
757
803
  init_storage_settings();
758
804
  init_storage_paths();
759
805
  DOTMEM_USER_ANCHOR_DIR_NAME = ".dotmem";
@@ -775,9 +821,9 @@ var init_storage_location = __esm({
775
821
  return proc && typeof proc.cwd === "function" ? proc.cwd() : ".";
776
822
  }, "currentWorkingDirectory");
777
823
  packageInstallPathHint = null;
778
- noteDotMemPackageInstallPath = /* @__PURE__ */ __name((path5) => {
779
- if (typeof path5 === "string" && path5.trim()) {
780
- packageInstallPathHint = normalizeStoragePath(path5.trim());
824
+ noteDotMemPackageInstallPath = /* @__PURE__ */ __name((path8) => {
825
+ if (typeof path8 === "string" && path8.trim()) {
826
+ packageInstallPathHint = normalizeStoragePath(path8.trim());
781
827
  }
782
828
  }, "noteDotMemPackageInstallPath");
783
829
  looksLikeDotMemInstallPath = /* @__PURE__ */ __name((value) => {
@@ -826,10 +872,10 @@ var init_storage_location = __esm({
826
872
  cliStorageRootOverride = null;
827
873
  }, "clearDotMemStorageRootOverride");
828
874
  hasRecognizableStore = /* @__PURE__ */ __name((root) => {
829
- const fs7 = getSyncFs();
830
- if (!fs7) return false;
875
+ const fs9 = getSyncFs();
876
+ if (!fs9) return false;
831
877
  try {
832
- const entries2 = fs7.readdirSync(root);
878
+ const entries2 = fs9.readdirSync(root);
833
879
  return entries2.some((name) => name.endsWith(".mem") || name === "policy" || name === "DOTMEM.md" || name === "projects");
834
880
  } catch {
835
881
  return false;
@@ -855,10 +901,10 @@ var init_storage_location = __esm({
855
901
  }
856
902
  const root = normalizeStoragePath(trimmed);
857
903
  assertNotInsidePackageInstall(root, source);
858
- const fs7 = getSyncFs();
859
- if (!fs7) return root;
904
+ const fs9 = getSyncFs();
905
+ if (!fs9) return root;
860
906
  try {
861
- const stats = fs7.statSync(root);
907
+ const stats = fs9.statSync(root);
862
908
  if (!stats.isDirectory()) {
863
909
  throw invalidConfiguredRoot(trimmed, source, "the path exists but is not a directory");
864
910
  }
@@ -872,11 +918,11 @@ var init_storage_location = __esm({
872
918
  __name(describeDotMemStorage, "describeDotMemStorage");
873
919
  __name(resolveDotMemStorageRoot, "resolveDotMemStorageRoot");
874
920
  __name(probeDotMemStorageCapabilities, "probeDotMemStorageCapabilities");
875
- collectRelativeEntries = /* @__PURE__ */ __name((fs7, root, prefix = "") => {
921
+ collectRelativeEntries = /* @__PURE__ */ __name((fs9, root, prefix = "") => {
876
922
  const entries2 = [];
877
923
  let dirents;
878
924
  try {
879
- dirents = fs7.readdirSync(root, { withFileTypes: true });
925
+ dirents = fs9.readdirSync(root, { withFileTypes: true });
880
926
  } catch {
881
927
  return entries2;
882
928
  }
@@ -884,23 +930,23 @@ var init_storage_location = __esm({
884
930
  const relative = prefix ? `${prefix}/${dirent.name}` : dirent.name;
885
931
  if (relative === DOTMEM_STORAGE_LOCATOR_FILE_NAME || relative === `${DOTMEM_STORAGE_LOCATOR_FILE_NAME}.tmp`) continue;
886
932
  if (dirent.isDirectory()) {
887
- entries2.push(...collectRelativeEntries(fs7, joinStoragePath(root, dirent.name), relative));
933
+ entries2.push(...collectRelativeEntries(fs9, joinStoragePath(root, dirent.name), relative));
888
934
  } else {
889
935
  entries2.push(relative);
890
936
  }
891
937
  }
892
938
  return entries2.sort();
893
939
  }, "collectRelativeEntries");
894
- verifyMigratedData = /* @__PURE__ */ __name((fs7, from, to) => {
895
- const expected = collectRelativeEntries(fs7, from);
896
- const migrated = new Set(collectRelativeEntries(fs7, to));
940
+ verifyMigratedData = /* @__PURE__ */ __name((fs9, from, to) => {
941
+ const expected = collectRelativeEntries(fs9, from);
942
+ const migrated = new Set(collectRelativeEntries(fs9, to));
897
943
  return expected.every((relative) => migrated.has(relative));
898
944
  }, "verifyMigratedData");
899
945
  migrateStorageData = /* @__PURE__ */ __name(async (from, to) => {
900
- const fs7 = getSyncFs();
901
- if (!fs7) throw new DotMemStorageLocationError("Storage migration requires filesystem access, which is unavailable in this runtime.");
946
+ const fs9 = getSyncFs();
947
+ if (!fs9) throw new DotMemStorageLocationError("Storage migration requires filesystem access, which is unavailable in this runtime.");
902
948
  const fsPromises = await nodeFsPromises();
903
- for (const relative of collectRelativeEntries(fs7, from)) {
949
+ for (const relative of collectRelativeEntries(fs9, from)) {
904
950
  const source = joinStoragePath(from, ...relative.split("/"));
905
951
  const destination = joinStoragePath(to, ...relative.split("/"));
906
952
  await fsPromises.mkdir(parentStoragePath(destination), { recursive: true });
@@ -921,10 +967,10 @@ var init_storage_location = __esm({
921
967
  await fsPromises.rename(temporary, locatorFile);
922
968
  }, "writeStorageLocator");
923
969
  clearMigratedSource = /* @__PURE__ */ __name(async (root, removeRoot) => {
924
- const fs7 = getSyncFs();
925
- if (!fs7) return;
970
+ const fs9 = getSyncFs();
971
+ if (!fs9) return;
926
972
  const fsPromises = await nodeFsPromises();
927
- for (const relative of collectRelativeEntries(fs7, root)) {
973
+ for (const relative of collectRelativeEntries(fs9, root)) {
928
974
  await fsPromises.rm(joinStoragePath(root, ...relative.split("/")), { recursive: true, force: true }).catch(() => void 0);
929
975
  }
930
976
  if (removeRoot && root !== resolveUserAnchor()) {
@@ -932,11 +978,11 @@ var init_storage_location = __esm({
932
978
  }
933
979
  }, "clearMigratedSource");
934
980
  writeSettingsFile = /* @__PURE__ */ __name(async (file, transform) => {
935
- const fs7 = getSyncFs();
936
- if (!fs7) throw new DotMemStorageLocationError("Writing storage settings requires filesystem access, which is unavailable in this runtime.");
981
+ const fs9 = getSyncFs();
982
+ if (!fs9) throw new DotMemStorageLocationError("Writing storage settings requires filesystem access, which is unavailable in this runtime.");
937
983
  let document = {};
938
984
  try {
939
- const raw = fs7.readFileSync(file, "utf8");
985
+ const raw = fs9.readFileSync(file, "utf8");
940
986
  const parsed = JSON.parse(raw);
941
987
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("not an object");
942
988
  document = parsed;
@@ -1691,8 +1737,8 @@ __export(brain_exports, {
1691
1737
  });
1692
1738
  async function brainLoad(brainPath) {
1693
1739
  try {
1694
- const fs7 = await nodeFs();
1695
- const raw = await fs7.readFile(brainPath, "utf8");
1740
+ const fs9 = await nodeFs();
1741
+ const raw = await fs9.readFile(brainPath, "utf8");
1696
1742
  const doc = JSON.parse(raw);
1697
1743
  if (doc.format !== "dotmem.brain" || doc.version !== 1) return emptyBrain();
1698
1744
  if (!Array.isArray(doc.relationships)) return emptyBrain();
@@ -1702,26 +1748,26 @@ async function brainLoad(brainPath) {
1702
1748
  }
1703
1749
  }
1704
1750
  async function brainSave(brainPath, document) {
1705
- const fs7 = await nodeFs();
1751
+ const fs9 = await nodeFs();
1706
1752
  const dir = brainPath.includes("/") ? brainPath.slice(0, brainPath.lastIndexOf("/")) : brainPath.includes("\\") ? brainPath.slice(0, brainPath.lastIndexOf("\\")) : ".";
1707
- await fs7.mkdir(dir, { recursive: true });
1753
+ await fs9.mkdir(dir, { recursive: true });
1708
1754
  const tmp = `${brainPath}.${process.pid}.${Date.now().toString(36)}.tmp`;
1709
1755
  try {
1710
- await fs7.writeFile(tmp, JSON.stringify(document, null, 2));
1711
- await fs7.rename(tmp, brainPath);
1756
+ await fs9.writeFile(tmp, JSON.stringify(document, null, 2));
1757
+ await fs9.rename(tmp, brainPath);
1712
1758
  } catch (error) {
1713
- await fs7.rm(tmp, { force: true }).catch(() => void 0);
1759
+ await fs9.rm(tmp, { force: true }).catch(() => void 0);
1714
1760
  throw error;
1715
1761
  }
1716
1762
  }
1717
1763
  async function getBrainDocument() {
1718
- const path5 = getBrainPath();
1719
- cachedBrainPath = path5;
1720
- return brainLoad(path5);
1764
+ const path8 = getBrainPath();
1765
+ cachedBrainPath = path8;
1766
+ return brainLoad(path8);
1721
1767
  }
1722
1768
  async function saveBrainDocument(document) {
1723
- const path5 = cachedBrainPath || getBrainPath();
1724
- await brainSave(path5, document);
1769
+ const path8 = cachedBrainPath || getBrainPath();
1770
+ await brainSave(path8, document);
1725
1771
  }
1726
1772
  function resetBrainPathCache() {
1727
1773
  cachedBrainPath = null;
@@ -1877,11 +1923,11 @@ var init_state = __esm({
1877
1923
  }
1878
1924
  for (let index = 0; index < evidence.length; index++) {
1879
1925
  const entry = evidence[index];
1880
- const path5 = `evidence[${index}]`;
1926
+ const path8 = `evidence[${index}]`;
1881
1927
  if (Array.isArray(entry)) {
1882
1928
  throw canonicalEvidenceError({
1883
1929
  claimId: claim.id,
1884
- path: path5,
1930
+ path: path8,
1885
1931
  problem: CANONICAL_EVIDENCE_PROBLEMS.tupleEntry,
1886
1932
  received: entry,
1887
1933
  fix: CANONICAL_EVIDENCE_FIX.tupleEntry
@@ -1890,7 +1936,7 @@ var init_state = __esm({
1890
1936
  if (!entry || typeof entry !== "object") {
1891
1937
  throw canonicalEvidenceError({
1892
1938
  claimId: claim.id,
1893
- path: path5,
1939
+ path: path8,
1894
1940
  problem: CANONICAL_EVIDENCE_PROBLEMS.nonObjectEntry,
1895
1941
  received: entry,
1896
1942
  fix: CANONICAL_EVIDENCE_FIX.nonObjectEntry
@@ -1899,7 +1945,7 @@ var init_state = __esm({
1899
1945
  if (!requiredText(entry.id)) {
1900
1946
  throw canonicalEvidenceError({
1901
1947
  claimId: claim.id,
1902
- path: `${path5}.id`,
1948
+ path: `${path8}.id`,
1903
1949
  problem: CANONICAL_EVIDENCE_PROBLEMS.missingId,
1904
1950
  received: entry,
1905
1951
  fix: CANONICAL_EVIDENCE_FIX.missingId
@@ -1910,7 +1956,7 @@ var init_state = __esm({
1910
1956
  if (fieldValue !== void 0 && !requiredText(fieldValue)) {
1911
1957
  throw canonicalEvidenceError({
1912
1958
  claimId: claim.id,
1913
- path: `${path5}.${field}`,
1959
+ path: `${path8}.${field}`,
1914
1960
  problem: CANONICAL_EVIDENCE_PROBLEMS.invalidOptionalField(field),
1915
1961
  received: fieldValue,
1916
1962
  fix: CANONICAL_EVIDENCE_FIX.invalidOptionalField(field)
@@ -2260,6 +2306,50 @@ var init_scope_eligibility = __esm({
2260
2306
  }
2261
2307
  });
2262
2308
 
2309
+ // core/knowledge/currentness.ts
2310
+ var asRecord, verifiedAtOf, findContestedIds, deriveCurrentness;
2311
+ var init_currentness = __esm({
2312
+ "core/knowledge/currentness.ts"() {
2313
+ asRecord = /* @__PURE__ */ __name((value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0, "asRecord");
2314
+ verifiedAtOf = /* @__PURE__ */ __name((claim) => {
2315
+ const value = asRecord(claim.knowledge)?.verifiedAt;
2316
+ if (typeof value !== "string") return void 0;
2317
+ const parsed = Date.parse(value);
2318
+ return Number.isNaN(parsed) ? void 0 : parsed;
2319
+ }, "verifiedAtOf");
2320
+ findContestedIds = /* @__PURE__ */ __name((claims) => {
2321
+ const retracting = /* @__PURE__ */ new Map();
2322
+ for (const claim of claims) {
2323
+ if (claim.revision?.kind === "retracts" && claim.revision.claimIds.length > 0) {
2324
+ retracting.set(claim.id, new Set(claim.revision.claimIds));
2325
+ }
2326
+ }
2327
+ const contested = /* @__PURE__ */ new Set();
2328
+ for (const [id, targets] of retracting) {
2329
+ for (const target of targets) {
2330
+ if (retracting.get(target)?.has(id)) {
2331
+ contested.add(id);
2332
+ contested.add(target);
2333
+ }
2334
+ }
2335
+ }
2336
+ return contested;
2337
+ }, "findContestedIds");
2338
+ deriveCurrentness = /* @__PURE__ */ __name((claim, context2 = {}) => {
2339
+ const now2 = context2.now ?? Date.now();
2340
+ if (context2.contestedIds?.has(claim.id)) return "contested";
2341
+ if (claim.revision?.kind === "retracts") return "historical";
2342
+ if (context2.retractedIds?.has(claim.id)) return "historical";
2343
+ if (context2.supersededIds?.has(claim.id)) return "superseded";
2344
+ if (claim.expiresAt !== void 0 && now2 >= claim.expiresAt) return "expired";
2345
+ const verifiedAt = verifiedAtOf(claim);
2346
+ if (verifiedAt !== void 0) return "verified";
2347
+ if (claim.epistemicType === "verified") return "unverified";
2348
+ return "unknown-currentness";
2349
+ }, "deriveCurrentness");
2350
+ }
2351
+ });
2352
+
2263
2353
  // core/knowledge/discover.ts
2264
2354
  var diagnostic, DEFAULT_LIMITS, FIELD_ORDER, FIELD_WEIGHT, normalize, discoveryTerms, jsonText, fieldText, acquiredTime, isExpired, rankCandidate, discoverAcquiredExperience;
2265
2355
  var init_discover = __esm({
@@ -2267,6 +2357,7 @@ var init_discover = __esm({
2267
2357
  init_state();
2268
2358
  init_applicability();
2269
2359
  init_scope_eligibility();
2360
+ init_currentness();
2270
2361
  init_env();
2271
2362
  diagnostic = /* @__PURE__ */ __name((message) => {
2272
2363
  if (typeof process !== "undefined" && typeof process.stderr?.write === "function") {
@@ -2379,11 +2470,82 @@ var init_discover = __esm({
2379
2470
  throw new Error("Discovery maxCandidates must be a positive integer");
2380
2471
  }
2381
2472
  const queryTerms = discoveryTerms(situation);
2473
+ const offset = options.cursor?.offset ?? 0;
2474
+ if (!Number.isInteger(offset) || offset < 0) {
2475
+ throw new Error("Discovery cursor offset must be a non-negative integer");
2476
+ }
2477
+ if (options.cursor && options.cursor.knowledgeVersion !== validated.version) {
2478
+ return {
2479
+ knowledgeVersion: validated.version,
2480
+ depth,
2481
+ queryTerms,
2482
+ candidates: [],
2483
+ omissions: [],
2484
+ offset: 0,
2485
+ snapshotChanged: true
2486
+ };
2487
+ }
2382
2488
  const available = activeClaims(validated);
2489
+ const availableIds = new Set(available.map((claim) => claim.id));
2490
+ const retractedIds = /* @__PURE__ */ new Set();
2491
+ const supersededIds = /* @__PURE__ */ new Set();
2492
+ const contestedIds = findContestedIds(validated.claims);
2493
+ for (const claim of validated.claims) {
2494
+ if (claim.revision?.kind === "retracts") {
2495
+ for (const id of claim.revision.claimIds) retractedIds.add(id);
2496
+ }
2497
+ if (claim.revision?.kind === "supersedes") {
2498
+ for (const id of claim.revision.claimIds) supersededIds.add(id);
2499
+ }
2500
+ }
2501
+ const revisionOmissions = validated.claims.filter((claim) => !availableIds.has(claim.id)).map((claim) => {
2502
+ const retracted = retractedIds.has(claim.id);
2503
+ const superseded = supersededIds.has(claim.id);
2504
+ return {
2505
+ id: claim.id,
2506
+ reason: retracted ? "retracted" : superseded ? "superseded" : "retracted",
2507
+ gate: "revision-resolution",
2508
+ ...retracted || superseded ? {} : { detail: "the claim itself retracts prior knowledge and is kept as history" }
2509
+ };
2510
+ }).sort((left, right) => left.id.localeCompare(right.id));
2383
2511
  const scopeEligible = options.currentProjectId === void 0 ? available : available.filter((claim) => isScopeEligible(claim, options.currentProjectId, sources.get(claim.id)));
2384
2512
  const freshEligible = scopeEligible.filter((claim) => !isExpired(claim));
2513
+ const scopeEligibleIds = new Set(scopeEligible.map((claim) => claim.id));
2514
+ const scopeOmissions = available.filter((claim) => !scopeEligibleIds.has(claim.id)).map((claim) => {
2515
+ const owner = claimOwnerProject(claim, sources.get(claim.id));
2516
+ return {
2517
+ id: claim.id,
2518
+ reason: "scope",
2519
+ gate: "scope",
2520
+ detail: owner === void 0 ? "owner project could not be resolved" : `owned by project ${owner}`
2521
+ };
2522
+ }).sort((left, right) => left.id.localeCompare(right.id));
2523
+ const freshIds = new Set(freshEligible.map((claim) => claim.id));
2524
+ const freshnessOmissions = scopeEligible.filter((claim) => !freshIds.has(claim.id)).map((claim) => ({
2525
+ id: claim.id,
2526
+ reason: "expired",
2527
+ gate: "freshness",
2528
+ detail: `expired at ${new Date(claim.expiresAt).toISOString()}`
2529
+ })).sort((left, right) => left.id.localeCompare(right.id));
2385
2530
  const situationApplicability = deriveSituationApplicability(situation, options.facts);
2386
- const eligible = freshEligible.map((claim) => ({ claim, match: isEligibleByApplicability(claim, situationApplicability) })).filter((candidate) => candidate.match.eligible);
2531
+ const applicabilityMatches = new Map(
2532
+ freshEligible.map((claim) => [claim.id, isEligibleByApplicability(claim, situationApplicability)])
2533
+ );
2534
+ const eligible = freshEligible.map((claim) => ({ claim, match: applicabilityMatches.get(claim.id) })).filter((candidate) => candidate.match.eligible);
2535
+ const eligibleForContext = options.includeRules === true ? eligible : eligible.filter((candidate) => {
2536
+ const knowledge = candidate.claim.knowledge;
2537
+ return !(knowledge && typeof knowledge === "object" && !Array.isArray(knowledge) && knowledge.kind === "rule");
2538
+ });
2539
+ const applicabilityOmissions = freshEligible.filter((claim) => !applicabilityMatches.get(claim.id).eligible).map((claim) => {
2540
+ const match = applicabilityMatches.get(claim.id);
2541
+ const mismatched = Object.entries(match.dimensions).filter(([, state3]) => state3 === "MISMATCH").map(([dimension]) => dimension);
2542
+ return {
2543
+ id: claim.id,
2544
+ reason: "applicability-mismatch",
2545
+ gate: "applicability",
2546
+ detail: `mismatching dimensions: ${mismatched.length > 0 ? mismatched.join(", ") : "none recorded"}`
2547
+ };
2548
+ }).sort((left, right) => left.id.localeCompare(right.id));
2387
2549
  if (DEV) {
2388
2550
  diagnostic(
2389
2551
  "[dotmem discovery] ACTIVE=" + JSON.stringify(
@@ -2395,12 +2557,15 @@ var init_discover = __esm({
2395
2557
  )
2396
2558
  );
2397
2559
  }
2560
+ const currentnessOf = /* @__PURE__ */ __name((claim) => deriveCurrentness(claim, { retractedIds, supersededIds, contestedIds }), "currentnessOf");
2398
2561
  if (queryTerms.length === 0) {
2399
- const baseline = eligible.filter((candidate) => candidate.claim.applicability?.baseline === true).map((candidate) => candidate.claim).sort((left, right) => {
2562
+ const baselineAll = eligibleForContext.filter((candidate) => candidate.claim.applicability?.baseline === true).map((candidate) => candidate.claim).sort((left, right) => {
2400
2563
  const leftTime = acquiredTime(left);
2401
2564
  const rightTime = acquiredTime(right);
2402
2565
  return rightTime - leftTime || Number(right.scope === "project") - Number(left.scope === "project") || left.id.localeCompare(right.id);
2403
- }).slice(0, maxCandidates);
2566
+ });
2567
+ const baseline = baselineAll.slice(offset, offset + maxCandidates);
2568
+ const limitOmissions = baselineAll.slice(offset + maxCandidates).map((claim) => ({ id: claim.id, reason: "limit", gate: "ranking" })).sort((left, right) => left.id.localeCompare(right.id));
2404
2569
  const baselineCandidates = baseline.map((claim) => {
2405
2570
  const explanation = {
2406
2571
  matchedTerms: [],
@@ -2413,7 +2578,8 @@ var init_discover = __esm({
2413
2578
  }
2414
2579
  return {
2415
2580
  claim,
2416
- explanation
2581
+ explanation,
2582
+ currentness: currentnessOf(claim)
2417
2583
  };
2418
2584
  });
2419
2585
  if (DEV) {
@@ -2426,10 +2592,18 @@ var init_discover = __esm({
2426
2592
  depth,
2427
2593
  queryTerms,
2428
2594
  situationApplicability,
2429
- candidates: baselineCandidates
2595
+ candidates: baselineCandidates,
2596
+ offset,
2597
+ omissions: [
2598
+ ...revisionOmissions,
2599
+ ...scopeOmissions,
2600
+ ...freshnessOmissions,
2601
+ ...applicabilityOmissions,
2602
+ ...limitOmissions
2603
+ ]
2430
2604
  };
2431
2605
  }
2432
- const candidates = eligible.map(
2606
+ const ranked = eligibleForContext.map(
2433
2607
  (candidate) => rankCandidate(
2434
2608
  candidate.claim,
2435
2609
  situation,
@@ -2441,16 +2615,40 @@ var init_discover = __esm({
2441
2615
  (candidate) => candidate !== null
2442
2616
  ).sort(
2443
2617
  (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)
2444
- ).slice(0, maxCandidates).map(({ claim, explanation }) => ({
2618
+ );
2619
+ const rankedIds = new Set(ranked.map((candidate) => candidate.claim.id));
2620
+ const rankingOmissions = [
2621
+ ...eligibleForContext.filter((candidate) => !rankedIds.has(candidate.claim.id)).map((candidate) => ({
2622
+ id: candidate.claim.id,
2623
+ reason: "no-term-match",
2624
+ gate: "ranking",
2625
+ detail: "passed every gate but shares no query term"
2626
+ })),
2627
+ ...ranked.slice(offset + maxCandidates).map((candidate) => ({
2628
+ id: candidate.claim.id,
2629
+ reason: "limit",
2630
+ gate: "ranking"
2631
+ }))
2632
+ ].sort((left, right) => left.id.localeCompare(right.id));
2633
+ const candidates = ranked.slice(offset, offset + maxCandidates).map(({ claim, explanation }) => ({
2445
2634
  claim,
2446
- explanation
2635
+ explanation,
2636
+ currentness: currentnessOf(claim)
2447
2637
  }));
2448
2638
  return {
2449
2639
  knowledgeVersion: validated.version,
2450
2640
  depth,
2451
2641
  queryTerms,
2452
2642
  situationApplicability,
2453
- candidates
2643
+ candidates,
2644
+ offset,
2645
+ omissions: [
2646
+ ...revisionOmissions,
2647
+ ...scopeOmissions,
2648
+ ...freshnessOmissions,
2649
+ ...applicabilityOmissions,
2650
+ ...rankingOmissions
2651
+ ]
2454
2652
  };
2455
2653
  }, "discoverAcquiredExperience");
2456
2654
  }
@@ -2719,9 +2917,9 @@ var init_policy_namespace_lock = __esm({
2719
2917
  acquiredAt: (/* @__PURE__ */ new Date()).toISOString(),
2720
2918
  token: `lock-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`
2721
2919
  }), "createOwner");
2722
- readLockOwner = /* @__PURE__ */ __name(async (fs7, lockPath) => {
2920
+ readLockOwner = /* @__PURE__ */ __name(async (fs9, lockPath) => {
2723
2921
  try {
2724
- const raw = await fs7.readFile(lockPath, "utf8");
2922
+ const raw = await fs9.readFile(lockPath, "utf8");
2725
2923
  const parsed = JSON.parse(raw);
2726
2924
  if (!parsed || typeof parsed !== "object") return null;
2727
2925
  return {
@@ -2734,11 +2932,11 @@ var init_policy_namespace_lock = __esm({
2734
2932
  return null;
2735
2933
  }
2736
2934
  }, "readLockOwner");
2737
- acquireLock = /* @__PURE__ */ __name(async (fs7, lockPath, owner) => {
2935
+ acquireLock = /* @__PURE__ */ __name(async (fs9, lockPath, owner) => {
2738
2936
  let brokenOwner = null;
2739
2937
  for (let attempt = 0; attempt <= POLICY_LOCK_RETRY_ATTEMPTS; attempt++) {
2740
2938
  try {
2741
- await fs7.writeFile(lockPath, JSON.stringify(owner), { encoding: "utf8", flag: "wx" });
2939
+ await fs9.writeFile(lockPath, JSON.stringify(owner), { encoding: "utf8", flag: "wx" });
2742
2940
  return brokenOwner;
2743
2941
  } catch (error) {
2744
2942
  const code = error?.code;
@@ -2747,12 +2945,12 @@ var init_policy_namespace_lock = __esm({
2747
2945
  `Policy namespace exclusive creation is not verifiable on this substrate (${String(code)}); policy mutation fails closed`
2748
2946
  );
2749
2947
  }
2750
- const held = await readLockOwner(fs7, lockPath);
2948
+ const held = await readLockOwner(fs9, lockPath);
2751
2949
  const acquiredAt = held ? Date.parse(held.acquiredAt) : Number.NaN;
2752
2950
  const age = Number.isFinite(acquiredAt) ? Date.now() - acquiredAt : Number.POSITIVE_INFINITY;
2753
2951
  if (age > POLICY_LOCK_TTL_MS) {
2754
2952
  const stale = held ?? { pid: 0, host: "unknown", acquiredAt: "", token: "" };
2755
- const outcome = await breakStalePolicyLock(fs7, lockPath, stale);
2953
+ const outcome = await breakStalePolicyLock(fs9, lockPath, stale);
2756
2954
  if (outcome === "broken") {
2757
2955
  brokenOwner = stale;
2758
2956
  }
@@ -2771,21 +2969,21 @@ var init_policy_namespace_lock = __esm({
2771
2969
  `Policy namespace lock could not be acquired after ${POLICY_LOCK_RETRY_ATTEMPTS} bounded retries; policy mutation fails closed`
2772
2970
  );
2773
2971
  }, "acquireLock");
2774
- breakStalePolicyLock = /* @__PURE__ */ __name(async (fs7, lockPath, staleOwner) => {
2972
+ breakStalePolicyLock = /* @__PURE__ */ __name(async (fs9, lockPath, staleOwner) => {
2775
2973
  const candidate = `${lockPath}.breaking-${staleOwner.token || "unknown"}`;
2776
2974
  try {
2777
- await fs7.rename(lockPath, candidate);
2975
+ await fs9.rename(lockPath, candidate);
2778
2976
  } catch (error) {
2779
2977
  if (error.code === "ENOENT") return "lost";
2780
2978
  throw error;
2781
2979
  }
2782
- const moved = await readLockOwner(fs7, candidate);
2980
+ const moved = await readLockOwner(fs9, candidate);
2783
2981
  if (moved && moved.token === staleOwner.token) {
2784
- await fs7.rm(candidate, { force: true }).catch(() => void 0);
2982
+ await fs9.rm(candidate, { force: true }).catch(() => void 0);
2785
2983
  return "broken";
2786
2984
  }
2787
2985
  try {
2788
- await fs7.link(candidate, lockPath);
2986
+ await fs9.link(candidate, lockPath);
2789
2987
  } catch (error) {
2790
2988
  const code = error?.code;
2791
2989
  if (code !== "EEXIST") {
@@ -2794,22 +2992,22 @@ var init_policy_namespace_lock = __esm({
2794
2992
  );
2795
2993
  }
2796
2994
  }
2797
- await fs7.rm(candidate, { force: true }).catch(() => void 0);
2995
+ await fs9.rm(candidate, { force: true }).catch(() => void 0);
2798
2996
  return "lost";
2799
2997
  }, "breakStalePolicyLock");
2800
- releaseLock = /* @__PURE__ */ __name(async (fs7, lockPath, owner) => {
2801
- const held = await readLockOwner(fs7, lockPath);
2998
+ releaseLock = /* @__PURE__ */ __name(async (fs9, lockPath, owner) => {
2999
+ const held = await readLockOwner(fs9, lockPath);
2802
3000
  if (!held || held.token !== owner.token) return;
2803
- await fs7.rm(lockPath, { force: true }).catch(() => void 0);
3001
+ await fs9.rm(lockPath, { force: true }).catch(() => void 0);
2804
3002
  }, "releaseLock");
2805
3003
  withPolicyNamespaceLock = /* @__PURE__ */ __name(async (operation, options = {}) => {
2806
3004
  const directory = options.directory ?? resolveUserPolicyDir();
2807
3005
  const lockPath = resolvePolicyNamespaceLockPath(directory);
2808
3006
  return enqueue(directory, async () => {
2809
- const fs7 = await nodeFs2();
3007
+ const fs9 = await nodeFs2();
2810
3008
  const owner = await createOwner();
2811
- await fs7.mkdir(parentDirectoryOf(lockPath), { recursive: true }).catch(() => void 0);
2812
- const brokenOwner = await acquireLock(fs7, lockPath, owner);
3009
+ await fs9.mkdir(parentDirectoryOf(lockPath), { recursive: true }).catch(() => void 0);
3010
+ const brokenOwner = await acquireLock(fs9, lockPath, owner);
2813
3011
  if (brokenOwner && options.onLockBreak) {
2814
3012
  options.onLockBreak({
2815
3013
  at: (/* @__PURE__ */ new Date()).toISOString(),
@@ -2820,7 +3018,7 @@ var init_policy_namespace_lock = __esm({
2820
3018
  try {
2821
3019
  return await operation({
2822
3020
  assertOwnership: /* @__PURE__ */ __name(async () => {
2823
- const held = await readLockOwner(fs7, lockPath);
3021
+ const held = await readLockOwner(fs9, lockPath);
2824
3022
  if (!held || held.token !== owner.token) {
2825
3023
  throw new PolicyNamespaceLockError(
2826
3024
  "Policy namespace lock ownership was lost before commit; policy mutation fails closed"
@@ -2829,7 +3027,7 @@ var init_policy_namespace_lock = __esm({
2829
3027
  }, "assertOwnership")
2830
3028
  });
2831
3029
  } finally {
2832
- await releaseLock(fs7, lockPath, owner);
3030
+ await releaseLock(fs9, lockPath, owner);
2833
3031
  }
2834
3032
  });
2835
3033
  }, "withPolicyNamespaceLock");
@@ -3157,35 +3355,35 @@ var init_policy_store = __esm({
3157
3355
  }
3158
3356
  /** Read one namespace document: always fresh, always validated. */
3159
3357
  async load(namespace2) {
3160
- const fs7 = await nodeFs3();
3161
- return this.readDocument(fs7, namespace2);
3358
+ const fs9 = await nodeFs3();
3359
+ return this.readDocument(fs9, namespace2);
3162
3360
  }
3163
- async readDocument(fs7, namespace2) {
3361
+ async readDocument(fs9, namespace2) {
3164
3362
  let raw;
3165
3363
  try {
3166
- raw = await fs7.readFile(this.filePath(namespace2), "utf8");
3364
+ raw = await fs9.readFile(this.filePath(namespace2), "utf8");
3167
3365
  } catch (error) {
3168
3366
  if (error.code === "ENOENT") return emptyPolicyDocument();
3169
3367
  throw error;
3170
3368
  }
3171
3369
  return validatePolicyDocument(JSON.parse(raw));
3172
3370
  }
3173
- async writeDocument(fs7, namespace2, document) {
3174
- await fs7.mkdir(this.dir(), { recursive: true });
3371
+ async writeDocument(fs9, namespace2, document) {
3372
+ await fs9.mkdir(this.dir(), { recursive: true });
3175
3373
  const filePath = this.filePath(namespace2);
3176
3374
  const temporary = `${filePath}.${process.pid}.${Date.now().toString(36)}.tmp`;
3177
3375
  try {
3178
- await fs7.writeFile(temporary, `${JSON.stringify(document, null, 2)}
3376
+ await fs9.writeFile(temporary, `${JSON.stringify(document, null, 2)}
3179
3377
  `, "utf8");
3180
- const handle = await fs7.open(temporary, "r+");
3378
+ const handle = await fs9.open(temporary, "r+");
3181
3379
  try {
3182
3380
  await handle.sync();
3183
3381
  } finally {
3184
3382
  await handle.close();
3185
3383
  }
3186
- await fs7.rename(temporary, filePath);
3384
+ await fs9.rename(temporary, filePath);
3187
3385
  } catch (error) {
3188
- await fs7.rm(temporary, { force: true }).catch(() => void 0);
3386
+ await fs9.rm(temporary, { force: true }).catch(() => void 0);
3189
3387
  throw error;
3190
3388
  }
3191
3389
  }
@@ -3204,8 +3402,8 @@ var init_policy_store = __esm({
3204
3402
  const lockBreaks = [];
3205
3403
  try {
3206
3404
  return await withPolicyNamespaceLock(async (session2) => {
3207
- const fs7 = await nodeFs3();
3208
- const document = await this.readDocument(fs7, namespace2);
3405
+ const fs9 = await nodeFs3();
3406
+ const document = await this.readDocument(fs9, namespace2);
3209
3407
  if (options.basedOnRevision !== void 0 && options.basedOnRevision !== document.revision) {
3210
3408
  throw new PolicyStoreError(
3211
3409
  `Stale policy revision: caller expected ${options.basedOnRevision}, current document revision is ${document.revision}`
@@ -3226,7 +3424,7 @@ var init_policy_store = __esm({
3226
3424
  }
3227
3425
  validatePolicyDocument(next);
3228
3426
  await session2.assertOwnership();
3229
- await this.writeDocument(fs7, namespace2, next);
3427
+ await this.writeDocument(fs9, namespace2, next);
3230
3428
  return outcome.result;
3231
3429
  }, { directory, onLockBreak: /* @__PURE__ */ __name((lockBreak) => {
3232
3430
  lockBreaks.push(lockBreak);
@@ -3507,7 +3705,7 @@ var init_policy_store = __esm({
3507
3705
  });
3508
3706
 
3509
3707
  // core/knowledge/acquisition-limits.ts
3510
- var MEMORY_ACQUIRE_LIMITS, MEMORY_ACQUIRE_LIMITS_MCP, MEMORY_STORE_LIMITS, DOTMEM_ACQUIRE_ERROR_CODES, MemoryAcquireLimitError, MemoryAcquireConcurrencyError, MemoryAcquireDuplicateClaimError, encoder, serializedBytes, measureKnowledge, checkAcquireLimits;
3708
+ var MEMORY_ACQUIRE_LIMITS, MEMORY_ACQUIRE_LIMITS_MCP, MEMORY_STORE_LIMITS, DOTMEM_ACQUIRE_ERROR_CODES, MemoryAcquireLimitError, MemoryAcquireConcurrencyError, MemoryAcquireDuplicateClaimError, encoder2, serializedBytes, measureKnowledge, checkAcquireLimits;
3511
3709
  var init_acquisition_limits = __esm({
3512
3710
  "core/knowledge/acquisition-limits.ts"() {
3513
3711
  MEMORY_ACQUIRE_LIMITS = Object.freeze({
@@ -3566,10 +3764,10 @@ var init_acquisition_limits = __esm({
3566
3764
  this.name = "MemoryAcquireDuplicateClaimError";
3567
3765
  }
3568
3766
  };
3569
- encoder = new TextEncoder();
3767
+ encoder2 = new TextEncoder();
3570
3768
  serializedBytes = /* @__PURE__ */ __name((value) => {
3571
3769
  const json = JSON.stringify(value);
3572
- return json === void 0 ? 0 : encoder.encode(json).length;
3770
+ return json === void 0 ? 0 : encoder2.encode(json).length;
3573
3771
  }, "serializedBytes");
3574
3772
  measureKnowledge = /* @__PURE__ */ __name((knowledge) => {
3575
3773
  const claimBytes = serializedBytes(knowledge);
@@ -3600,6 +3798,74 @@ var init_acquisition_limits = __esm({
3600
3798
  }
3601
3799
  });
3602
3800
 
3801
+ // core/knowledge/verification.ts
3802
+ var deriveTrustBasis, buildVerificationRecord, callerInjectedVerificationMetadata, isCallerDeclaredVerified;
3803
+ var init_verification = __esm({
3804
+ "core/knowledge/verification.ts"() {
3805
+ deriveTrustBasis = /* @__PURE__ */ __name((claim, options = {}) => {
3806
+ const { packageAuth, externalAttestation, verificationRecord, resolvedEvidence } = options;
3807
+ const evidenceCount = Array.isArray(claim.evidence) ? claim.evidence.length : 0;
3808
+ const resolvedIds = resolvedEvidence ?? /* @__PURE__ */ new Set();
3809
+ const evidenceResolved = evidenceCount > 0 && resolvedIds.size === evidenceCount;
3810
+ const mechanicallyChecked = verificationRecord !== null && verificationRecord !== void 0 && verificationRecord.verifyStatus === "valid";
3811
+ const externallyAttested = packageAuth !== void 0 && packageAuth.status === "valid" && externalAttestation !== void 0 && externalAttestation.validated === true;
3812
+ if (externallyAttested) {
3813
+ return {
3814
+ basis: "externally-attested",
3815
+ reason: "Package signature is cryptographically valid and an external attestation was validated by a trusted mechanism",
3816
+ evidenceResolved,
3817
+ mechanicallyChecked,
3818
+ externallyAttested: true
3819
+ };
3820
+ }
3821
+ if (mechanicallyChecked) {
3822
+ return {
3823
+ basis: "mechanically-checked",
3824
+ reason: `A ${verificationRecord.check.kind} check executed by ${verificationRecord.verifiedBy} at ${verificationRecord.verifiedAt} succeeded; status bounded to ${verificationRecord.verifyStatus}`,
3825
+ evidenceResolved,
3826
+ mechanicallyChecked: true,
3827
+ externallyAttested: false
3828
+ };
3829
+ }
3830
+ if (evidenceCount > 0) {
3831
+ return {
3832
+ basis: "evidenced",
3833
+ reason: `${evidenceCount} evidence reference(s) present but not independently resolved and validated`,
3834
+ evidenceResolved: false,
3835
+ mechanicallyChecked: false,
3836
+ externallyAttested: false
3837
+ };
3838
+ }
3839
+ const declaredLabel = claim.epistemicType === "verified" ? ` (stored label ${claim.epistemicType})` : "";
3840
+ return {
3841
+ basis: "declared",
3842
+ reason: `Caller/author assertion without independent validation${declaredLabel}. Trust follows provenance, not the label.`,
3843
+ evidenceResolved: false,
3844
+ mechanicallyChecked: false,
3845
+ externallyAttested: false
3846
+ };
3847
+ }, "deriveTrustBasis");
3848
+ buildVerificationRecord = /* @__PURE__ */ __name((claimId, probe) => {
3849
+ if (probe.status !== "valid") return null;
3850
+ return {
3851
+ verifiedAt: (/* @__PURE__ */ new Date()).toISOString(),
3852
+ verifiedBy: "dotmem-verify",
3853
+ verifyStatus: probe.status,
3854
+ check: { kind: probe.kind, target: probe.target }
3855
+ };
3856
+ }, "buildVerificationRecord");
3857
+ callerInjectedVerificationMetadata = /* @__PURE__ */ __name((knowledge) => {
3858
+ if (!knowledge || typeof knowledge !== "object" || Array.isArray(knowledge)) return [];
3859
+ const keys = [];
3860
+ for (const key of ["verifiedAt", "verifiedBy", "verifyStatus"]) {
3861
+ if (key in knowledge) keys.push(key);
3862
+ }
3863
+ return keys;
3864
+ }, "callerInjectedVerificationMetadata");
3865
+ isCallerDeclaredVerified = /* @__PURE__ */ __name((value) => value === "verified", "isCallerDeclaredVerified");
3866
+ }
3867
+ });
3868
+
3603
3869
  // core/knowledge/acquisition-boundary.ts
3604
3870
  var MEMORY_ACQUIRE_EVENT, crossAcquisitionBoundary;
3605
3871
  var init_acquisition_boundary = __esm({
@@ -3609,6 +3875,7 @@ var init_acquisition_boundary = __esm({
3609
3875
  init_policy_store();
3610
3876
  init_applicability();
3611
3877
  init_acquisition_limits();
3878
+ init_verification();
3612
3879
  MEMORY_ACQUIRE_EVENT = "memory.acquire";
3613
3880
  if (!(MEMORY_ACQUIRE_EVENT in CANONICAL_EVENTS)) {
3614
3881
  throw new Error(
@@ -3618,6 +3885,12 @@ var init_acquisition_boundary = __esm({
3618
3885
  crossAcquisitionBoundary = /* @__PURE__ */ __name(async (opts, dependencies = {}) => {
3619
3886
  const limits = dependencies.limits ?? MEMORY_ACQUIRE_LIMITS;
3620
3887
  checkAcquireLimits(opts.knowledge, limits);
3888
+ const injected = callerInjectedVerificationMetadata(opts.knowledge);
3889
+ if (injected.length > 0) {
3890
+ throw new Error(
3891
+ `Claim ${opts.id} rejected at write time: caller-supplied verification metadata is not accepted: ${injected.join(", ")}`
3892
+ );
3893
+ }
3621
3894
  const sanitized = sanitizeKnowledge(opts.knowledge);
3622
3895
  if (sanitized.disposition === "reject") {
3623
3896
  throw new Error(
@@ -3664,10 +3937,11 @@ var init_context_constants = __esm({
3664
3937
  });
3665
3938
 
3666
3939
  // core/knowledge/project.ts
3667
- 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;
3940
+ 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;
3668
3941
  var init_project = __esm({
3669
3942
  "core/knowledge/project.ts"() {
3670
3943
  init_state();
3944
+ init_verification();
3671
3945
  init_user_paths();
3672
3946
  init_discover();
3673
3947
  init_context_constants();
@@ -3679,21 +3953,41 @@ var init_project = __esm({
3679
3953
  MIN_MAX_CHARACTERS = DOTMEM_CONTEXT_DEFAULT_MIN_MAX__CHARACTERS;
3680
3954
  projectCandidate = /* @__PURE__ */ __name((candidate) => {
3681
3955
  const claim = validateClaim(candidate.claim);
3956
+ 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" ? {
3957
+ verifiedAt: String(claim.knowledge.verifiedAt),
3958
+ verifiedBy: "dotmem-verify",
3959
+ verifyStatus: String(claim.knowledge.verifyStatus),
3960
+ check: { kind: "probe", target: claim.id }
3961
+ } : null;
3962
+ const derivation = deriveTrustBasis(claim, {
3963
+ verificationRecord,
3964
+ resolvedEvidence: new Set(claim.evidence.map((evidence) => evidence.id).filter((id) => id.length > 0))
3965
+ });
3966
+ const trustBasis = {
3967
+ trustBasis: derivation.basis,
3968
+ evidenceResolved: derivation.evidenceResolved,
3969
+ mechanicallyChecked: derivation.mechanicallyChecked,
3970
+ externallyAttested: derivation.externallyAttested,
3971
+ evidenceResolution: claim.evidence.map((evidence) => ({ id: evidence.id, resolved: false }))
3972
+ };
3682
3973
  return structuredClone({
3683
3974
  id: claim.id,
3684
3975
  status: "prior-acquired-experience-candidate",
3685
3976
  experience: claim.knowledge,
3686
3977
  applicability: claim.applicability,
3687
- evidence: claim.evidence,
3978
+ evidence: claim.evidence.map((evidence) => ({ ...evidence, resolved: false })),
3688
3979
  ...claim.epistemicType ? { epistemicType: claim.epistemicType } : {},
3689
3980
  ...claim.provenance ? { provenance: claim.provenance } : {},
3690
3981
  ...claim.acquiredAt ? { acquiredAt: claim.acquiredAt } : {},
3691
3982
  ...claim.revision ? { revision: claim.revision } : {},
3692
- ...candidate.explanation.sourceId ? { sourceId: candidate.explanation.sourceId } : {}
3983
+ ...candidate.explanation.sourceId ? { sourceId: candidate.explanation.sourceId } : {},
3984
+ ...candidate.currentness ? { currentness: candidate.currentness } : {},
3985
+ trustBasis
3693
3986
  });
3694
3987
  }, "projectCandidate");
3695
3988
  GIST_MAX_LENGTH = 80;
3696
3989
  GIST_KEYS = ["gist", "summary", "statement", "title", "reason", "principle", "finding", "detail"];
3990
+ MANIFEST_ID_LIMIT = 40;
3697
3991
  deriveIndexTopic = /* @__PURE__ */ __name((applicability) => {
3698
3992
  const topic = applicability.topic;
3699
3993
  if (typeof topic === "string" && topic.length > 0) return topic;
@@ -3743,27 +4037,72 @@ var init_project = __esm({
3743
4037
  evidence.supports ?? null
3744
4038
  ]),
3745
4039
  ...experience.epistemicType ? { epistemic: experience.epistemicType } : {},
4040
+ ...experience.currentness ? { currentness: experience.currentness } : {},
3746
4041
  ...experience.provenance ? { provenance: [experience.provenance.source, experience.provenance.detail ?? null] } : {},
3747
4042
  ...experience.acquiredAt ? { acquiredAt: experience.acquiredAt } : {},
3748
4043
  ...experience.revision ? { revision: experience.revision } : {},
3749
- ...experience.sourceId ? { source: experience.sourceId } : {}
4044
+ ...experience.sourceId ? { source: experience.sourceId } : {},
4045
+ ...experience.trustBasis ? { trustBasis: experience.trustBasis } : {}
3750
4046
  }), "renderExperience");
3751
- renderText = /* @__PURE__ */ __name((header, experiences, omittedCandidates) => `${header}${experiences.length ? `
3752
- ${experiences.map(renderExperience).join("\n")}` : ""}
3753
- OMITTED:${omittedCandidates}`, "renderText");
4047
+ renderText = /* @__PURE__ */ __name((header, experiences, omittedCandidates, manifest, render = renderExperience, currentnessSummary) => {
4048
+ const lines = [header];
4049
+ if (experiences.length > 0) lines.push(...experiences.map(render));
4050
+ lines.push(`OMITTED:${omittedCandidates}`);
4051
+ if (manifest && manifest.byReason.length > 0) {
4052
+ lines.push(`OMITTED_BY_REASON:${manifest.byReason.map((entry) => `${entry.reason}=${entry.count}`).join(",")}`);
4053
+ }
4054
+ if (manifest && manifest.items.length > 0) {
4055
+ lines.push(`OMITTED_IDS:${manifest.items.slice(0, MANIFEST_ID_LIMIT).map((item) => item.id).join(",")}`);
4056
+ if (manifest.items.length > MANIFEST_ID_LIMIT) {
4057
+ lines.push(`OMITTED_IDS_TRUNCATED:${manifest.items.length - MANIFEST_ID_LIMIT}`);
4058
+ }
4059
+ }
4060
+ if (currentnessSummary) {
4061
+ lines.push(`CURRENTNESS:${currentnessSummary}`);
4062
+ }
4063
+ return lines.join("\n");
4064
+ }, "renderText");
4065
+ byteLength = /* @__PURE__ */ __name((value) => new TextEncoder().encode(value).length, "byteLength");
4066
+ summarizeOmissions = /* @__PURE__ */ __name((items) => {
4067
+ const counts = /* @__PURE__ */ new Map();
4068
+ for (const item of items) counts.set(item.reason, (counts.get(item.reason) ?? 0) + 1);
4069
+ return [...counts.entries()].map(([reason, count]) => ({ reason, count })).sort((left, right) => left.reason.localeCompare(right.reason));
4070
+ }, "summarizeOmissions");
4071
+ renderManifestFitting = /* @__PURE__ */ __name((header, experiences, omittedCandidates, manifest, maxCharacters, render, currentnessSummary) => {
4072
+ const full = renderText(header, experiences, omittedCandidates, manifest, render, currentnessSummary);
4073
+ if (byteLength(full) <= maxCharacters) return full;
4074
+ const withoutIds = { ...manifest, items: [] };
4075
+ return renderText(header, experiences, omittedCandidates, withoutIds, render, currentnessSummary);
4076
+ }, "renderManifestFitting");
4077
+ renderCompactExperience = /* @__PURE__ */ __name((experience) => JSON.stringify({
4078
+ id: experience.id,
4079
+ status: "candidate",
4080
+ gist: deriveGist(experience.experience),
4081
+ epistemic: experience.epistemicType ?? null,
4082
+ currentness: experience.currentness ?? null,
4083
+ trustBasis: experience.trustBasis?.trustBasis ?? null,
4084
+ ...experience.revision ? { revision: experience.revision.kind } : {}
4085
+ }), "renderCompactExperience");
3754
4086
  projectDiscoveredExperience = /* @__PURE__ */ __name((discovery, options = {}) => {
3755
4087
  if (!discovery || !Number.isInteger(discovery.knowledgeVersion) || discovery.knowledgeVersion < 0 || !Array.isArray(discovery.candidates)) {
3756
4088
  throw new Error("Valid DiscoveryResult is required for context projection");
3757
4089
  }
3758
4090
  const maxCandidates = options.maxCandidates ?? DEFAULT_MAX_CANDIDATES;
3759
4091
  const maxCharacters = options.maxCharacters ?? DEFAULT_MAX_CHARACTERS;
4092
+ const format = options.format ?? "compact";
4093
+ if (format !== "compact" && format !== "standard" && format !== "full") {
4094
+ throw new Error("Projection format must be compact, standard or full");
4095
+ }
3760
4096
  if (!Number.isInteger(maxCandidates) || maxCandidates < 1) throw new Error("Projection maxCandidates must be a positive integer");
3761
4097
  if (!Number.isInteger(maxCharacters) || maxCharacters < MIN_MAX_CHARACTERS) {
3762
4098
  throw new Error(`Projection maxCharacters must be an integer of at least ${MIN_MAX_CHARACTERS}`);
3763
4099
  }
3764
- const totalCandidates = discovery.candidates.length;
4100
+ const render = /* @__PURE__ */ __name((experience) => format === "compact" ? renderCompactExperience(experience) : renderExperience(experience), "render");
4101
+ const gateOmissions = discovery.omissions ?? [];
4102
+ const totalCandidates = discovery.candidates.length + gateOmissions.length;
3765
4103
  const header = renderHeader(discovery.knowledgeVersion, totalCandidates);
3766
- if (renderText(header, [], totalCandidates).length > maxCharacters) {
4104
+ const emptyManifest = { considered: totalCandidates, included: 0, items: [], byReason: [] };
4105
+ if (byteLength(renderText(header, [], totalCandidates, emptyManifest)) > maxCharacters) {
3767
4106
  throw new Error("Projection maxCharacters is too small for the projection envelope");
3768
4107
  }
3769
4108
  const experiences = [];
@@ -3772,12 +4111,49 @@ OMITTED:${omittedCandidates}`, "renderText");
3772
4111
  const projected = projectCandidate(candidate);
3773
4112
  const possibleExperiences = [...experiences, projected];
3774
4113
  const possibleOmitted = totalCandidates - possibleExperiences.length;
3775
- if (renderText(header, possibleExperiences, possibleOmitted).length <= maxCharacters) {
4114
+ const candidateManifest = {
4115
+ considered: totalCandidates,
4116
+ included: possibleExperiences.length,
4117
+ items: gateOmissions,
4118
+ byReason: summarizeOmissions(gateOmissions)
4119
+ };
4120
+ if (byteLength(renderText(header, possibleExperiences, possibleOmitted, candidateManifest, render)) <= maxCharacters) {
4121
+ experiences.push(projected);
4122
+ continue;
4123
+ }
4124
+ if (byteLength(renderText(header, possibleExperiences, possibleOmitted, void 0, render)) <= maxCharacters) {
3776
4125
  experiences.push(projected);
3777
4126
  }
3778
4127
  }
4128
+ const projectedIds = new Set(experiences.map((experience) => experience.id));
4129
+ const budgetOmissions = discovery.candidates.filter((candidate) => !projectedIds.has(candidate.claim.id)).map((candidate) => ({ id: candidate.claim.id, reason: "budget", gate: "projection" }));
4130
+ const items = [...gateOmissions, ...budgetOmissions];
3779
4131
  const omittedCandidates = totalCandidates - experiences.length;
3780
- const text = renderText(header, experiences, omittedCandidates);
4132
+ const manifest = {
4133
+ considered: totalCandidates,
4134
+ included: experiences.length,
4135
+ items,
4136
+ byReason: summarizeOmissions(items)
4137
+ };
4138
+ const currentnessCounts = /* @__PURE__ */ new Map();
4139
+ for (const experience of experiences) {
4140
+ if (experience.currentness) {
4141
+ currentnessCounts.set(
4142
+ experience.currentness,
4143
+ (currentnessCounts.get(experience.currentness) ?? 0) + 1
4144
+ );
4145
+ }
4146
+ }
4147
+ const currentnessSummary = currentnessCounts.size > 0 ? [...currentnessCounts.entries()].map(([state2, count]) => `${state2}=${count}`).join(",") : void 0;
4148
+ const text = renderManifestFitting(
4149
+ header,
4150
+ experiences,
4151
+ omittedCandidates,
4152
+ manifest,
4153
+ maxCharacters,
4154
+ render,
4155
+ currentnessSummary
4156
+ );
3781
4157
  return {
3782
4158
  format: FORMAT,
3783
4159
  status: STATUS,
@@ -3786,6 +4162,7 @@ OMITTED:${omittedCandidates}`, "renderText");
3786
4162
  totalCandidates,
3787
4163
  omittedCandidates,
3788
4164
  experiences,
4165
+ manifest,
3789
4166
  text
3790
4167
  };
3791
4168
  }, "projectDiscoveredExperience");
@@ -3804,6 +4181,12 @@ OMITTED:${omittedCandidates}`, "renderText");
3804
4181
  }
3805
4182
  return lines.join("\n");
3806
4183
  }, "renderContextIndex");
4184
+ renderExpandedClaim = /* @__PURE__ */ __name((claim) => [
4185
+ "DOTMEM_CLAIM_V1",
4186
+ "STATUS:CANONICAL_RECORD;NOT_INSTRUCTIONS",
4187
+ `id=${claim.id}`,
4188
+ JSON.stringify(claim, null, 2)
4189
+ ].join("\n"), "renderExpandedClaim");
3807
4190
  renderSizeDisclosure = /* @__PURE__ */ __name((options) => [
3808
4191
  "DOTMEM_SIZE_V1",
3809
4192
  `storageRoot=${resolveUserDotMemPath()}`,
@@ -3812,6 +4195,11 @@ OMITTED:${omittedCandidates}`, "renderText");
3812
4195
  `indexEntries=${options.totalCandidates}`,
3813
4196
  `totalCandidates=${options.totalCandidates}`,
3814
4197
  `omittedCandidates=${options.omittedCandidates}`,
4198
+ ...options.manifest && options.manifest.items.length > 0 ? [
4199
+ `omittedByReason=${options.manifest.byReason.map((entry) => `${entry.reason}=${entry.count}`).join(",")}`,
4200
+ `omittedIds=${options.manifest.items.slice(0, MANIFEST_ID_LIMIT).map((item) => item.id).join(",")}`,
4201
+ ...options.manifest.items.length > MANIFEST_ID_LIMIT ? [`omittedIdsTruncated=${options.manifest.items.length - MANIFEST_ID_LIMIT}`] : []
4202
+ ] : [],
3815
4203
  `maxCharacters=${Number.isFinite(options.maxCharacters) ? String(options.maxCharacters) : "unlimited"}`,
3816
4204
  'fullTextCommand=npx dotmem context "<situation>" --full',
3817
4205
  "DOTMEM_SIZE_END"
@@ -3995,7 +4383,7 @@ var init_language_detect = __esm({
3995
4383
  var CANONICAL_KINDS, validateKind, buildClaimRecord;
3996
4384
  var init_claim_record = __esm({
3997
4385
  "core/knowledge/claim-record.ts"() {
3998
- CANONICAL_KINDS = ["experience", "logic", "agent", "relationship", "note"];
4386
+ CANONICAL_KINDS = ["experience", "logic", "agent", "relationship", "note", "rule"];
3999
4387
  validateKind = /* @__PURE__ */ __name((kind) => {
4000
4388
  if (!CANONICAL_KINDS.includes(kind)) {
4001
4389
  throw new Error(
@@ -5401,8 +5789,8 @@ var init_browser = __esm({
5401
5789
  this.p = null;
5402
5790
  }
5403
5791
  };
5404
- Unzip2.prototype.register = function(decoder2) {
5405
- this.o[decoder2.compression] = decoder2;
5792
+ Unzip2.prototype.register = function(decoder) {
5793
+ this.o[decoder.compression] = decoder;
5406
5794
  };
5407
5795
  return Unzip2;
5408
5796
  })();
@@ -5422,6 +5810,15 @@ function encodeMemFile(stateValue, preserved) {
5422
5810
  if (!map.claim.includes("kind")) {
5423
5811
  map.claim.push("kind");
5424
5812
  }
5813
+ if (!map.claim.includes("expires-at")) {
5814
+ map.claim.push("expires-at");
5815
+ }
5816
+ if (!map.claim.includes("bootstrap-priority")) {
5817
+ map.claim.push("bootstrap-priority");
5818
+ }
5819
+ if (!map.claim.includes("check")) {
5820
+ map.claim.push("check");
5821
+ }
5425
5822
  const indexes = Object.fromEntries(Object.keys(expectedFields).map((name) => [name, fieldIndexes(map, name)]));
5426
5823
  validateVocabulary(map.epistemicType, epistemicTypes, "epistemicType");
5427
5824
  validateVocabulary(map.revisionKind, revisionKinds, "revisionKind");
@@ -5471,6 +5868,15 @@ function encodeMemFile(stateValue, preserved) {
5471
5868
  if (indexes.claim.has("kind")) {
5472
5869
  putOptional(record, indexes.claim, "kind", claim.kind ?? void 0, original !== void 0);
5473
5870
  }
5871
+ if (indexes.claim.has("expires-at")) {
5872
+ putOptional(record, indexes.claim, "expires-at", claim.expiresAt, original !== void 0);
5873
+ }
5874
+ if (indexes.claim.has("bootstrap-priority")) {
5875
+ putOptional(record, indexes.claim, "bootstrap-priority", claim.bootstrapPriority, original !== void 0);
5876
+ }
5877
+ if (indexes.claim.has("check")) {
5878
+ putOptional(record, indexes.claim, "check", claim.check, original !== void 0);
5879
+ }
5474
5880
  return original ? record : trimRecord(record);
5475
5881
  }, "encodeClaim");
5476
5882
  const stateRecord = structuredClone(preserved?.data ?? []);
@@ -5539,8 +5945,37 @@ function decodeMemDocument(value) {
5539
5945
  const scope = optionalGet(record, indexes.claim, "scope");
5540
5946
  const sourceProject = optionalGet(record, indexes.claim, "source-project");
5541
5947
  const kindValue = optionalGet(record, indexes.claim, "kind");
5948
+ const expiresAtValue = indexes.claim.has("expires-at") ? optionalGet(record, indexes.claim, "expires-at") : void 0;
5949
+ const bootstrapPriorityValue = indexes.claim.has("bootstrap-priority") ? optionalGet(record, indexes.claim, "bootstrap-priority") : void 0;
5950
+ const checkValue = indexes.claim.has("check") ? optionalGet(record, indexes.claim, "check") : void 0;
5542
5951
  if (epistemicIndex !== void 0 && (!Number.isInteger(epistemicIndex) || epistemicIndex < 0 || epistemicIndex >= epistemic.length)) throw new Error("Invalid .mem epistemic value");
5543
5952
  if (kindIndex !== void 0 && (!Number.isInteger(kindIndex) || kindIndex < 0 || kindIndex >= revisions.length)) throw new Error("Invalid .mem revision value");
5953
+ if (expiresAtValue !== void 0 && (!Number.isInteger(expiresAtValue) || expiresAtValue < 0)) {
5954
+ throw new Error("Invalid .mem expiresAt value");
5955
+ }
5956
+ if (bootstrapPriorityValue !== void 0 && !bootstrapPriorities.includes(bootstrapPriorityValue)) {
5957
+ throw new Error("Invalid .mem bootstrapPriority value");
5958
+ }
5959
+ let check;
5960
+ if (checkValue !== void 0) {
5961
+ if (!checkValue || typeof checkValue !== "object" || Array.isArray(checkValue)) {
5962
+ throw new Error("Invalid .mem check record");
5963
+ }
5964
+ const checkRecord = checkValue;
5965
+ const description = checkRecord.description;
5966
+ if (typeof description !== "undefined" && typeof description !== "string") {
5967
+ throw new Error("Invalid .mem check record");
5968
+ }
5969
+ if (checkRecord.kind !== "regex" || typeof checkRecord.pattern !== "string" || checkRecord.pattern.length === 0 || !checkTargets.includes(checkRecord.on)) {
5970
+ throw new Error("Invalid .mem check record");
5971
+ }
5972
+ check = {
5973
+ kind: "regex",
5974
+ pattern: checkRecord.pattern,
5975
+ on: checkRecord.on,
5976
+ ...typeof description === "string" ? { description } : {}
5977
+ };
5978
+ }
5544
5979
  const understoodEpistemic = typeof epistemicIndex === "number" && epistemicTypes.includes(epistemic[epistemicIndex]) ? epistemic[epistemicIndex] : void 0;
5545
5980
  const understoodRevision = typeof kindIndex === "number" && revisionKinds.includes(revisions[kindIndex]);
5546
5981
  const claim = {
@@ -5565,6 +6000,9 @@ function decodeMemDocument(value) {
5565
6000
  } : {},
5566
6001
  ...scope === void 0 ? {} : { scope },
5567
6002
  ...sourceProject === void 0 ? {} : { sourceProject },
6003
+ ...expiresAtValue === void 0 ? {} : { expiresAt: expiresAtValue },
6004
+ ...bootstrapPriorityValue === void 0 ? {} : { bootstrapPriority: bootstrapPriorityValue },
6005
+ ...check === void 0 ? {} : { check },
5568
6006
  ...claimKinds.includes(kindValue) ? { kind: kindValue } : {}
5569
6007
  };
5570
6008
  return validateClaim(claim);
@@ -5574,7 +6012,7 @@ function decodeMemDocument(value) {
5574
6012
  preserved: { map: structuredClone(map), data: structuredClone(stateRecord) }
5575
6013
  };
5576
6014
  }
5577
- 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;
6015
+ 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;
5578
6016
  var init_mem_codec = __esm({
5579
6017
  "core/knowledge/mem-codec.ts"() {
5580
6018
  init_state();
@@ -5591,7 +6029,9 @@ var init_mem_codec = __esm({
5591
6029
  };
5592
6030
  epistemicTypes = ["observed", "inferred", "human-stated", "verified"];
5593
6031
  revisionKinds = ["refines", "supersedes", "retracts"];
5594
- claimKinds = ["experience", "agent", "relationship", "logic", "note"];
6032
+ claimKinds = ["experience", "agent", "relationship", "logic", "note", "rule"];
6033
+ bootstrapPriorities = ["P1", "P2", "P3", "P4", "P5", "unclassified"];
6034
+ checkTargets = ["staged", "committed", "working-tree"];
5595
6035
  isJsonValue2 = /* @__PURE__ */ __name((value) => {
5596
6036
  if (value === null || typeof value === "string" || typeof value === "boolean") return true;
5597
6037
  if (typeof value === "number") return Number.isFinite(value);
@@ -5671,8 +6111,8 @@ async function signMemPackage(input, privateKey, publicKey) {
5671
6111
  const artifact = await decodePackage(input);
5672
6112
  const rawPublicKey = new Uint8Array(await crypto.subtle.exportKey("raw", publicKey));
5673
6113
  const keyId = await keyIdentity(rawPublicKey);
5674
- const path5 = signaturePath(keyId);
5675
- const existingSignatures = { ...artifact.package?.signatures, [path5]: jsonBytes({}) };
6114
+ const path8 = signaturePath(keyId);
6115
+ const existingSignatures = { ...artifact.package?.signatures, [path8]: jsonBytes({}) };
5676
6116
  const declaredPackage = await encodePackage(artifact.state, artifact.preserved, artifact.package, existingSignatures);
5677
6117
  const declaredArtifact = await decodePackage(declaredPackage);
5678
6118
  const signature = new Uint8Array(await crypto.subtle.sign(
@@ -5691,18 +6131,18 @@ async function signMemPackage(input, privateKey, publicKey) {
5691
6131
  };
5692
6132
  return encodePackage(artifact.state, artifact.preserved, artifact.package, {
5693
6133
  ...artifact.package?.signatures,
5694
- [path5]: jsonBytes(document)
6134
+ [path8]: jsonBytes(document)
5695
6135
  });
5696
6136
  }
5697
6137
  async function decodeMemArtifact(input) {
5698
- const bytes = typeof input === "string" ? encoder2.encode(input) : input;
6138
+ const bytes = typeof input === "string" ? encoder3.encode(input) : input;
5699
6139
  if (isZip(bytes)) {
5700
6140
  const { parts: _parts, integrity: _integrity, ...artifact } = await decodePackage(bytes);
5701
6141
  return artifact;
5702
6142
  }
5703
6143
  let value;
5704
6144
  try {
5705
- value = JSON.parse(decoder.decode(bytes).replace(/^\uFEFF/, ""));
6145
+ value = JSON.parse(decodeText(bytes));
5706
6146
  } catch (error) {
5707
6147
  throw new MemArtifactError("corrupt", `Unsupported or corrupt MEM artifact: ${error.message}`);
5708
6148
  }
@@ -5717,13 +6157,13 @@ async function decodeMemArtifact(input) {
5717
6157
  }
5718
6158
  async function inspectMem(input) {
5719
6159
  try {
5720
- const bytes = typeof input === "string" ? encoder2.encode(input) : input;
6160
+ const bytes = typeof input === "string" ? encodeText(input) : input;
5721
6161
  if (isZip(bytes)) {
5722
6162
  const artifact2 = await decodePackage(bytes);
5723
6163
  const knownMapKeys = /* @__PURE__ */ new Set(["state", "claim", "evidence", "provenance", "revision", "epistemicType", "revisionKind"]);
5724
6164
  const unknownMapEntries = Object.keys(artifact2.preserved?.map ?? {}).filter((key) => !knownMapKeys.has(key)).length;
5725
6165
  const vocabularyEntries = Math.max(0, (artifact2.preserved?.map.epistemicType.length ?? 4) - 4) + Math.max(0, (artifact2.preserved?.map.revisionKind.length ?? 3) - 3);
5726
- 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)));
6166
+ 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)));
5727
6167
  const authenticityStatus = signatures.length === 0 ? "unsigned" : signatures.some((signature) => signature.status === "invalid") ? "invalid" : signatures.some((signature) => signature.status === "unsupported") ? "unsupported" : "valid";
5728
6168
  return {
5729
6169
  status: "valid",
@@ -5732,10 +6172,10 @@ async function inspectMem(input) {
5732
6172
  packageVersion: MEM_PACKAGE_VERSION,
5733
6173
  memoryVersion: MEM_FORMAT_VERSION,
5734
6174
  contentId: artifact2.integrity.contentId,
5735
- parts: Object.entries(artifact2.parts).sort(([a], [b]) => a.localeCompare(b)).map(([path5, part]) => ({
5736
- path: path5,
6175
+ parts: Object.entries(artifact2.parts).sort(([a], [b]) => a.localeCompare(b)).map(([path8, part]) => ({
6176
+ path: path8,
5737
6177
  bytes: part.length,
5738
- protected: path5 !== INTEGRITY_PATH && !path5.startsWith("security/signatures/")
6178
+ protected: path8 !== INTEGRITY_PATH && !path8.startsWith("security/signatures/")
5739
6179
  })),
5740
6180
  knowledge: artifact2.state,
5741
6181
  unknownSemantics: { mapEntries: unknownMapEntries, vocabularyEntries, extensionParts: Object.keys(artifact2.package?.extensions ?? {}).sort() },
@@ -5758,11 +6198,12 @@ async function inspectMem(input) {
5758
6198
  return { status: artifactError.code, representation: "unknown", message: artifactError.message, parts: [] };
5759
6199
  }
5760
6200
  }
5761
- 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;
6201
+ 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;
5762
6202
  var init_mem_package = __esm({
5763
6203
  "core/knowledge/mem-package.ts"() {
5764
6204
  init_browser();
5765
6205
  init_mem_codec();
6206
+ init_text_encoding();
5766
6207
  MEM_PACKAGE_FORMAT = "dotmem.package";
5767
6208
  MEM_PACKAGE_FORMAT_LEGACY = "memorio.package";
5768
6209
  MEM_PACKAGE_VERSION = 1;
@@ -5786,8 +6227,7 @@ var init_mem_package = __esm({
5786
6227
  DATA_PATH = "memory/data.json";
5787
6228
  INTEGRITY_PATH = "security/integrity.json";
5788
6229
  requiredParts = [MANIFEST_PATH, MAP_PATH, DATA_PATH];
5789
- encoder2 = new TextEncoder();
5790
- decoder = new TextDecoder("utf-8", { fatal: true });
6230
+ encoder3 = new TextEncoder();
5791
6231
  MemArtifactError = class extends Error {
5792
6232
  constructor(code, message) {
5793
6233
  super(message);
@@ -5806,21 +6246,21 @@ var init_mem_package = __esm({
5806
6246
  }
5807
6247
  return value;
5808
6248
  }, "stableValue");
5809
- jsonBytes = /* @__PURE__ */ __name((value) => encoder2.encode(`${JSON.stringify(stableValue(value), null, 2)}
6249
+ jsonBytes = /* @__PURE__ */ __name((value) => encoder3.encode(`${JSON.stringify(stableValue(value), null, 2)}
5810
6250
  `), "jsonBytes");
5811
6251
  sha256 = /* @__PURE__ */ __name(async (data) => {
5812
6252
  if (!globalThis.crypto?.subtle) throw new MemArtifactError("unsupported", "SHA-256 is unavailable in this runtime");
5813
6253
  const digest = await globalThis.crypto.subtle.digest("SHA-256", data);
5814
6254
  return `sha256:${[...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
5815
6255
  }, "sha256");
5816
- parseJson = /* @__PURE__ */ __name((bytes, path5) => {
6256
+ parseJson = /* @__PURE__ */ __name((bytes, path8) => {
5817
6257
  try {
5818
- return JSON.parse(decoder.decode(bytes));
6258
+ return JSON.parse(decodeText(bytes));
5819
6259
  } catch (error) {
5820
- throw new MemArtifactError("invalid", `Invalid UTF-8 JSON in ${path5}: ${error.message}`);
6260
+ throw new MemArtifactError("invalid", `Invalid UTF-8 JSON in ${path8}: ${error.message}`);
5821
6261
  }
5822
6262
  }, "parseJson");
5823
- 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");
6263
+ 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");
5824
6264
  concatenate = /* @__PURE__ */ __name((chunks, size) => {
5825
6265
  const result = new Uint8Array(size);
5826
6266
  let offset = 0;
@@ -5881,7 +6321,7 @@ var init_mem_package = __esm({
5881
6321
  parts: { map: MAP_PATH, data: DATA_PATH, integrity: INTEGRITY_PATH }
5882
6322
  }), "createManifest");
5883
6323
  digestTableIdentity = /* @__PURE__ */ __name((files) => sha256(jsonBytes(files)), "digestTableIdentity");
5884
- signaturePayload = /* @__PURE__ */ __name((contentId) => encoder2.encode(`DOTMEM-PACKAGE-SIGNATURE-V1
6324
+ signaturePayload = /* @__PURE__ */ __name((contentId) => encoder3.encode(`DOTMEM-PACKAGE-SIGNATURE-V1
5885
6325
  ${contentId}
5886
6326
  `), "signaturePayload");
5887
6327
  base64UrlEncode = /* @__PURE__ */ __name((value) => {
@@ -5912,31 +6352,31 @@ ${contentId}
5912
6352
  [DATA_PATH]: jsonBytes(memory2.data),
5913
6353
  ...structuredClone(preservedPackage?.extensions ?? {})
5914
6354
  };
5915
- for (const path5 of Object.keys(protectedParts)) {
5916
- if (!requiredParts.includes(path5) && !path5.startsWith("extensions/")) {
5917
- throw new MemArtifactError("invalid", `Unsupported preserved package part: ${path5}`);
6355
+ for (const path8 of Object.keys(protectedParts)) {
6356
+ if (!requiredParts.includes(path8) && !path8.startsWith("extensions/")) {
6357
+ throw new MemArtifactError("invalid", `Unsupported preserved package part: ${path8}`);
5918
6358
  }
5919
- if (!validEntryPath(path5)) throw new MemArtifactError("invalid", `Unsafe MEM package path: ${path5}`);
6359
+ if (!validEntryPath(path8)) throw new MemArtifactError("invalid", `Unsafe MEM package path: ${path8}`);
5920
6360
  }
5921
- for (const path5 of Object.keys(signatures)) {
5922
- if (!/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path5)) {
5923
- throw new MemArtifactError("invalid", `Invalid MEM signature path: ${path5}`);
6361
+ for (const path8 of Object.keys(signatures)) {
6362
+ if (!/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path8)) {
6363
+ throw new MemArtifactError("invalid", `Invalid MEM signature path: ${path8}`);
5924
6364
  }
5925
6365
  }
5926
6366
  const files = {};
5927
- for (const path5 of Object.keys(protectedParts).sort()) files[path5] = await sha256(protectedParts[path5]);
6367
+ for (const path8 of Object.keys(protectedParts).sort()) files[path8] = await sha256(protectedParts[path8]);
5928
6368
  const integrity = { algorithm: "sha256", files, contentId: await digestTableIdentity(files) };
5929
6369
  const parts = { ...protectedParts, [INTEGRITY_PATH]: jsonBytes(integrity), ...signatures };
5930
- for (const [path5, bytes] of Object.entries(parts)) {
6370
+ for (const [path8, bytes] of Object.entries(parts)) {
5931
6371
  if (bytes.length > MEM_PACKAGE_WRITE_LIMITS.maximumEntryBytes) {
5932
- throw new MemArtifactError("invalid", `MEM package entry exceeds the write limit: ${path5}`);
6372
+ throw new MemArtifactError("invalid", `MEM package entry exceeds the write limit: ${path8}`);
5933
6373
  }
5934
6374
  }
5935
6375
  const uncompressedBytes = Object.values(parts).reduce((total, bytes) => total + bytes.length, 0);
5936
6376
  if (uncompressedBytes > MEM_PACKAGE_WRITE_LIMITS.maximumUncompressedBytes) {
5937
6377
  throw new MemArtifactError("invalid", "MEM package exceeds the write limit for uncompressed content");
5938
6378
  }
5939
- const zippable = Object.fromEntries(Object.keys(parts).sort().map((path5) => [path5, [parts[path5], {
6379
+ const zippable = Object.fromEntries(Object.keys(parts).sort().map((path8) => [path8, [parts[path8], {
5940
6380
  level: 6,
5941
6381
  mtime: /* @__PURE__ */ new Date("1980-01-02T00:00:00.000Z")
5942
6382
  }]]));
@@ -5951,8 +6391,8 @@ ${contentId}
5951
6391
  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");
5952
6392
  decodePackage = /* @__PURE__ */ __name(async (bytes) => {
5953
6393
  const parts = readZipParts(bytes);
5954
- for (const path5 of [...requiredParts, INTEGRITY_PATH]) {
5955
- if (!parts[path5]) throw new MemArtifactError("invalid", `Missing MEM package part: ${path5}`);
6394
+ for (const path8 of [...requiredParts, INTEGRITY_PATH]) {
6395
+ if (!parts[path8]) throw new MemArtifactError("invalid", `Missing MEM package part: ${path8}`);
5956
6396
  }
5957
6397
  const manifest = parseJson(parts[MANIFEST_PATH], MANIFEST_PATH);
5958
6398
  if (manifest.format !== MEM_PACKAGE_FORMAT && manifest.format !== MEM_PACKAGE_FORMAT_LEGACY || manifest.version !== MEM_PACKAGE_VERSION) {
@@ -5963,8 +6403,8 @@ ${contentId}
5963
6403
  }
5964
6404
  const integrity = parseJson(parts[INTEGRITY_PATH], INTEGRITY_PATH);
5965
6405
  if (integrity.algorithm !== "sha256") throw new MemArtifactError("unsupported", "Unsupported MEM package integrity algorithm");
5966
- const signaturePaths = Object.keys(parts).filter((path5) => path5.startsWith("security/signatures/")).sort();
5967
- if (signaturePaths.some((path5) => !/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path5))) {
6406
+ const signaturePaths = Object.keys(parts).filter((path8) => path8.startsWith("security/signatures/")).sort();
6407
+ if (signaturePaths.some((path8) => !/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path8))) {
5968
6408
  throw new MemArtifactError("invalid", "Invalid MEM signature entry path");
5969
6409
  }
5970
6410
  if (manifest.authenticity !== void 0 && manifest.authenticity.signed !== true) {
@@ -5973,14 +6413,14 @@ ${contentId}
5973
6413
  if (manifest.authenticity?.signed === true !== signaturePaths.length > 0) {
5974
6414
  throw new MemArtifactError("invalid", "Declared MEM signatures do not match package entries");
5975
6415
  }
5976
- const archivePaths = Object.keys(parts).filter((path5) => path5 !== INTEGRITY_PATH && !path5.startsWith("security/signatures/")).sort();
6416
+ const archivePaths = Object.keys(parts).filter((path8) => path8 !== INTEGRITY_PATH && !path8.startsWith("security/signatures/")).sort();
5977
6417
  const protectedPaths = Object.keys(integrity.files ?? {}).sort();
5978
6418
  if (JSON.stringify(archivePaths) !== JSON.stringify(protectedPaths)) {
5979
6419
  throw new MemArtifactError("invalid", "MEM package protected-parts table does not match archive contents");
5980
6420
  }
5981
- for (const path5 of protectedPaths) {
5982
- const actual = await sha256(parts[path5]);
5983
- if (integrity.files[path5] !== actual) throw new MemArtifactError("checksum_mismatch", `Checksum mismatch for ${path5}`);
6421
+ for (const path8 of protectedPaths) {
6422
+ const actual = await sha256(parts[path8]);
6423
+ if (integrity.files[path8] !== actual) throw new MemArtifactError("checksum_mismatch", `Checksum mismatch for ${path8}`);
5984
6424
  }
5985
6425
  if (integrity.contentId !== await digestTableIdentity(integrity.files)) {
5986
6426
  throw new MemArtifactError("checksum_mismatch", "MEM package content identity mismatch");
@@ -5993,14 +6433,14 @@ ${contentId}
5993
6433
  } catch (error) {
5994
6434
  throw new MemArtifactError("invalid", `Invalid packaged MEM semantics: ${error.message}`);
5995
6435
  }
5996
- const extensions = Object.fromEntries(Object.entries(parts).filter(([path5]) => path5.startsWith("extensions/")));
5997
- const signatures = Object.fromEntries(signaturePaths.map((path5) => [path5, parts[path5]]));
6436
+ const extensions = Object.fromEntries(Object.entries(parts).filter(([path8]) => path8.startsWith("extensions/")));
6437
+ const signatures = Object.fromEntries(signaturePaths.map((path8) => [path8, parts[path8]]));
5998
6438
  return { ...decoded, representation: "package-v1", package: { manifest, extensions, signatures }, parts, integrity };
5999
6439
  }, "decodePackage");
6000
- verifySignature = /* @__PURE__ */ __name(async (path5, bytes, contentId) => {
6440
+ verifySignature = /* @__PURE__ */ __name(async (path8, bytes, contentId) => {
6001
6441
  let document;
6002
6442
  try {
6003
- document = parseJson(bytes, path5);
6443
+ document = parseJson(bytes, path8);
6004
6444
  } catch (error) {
6005
6445
  return { status: "invalid", message: error.message };
6006
6446
  }
@@ -6032,7 +6472,7 @@ ${contentId}
6032
6472
  const publicKeyBytes = base64UrlDecode(document.publicKey.value);
6033
6473
  const signatureBytes = base64UrlDecode(document.signature.value);
6034
6474
  const derivedKeyId = await keyIdentity(publicKeyBytes);
6035
- if (derivedKeyId !== document.keyId || signaturePath(derivedKeyId) !== path5) {
6475
+ if (derivedKeyId !== document.keyId || signaturePath(derivedKeyId) !== path8) {
6036
6476
  return {
6037
6477
  status: "invalid",
6038
6478
  algorithm: document.algorithm,
@@ -6071,10 +6511,12 @@ ${contentId}
6071
6511
  });
6072
6512
 
6073
6513
  // core/storage-coordinator/index.ts
6074
- var nodeFs4, withStorageLock, readStorageGeneration, writeStorageGeneration;
6514
+ var nodeFs4, heldLocks, withStorageLock, readStorageGeneration, writeStorageGeneration;
6075
6515
  var init_storage_coordinator = __esm({
6076
6516
  "core/storage-coordinator/index.ts"() {
6517
+ init_text_encoding();
6077
6518
  nodeFs4 = /* @__PURE__ */ __name(async () => import('fs/promises'), "nodeFs");
6519
+ heldLocks = /* @__PURE__ */ new Map();
6078
6520
  withStorageLock = /* @__PURE__ */ __name(async (directoryPath, operationOrOptions, operation, _options = {}) => {
6079
6521
  const opts = typeof operationOrOptions === "function" ? operation ?? {} : operationOrOptions ?? {};
6080
6522
  const op = typeof operationOrOptions === "function" ? operationOrOptions : operation;
@@ -6082,14 +6524,23 @@ var init_storage_coordinator = __esm({
6082
6524
  const staleMs = opts.staleMs ?? 6e4;
6083
6525
  const lockName = opts.lockName ?? ".storage.lock";
6084
6526
  const lockPath = `${directoryPath}/${lockName}`;
6085
- const fs7 = await nodeFs4();
6527
+ const fs9 = await nodeFs4();
6086
6528
  const started = Date.now();
6087
- await fs7.mkdir(directoryPath, { recursive: true });
6529
+ const heldDepth = heldLocks.get(lockPath) ?? 0;
6530
+ if (heldDepth > 0) {
6531
+ heldLocks.set(lockPath, heldDepth + 1);
6532
+ try {
6533
+ return await op();
6534
+ } finally {
6535
+ heldLocks.set(lockPath, heldDepth);
6536
+ }
6537
+ }
6538
+ await fs9.mkdir(directoryPath, { recursive: true });
6088
6539
  while (true) {
6089
6540
  try {
6090
- await fs7.mkdir(lockPath);
6541
+ await fs9.mkdir(lockPath);
6091
6542
  const token2 = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
6092
- await fs7.writeFile(`${lockPath}/owner.json`, JSON.stringify({ token: token2, pid: process.pid, createdAt: Date.now() }), { flag: "wx" });
6543
+ await fs9.writeFile(`${lockPath}/owner.json`, JSON.stringify({ token: token2, pid: process.pid, createdAt: Date.now() }), { flag: "wx" });
6093
6544
  break;
6094
6545
  } catch (error) {
6095
6546
  const code = error.code;
@@ -6097,8 +6548,8 @@ var init_storage_coordinator = __esm({
6097
6548
  let stale = false;
6098
6549
  let processDead = false;
6099
6550
  try {
6100
- const raw = await fs7.readFile(`${lockPath}/owner.json`, "utf8");
6101
- const parsed = JSON.parse(raw);
6551
+ const raw = await fs9.readFile(`${lockPath}/owner.json`);
6552
+ const parsed = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` }));
6102
6553
  const ageStale = typeof parsed.createdAt === "number" && Date.now() - parsed.createdAt > staleMs;
6103
6554
  if (typeof parsed.pid === "number") {
6104
6555
  try {
@@ -6116,13 +6567,13 @@ var init_storage_coordinator = __esm({
6116
6567
  if (stale) {
6117
6568
  if (processDead) {
6118
6569
  try {
6119
- await fs7.rm(lockPath, { recursive: true, force: true });
6570
+ await fs9.rm(lockPath, { recursive: true, force: true });
6120
6571
  continue;
6121
6572
  } catch {
6122
6573
  }
6123
6574
  }
6124
6575
  try {
6125
- await fs7.rmdir(lockPath);
6576
+ await fs9.rmdir(lockPath);
6126
6577
  continue;
6127
6578
  } catch {
6128
6579
  }
@@ -6135,40 +6586,42 @@ var init_storage_coordinator = __esm({
6135
6586
  }
6136
6587
  let token = "";
6137
6588
  try {
6138
- const raw = await fs7.readFile(`${lockPath}/owner.json`, "utf8");
6139
- token = JSON.parse(raw).token ?? "";
6589
+ const raw = await fs9.readFile(`${lockPath}/owner.json`);
6590
+ token = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` })).token ?? "";
6140
6591
  } catch {
6141
6592
  token = "";
6142
6593
  }
6143
6594
  try {
6595
+ heldLocks.set(lockPath, 1);
6144
6596
  return await op();
6145
6597
  } finally {
6598
+ heldLocks.delete(lockPath);
6146
6599
  try {
6147
- const raw = await fs7.readFile(`${lockPath}/owner.json`, "utf8");
6148
- const parsed = JSON.parse(raw);
6600
+ const raw = await fs9.readFile(`${lockPath}/owner.json`);
6601
+ const parsed = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` }));
6149
6602
  if (parsed.token === token && token) {
6150
- await fs7.rm(lockPath, { recursive: true, force: true });
6603
+ await fs9.rm(lockPath, { recursive: true, force: true });
6151
6604
  }
6152
6605
  } catch {
6153
6606
  }
6154
6607
  }
6155
6608
  }, "withStorageLock");
6156
6609
  readStorageGeneration = /* @__PURE__ */ __name(async (directoryPath) => {
6157
- const fs7 = await nodeFs4();
6610
+ const fs9 = await nodeFs4();
6158
6611
  try {
6159
- const raw = await fs7.readFile(`${directoryPath}/.storage.generation`, "utf8");
6160
- const value = Number(raw.trim());
6612
+ const raw = await fs9.readFile(`${directoryPath}/.storage.generation`);
6613
+ const value = Number(decodeText(raw, { source: `${directoryPath}/.storage.generation` }).trim());
6161
6614
  return Number.isFinite(value) && value >= 0 ? value : 0;
6162
6615
  } catch {
6163
6616
  return 0;
6164
6617
  }
6165
6618
  }, "readStorageGeneration");
6166
6619
  writeStorageGeneration = /* @__PURE__ */ __name(async (directoryPath, value) => {
6167
- const fs7 = await nodeFs4();
6168
- await fs7.mkdir(directoryPath, { recursive: true });
6620
+ const fs9 = await nodeFs4();
6621
+ await fs9.mkdir(directoryPath, { recursive: true });
6169
6622
  const temp = `${directoryPath}/.storage.generation.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
6170
- await fs7.writeFile(temp, String(value));
6171
- await fs7.rename(temp, `${directoryPath}/.storage.generation`);
6623
+ await fs9.writeFile(temp, String(value));
6624
+ await fs9.rename(temp, `${directoryPath}/.storage.generation`);
6172
6625
  }, "writeStorageGeneration");
6173
6626
  }
6174
6627
  });
@@ -6681,17 +7134,16 @@ function resolveLanguagePath() {
6681
7134
  function resolveLanguagePreferencePath() {
6682
7135
  return resolveUserLanguagePath();
6683
7136
  }
6684
- function readJsonFile(path5) {
6685
- const fs7 = getSyncFs();
6686
- if (!fs7) return null;
7137
+ function readJsonFile(path8) {
7138
+ const fs9 = getSyncFs();
7139
+ if (!fs9) return null;
6687
7140
  let raw;
6688
7141
  try {
6689
- raw = fs7.readFileSync(path5, "utf8");
7142
+ raw = decodeText(fs9.readFileSync(path8), { source: path8 });
6690
7143
  } catch {
6691
7144
  return null;
6692
7145
  }
6693
7146
  if (typeof raw !== "string") return null;
6694
- if (raw.charCodeAt(0) === 65279) raw = raw.slice(1);
6695
7147
  try {
6696
7148
  return JSON.parse(raw);
6697
7149
  } catch {
@@ -6720,9 +7172,9 @@ function extractLanguage(value) {
6720
7172
  return null;
6721
7173
  }
6722
7174
  function loadUserLanguage() {
6723
- const fs7 = getSyncFs();
7175
+ const fs9 = getSyncFs();
6724
7176
  const anchor = resolveUserDotMemPath();
6725
- if (fs7) {
7177
+ if (fs9) {
6726
7178
  for (const name of LANGUAGE_FILE_NAMES) {
6727
7179
  const candidatePath = joinPath3(anchor, name);
6728
7180
  const parsed = readJsonFile(candidatePath);
@@ -6784,14 +7236,14 @@ function getResponseLanguage() {
6784
7236
  }
6785
7237
  async function setUserLanguage(language2) {
6786
7238
  const fsMod = await import('fs/promises');
6787
- const path5 = resolveUserLanguagePath();
6788
- const dir = parentStoragePath(path5);
7239
+ const path8 = resolveUserLanguagePath();
7240
+ const dir = parentStoragePath(path8);
6789
7241
  await fsMod.mkdir(dir, { recursive: true });
6790
7242
  const payload = { format: "dotmem.language", version: 1, language: String(language2).trim() };
6791
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
7243
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
6792
7244
  await fsMod.writeFile(temporary, `${JSON.stringify(payload, null, 2)}
6793
7245
  `, "utf8");
6794
- await fsMod.rename(temporary, path5);
7246
+ await fsMod.rename(temporary, path8);
6795
7247
  return payload.language;
6796
7248
  }
6797
7249
  async function saveUserLanguage(language2) {
@@ -6815,6 +7267,7 @@ var init_user_language = __esm({
6815
7267
  "core/knowledge/user-language.ts"() {
6816
7268
  init_user_paths();
6817
7269
  init_storage_paths();
7270
+ init_text_encoding();
6818
7271
  USER_LANGUAGE_FILE_NAME = "language.json";
6819
7272
  USER_LANGUAGE_PREFERENCE_FILE_NAME = "user-language.json";
6820
7273
  LANGUAGE_PREFERENCE_FILE_NAME = "language-preference.json";
@@ -10365,11 +10818,11 @@ var init_identity_governance = __esm({
10365
10818
  updatedAt: (/* @__PURE__ */ new Date(0)).toISOString()
10366
10819
  }), "defaultIdentityGovernance");
10367
10820
  loadIdentityGovernance = /* @__PURE__ */ __name((canonicalAgentName) => {
10368
- const fs7 = getSyncFs();
10369
- if (!fs7) return defaultIdentityGovernance(canonicalAgentName);
10821
+ const fs9 = getSyncFs();
10822
+ if (!fs9) return defaultIdentityGovernance(canonicalAgentName);
10370
10823
  let raw;
10371
10824
  try {
10372
- raw = fs7.readFileSync(resolveUserIdentityGovernancePath(), "utf8");
10825
+ raw = fs9.readFileSync(resolveUserIdentityGovernancePath(), "utf8");
10373
10826
  } catch {
10374
10827
  return defaultIdentityGovernance(canonicalAgentName);
10375
10828
  }
@@ -10389,19 +10842,19 @@ var init_identity_governance = __esm({
10389
10842
  authority,
10390
10843
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
10391
10844
  });
10392
- const fs7 = getSyncFs();
10393
- if (!fs7) {
10845
+ const fs9 = getSyncFs();
10846
+ if (!fs9) {
10394
10847
  throw new IdentityGovernanceError("Identity governance write requires filesystem access, unavailable in this runtime");
10395
10848
  }
10396
10849
  const filePath = resolveUserIdentityGovernancePath();
10397
- await fs7.promises.mkdir(parentStoragePath(filePath), { recursive: true });
10850
+ await fs9.promises.mkdir(parentStoragePath(filePath), { recursive: true });
10398
10851
  const temporary = `${filePath}.${process.pid}.${Date.now().toString(36)}.tmp`;
10399
10852
  try {
10400
- await fs7.promises.writeFile(temporary, `${JSON.stringify(document, null, 2)}
10853
+ await fs9.promises.writeFile(temporary, `${JSON.stringify(document, null, 2)}
10401
10854
  `, "utf8");
10402
- await fs7.promises.rename(temporary, filePath);
10855
+ await fs9.promises.rename(temporary, filePath);
10403
10856
  } catch (error) {
10404
- await fs7.promises.rm(temporary, { force: true }).catch(() => void 0);
10857
+ await fs9.promises.rm(temporary, { force: true }).catch(() => void 0);
10405
10858
  throw error;
10406
10859
  }
10407
10860
  return document;
@@ -10598,20 +11051,20 @@ var init_detection_journal = __esm({
10598
11051
  }, "validateDetectionJournalDocument");
10599
11052
  appendDetectionJournal = /* @__PURE__ */ __name(async (events) => {
10600
11053
  if (events.length === 0) return;
10601
- const fs7 = getSyncFs();
10602
- if (!fs7) return;
11054
+ const fs9 = getSyncFs();
11055
+ if (!fs9) return;
10603
11056
  await withPolicyNamespaceLock(async () => {
10604
11057
  await appendDetectionJournalUnlocked(events);
10605
11058
  }, { directory: resolveUserPolicyDir() });
10606
11059
  }, "appendDetectionJournal");
10607
11060
  appendDetectionJournalUnlocked = /* @__PURE__ */ __name(async (events) => {
10608
11061
  if (events.length === 0) return;
10609
- const fs7 = getSyncFs();
10610
- if (!fs7) return;
11062
+ const fs9 = getSyncFs();
11063
+ if (!fs9) return;
10611
11064
  const filePath = resolveUserDetectionJournalPath();
10612
11065
  let document = emptyDetectionJournal();
10613
11066
  try {
10614
- const raw = await fs7.promises.readFile(filePath, "utf8");
11067
+ const raw = await fs9.promises.readFile(filePath, "utf8");
10615
11068
  document = validateDetectionJournalDocument(JSON.parse(raw));
10616
11069
  } catch (error) {
10617
11070
  const code = error?.code;
@@ -10625,22 +11078,22 @@ var init_detection_journal = __esm({
10625
11078
  }
10626
11079
  const merged = [...document.events, ...events].slice(-DETECTION_JOURNAL_RETENTION);
10627
11080
  const dir = filePath.slice(0, Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\")));
10628
- await fs7.promises.mkdir(dir, { recursive: true });
11081
+ await fs9.promises.mkdir(dir, { recursive: true });
10629
11082
  const temporary = `${filePath}.${process.pid}.${Date.now().toString(36)}.tmp`;
10630
11083
  try {
10631
- await fs7.promises.writeFile(temporary, `${JSON.stringify({ ...document, events: merged }, null, 2)}
11084
+ await fs9.promises.writeFile(temporary, `${JSON.stringify({ ...document, events: merged }, null, 2)}
10632
11085
  `, "utf8");
10633
- await fs7.promises.rename(temporary, filePath);
11086
+ await fs9.promises.rename(temporary, filePath);
10634
11087
  } catch (error) {
10635
- await fs7.promises.rm(temporary, { force: true }).catch(() => void 0);
11088
+ await fs9.promises.rm(temporary, { force: true }).catch(() => void 0);
10636
11089
  throw error;
10637
11090
  }
10638
11091
  }, "appendDetectionJournalUnlocked");
10639
11092
  loadDetectionJournal = /* @__PURE__ */ __name(async () => {
10640
- const fs7 = getSyncFs();
10641
- if (!fs7) return emptyDetectionJournal();
11093
+ const fs9 = getSyncFs();
11094
+ if (!fs9) return emptyDetectionJournal();
10642
11095
  try {
10643
- const raw = await fs7.promises.readFile(resolveUserDetectionJournalPath(), "utf8");
11096
+ const raw = await fs9.promises.readFile(resolveUserDetectionJournalPath(), "utf8");
10644
11097
  return validateDetectionJournalDocument(JSON.parse(raw));
10645
11098
  } catch {
10646
11099
  return emptyDetectionJournal();
@@ -10716,11 +11169,11 @@ var init_store_queue = __esm({
10716
11169
  async function resolveProjectIdentity(cwd, hints) {
10717
11170
  const explicit = sanitizeIdentity(process.env.DOTMEM_PROJECT_ID);
10718
11171
  if (explicit) return explicit;
10719
- const fs7 = await import('fs/promises');
11172
+ const fs9 = await import('fs/promises');
10720
11173
  const pkgPath = cwd.endsWith("/") || cwd.endsWith("\\") ? `${cwd}package.json` : `${cwd}/package.json`;
10721
11174
  let pkgJson;
10722
11175
  try {
10723
- const content = await fs7.readFile(pkgPath, "utf8");
11176
+ const content = await fs9.readFile(pkgPath, "utf8");
10724
11177
  pkgJson = JSON.parse(content);
10725
11178
  } catch {
10726
11179
  }
@@ -10865,8 +11318,8 @@ var init_staging = __esm({
10865
11318
  };
10866
11319
  const requestId = generateRequestId();
10867
11320
  const stagePath = stagePathFor(requestId);
10868
- const fs7 = await nodeFs6();
10869
- await fs7.mkdir(resolveStagingDirectory(), { recursive: true });
11321
+ const fs9 = await nodeFs6();
11322
+ await fs9.mkdir(resolveStagingDirectory(), { recursive: true });
10870
11323
  const stageFile = {
10871
11324
  format: DOTMEM_STAGE_FORMAT,
10872
11325
  version: DOTMEM_STAGE_VERSION,
@@ -10875,9 +11328,9 @@ var init_staging = __esm({
10875
11328
  ...sourceProject ? { sourceProject } : {},
10876
11329
  claim: sanitizedClaim
10877
11330
  };
10878
- await fs7.writeFile(stagePath, JSON.stringify(stageFile), { mode: 384 });
11331
+ await fs9.writeFile(stagePath, JSON.stringify(stageFile), { mode: 384 });
10879
11332
  try {
10880
- await fs7.access(stagePath);
11333
+ await fs9.access(stagePath);
10881
11334
  } catch {
10882
11335
  throw new StageFileError(`Stage file write verification failed: ${requestId} does not exist on disk`, requestId);
10883
11336
  }
@@ -10885,9 +11338,9 @@ var init_staging = __esm({
10885
11338
  }, "writeStageFile");
10886
11339
  readStageFile = /* @__PURE__ */ __name(async (requestId) => {
10887
11340
  const stagePath = stagePathFor(requestId);
10888
- const fs7 = await nodeFs6();
11341
+ const fs9 = await nodeFs6();
10889
11342
  try {
10890
- const content = await fs7.readFile(stagePath, "utf8");
11343
+ const content = await fs9.readFile(stagePath, "utf8");
10891
11344
  return JSON.parse(content);
10892
11345
  } catch (error) {
10893
11346
  if (error.code === "ENOENT") {
@@ -10970,10 +11423,13 @@ var init_staging = __esm({
10970
11423
  epistemicType: sanitizedClaim.epistemicType,
10971
11424
  provenance: sanitizedClaim.provenance,
10972
11425
  acquiredAt: sanitizedClaim.acquiredAt,
11426
+ ...sanitizedClaim.expiresAt === void 0 ? {} : { expiresAt: sanitizedClaim.expiresAt },
11427
+ ...sanitizedClaim.bootstrapPriority === void 0 ? {} : { bootstrapPriority: sanitizedClaim.bootstrapPriority },
10973
11428
  revision,
10974
11429
  scope,
10975
11430
  sourceProject,
10976
- kind
11431
+ kind,
11432
+ ...sanitizedClaim.check === void 0 ? {} : { check: sanitizedClaim.check }
10977
11433
  });
10978
11434
  await withStoreQueue(acquisitionStoreKey(kind, scope, sourceProject), async () => {
10979
11435
  const state2 = await target.runtime.select([]);
@@ -10997,9 +11453,9 @@ var init_staging = __esm({
10997
11453
  }, "commitStageFile");
10998
11454
  cleanupStageFile = /* @__PURE__ */ __name(async (requestId) => {
10999
11455
  const stagePath = stagePathFor(requestId);
11000
- const fs7 = await nodeFs6();
11456
+ const fs9 = await nodeFs6();
11001
11457
  try {
11002
- await fs7.unlink(stagePath);
11458
+ await fs9.unlink(stagePath);
11003
11459
  } catch (error) {
11004
11460
  if (error.code !== "ENOENT") {
11005
11461
  throw error;
@@ -11008,19 +11464,19 @@ var init_staging = __esm({
11008
11464
  }, "cleanupStageFile");
11009
11465
  cleanupStaleStages = /* @__PURE__ */ __name(async (maxAgeMs = 24 * 60 * 60 * 1e3) => {
11010
11466
  const stagingDir = resolveStagingDirectory();
11011
- const fs7 = await nodeFs6();
11467
+ const fs9 = await nodeFs6();
11012
11468
  let count = 0;
11013
11469
  try {
11014
- const entries2 = await fs7.readdir(stagingDir, { withFileTypes: true });
11470
+ const entries2 = await fs9.readdir(stagingDir, { withFileTypes: true });
11015
11471
  const now2 = Date.now();
11016
11472
  for (const entry of entries2) {
11017
11473
  if (!entry.isFile() || !entry.name.endsWith(".stage")) continue;
11018
11474
  const filePath = `${stagingDir}/${entry.name}`;
11019
11475
  try {
11020
- const stat = await fs7.stat(filePath);
11476
+ const stat = await fs9.stat(filePath);
11021
11477
  const age = now2 - stat.mtimeMs;
11022
11478
  if (age > maxAgeMs) {
11023
- await fs7.unlink(filePath);
11479
+ await fs9.unlink(filePath);
11024
11480
  count++;
11025
11481
  }
11026
11482
  } catch {
@@ -11044,25 +11500,25 @@ function joinPath4(base, child) {
11044
11500
  function resolveLoopsFilePath() {
11045
11501
  return joinPath4(resolveUserDotMemPath(), LOOPS_FILE_NAME);
11046
11502
  }
11047
- async function readFile(path5) {
11503
+ async function readFile(path8) {
11048
11504
  try {
11049
- const fs7 = await import('fs/promises');
11050
- return await fs7.readFile(path5, "utf8");
11505
+ const fs9 = await import('fs/promises');
11506
+ return await fs9.readFile(path8, "utf8");
11051
11507
  } catch {
11052
11508
  return null;
11053
11509
  }
11054
11510
  }
11055
- async function writeFile(path5, content) {
11056
- const fs7 = await import('fs/promises');
11057
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
11058
- await fs7.mkdir(dir, { recursive: true });
11059
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
11511
+ async function writeFile(path8, content) {
11512
+ const fs9 = await import('fs/promises');
11513
+ const dir = path8.replace(/[\\/][^\\/]+$/, "");
11514
+ await fs9.mkdir(dir, { recursive: true });
11515
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
11060
11516
  try {
11061
- await fs7.writeFile(temporary, content, "utf8");
11062
- await fs7.rename(temporary, path5);
11517
+ await fs9.writeFile(temporary, content, "utf8");
11518
+ await fs9.rename(temporary, path8);
11063
11519
  } catch {
11064
- await fs7.rm(temporary, { force: true }).catch(() => void 0);
11065
- throw new Error(`Failed to write loops file at ${path5}`);
11520
+ await fs9.rm(temporary, { force: true }).catch(() => void 0);
11521
+ throw new Error(`Failed to write loops file at ${path8}`);
11066
11522
  }
11067
11523
  }
11068
11524
  function emptyDocument() {
@@ -11483,9 +11939,9 @@ async function getCommittedFiles() {
11483
11939
  return result.stdout.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
11484
11940
  }
11485
11941
  async function getFileContent(filePath) {
11486
- const fs7 = await import('fs/promises');
11942
+ const fs9 = await import('fs/promises');
11487
11943
  try {
11488
- return await fs7.readFile(filePath, "utf8");
11944
+ return await fs9.readFile(filePath, "utf8");
11489
11945
  } catch {
11490
11946
  return null;
11491
11947
  }
@@ -11601,25 +12057,25 @@ function joinPath5(base, child) {
11601
12057
  function resolveVaultFilePath() {
11602
12058
  return joinPath5(resolveUserDotMemPath(), VAULT_FILE_NAME);
11603
12059
  }
11604
- async function readFile2(path5) {
12060
+ async function readFile2(path8) {
11605
12061
  try {
11606
- const fs7 = await import('fs/promises');
11607
- return await fs7.readFile(path5, "utf8");
12062
+ const fs9 = await import('fs/promises');
12063
+ return await fs9.readFile(path8, "utf8");
11608
12064
  } catch {
11609
12065
  return null;
11610
12066
  }
11611
12067
  }
11612
- async function writeFile2(path5, content) {
11613
- const fs7 = await import('fs/promises');
11614
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
11615
- await fs7.mkdir(dir, { recursive: true });
11616
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
12068
+ async function writeFile2(path8, content) {
12069
+ const fs9 = await import('fs/promises');
12070
+ const dir = path8.replace(/[\\/][^\\/]+$/, "");
12071
+ await fs9.mkdir(dir, { recursive: true });
12072
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
11617
12073
  try {
11618
- await fs7.writeFile(temporary, content, "utf8");
11619
- await fs7.rename(temporary, path5);
12074
+ await fs9.writeFile(temporary, content, "utf8");
12075
+ await fs9.rename(temporary, path8);
11620
12076
  } catch {
11621
- await fs7.rm(temporary, { force: true }).catch(() => void 0);
11622
- throw new Error(`Failed to write vault file at ${path5}`);
12077
+ await fs9.rm(temporary, { force: true }).catch(() => void 0);
12078
+ throw new Error(`Failed to write vault file at ${path8}`);
11623
12079
  }
11624
12080
  }
11625
12081
  function emptyDocument2() {
@@ -11737,9 +12193,9 @@ function joinPath6(base, child) {
11737
12193
  return `${base.replace(/[\\/]+/g, separator3)}${separator3}${child}`;
11738
12194
  }
11739
12195
  async function readJsonFile2(filePath, pointer) {
11740
- const fs7 = await import('fs/promises');
12196
+ const fs9 = await import('fs/promises');
11741
12197
  try {
11742
- const content = await fs7.readFile(filePath, "utf8");
12198
+ const content = await fs9.readFile(filePath, "utf8");
11743
12199
  const data = JSON.parse(content);
11744
12200
  const pathParts = pointer.replace(/^\//, "").split("/").filter((p) => p.length > 0);
11745
12201
  let current = data;
@@ -11802,6 +12258,39 @@ async function evaluateClaim(claim) {
11802
12258
  detail: `Value is ${result.valueStr}, expected ${expected}`
11803
12259
  };
11804
12260
  }
12261
+ if (kind === "regex") {
12262
+ const pattern = check.pattern;
12263
+ const target = String(check.expect ?? "");
12264
+ let regex;
12265
+ try {
12266
+ regex = new RegExp(pattern);
12267
+ } catch {
12268
+ return {
12269
+ claimId: claim.id,
12270
+ probe,
12271
+ status: "error",
12272
+ detail: `Invalid regex pattern: ${pattern}`
12273
+ };
12274
+ }
12275
+ if (regex.test(target)) {
12276
+ return {
12277
+ claimId: claim.id,
12278
+ probe,
12279
+ status: "valid",
12280
+ currentValue: target,
12281
+ expectedValue: pattern,
12282
+ detail: `Value matches regex: ${pattern}`
12283
+ };
12284
+ }
12285
+ return {
12286
+ claimId: claim.id,
12287
+ probe,
12288
+ status: "stale",
12289
+ currentValue: target,
12290
+ expectedValue: pattern,
12291
+ detail: `Value does not match regex: ${pattern}`
12292
+ };
12293
+ }
11805
12294
  return {
11806
12295
  claimId: claim.id,
11807
12296
  probe,
@@ -11887,144 +12376,678 @@ function formatVerifyResult(result) {
11887
12376
  }
11888
12377
  return lines.join("\n");
11889
12378
  }
12379
+ function applyVerification(state2, claimId, record) {
12380
+ const validated = validateKnowledgeState(state2);
12381
+ const claimIndex = validated.claims.findIndex((candidate) => candidate.id === claimId);
12382
+ if (claimIndex === -1) {
12383
+ throw new Error(`Cannot verify unknown claim: ${claimId}`);
12384
+ }
12385
+ const claim = validated.claims[claimIndex];
12386
+ const knowledge = claim.knowledge;
12387
+ const existing = knowledge?.verifiedAt;
12388
+ if (typeof existing === "string") {
12389
+ const existingTime = Date.parse(existing);
12390
+ const newTime = Date.parse(record.verifiedAt);
12391
+ if (Number.isFinite(existingTime) && Number.isFinite(newTime) && existingTime >= newTime) {
12392
+ return structuredClone(validated);
12393
+ }
12394
+ }
12395
+ const nextKnowledge = knowledge ? { ...knowledge } : {};
12396
+ nextKnowledge.verifiedAt = record.verifiedAt;
12397
+ nextKnowledge.verifiedBy = record.verifiedBy;
12398
+ nextKnowledge.verifyStatus = record.verifyStatus;
12399
+ const nextClaims = validated.claims.map(
12400
+ (candidate, index) => index === claimIndex ? { ...candidate, knowledge: nextKnowledge } : candidate
12401
+ );
12402
+ return structuredClone({ ...validated, version: validated.version + 1, claims: nextClaims });
12403
+ }
12404
+ async function verifyAndPersistClaims(state2, save) {
12405
+ const validated = validateKnowledgeState(state2);
12406
+ const result = await verifyDueClaims(validated);
12407
+ const persisted = [];
12408
+ let current = validated;
12409
+ for (const probe of result.results) {
12410
+ if (probe.status !== "valid") continue;
12411
+ const record = buildVerificationRecord(probe.claimId, {
12412
+ kind: probe.probe.split(":")[0],
12413
+ target: probe.probe.split(":").slice(1).join(":"),
12414
+ status: probe.status
12415
+ });
12416
+ if (!record) continue;
12417
+ current = applyVerification(current, probe.claimId, record);
12418
+ await save(current, current.version);
12419
+ persisted.push(probe.claimId);
12420
+ }
12421
+ return { result, persisted };
12422
+ }
11890
12423
  var init_verify = __esm({
11891
12424
  "core/knowledge/verify.ts"() {
11892
12425
  init_state();
12426
+ init_verification();
11893
12427
  __name(joinPath6, "joinPath");
11894
12428
  __name(readJsonFile2, "readJsonFile");
11895
12429
  __name(evaluateClaim, "evaluateClaim");
11896
12430
  __name(isDue, "isDue");
11897
12431
  __name(verifyDueClaims, "verifyDueClaims");
11898
12432
  __name(formatVerifyResult, "formatVerifyResult");
12433
+ __name(applyVerification, "applyVerification");
12434
+ __name(verifyAndPersistClaims, "verifyAndPersistClaims");
11899
12435
  }
11900
12436
  });
11901
12437
 
11902
- // core/knowledge/context-budget.ts
11903
- function estimateTokens(text) {
11904
- return Math.ceil(text.length / 4);
11905
- }
11906
- function estimateClaimSize(claim) {
11907
- const serialized = JSON.stringify(claim.knowledge ?? {});
11908
- const characters = serialized.length;
11909
- return { tokens: estimateTokens(serialized), characters };
11910
- }
11911
- function calculateBudgetUsage(claims, budget) {
11912
- let totalChars = 0;
11913
- for (const claim of claims) {
11914
- totalChars += estimateClaimSize(claim).characters;
11915
- }
11916
- const tokens = estimateTokens(String(totalChars));
11917
- const utilization = budget === "unlimited" || budget === 0 ? 1 : Math.min(totalChars / (budget * 4), 1);
11918
- return {
11919
- tokens,
11920
- characters: totalChars,
11921
- claimCount: claims.length,
11922
- budget,
11923
- utilization
11924
- };
11925
- }
11926
- function explainBudgetAllocation(included, excluded, budget) {
11927
- const result = {
11928
- included: included.map((claim) => {
11929
- const size = estimateClaimSize(claim);
11930
- return {
11931
- claimId: claim.id,
11932
- reason: "matched discovery",
11933
- estimatedTokens: size.tokens,
11934
- estimatedCharacters: size.characters
11935
- };
11936
- }),
11937
- excluded: excluded.map((item) => ({
11938
- claimId: item.id,
11939
- reason: item.reason
11940
- })),
11941
- total: calculateBudgetUsage(included, budget)
11942
- };
11943
- if (result.total.utilization >= 0.9 && budget !== "unlimited") {
11944
- result.excluded.push({
11945
- claimId: "__budget__",
11946
- reason: `Budget at ${Math.round(result.total.utilization * 100)}% utilization (${result.total.tokens} tokens of ${budget})`
11947
- });
11948
- }
11949
- return result;
11950
- }
11951
- function formatBudgetExplanation(explanation) {
11952
- const lines = [
11953
- "Context Budget Report",
11954
- "",
11955
- `Total claims included: ${explanation.total.claimCount}`,
11956
- `Estimated tokens: ${explanation.total.tokens}`,
11957
- `Budget: ${explanation.total.budget === "unlimited" ? "unlimited" : explanation.total.budget}`,
11958
- `Utilization: ${Math.round(explanation.total.utilization * 100)}%`,
11959
- ""
11960
- ];
11961
- if (explanation.included.length > 0) {
11962
- lines.push("Included claims:");
11963
- for (const item of explanation.included) {
11964
- lines.push(` [${item.claimId}] ${item.estimatedTokens} tokens \u2014 ${item.reason}`);
11965
- }
11966
- lines.push("");
11967
- }
11968
- if (explanation.excluded.length > 0) {
11969
- lines.push("Excluded claims:");
11970
- for (const item of explanation.excluded) {
11971
- lines.push(` [${item.claimId}] ${item.reason}`);
11972
- }
11973
- lines.push("");
11974
- }
11975
- return lines.join("\n");
11976
- }
11977
- var init_context_budget = __esm({
11978
- "core/knowledge/context-budget.ts"() {
11979
- __name(estimateTokens, "estimateTokens");
11980
- __name(estimateClaimSize, "estimateClaimSize");
11981
- __name(calculateBudgetUsage, "calculateBudgetUsage");
11982
- __name(explainBudgetAllocation, "explainBudgetAllocation");
11983
- __name(formatBudgetExplanation, "formatBudgetExplanation");
11984
- }
11985
- });
11986
-
11987
- // core/knowledge/feedback.ts
12438
+ // core/knowledge/violations.ts
11988
12439
  function joinPath7(base, child) {
11989
12440
  const separator3 = process.platform === "win32" ? "\\" : "/";
11990
12441
  return `${base.replace(/[\\/]+/g, separator3)}${separator3}${child}`;
11991
12442
  }
11992
- function resolveFeedbackFilePath() {
11993
- return joinPath7(resolveUserDotMemPath(), FEEDBACK_FILE_NAME);
12443
+ function resolveViolationFilePath() {
12444
+ return joinPath7(resolveUserDotMemPath(), VIOLATION_FILE_NAME);
11994
12445
  }
11995
- async function readFile3(path5) {
12446
+ async function readFile3(path8) {
11996
12447
  try {
11997
- const fs7 = await import('fs/promises');
11998
- return await fs7.readFile(path5, "utf8");
12448
+ const fs9 = await import('fs/promises');
12449
+ return await fs9.readFile(path8, "utf8");
11999
12450
  } catch {
12000
12451
  return null;
12001
12452
  }
12002
12453
  }
12003
- async function writeFile3(path5, content) {
12004
- const fs7 = await import('fs/promises');
12005
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
12006
- await fs7.mkdir(dir, { recursive: true });
12007
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
12008
- await fs7.writeFile(temporary, content, "utf8");
12009
- await fs7.rename(temporary, path5);
12454
+ async function writeFile3(path8, content) {
12455
+ const fs9 = await import('fs/promises');
12456
+ const dir = path8.replace(/[\\/][^\\/]+$/, "");
12457
+ await fs9.mkdir(dir, { recursive: true });
12458
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
12459
+ await fs9.writeFile(temporary, content, "utf8");
12460
+ await fs9.rename(temporary, path8);
12010
12461
  }
12011
- async function loadFeedback() {
12012
- const raw = await readFile3(resolveFeedbackFilePath());
12013
- if (!raw) return { version: FEEDBACK_FORMAT_VERSION, entries: [] };
12462
+ async function loadViolations() {
12463
+ const raw = await readFile3(resolveViolationFilePath());
12464
+ if (!raw) return { version: VIOLATION_FORMAT_VERSION, entries: [] };
12014
12465
  try {
12015
12466
  const parsed = JSON.parse(raw);
12016
- if (parsed.version === FEEDBACK_FORMAT_VERSION && Array.isArray(parsed.entries)) {
12017
- return { version: FEEDBACK_FORMAT_VERSION, entries: parsed.entries };
12467
+ if (parsed.version === VIOLATION_FORMAT_VERSION && Array.isArray(parsed.entries)) {
12468
+ return { version: VIOLATION_FORMAT_VERSION, entries: parsed.entries };
12018
12469
  }
12019
12470
  } catch {
12020
12471
  }
12021
- return { version: FEEDBACK_FORMAT_VERSION, entries: [] };
12472
+ return { version: VIOLATION_FORMAT_VERSION, entries: [] };
12022
12473
  }
12023
- async function saveFeedback(document) {
12024
- await writeFile3(resolveFeedbackFilePath(), JSON.stringify(document, null, 2) + "\n");
12474
+ async function saveViolations(document) {
12475
+ await writeFile3(resolveViolationFilePath(), JSON.stringify(document, null, 2) + "\n");
12025
12476
  }
12026
- function validateFeedbackEntry(entry) {
12027
- if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
12477
+ async function logViolation(ruleId, situation, description = "") {
12478
+ const document = await loadViolations();
12479
+ const record = {
12480
+ ruleId,
12481
+ violatedAt: (/* @__PURE__ */ new Date()).toISOString(),
12482
+ description,
12483
+ situation
12484
+ };
12485
+ document.entries.push(record);
12486
+ await saveViolations(document);
12487
+ return record;
12488
+ }
12489
+ async function countViolations(ruleId) {
12490
+ const document = await loadViolations();
12491
+ return document.entries.filter((e) => e.ruleId === ruleId).length;
12492
+ }
12493
+ async function lastViolation(ruleId) {
12494
+ const document = await loadViolations();
12495
+ const entries2 = document.entries.filter((e) => e.ruleId === ruleId).sort((a, b) => b.violatedAt.localeCompare(a.violatedAt));
12496
+ return entries2[0]?.violatedAt;
12497
+ }
12498
+ async function listViolations(ruleId) {
12499
+ const document = await loadViolations();
12500
+ if (!ruleId) return document.entries;
12501
+ return document.entries.filter((e) => e.ruleId === ruleId);
12502
+ }
12503
+ async function clearViolations(ruleId) {
12504
+ const document = await loadViolations();
12505
+ const beforeCount = document.entries.length;
12506
+ if (ruleId) {
12507
+ document.entries = document.entries.filter((e) => e.ruleId !== ruleId);
12508
+ } else {
12509
+ document.entries = [];
12510
+ }
12511
+ await saveViolations(document);
12512
+ return beforeCount - document.entries.length;
12513
+ }
12514
+ var VIOLATION_FILE_NAME, VIOLATION_FORMAT_VERSION;
12515
+ var init_violations = __esm({
12516
+ "core/knowledge/violations.ts"() {
12517
+ init_user_paths();
12518
+ VIOLATION_FILE_NAME = "violations.json";
12519
+ VIOLATION_FORMAT_VERSION = 1;
12520
+ __name(joinPath7, "joinPath");
12521
+ __name(resolveViolationFilePath, "resolveViolationFilePath");
12522
+ __name(readFile3, "readFile");
12523
+ __name(writeFile3, "writeFile");
12524
+ __name(loadViolations, "loadViolations");
12525
+ __name(saveViolations, "saveViolations");
12526
+ __name(logViolation, "logViolation");
12527
+ __name(countViolations, "countViolations");
12528
+ __name(lastViolation, "lastViolation");
12529
+ __name(listViolations, "listViolations");
12530
+ __name(clearViolations, "clearViolations");
12531
+ }
12532
+ });
12533
+ function isRuleClaim(claim) {
12534
+ const knowledge = claim.knowledge;
12535
+ return knowledge?.kind === "rule";
12536
+ }
12537
+ function isIronRule(claim) {
12538
+ return claim.epistemicType === "human-stated" && isRuleClaim(claim);
12539
+ }
12540
+ function extractIronRules(state2, violations = {}) {
12541
+ const validated = validateKnowledgeState(state2);
12542
+ const claims = activeClaims(validated);
12543
+ const rules = [];
12544
+ for (const claim of claims) {
12545
+ if (!isIronRule(claim)) continue;
12546
+ const knowledge = claim.knowledge;
12547
+ const applicability = claim.applicability;
12548
+ const iron = applicability.iron === true || applicability.priority === "iron";
12549
+ if (!iron) continue;
12550
+ rules.push({
12551
+ id: claim.id,
12552
+ text: String(knowledge.text ?? knowledge.rule ?? claim.id),
12553
+ why: String(knowledge.why ?? knowledge.reason ?? ""),
12554
+ appliesWhen: String(knowledge.appliesWhen ?? knowledge.when ?? ""),
12555
+ violatedOn: Array.isArray(knowledge.violatedOn) ? knowledge.violatedOn : void 0,
12556
+ lastViolation: typeof knowledge.lastViolation === "string" ? knowledge.lastViolation : void 0,
12557
+ frequency: typeof knowledge.frequency === "number" ? knowledge.frequency : violations[claim.id] ?? 0
12558
+ });
12559
+ }
12560
+ return rules;
12561
+ }
12562
+ function sortRulesByViolationFrequency(rules) {
12563
+ return [...rules].sort((a, b) => {
12564
+ if (b.frequency !== a.frequency) return b.frequency - a.frequency;
12565
+ if (a.lastViolation && b.lastViolation) {
12566
+ return b.lastViolation.localeCompare(a.lastViolation);
12567
+ }
12568
+ return 0;
12569
+ });
12570
+ }
12571
+ function loadIronRules(state2) {
12572
+ const rules = sortRulesByViolationFrequency(
12573
+ extractIronRules(state2, readViolationCounts(`${resolveUserDotMemPath()}/${VIOLATION_FILE_NAME}`))
12574
+ );
12575
+ return {
12576
+ rules,
12577
+ count: rules.length,
12578
+ sortedBy: "violation-frequency"
12579
+ };
12580
+ }
12581
+ function formatRulesForSessionStart(rules) {
12582
+ if (rules.length === 0) {
12583
+ return "";
12584
+ }
12585
+ const lines = ["---", "IRON RULES (must always arrive)", "---"];
12586
+ for (const rule of rules) {
12587
+ lines.push(`${rule.id}: ${rule.text}`);
12588
+ }
12589
+ return lines.join("\n");
12590
+ }
12591
+ function formatRuleWithExplanation(rule) {
12592
+ const parts = [];
12593
+ parts.push(`[${rule.id}] ${rule.text}`);
12594
+ if (rule.why) parts.push(` WHY: ${rule.why}`);
12595
+ if (rule.appliesWhen) parts.push(` APPLIES WHEN: ${rule.appliesWhen}`);
12596
+ if (rule.violatedOn && rule.violatedOn.length > 0) {
12597
+ parts.push(` VIOLATED ${rule.violatedOn.length} TIME(S)`);
12598
+ if (rule.lastViolation) parts.push(` Last: ${rule.lastViolation}`);
12599
+ }
12600
+ return parts.join("\n");
12601
+ }
12602
+ var readViolationCounts, ruleSetSignature, formatRulesReference;
12603
+ var init_rules_loader = __esm({
12604
+ "core/knowledge/rules-loader.ts"() {
12605
+ init_state();
12606
+ init_user_paths();
12607
+ init_violations();
12608
+ __name(isRuleClaim, "isRuleClaim");
12609
+ __name(isIronRule, "isIronRule");
12610
+ __name(extractIronRules, "extractIronRules");
12611
+ readViolationCounts = /* @__PURE__ */ __name((file) => {
12612
+ try {
12613
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
12614
+ const counts = {};
12615
+ for (const violation of Array.isArray(parsed.violations) ? parsed.violations : []) {
12616
+ const ruleId = typeof violation?.ruleId === "string" ? violation.ruleId : "";
12617
+ if (!ruleId) continue;
12618
+ counts[ruleId] = (counts[ruleId] ?? 0) + 1;
12619
+ }
12620
+ return counts;
12621
+ } catch {
12622
+ return {};
12623
+ }
12624
+ }, "readViolationCounts");
12625
+ __name(sortRulesByViolationFrequency, "sortRulesByViolationFrequency");
12626
+ __name(loadIronRules, "loadIronRules");
12627
+ ruleSetSignature = /* @__PURE__ */ __name((rules) => {
12628
+ const material = rules.map((rule) => `${rule.id}\0${rule.text}`).join("");
12629
+ let hash = 2166136261;
12630
+ for (let index = 0; index < material.length; index += 1) {
12631
+ hash ^= material.charCodeAt(index);
12632
+ hash = Math.imul(hash, 16777619) >>> 0;
12633
+ }
12634
+ return hash.toString(16).padStart(8, "0");
12635
+ }, "ruleSetSignature");
12636
+ formatRulesReference = /* @__PURE__ */ __name((rules) => {
12637
+ if (rules.length === 0) return "DOTMEM_IRON_RULES_V1\ncount=0";
12638
+ return [
12639
+ "DOTMEM_IRON_RULES_V1",
12640
+ `count=${rules.length}`,
12641
+ `signature=${ruleSetSignature(rules)}`,
12642
+ `ids=${rules.map((rule) => rule.id).join(",")}`
12643
+ ].join("\n");
12644
+ }, "formatRulesReference");
12645
+ __name(formatRulesForSessionStart, "formatRulesForSessionStart");
12646
+ __name(formatRuleWithExplanation, "formatRuleWithExplanation");
12647
+ }
12648
+ });
12649
+
12650
+ // core/knowledge/bootstrap.ts
12651
+ var unchangedResponse, composeBootstrap;
12652
+ var init_bootstrap = __esm({
12653
+ "core/knowledge/bootstrap.ts"() {
12654
+ init_discover();
12655
+ init_project();
12656
+ init_rules_loader();
12657
+ init_user_paths();
12658
+ init_context_constants();
12659
+ unchangedResponse = /* @__PURE__ */ __name((knowledgeVersion, sinceVersion) => {
12660
+ const text = [
12661
+ "DOTMEM_BOOTSTRAP_V1",
12662
+ `storage=${resolveUserDotMemPath()}`,
12663
+ `knowledgeVersion=${knowledgeVersion}`,
12664
+ `rules=DOTMEM_IRON_RULES_V1 count=0 signature=00000000 ids=`,
12665
+ `UNCHANGED:true`,
12666
+ `sinceVersion=${sinceVersion}`,
12667
+ `assertedVersion=${knowledgeVersion}`
12668
+ ].join("\n");
12669
+ return {
12670
+ format: "dotmem-bootstrap-v1",
12671
+ storage: resolveUserDotMemPath(),
12672
+ knowledgeVersion,
12673
+ rules: { count: 0, signature: "00000000", ids: [] },
12674
+ context: null,
12675
+ unchanged: true,
12676
+ sinceVersion,
12677
+ text
12678
+ };
12679
+ }, "unchangedResponse");
12680
+ composeBootstrap = /* @__PURE__ */ __name(async (options = {}) => {
12681
+ const { sinceVersion, situation } = options;
12682
+ const { loadCombinedKnowledgeState: loadCombinedKnowledgeState2 } = await Promise.resolve().then(() => (init_memory(), memory_exports));
12683
+ const state2 = await loadCombinedKnowledgeState2();
12684
+ const knowledgeVersion = state2.version;
12685
+ if (Number.isInteger(sinceVersion) && sinceVersion >= 0 && sinceVersion === knowledgeVersion) {
12686
+ return unchangedResponse(knowledgeVersion, sinceVersion);
12687
+ }
12688
+ const discovery = await discoverAcquiredExperience(
12689
+ state2,
12690
+ situation ?? "",
12691
+ { maxCandidates: DOTMEM_CONTEXT_DEFAULT_MAX_CANDIDATES }
12692
+ );
12693
+ const context2 = projectDiscoveredExperience(discovery, {
12694
+ maxCandidates: DOTMEM_CONTEXT_DEFAULT_MAX_CANDIDATES,
12695
+ maxCharacters: DOTMEM_CONTEXT_DEFAULT_MAX_CHARACTERS
12696
+ });
12697
+ let rules = [];
12698
+ try {
12699
+ rules = loadIronRules(state2).rules;
12700
+ } catch {
12701
+ rules = [];
12702
+ }
12703
+ const rulesReference = {
12704
+ count: rules.length,
12705
+ signature: ruleSetSignature(rules),
12706
+ ids: rules.map((rule) => rule.id)
12707
+ };
12708
+ const text = [
12709
+ "DOTMEM_BOOTSTRAP_V1",
12710
+ `storage=${resolveUserDotMemPath()}`,
12711
+ `knowledgeVersion=${knowledgeVersion}`,
12712
+ `rules=DOTMEM_IRON_RULES_V1 count=${rulesReference.count} signature=${rulesReference.signature} ids=${rulesReference.ids.join(",")}`,
12713
+ "UNCHANGED:false",
12714
+ "",
12715
+ context2.text
12716
+ ].join("\n");
12717
+ return {
12718
+ format: "dotmem-bootstrap-v1",
12719
+ storage: resolveUserDotMemPath(),
12720
+ knowledgeVersion,
12721
+ rules: rulesReference,
12722
+ context: context2,
12723
+ unchanged: false,
12724
+ text
12725
+ };
12726
+ }, "composeBootstrap");
12727
+ }
12728
+ });
12729
+
12730
+ // core/knowledge/inspect-report.ts
12731
+ var redactValue, redactKnowledge, statusProse, formatParts, redactKnowledgeInInspection, renderInspectReport;
12732
+ var init_inspect_report = __esm({
12733
+ "core/knowledge/inspect-report.ts"() {
12734
+ init_sanitizer();
12735
+ redactValue = /* @__PURE__ */ __name((value) => {
12736
+ if (typeof value === "string" && looksLikeSecretValue(value)) {
12737
+ return "[redacted]";
12738
+ }
12739
+ return value;
12740
+ }, "redactValue");
12741
+ redactKnowledge = /* @__PURE__ */ __name((knowledge, redact) => {
12742
+ if (knowledge === null || typeof knowledge !== "object") {
12743
+ return redactValue(knowledge);
12744
+ }
12745
+ if (Array.isArray(knowledge)) {
12746
+ return knowledge.map((item) => redactKnowledge(item, redact));
12747
+ }
12748
+ const obj = knowledge;
12749
+ const result = {};
12750
+ for (const [key, value] of Object.entries(obj)) {
12751
+ if (redact && (isSecretKey(key) || looksLikeSecretValue(value))) {
12752
+ result[key] = { requiresSecret: true, secretStorage: "external" };
12753
+ continue;
12754
+ }
12755
+ result[key] = redactKnowledge(value, redact);
12756
+ }
12757
+ return result;
12758
+ }, "redactKnowledge");
12759
+ statusProse = /* @__PURE__ */ __name((status) => {
12760
+ switch (status) {
12761
+ case "valid":
12762
+ return "The MEM artifact is valid and intact.";
12763
+ case "invalid":
12764
+ return "The MEM artifact is invalid: its structure or semantics do not conform to the MEM format.";
12765
+ case "checksum_mismatch":
12766
+ return "The MEM artifact failed integrity verification: one or more parts do not match their recorded checksums.";
12767
+ case "unsupported":
12768
+ return "The MEM artifact uses an unsupported format or version.";
12769
+ case "corrupt":
12770
+ return "The MEM artifact is corrupt and could not be decoded.";
12771
+ default:
12772
+ return `The MEM artifact status is ${status}.`;
12773
+ }
12774
+ }, "statusProse");
12775
+ formatParts = /* @__PURE__ */ __name((parts) => {
12776
+ const list2 = parts ?? [];
12777
+ const lines = [` total: ${list2.length}`];
12778
+ for (const part of list2) {
12779
+ lines.push(` - ${part.path} (${part.bytes} bytes, protected=${part.protected})`);
12780
+ }
12781
+ return lines;
12782
+ }, "formatParts");
12783
+ redactKnowledgeInInspection = /* @__PURE__ */ __name((inspection, redact) => {
12784
+ if (!redact || !inspection.knowledge) return inspection;
12785
+ return {
12786
+ ...inspection,
12787
+ knowledge: redactKnowledge(inspection.knowledge, redact)
12788
+ };
12789
+ }, "redactKnowledgeInInspection");
12790
+ renderInspectReport = /* @__PURE__ */ __name((inspection, options = {}) => {
12791
+ const { redact = true, includeKnowledge = false, limit = 50 } = options;
12792
+ const report = redactKnowledgeInInspection(inspection, redact);
12793
+ const lines = [];
12794
+ lines.push("# Dotmem MEM Inspection Report");
12795
+ lines.push("");
12796
+ lines.push(`- **Status:** ${report.status}`);
12797
+ lines.push(`- **Message:** ${statusProse(report.status)}`);
12798
+ lines.push(`- **Representation:** ${report.representation}`);
12799
+ if (report.packageVersion !== void 0) lines.push(`- **Package version:** ${report.packageVersion}`);
12800
+ if (report.memoryVersion !== void 0) lines.push(`- **Memory version:** ${report.memoryVersion}`);
12801
+ if (report.contentId) lines.push(`- **Content ID:** ${report.contentId}`);
12802
+ lines.push("");
12803
+ lines.push("## Integrity");
12804
+ if (report.integrity) {
12805
+ lines.push(`- **Status:** ${report.integrity.status}`);
12806
+ lines.push(`- **Algorithm:** ${report.integrity.algorithm}`);
12807
+ lines.push(`- **Content ID:** ${report.integrity.contentId}`);
12808
+ } else {
12809
+ lines.push("- **Status:** not available");
12810
+ }
12811
+ lines.push("");
12812
+ lines.push("## Authenticity");
12813
+ if (report.authenticity) {
12814
+ lines.push(`- **Status:** ${report.authenticity.status}`);
12815
+ lines.push(`- **Trust:** ${report.authenticity.trust}`);
12816
+ lines.push(`- **Signatures:** ${report.authenticity.signatures.length}`);
12817
+ if (report.authenticity.signatures.length > 0) {
12818
+ lines.push("");
12819
+ lines.push("### Signatures");
12820
+ for (const signature of report.authenticity.signatures) {
12821
+ lines.push(`- ${signature.algorithm ?? "unknown"} / ${signature.keyId ?? "unknown-key"}: **${signature.status}**`);
12822
+ if (signature.message) lines.push(` - ${signature.message}`);
12823
+ }
12824
+ }
12825
+ lines.push("");
12826
+ lines.push("> Unsigned does not mean corrupt: the package has integrity but no cryptographic signature.");
12827
+ } else {
12828
+ lines.push("- **Status:** not available");
12829
+ }
12830
+ lines.push("");
12831
+ lines.push("## Parts");
12832
+ lines.push(...formatParts(report.parts));
12833
+ lines.push("");
12834
+ lines.push("## Claims");
12835
+ const claims = report.knowledge?.claims;
12836
+ if (Array.isArray(claims)) {
12837
+ lines.push(`- **Total:** ${claims.length}`);
12838
+ lines.push(`- **Shown:** ${Math.min(claims.length, limit)}`);
12839
+ lines.push("");
12840
+ for (const claim of claims.slice(0, limit)) {
12841
+ lines.push(`- \`${claim.id}\``);
12842
+ if (claim.epistemicType) lines.push(` - epistemicType: ${claim.epistemicType}`);
12843
+ if (claim.evidence?.length) {
12844
+ lines.push(` - evidence: ${claim.evidence.map((e) => e.id).join(", ")}`);
12845
+ }
12846
+ if (claim.revision) lines.push(` - revision: ${claim.revision.kind}`);
12847
+ }
12848
+ } else {
12849
+ lines.push("- **Total:** not available (knowledge payload not present)");
12850
+ }
12851
+ lines.push("");
12852
+ lines.push("## Redaction");
12853
+ lines.push(`- **Redacted:** ${redact ? "yes" : "no"}`);
12854
+ lines.push("- Secret-shaped values are replaced with placeholders by default. Use --no-redact (CLI only) to disable.");
12855
+ const markdown = lines.join("\n");
12856
+ const json = {
12857
+ status: report.status,
12858
+ representation: report.representation,
12859
+ message: statusProse(report.status),
12860
+ ...report.packageVersion !== void 0 ? { packageVersion: report.packageVersion } : {},
12861
+ ...report.memoryVersion !== void 0 ? { memoryVersion: report.memoryVersion } : {},
12862
+ ...report.contentId ? { contentId: report.contentId } : {},
12863
+ integrity: report.integrity ?? null,
12864
+ authenticity: report.authenticity ?? null,
12865
+ parts: report.parts,
12866
+ claims: includeKnowledge && Array.isArray(report.knowledge?.claims) ? report.knowledge.claims.slice(0, limit).map((claim) => ({
12867
+ id: claim.id,
12868
+ epistemicType: claim.epistemicType,
12869
+ evidence: claim.evidence,
12870
+ revision: claim.revision
12871
+ })) : void 0,
12872
+ claimCount: Array.isArray(report.knowledge?.claims) ? report.knowledge.claims.length : null,
12873
+ redacted: redact,
12874
+ ...includeKnowledge && report.knowledge ? { knowledge: redactKnowledge(report.knowledge, redact) } : {}
12875
+ };
12876
+ return { markdown, json };
12877
+ }, "renderInspectReport");
12878
+ }
12879
+ });
12880
+ var readPackage, listStore;
12881
+ var init_read_only = __esm({
12882
+ "core/knowledge/read-only.ts"() {
12883
+ init_mem_package();
12884
+ init_user_paths();
12885
+ readPackage = /* @__PURE__ */ __name(async (file) => {
12886
+ const resolved = path3.resolve(file);
12887
+ const bytes = await fs.readFile(resolved);
12888
+ const inspection = await inspectMem(bytes);
12889
+ return { ...inspection, file: resolved };
12890
+ }, "readPackage");
12891
+ listStore = /* @__PURE__ */ __name(async (root) => {
12892
+ const storageRoot = root ?? resolveUserDotMemPath();
12893
+ const packages = [];
12894
+ let dirents;
12895
+ try {
12896
+ dirents = await fs.readdir(storageRoot, { withFileTypes: true });
12897
+ } catch {
12898
+ return { root: storageRoot, packages: [] };
12899
+ }
12900
+ for (const entry of dirents) {
12901
+ if (!entry.isFile() || !entry.name.endsWith(".mem") || entry.name === "@brain.mem") continue;
12902
+ const filePath = path3.join(storageRoot, entry.name);
12903
+ try {
12904
+ const inspection = await readPackage(filePath);
12905
+ packages.push({ file: inspection.file, path: entry.name, inspection });
12906
+ } catch (error) {
12907
+ packages.push({
12908
+ file: filePath,
12909
+ path: entry.name,
12910
+ inspection: {
12911
+ status: "corrupt",
12912
+ representation: "unknown",
12913
+ message: `Unable to inspect: ${error instanceof Error ? error.message : String(error)}`,
12914
+ parts: []
12915
+ }
12916
+ });
12917
+ }
12918
+ }
12919
+ packages.sort((left, right) => left.path.localeCompare(right.path));
12920
+ return { root: storageRoot, packages };
12921
+ }, "listStore");
12922
+ }
12923
+ });
12924
+
12925
+ // core/knowledge/context-budget.ts
12926
+ function estimateTokens(text) {
12927
+ return Math.ceil(text.length / 4);
12928
+ }
12929
+ function estimateClaimSize(claim) {
12930
+ const serialized = JSON.stringify(claim.knowledge ?? {});
12931
+ const characters = serialized.length;
12932
+ return { tokens: estimateTokens(serialized), characters };
12933
+ }
12934
+ function calculateBudgetUsage(claims, budget) {
12935
+ let totalChars = 0;
12936
+ for (const claim of claims) {
12937
+ totalChars += estimateClaimSize(claim).characters;
12938
+ }
12939
+ const tokens = estimateTokens(String(totalChars));
12940
+ const utilization = budget === "unlimited" || budget === 0 ? 1 : Math.min(totalChars / (budget * 4), 1);
12941
+ return {
12942
+ tokens,
12943
+ characters: totalChars,
12944
+ claimCount: claims.length,
12945
+ budget,
12946
+ utilization
12947
+ };
12948
+ }
12949
+ function explainBudgetAllocation(included, excluded, budget) {
12950
+ const result = {
12951
+ included: included.map((claim) => {
12952
+ const size = estimateClaimSize(claim);
12953
+ return {
12954
+ claimId: claim.id,
12955
+ reason: "matched discovery",
12956
+ estimatedTokens: size.tokens,
12957
+ estimatedCharacters: size.characters
12958
+ };
12959
+ }),
12960
+ excluded: excluded.map((item) => ({
12961
+ claimId: item.id,
12962
+ reason: item.reason
12963
+ })),
12964
+ total: calculateBudgetUsage(included, budget)
12965
+ };
12966
+ if (result.total.utilization >= 0.9 && budget !== "unlimited") {
12967
+ result.excluded.push({
12968
+ claimId: "__budget__",
12969
+ reason: `Budget at ${Math.round(result.total.utilization * 100)}% utilization (${result.total.tokens} tokens of ${budget})`
12970
+ });
12971
+ }
12972
+ return result;
12973
+ }
12974
+ function formatBudgetExplanation(explanation) {
12975
+ const lines = [
12976
+ "Context Budget Report",
12977
+ "",
12978
+ `Total claims included: ${explanation.total.claimCount}`,
12979
+ `Estimated tokens: ${explanation.total.tokens}`,
12980
+ `Budget: ${explanation.total.budget === "unlimited" ? "unlimited" : explanation.total.budget}`,
12981
+ `Utilization: ${Math.round(explanation.total.utilization * 100)}%`,
12982
+ ""
12983
+ ];
12984
+ if (explanation.included.length > 0) {
12985
+ lines.push("Included claims:");
12986
+ for (const item of explanation.included) {
12987
+ lines.push(` [${item.claimId}] ${item.estimatedTokens} tokens \u2014 ${item.reason}`);
12988
+ }
12989
+ lines.push("");
12990
+ }
12991
+ if (explanation.excluded.length > 0) {
12992
+ lines.push("Excluded claims:");
12993
+ for (const item of explanation.excluded) {
12994
+ lines.push(` [${item.claimId}] ${item.reason}`);
12995
+ }
12996
+ lines.push("");
12997
+ }
12998
+ return lines.join("\n");
12999
+ }
13000
+ var init_context_budget = __esm({
13001
+ "core/knowledge/context-budget.ts"() {
13002
+ __name(estimateTokens, "estimateTokens");
13003
+ __name(estimateClaimSize, "estimateClaimSize");
13004
+ __name(calculateBudgetUsage, "calculateBudgetUsage");
13005
+ __name(explainBudgetAllocation, "explainBudgetAllocation");
13006
+ __name(formatBudgetExplanation, "formatBudgetExplanation");
13007
+ }
13008
+ });
13009
+
13010
+ // core/knowledge/feedback.ts
13011
+ function joinPath8(base, child) {
13012
+ const separator3 = process.platform === "win32" ? "\\" : "/";
13013
+ return `${base.replace(/[\\/]+/g, separator3)}${separator3}${child}`;
13014
+ }
13015
+ function resolveFeedbackFilePath() {
13016
+ return joinPath8(resolveUserDotMemPath(), FEEDBACK_FILE_NAME);
13017
+ }
13018
+ async function readFile4(path8) {
13019
+ try {
13020
+ const fs9 = await import('fs/promises');
13021
+ return await fs9.readFile(path8, "utf8");
13022
+ } catch {
13023
+ return null;
13024
+ }
13025
+ }
13026
+ async function writeFile4(path8, content) {
13027
+ const fs9 = await import('fs/promises');
13028
+ const dir = path8.replace(/[\\/][^\\/]+$/, "");
13029
+ await fs9.mkdir(dir, { recursive: true });
13030
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
13031
+ await fs9.writeFile(temporary, content, "utf8");
13032
+ await fs9.rename(temporary, path8);
13033
+ }
13034
+ async function loadFeedback() {
13035
+ const raw = await readFile4(resolveFeedbackFilePath());
13036
+ if (!raw) return { version: FEEDBACK_FORMAT_VERSION, entries: [] };
13037
+ try {
13038
+ const parsed = JSON.parse(raw);
13039
+ if (parsed.version === FEEDBACK_FORMAT_VERSION && Array.isArray(parsed.entries)) {
13040
+ return { version: FEEDBACK_FORMAT_VERSION, entries: parsed.entries };
13041
+ }
13042
+ } catch {
13043
+ }
13044
+ return { version: FEEDBACK_FORMAT_VERSION, entries: [] };
13045
+ }
13046
+ async function saveFeedback(document) {
13047
+ await writeFile4(resolveFeedbackFilePath(), JSON.stringify(document, null, 2) + "\n");
13048
+ }
13049
+ function validateFeedbackEntry(entry) {
13050
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
12028
13051
  throw new Error("Feedback entry must be an object");
12029
13052
  }
12030
13053
  const feedback = entry;
@@ -12084,10 +13107,10 @@ var init_feedback = __esm({
12084
13107
  init_user_paths();
12085
13108
  FEEDBACK_FILE_NAME = "feedback.json";
12086
13109
  FEEDBACK_FORMAT_VERSION = 1;
12087
- __name(joinPath7, "joinPath");
13110
+ __name(joinPath8, "joinPath");
12088
13111
  __name(resolveFeedbackFilePath, "resolveFeedbackFilePath");
12089
- __name(readFile3, "readFile");
12090
- __name(writeFile3, "writeFile");
13112
+ __name(readFile4, "readFile");
13113
+ __name(writeFile4, "writeFile");
12091
13114
  VALID_KINDS = /* @__PURE__ */ new Set(["helped", "misled", "ignored"]);
12092
13115
  __name(loadFeedback, "loadFeedback");
12093
13116
  __name(saveFeedback, "saveFeedback");
@@ -12145,302 +13168,125 @@ var init_correction = __esm({
12145
13168
  __name(saveCorrectionDrafts, "saveCorrectionDrafts");
12146
13169
  }
12147
13170
  });
12148
-
12149
- // core/knowledge/incidents.ts
12150
- function findIncidentById(id) {
12151
- return INCIDENT_EVAL_TEST_SET.find((incident) => incident.id === id);
12152
- }
12153
- function listIncidents() {
12154
- return [...INCIDENT_EVAL_TEST_SET];
12155
- }
12156
- function buildIncidentState(overrides = {}) {
12157
- const baseClaims = [
12158
- {
12159
- id: "behavior:watch-files",
12160
- epistemicType: "observed",
12161
- applicability: { verified: true },
12162
- evidence: [{ id: "ev-watch-1", observedAt: "2026-01-01T00:00:00Z" }],
12163
- knowledge: { trigger: "file watching", rule: "watch files with watch tool" },
12164
- acquiredAt: "2026-01-01T00:00:00Z"
12165
- },
12166
- {
12167
- id: "behavior:state-engine",
12168
- epistemicType: "observed",
12169
- applicability: { verified: true },
12170
- evidence: [{ id: "ev-state-1", observedAt: "2026-01-01T00:00:00Z" }],
12171
- knowledge: { trigger: "state engine", rule: "state is foundation" },
12172
- acquiredAt: "2026-01-01T00:00:00Z"
12173
- },
12174
- {
12175
- id: "behavior:git-push-guard",
12176
- epistemicType: "observed",
12177
- applicability: { verified: true },
12178
- evidence: [{ id: "ev-push-1", observedAt: "2026-01-01T00:00:00Z" }],
12179
- knowledge: { trigger: "git push", rule: "guard git operations" },
12180
- acquiredAt: "2026-01-01T00:00:00Z"
12181
- },
12182
- {
12183
- id: "behavior:memory-layer",
12184
- epistemicType: "observed",
12185
- applicability: { verified: true },
12186
- evidence: [{ id: "ev-mem-1", observedAt: "2026-01-01T00:00:00Z" }],
12187
- knowledge: { trigger: "memory", rule: "memory is state plus store" },
12188
- acquiredAt: "2026-01-01T00:00:00Z"
12189
- },
12190
- {
12191
- id: "project:current-project",
12192
- epistemicType: "observed",
12193
- applicability: { scope: "project", verified: true },
12194
- evidence: [{ id: "ev-proj-1", observedAt: "2026-01-01T00:00:00Z" }],
12195
- knowledge: { trigger: "current project", anchor: "project root" },
12196
- acquiredAt: "2026-01-01T00:00:00Z"
12197
- }
12198
- ];
12199
- return {
12200
- version: 1,
12201
- claims: [...baseClaims, ...overrides.claims ?? []]
12202
- };
12203
- }
12204
- function evaluateIncident(incident, matchedClaims) {
12205
- const got = matchedClaims;
12206
- const missing = incident.expectedClaimIds.filter((id) => !got.includes(id));
12207
- const unexpected = got.filter((id) => !incident.expectedClaimIds.includes(id));
12208
- return {
12209
- incidentId: incident.id,
12210
- passed: missing.length === 0 && unexpected.length === 0,
12211
- expected: incident.expectedClaimIds,
12212
- got,
12213
- missing,
12214
- unexpected
12215
- };
12216
- }
12217
- function formatIncidentReport(report) {
12218
- const lines = [
12219
- `Incident Eval Report: ${report.passed}/${report.total} passed`,
12220
- ""
12221
- ];
12222
- for (const result of report.results) {
12223
- const status = result.passed ? "PASS" : "FAIL";
12224
- lines.push(`[${status}] ${result.incidentId}`);
12225
- if (!result.passed) {
12226
- if (result.missing.length > 0) {
12227
- lines.push(` Missing: ${result.missing.join(", ")}`);
12228
- }
12229
- if (result.unexpected.length > 0) {
12230
- lines.push(` Unexpected: ${result.unexpected.join(", ")}`);
12231
- }
12232
- }
12233
- }
12234
- return lines.join("\n");
12235
- }
12236
- var INCIDENT_EVAL_TEST_SET;
12237
- var init_incidents = __esm({
12238
- "core/knowledge/incidents.ts"() {
12239
- INCIDENT_EVAL_TEST_SET = [
12240
- {
12241
- id: "incident-001",
12242
- situation: "user asks about file watching",
12243
- expectedClaimIds: ["behavior:watch-files"],
12244
- excludedIds: ["behavior:state-engine"],
12245
- description: "File watching should pull the watch-files rule, not the state engine rule"
12246
- },
12247
- {
12248
- id: "incident-002",
12249
- situation: "user asks about git push",
12250
- expectedClaimIds: ["behavior:git-push-guard"],
12251
- excludedIds: ["behavior:memory-layer"],
12252
- description: "Git push should trigger the push guard, not the memory layer"
12253
- },
12254
- {
12255
- id: "incident-003",
12256
- situation: "current project context",
12257
- expectedClaimIds: ["project:current-project"],
12258
- excludedIds: ["behavior:state-engine"],
12259
- description: "Current project situation should surface the project anchor claim"
12260
- }
12261
- ];
12262
- __name(findIncidentById, "findIncidentById");
12263
- __name(listIncidents, "listIncidents");
12264
- __name(buildIncidentState, "buildIncidentState");
12265
- __name(evaluateIncident, "evaluateIncident");
12266
- __name(formatIncidentReport, "formatIncidentReport");
12267
- }
12268
- });
12269
-
12270
- // core/knowledge/rules-loader.ts
12271
- function isRuleClaim(claim) {
12272
- const knowledge = claim.knowledge;
12273
- return knowledge?.kind === "rule";
12274
- }
12275
- function isIronRule(claim) {
12276
- return claim.epistemicType === "human-stated" && isRuleClaim(claim);
12277
- }
12278
- function extractIronRules(state2) {
12279
- const validated = validateKnowledgeState(state2);
12280
- const claims = activeClaims(validated);
12281
- const rules = [];
12282
- for (const claim of claims) {
12283
- if (!isIronRule(claim)) continue;
12284
- const knowledge = claim.knowledge;
12285
- const applicability = claim.applicability;
12286
- const iron = applicability.iron === true || applicability.priority === "iron";
12287
- if (!iron) continue;
12288
- rules.push({
12289
- id: claim.id,
12290
- text: String(knowledge.text ?? knowledge.rule ?? claim.id),
12291
- why: String(knowledge.why ?? knowledge.reason ?? ""),
12292
- appliesWhen: String(knowledge.appliesWhen ?? knowledge.when ?? ""),
12293
- violatedOn: Array.isArray(knowledge.violatedOn) ? knowledge.violatedOn : void 0,
12294
- lastViolation: typeof knowledge.lastViolation === "string" ? knowledge.lastViolation : void 0,
12295
- frequency: typeof knowledge.frequency === "number" ? knowledge.frequency : 0
12296
- });
12297
- }
12298
- return rules;
12299
- }
12300
- function sortRulesByViolationFrequency(rules) {
12301
- return [...rules].sort((a, b) => {
12302
- if (b.frequency !== a.frequency) return b.frequency - a.frequency;
12303
- if (a.lastViolation && b.lastViolation) {
12304
- return b.lastViolation.localeCompare(a.lastViolation);
12305
- }
12306
- return 0;
12307
- });
12308
- }
12309
- function loadIronRules(state2) {
12310
- const rules = sortRulesByViolationFrequency(extractIronRules(state2));
12311
- return {
12312
- rules,
12313
- count: rules.length,
12314
- sortedBy: "violation-frequency"
12315
- };
12316
- }
12317
- function formatRulesForSessionStart(rules) {
12318
- if (rules.length === 0) {
12319
- return "";
12320
- }
12321
- const lines = ["---", "IRON RULES (must always arrive)", "---"];
12322
- for (const rule of rules) {
12323
- lines.push(`${rule.id}: ${rule.text}`);
12324
- }
12325
- return lines.join("\n");
12326
- }
12327
- function formatRuleWithExplanation(rule) {
12328
- const parts = [];
12329
- parts.push(`[${rule.id}] ${rule.text}`);
12330
- if (rule.why) parts.push(` WHY: ${rule.why}`);
12331
- if (rule.appliesWhen) parts.push(` APPLIES WHEN: ${rule.appliesWhen}`);
12332
- if (rule.violatedOn && rule.violatedOn.length > 0) {
12333
- parts.push(` VIOLATED ${rule.violatedOn.length} TIME(S)`);
12334
- if (rule.lastViolation) parts.push(` Last: ${rule.lastViolation}`);
12335
- }
12336
- return parts.join("\n");
12337
- }
12338
- var init_rules_loader = __esm({
12339
- "core/knowledge/rules-loader.ts"() {
12340
- init_state();
12341
- __name(isRuleClaim, "isRuleClaim");
12342
- __name(isIronRule, "isIronRule");
12343
- __name(extractIronRules, "extractIronRules");
12344
- __name(sortRulesByViolationFrequency, "sortRulesByViolationFrequency");
12345
- __name(loadIronRules, "loadIronRules");
12346
- __name(formatRulesForSessionStart, "formatRulesForSessionStart");
12347
- __name(formatRuleWithExplanation, "formatRuleWithExplanation");
12348
- }
12349
- });
12350
-
12351
- // core/knowledge/violations.ts
12352
- function joinPath8(base, child) {
12353
- const separator3 = process.platform === "win32" ? "\\" : "/";
12354
- return `${base.replace(/[\\/]+/g, separator3)}${separator3}${child}`;
12355
- }
12356
- function resolveViolationFilePath() {
12357
- return joinPath8(resolveUserDotMemPath(), VIOLATION_FILE_NAME);
12358
- }
12359
- async function readFile4(path5) {
12360
- try {
12361
- const fs7 = await import('fs/promises');
12362
- return await fs7.readFile(path5, "utf8");
12363
- } catch {
12364
- return null;
12365
- }
12366
- }
12367
- async function writeFile4(path5, content) {
12368
- const fs7 = await import('fs/promises');
12369
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
12370
- await fs7.mkdir(dir, { recursive: true });
12371
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
12372
- await fs7.writeFile(temporary, content, "utf8");
12373
- await fs7.rename(temporary, path5);
12374
- }
12375
- async function loadViolations() {
12376
- const raw = await readFile4(resolveViolationFilePath());
12377
- if (!raw) return { version: VIOLATION_FORMAT_VERSION, entries: [] };
12378
- try {
12379
- const parsed = JSON.parse(raw);
12380
- if (parsed.version === VIOLATION_FORMAT_VERSION && Array.isArray(parsed.entries)) {
12381
- return { version: VIOLATION_FORMAT_VERSION, entries: parsed.entries };
12382
- }
12383
- } catch {
12384
- }
12385
- return { version: VIOLATION_FORMAT_VERSION, entries: [] };
12386
- }
12387
- async function saveViolations(document) {
12388
- await writeFile4(resolveViolationFilePath(), JSON.stringify(document, null, 2) + "\n");
12389
- }
12390
- async function logViolation(ruleId, situation, description = "") {
12391
- const document = await loadViolations();
12392
- const record = {
12393
- ruleId,
12394
- violatedAt: (/* @__PURE__ */ new Date()).toISOString(),
12395
- description,
12396
- situation
12397
- };
12398
- document.entries.push(record);
12399
- await saveViolations(document);
12400
- return record;
13171
+
13172
+ // core/knowledge/incidents.ts
13173
+ function findIncidentById(id) {
13174
+ return INCIDENT_EVAL_TEST_SET.find((incident) => incident.id === id);
12401
13175
  }
12402
- async function countViolations(ruleId) {
12403
- const document = await loadViolations();
12404
- return document.entries.filter((e) => e.ruleId === ruleId).length;
13176
+ function listIncidents() {
13177
+ return [...INCIDENT_EVAL_TEST_SET];
12405
13178
  }
12406
- async function lastViolation(ruleId) {
12407
- const document = await loadViolations();
12408
- const entries2 = document.entries.filter((e) => e.ruleId === ruleId).sort((a, b) => b.violatedAt.localeCompare(a.violatedAt));
12409
- return entries2[0]?.violatedAt;
13179
+ function buildIncidentState(overrides = {}) {
13180
+ const baseClaims = [
13181
+ {
13182
+ id: "behavior:watch-files",
13183
+ epistemicType: "observed",
13184
+ applicability: { verified: true },
13185
+ evidence: [{ id: "ev-watch-1", observedAt: "2026-01-01T00:00:00Z" }],
13186
+ knowledge: { trigger: "file watching", rule: "watch files with watch tool" },
13187
+ acquiredAt: "2026-01-01T00:00:00Z"
13188
+ },
13189
+ {
13190
+ id: "behavior:state-engine",
13191
+ epistemicType: "observed",
13192
+ applicability: { verified: true },
13193
+ evidence: [{ id: "ev-state-1", observedAt: "2026-01-01T00:00:00Z" }],
13194
+ knowledge: { trigger: "state engine", rule: "state is foundation" },
13195
+ acquiredAt: "2026-01-01T00:00:00Z"
13196
+ },
13197
+ {
13198
+ id: "behavior:git-push-guard",
13199
+ epistemicType: "observed",
13200
+ applicability: { verified: true },
13201
+ evidence: [{ id: "ev-push-1", observedAt: "2026-01-01T00:00:00Z" }],
13202
+ knowledge: { trigger: "git push", rule: "guard git operations" },
13203
+ acquiredAt: "2026-01-01T00:00:00Z"
13204
+ },
13205
+ {
13206
+ id: "behavior:memory-layer",
13207
+ epistemicType: "observed",
13208
+ applicability: { verified: true },
13209
+ evidence: [{ id: "ev-mem-1", observedAt: "2026-01-01T00:00:00Z" }],
13210
+ knowledge: { trigger: "memory", rule: "memory is state plus store" },
13211
+ acquiredAt: "2026-01-01T00:00:00Z"
13212
+ },
13213
+ {
13214
+ id: "project:current-project",
13215
+ epistemicType: "observed",
13216
+ applicability: { scope: "project", verified: true },
13217
+ evidence: [{ id: "ev-proj-1", observedAt: "2026-01-01T00:00:00Z" }],
13218
+ knowledge: { trigger: "current project", anchor: "project root" },
13219
+ acquiredAt: "2026-01-01T00:00:00Z"
13220
+ }
13221
+ ];
13222
+ return {
13223
+ version: 1,
13224
+ claims: [...baseClaims, ...overrides.claims ?? []]
13225
+ };
12410
13226
  }
12411
- async function listViolations(ruleId) {
12412
- const document = await loadViolations();
12413
- if (!ruleId) return document.entries;
12414
- return document.entries.filter((e) => e.ruleId === ruleId);
13227
+ function evaluateIncident(incident, matchedClaims) {
13228
+ const got = matchedClaims;
13229
+ const missing = incident.expectedClaimIds.filter((id) => !got.includes(id));
13230
+ const unexpected = got.filter((id) => !incident.expectedClaimIds.includes(id));
13231
+ return {
13232
+ incidentId: incident.id,
13233
+ passed: missing.length === 0 && unexpected.length === 0,
13234
+ expected: incident.expectedClaimIds,
13235
+ got,
13236
+ missing,
13237
+ unexpected
13238
+ };
12415
13239
  }
12416
- async function clearViolations(ruleId) {
12417
- const document = await loadViolations();
12418
- const beforeCount = document.entries.length;
12419
- if (ruleId) {
12420
- document.entries = document.entries.filter((e) => e.ruleId !== ruleId);
12421
- } else {
12422
- document.entries = [];
13240
+ function formatIncidentReport(report) {
13241
+ const lines = [
13242
+ `Incident Eval Report: ${report.passed}/${report.total} passed`,
13243
+ ""
13244
+ ];
13245
+ for (const result of report.results) {
13246
+ const status = result.passed ? "PASS" : "FAIL";
13247
+ lines.push(`[${status}] ${result.incidentId}`);
13248
+ if (!result.passed) {
13249
+ if (result.missing.length > 0) {
13250
+ lines.push(` Missing: ${result.missing.join(", ")}`);
13251
+ }
13252
+ if (result.unexpected.length > 0) {
13253
+ lines.push(` Unexpected: ${result.unexpected.join(", ")}`);
13254
+ }
13255
+ }
12423
13256
  }
12424
- await saveViolations(document);
12425
- return beforeCount - document.entries.length;
13257
+ return lines.join("\n");
12426
13258
  }
12427
- var VIOLATION_FILE_NAME, VIOLATION_FORMAT_VERSION;
12428
- var init_violations = __esm({
12429
- "core/knowledge/violations.ts"() {
12430
- init_user_paths();
12431
- VIOLATION_FILE_NAME = "violations.json";
12432
- VIOLATION_FORMAT_VERSION = 1;
12433
- __name(joinPath8, "joinPath");
12434
- __name(resolveViolationFilePath, "resolveViolationFilePath");
12435
- __name(readFile4, "readFile");
12436
- __name(writeFile4, "writeFile");
12437
- __name(loadViolations, "loadViolations");
12438
- __name(saveViolations, "saveViolations");
12439
- __name(logViolation, "logViolation");
12440
- __name(countViolations, "countViolations");
12441
- __name(lastViolation, "lastViolation");
12442
- __name(listViolations, "listViolations");
12443
- __name(clearViolations, "clearViolations");
13259
+ var INCIDENT_EVAL_TEST_SET;
13260
+ var init_incidents = __esm({
13261
+ "core/knowledge/incidents.ts"() {
13262
+ INCIDENT_EVAL_TEST_SET = [
13263
+ {
13264
+ id: "incident-001",
13265
+ situation: "user asks about file watching",
13266
+ expectedClaimIds: ["behavior:watch-files"],
13267
+ excludedIds: ["behavior:state-engine"],
13268
+ description: "File watching should pull the watch-files rule, not the state engine rule"
13269
+ },
13270
+ {
13271
+ id: "incident-002",
13272
+ situation: "user asks about git push",
13273
+ expectedClaimIds: ["behavior:git-push-guard"],
13274
+ excludedIds: ["behavior:memory-layer"],
13275
+ description: "Git push should trigger the push guard, not the memory layer"
13276
+ },
13277
+ {
13278
+ id: "incident-003",
13279
+ situation: "current project context",
13280
+ expectedClaimIds: ["project:current-project"],
13281
+ excludedIds: ["behavior:state-engine"],
13282
+ description: "Current project situation should surface the project anchor claim"
13283
+ }
13284
+ ];
13285
+ __name(findIncidentById, "findIncidentById");
13286
+ __name(listIncidents, "listIncidents");
13287
+ __name(buildIncidentState, "buildIncidentState");
13288
+ __name(evaluateIncident, "evaluateIncident");
13289
+ __name(formatIncidentReport, "formatIncidentReport");
12444
13290
  }
12445
13291
  });
12446
13292
 
@@ -12452,21 +13298,21 @@ function joinPath9(base, child) {
12452
13298
  function resolveSessionFilePath() {
12453
13299
  return joinPath9(resolveUserDotMemPath(), SESSION_FILE_NAME);
12454
13300
  }
12455
- async function readFile5(path5) {
13301
+ async function readFile5(path8) {
12456
13302
  try {
12457
- const fs7 = await import('fs/promises');
12458
- return await fs7.readFile(path5, "utf8");
13303
+ const fs9 = await import('fs/promises');
13304
+ return await fs9.readFile(path8, "utf8");
12459
13305
  } catch {
12460
13306
  return null;
12461
13307
  }
12462
13308
  }
12463
- async function writeFile5(path5, content) {
12464
- const fs7 = await import('fs/promises');
12465
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
12466
- await fs7.mkdir(dir, { recursive: true });
12467
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
12468
- await fs7.writeFile(temporary, content, "utf8");
12469
- await fs7.rename(temporary, path5);
13309
+ async function writeFile5(path8, content) {
13310
+ const fs9 = await import('fs/promises');
13311
+ const dir = path8.replace(/[\\/][^\\/]+$/, "");
13312
+ await fs9.mkdir(dir, { recursive: true });
13313
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
13314
+ await fs9.writeFile(temporary, content, "utf8");
13315
+ await fs9.rename(temporary, path8);
12470
13316
  }
12471
13317
  async function loadSession() {
12472
13318
  const raw = await readFile5(resolveSessionFilePath());
@@ -12568,25 +13414,25 @@ function joinPath10(base, child) {
12568
13414
  function resolveExemplarsPath() {
12569
13415
  return joinPath10(resolveUserDotMemPath(), EXEMPLARS_FILE_NAME);
12570
13416
  }
12571
- async function readFile6(path5) {
13417
+ async function readFile6(path8) {
12572
13418
  try {
12573
- const fs7 = await import('fs/promises');
12574
- return await fs7.readFile(path5, "utf8");
13419
+ const fs9 = await import('fs/promises');
13420
+ return await fs9.readFile(path8, "utf8");
12575
13421
  } catch {
12576
13422
  return null;
12577
13423
  }
12578
13424
  }
12579
- async function writeFile6(path5, content) {
12580
- const fs7 = await import('fs/promises');
12581
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
12582
- await fs7.mkdir(dir, { recursive: true });
12583
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
13425
+ async function writeFile6(path8, content) {
13426
+ const fs9 = await import('fs/promises');
13427
+ const dir = path8.replace(/[\\/][^\\/]+$/, "");
13428
+ await fs9.mkdir(dir, { recursive: true });
13429
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
12584
13430
  try {
12585
- await fs7.writeFile(temporary, content, "utf8");
12586
- await fs7.rename(temporary, path5);
13431
+ await fs9.writeFile(temporary, content, "utf8");
13432
+ await fs9.rename(temporary, path8);
12587
13433
  } catch {
12588
- await fs7.rm(temporary, { force: true }).catch(() => void 0);
12589
- throw new Error(`Failed to write exemplars file at ${path5}`);
13434
+ await fs9.rm(temporary, { force: true }).catch(() => void 0);
13435
+ throw new Error(`Failed to write exemplars file at ${path8}`);
12590
13436
  }
12591
13437
  }
12592
13438
  function emptyStore() {
@@ -12800,25 +13646,25 @@ function joinPath11(base, child) {
12800
13646
  function resolvePersonalityAnchorPath() {
12801
13647
  return joinPath11(resolveUserDotMemPath(), PERSONALITY_ANCHOR_FILE_NAME);
12802
13648
  }
12803
- async function readFile7(path5) {
13649
+ async function readFile7(path8) {
12804
13650
  try {
12805
- const fs7 = await import('fs/promises');
12806
- return await fs7.readFile(path5, "utf8");
13651
+ const fs9 = await import('fs/promises');
13652
+ return await fs9.readFile(path8, "utf8");
12807
13653
  } catch {
12808
13654
  return null;
12809
13655
  }
12810
13656
  }
12811
- async function writeFile7(path5, content) {
12812
- const fs7 = await import('fs/promises');
12813
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
12814
- await fs7.mkdir(dir, { recursive: true });
12815
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
13657
+ async function writeFile7(path8, content) {
13658
+ const fs9 = await import('fs/promises');
13659
+ const dir = path8.replace(/[\\/][^\\/]+$/, "");
13660
+ await fs9.mkdir(dir, { recursive: true });
13661
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
12816
13662
  try {
12817
- await fs7.writeFile(temporary, content, "utf8");
12818
- await fs7.rename(temporary, path5);
13663
+ await fs9.writeFile(temporary, content, "utf8");
13664
+ await fs9.rename(temporary, path8);
12819
13665
  } catch {
12820
- await fs7.rm(temporary, { force: true }).catch(() => void 0);
12821
- throw new Error(`Failed to write personality anchor at ${path5}`);
13666
+ await fs9.rm(temporary, { force: true }).catch(() => void 0);
13667
+ throw new Error(`Failed to write personality anchor at ${path8}`);
12822
13668
  }
12823
13669
  }
12824
13670
  function emptyAnchor() {
@@ -12956,8 +13802,8 @@ async function loadPersonalityAnchor() {
12956
13802
  async function savePersonalityAnchor(anchor) {
12957
13803
  const validated = validateAnchor(anchor);
12958
13804
  const dirPath = resolveUserDotMemPath();
12959
- const fs7 = await import('fs/promises');
12960
- await fs7.mkdir(dirPath, { recursive: true });
13805
+ const fs9 = await import('fs/promises');
13806
+ await fs9.mkdir(dirPath, { recursive: true });
12961
13807
  await writeFile7(resolvePersonalityAnchorPath(), JSON.stringify(validated, null, 2));
12962
13808
  }
12963
13809
  async function updatePersonalityAnchor(updates) {
@@ -13059,7 +13905,7 @@ function pkgDirname() {
13059
13905
  return __dirname;
13060
13906
  }
13061
13907
  try {
13062
- return path2.dirname(fileURLToPath(import.meta.url));
13908
+ return path3.dirname(fileURLToPath(import.meta.url));
13063
13909
  } catch {
13064
13910
  return process.cwd();
13065
13911
  }
@@ -13067,7 +13913,7 @@ function pkgDirname() {
13067
13913
  function candidatePaths() {
13068
13914
  const paths = [];
13069
13915
  try {
13070
- paths.push(path2.join(pkgDirname(), "built-in-context.json"));
13916
+ paths.push(path3.join(pkgDirname(), "built-in-context.json"));
13071
13917
  } catch {
13072
13918
  }
13073
13919
  return paths;
@@ -13136,10 +13982,10 @@ function loadBuiltInContext() {
13136
13982
  let lastError = "Built-in context artifact not found";
13137
13983
  const candidates = _artifactPathOverride ? [_artifactPathOverride] : candidatePaths();
13138
13984
  for (const candidate of candidates) {
13139
- if (!fs2.existsSync(candidate)) continue;
13985
+ if (!fs3.existsSync(candidate)) continue;
13140
13986
  try {
13141
- const raw = fs2.readFileSync(candidate, "utf8");
13142
- const parsed = JSON.parse(raw);
13987
+ const raw = fs3.readFileSync(candidate);
13988
+ const parsed = JSON.parse(decodeText(raw, { source: candidate }));
13143
13989
  const artifact = validateArtifact(parsed);
13144
13990
  cached = artifact;
13145
13991
  cachedStatus = {
@@ -13169,14 +14015,14 @@ function loadBuiltInContext() {
13169
14015
  }
13170
14016
  let attemptedPath = "";
13171
14017
  try {
13172
- attemptedPath = path2.join(pkgDirname(), "built-in-context.json");
14018
+ attemptedPath = path3.join(pkgDirname(), "built-in-context.json");
13173
14019
  } catch {
13174
14020
  }
13175
14021
  let packageVersion = "unknown";
13176
14022
  try {
13177
- const pkgPath = path2.join(pkgDirname(), "package.json");
13178
- if (fs2.existsSync(pkgPath)) {
13179
- const pkg = JSON.parse(fs2.readFileSync(pkgPath, "utf8"));
14023
+ const pkgPath = path3.join(pkgDirname(), "package.json");
14024
+ if (fs3.existsSync(pkgPath)) {
14025
+ const pkg = JSON.parse(fs3.readFileSync(pkgPath, "utf8"));
13180
14026
  packageVersion = typeof pkg.version === "string" ? pkg.version : "unknown";
13181
14027
  }
13182
14028
  } catch {
@@ -13222,6 +14068,7 @@ function resetBuiltInContextCache() {
13222
14068
  var BUILT_IN_CONTEXT_FORMAT, BUILT_IN_CONTEXT_FORMAT_VERSION, cached, cachedStatus, _artifactPathOverride;
13223
14069
  var init_built_in_context = __esm({
13224
14070
  "core/knowledge/built-in-context.ts"() {
14071
+ init_text_encoding();
13225
14072
  BUILT_IN_CONTEXT_FORMAT = "dotmem.built-in-context";
13226
14073
  BUILT_IN_CONTEXT_FORMAT_VERSION = 1;
13227
14074
  cached = null;
@@ -13388,14 +14235,17 @@ __export(knowledge_exports, {
13388
14235
  addLoop: () => addLoop,
13389
14236
  addWaitingForUser: () => addWaitingForUser,
13390
14237
  appendDetectionJournal: () => appendDetectionJournal,
14238
+ applyVerification: () => applyVerification,
13391
14239
  assertBuiltInContextAvailable: () => assertBuiltInContextAvailable,
13392
14240
  assertNoConversationalOverride: () => assertNoConversationalOverride,
13393
14241
  authorityRelaxationPermitted: () => authorityRelaxationPermitted,
13394
14242
  authorityRevocationPermitted: () => authorityRevocationPermitted,
13395
14243
  buildIncidentState: () => buildIncidentState,
14244
+ buildVerificationRecord: () => buildVerificationRecord,
13396
14245
  builtInContextRulesMapped: () => builtInContextRulesMapped,
13397
14246
  calculateAnchorBudget: () => calculateAnchorBudget,
13398
14247
  calculateBudgetUsage: () => calculateBudgetUsage,
14248
+ callerInjectedVerificationMetadata: () => callerInjectedVerificationMetadata,
13399
14249
  canonicalApplicabilityValue: () => canonicalApplicabilityValue,
13400
14250
  canonicalEvent: () => canonicalEvent,
13401
14251
  canonicalEvidenceError: () => canonicalEvidenceError,
@@ -13414,6 +14264,7 @@ __export(knowledge_exports, {
13414
14264
  clearViolations: () => clearViolations,
13415
14265
  closeLoop: () => closeLoop,
13416
14266
  commitStageFile: () => commitStageFile,
14267
+ composeBootstrap: () => composeBootstrap,
13417
14268
  constructEffectiveAgentContract: () => constructEffectiveAgentContract,
13418
14269
  countViolations: () => countViolations,
13419
14270
  crossAcquisitionBoundary: () => crossAcquisitionBoundary,
@@ -13421,7 +14272,9 @@ __export(knowledge_exports, {
13421
14272
  defaultIdentityGovernance: () => defaultIdentityGovernance,
13422
14273
  defaultOverrideId: () => defaultOverrideId,
13423
14274
  defaultPolicyId: () => defaultPolicyId,
14275
+ deriveCurrentness: () => deriveCurrentness,
13424
14276
  deriveSituationApplicability: () => deriveSituationApplicability,
14277
+ deriveTrustBasis: () => deriveTrustBasis,
13425
14278
  describeDotMemStorage: () => describeDotMemStorage,
13426
14279
  detectAuthorityEscalationAttempt: () => detectAuthorityEscalationAttempt,
13427
14280
  detectBehaviorCoreMutationAttempt: () => detectBehaviorCoreMutationAttempt,
@@ -13447,6 +14300,7 @@ __export(knowledge_exports, {
13447
14300
  explainDiscovery: () => explainDiscovery,
13448
14301
  explainIdentityResolution: () => explainIdentityResolution,
13449
14302
  extractIronRules: () => extractIronRules,
14303
+ findContestedIds: () => findContestedIds,
13450
14304
  findExemplar: () => findExemplar,
13451
14305
  findIncidentById: () => findIncidentById,
13452
14306
  fingerprintFromState: () => fingerprintFromState,
@@ -13473,6 +14327,7 @@ __export(knowledge_exports, {
13473
14327
  inspectMem: () => inspectMem,
13474
14328
  isBaselineClaim: () => isBaselineClaim,
13475
14329
  isBuiltInContextAvailable: () => isBuiltInContextAvailable,
14330
+ isCallerDeclaredVerified: () => isCallerDeclaredVerified,
13476
14331
  isEligibleByApplicability: () => isEligibleByApplicability,
13477
14332
  isIronRule: () => isIronRule,
13478
14333
  isItalian: () => isItalian,
@@ -13484,6 +14339,7 @@ __export(knowledge_exports, {
13484
14339
  listExemplars: () => listExemplars,
13485
14340
  listIncidents: () => listIncidents,
13486
14341
  listLoops: () => listLoops,
14342
+ listStore: () => listStore,
13487
14343
  listViews: () => listViews,
13488
14344
  listViolations: () => listViolations,
13489
14345
  loadBuiltInContext: () => loadBuiltInContext,
@@ -13513,6 +14369,7 @@ __export(knowledge_exports, {
13513
14369
  projectExemplarContext: () => projectExemplarContext,
13514
14370
  projectPersonalityAnchor: () => projectPersonalityAnchor,
13515
14371
  readDotMemStorageLocator: () => readDotMemStorageLocator,
14372
+ readPackage: () => readPackage,
13516
14373
  readStageFile: () => readStageFile,
13517
14374
  readStorageSettings: () => readStorageSettings,
13518
14375
  readUserLanguage: () => readUserLanguage,
@@ -13522,7 +14379,9 @@ __export(knowledge_exports, {
13522
14379
  relocateDotMemStorage: () => relocateDotMemStorage,
13523
14380
  removeExemplar: () => removeExemplar,
13524
14381
  renderAgentRules: () => renderAgentRules,
14382
+ renderExpandedClaim: () => renderExpandedClaim,
13525
14383
  renderExplanation: () => renderExplanation,
14384
+ renderInspectReport: () => renderInspectReport,
13526
14385
  renderMarkdownIndex: () => renderMarkdownIndex,
13527
14386
  renderOperatorContract: () => renderOperatorContract,
13528
14387
  renderView: () => renderView,
@@ -13610,6 +14469,7 @@ __export(knowledge_exports, {
13610
14469
  vaultList: () => vaultList,
13611
14470
  vaultPut: () => vaultPut,
13612
14471
  vaultResolve: () => vaultResolve,
14472
+ verifyAndPersistClaims: () => verifyAndPersistClaims,
13613
14473
  verifyDueClaims: () => verifyDueClaims,
13614
14474
  withPolicyNamespaceLock: () => withPolicyNamespaceLock,
13615
14475
  withoutOverlays: () => withoutOverlays,
@@ -13625,6 +14485,7 @@ var init_knowledge = __esm({
13625
14485
  init_state();
13626
14486
  init_select();
13627
14487
  init_discover();
14488
+ init_currentness();
13628
14489
  init_project();
13629
14490
  init_applicability();
13630
14491
  init_policy();
@@ -13658,6 +14519,10 @@ var init_knowledge = __esm({
13658
14519
  init_rule_checker();
13659
14520
  init_vault();
13660
14521
  init_verify();
14522
+ init_verification();
14523
+ init_bootstrap();
14524
+ init_inspect_report();
14525
+ init_read_only();
13661
14526
  init_context_budget();
13662
14527
  init_feedback();
13663
14528
  init_correction();
@@ -13732,7 +14597,6 @@ function _inferConfidence(claim) {
13732
14597
  var LOGIC_MEM_FILE, nodeCwd2, cachedRuntime, LogicEngine, logic, logic_default;
13733
14598
  var init_logic = __esm({
13734
14599
  "core/logic/index.ts"() {
13735
- init_suppress_idb_warning();
13736
14600
  init_knowledge();
13737
14601
  init_mem_repository();
13738
14602
  init_acquisition_boundary();
@@ -13887,16 +14751,16 @@ function detectLineEnding(content) {
13887
14751
  return content.includes("\r\n") ? "\r\n" : "\n";
13888
14752
  }
13889
14753
  async function ensureDotMemReadme(_projectRoot, readmeSource) {
13890
- const fs7 = await import('fs/promises');
14754
+ const fs9 = await import('fs/promises');
13891
14755
  const dotmemDir = resolveUserDotMemPath();
13892
14756
  try {
13893
- await fs7.mkdir(dotmemDir, { recursive: true });
14757
+ await fs9.mkdir(dotmemDir, { recursive: true });
13894
14758
  } catch {
13895
14759
  }
13896
14760
  const contractDestination = resolveUserContractPath();
13897
14761
  const readmeDestination = resolveUserReadmePath();
13898
14762
  try {
13899
- await fs7.access(contractDestination);
14763
+ await fs9.access(contractDestination);
13900
14764
  } catch {
13901
14765
  let source = readmeSource;
13902
14766
  if (!source) {
@@ -13914,7 +14778,7 @@ async function ensureDotMemReadme(_projectRoot, readmeSource) {
13914
14778
  return pathname.startsWith("/") && pathname.length > 3 && pathname[2] === ":" ? pathname.slice(1) : pathname;
13915
14779
  });
13916
14780
  for (const candidate of sourceCandidates) {
13917
- if (await fs7.access(candidate).then(() => true).catch(() => false)) {
14781
+ if (await fs9.access(candidate).then(() => true).catch(() => false)) {
13918
14782
  source = candidate;
13919
14783
  break;
13920
14784
  }
@@ -13922,22 +14786,22 @@ async function ensureDotMemReadme(_projectRoot, readmeSource) {
13922
14786
  source ??= sourceCandidates.at(-1);
13923
14787
  }
13924
14788
  try {
13925
- const contractContent = await fs7.readFile(source, "utf8");
14789
+ const contractContent = await fs9.readFile(source, "utf8");
13926
14790
  if (!contractContent.trim()) {
13927
14791
  throw new Error(`Refusing to install ${source} as the dotmem contract: the file is empty`);
13928
14792
  }
13929
- await fs7.writeFile(contractDestination, contractContent, "utf8");
14793
+ await fs9.writeFile(contractDestination, contractContent, "utf8");
13930
14794
  } catch (error) {
13931
14795
  throw new Error(`Failed to install dotmem contract from ${source} to ${contractDestination}: ${error instanceof Error ? error.message : String(error)}`);
13932
14796
  }
13933
14797
  }
13934
14798
  try {
13935
- await fs7.access(readmeDestination);
14799
+ await fs9.access(readmeDestination);
13936
14800
  return { action: "already-present", path: readmeDestination };
13937
14801
  } catch {
13938
14802
  }
13939
14803
  try {
13940
- await fs7.writeFile(readmeDestination, DEFAULT_README_CONTENT, "utf8");
14804
+ await fs9.writeFile(readmeDestination, DEFAULT_README_CONTENT, "utf8");
13941
14805
  return { action: "created", path: readmeDestination };
13942
14806
  } catch (error) {
13943
14807
  throw new Error(`Failed to write dotmem README at ${readmeDestination}: ${error instanceof Error ? error.message : String(error)}`);
@@ -14120,7 +14984,6 @@ async function loadCombinedKnowledgeState() {
14120
14984
  var EmptyLogicRepository, KNOWLEDGE_STATE_KEY, knowledgeSaveQueue, StoreKnowledgeRepository, RuntimeSlot, projectSlot, userSlot, installDotMemReadme;
14121
14985
  var init_knowledge_runtime = __esm({
14122
14986
  "core/memory/knowledge-runtime.ts"() {
14123
- init_suppress_idb_warning();
14124
14987
  init_knowledge();
14125
14988
  init_project_identity();
14126
14989
  init_user_paths();
@@ -14474,11 +15337,11 @@ function denoFs() {
14474
15337
  writeFile: writeFile8,
14475
15338
  rename,
14476
15339
  copyFile,
14477
- rm: /* @__PURE__ */ __name((path5, opts) => rm(path5, opts), "rm"),
15340
+ rm: /* @__PURE__ */ __name((path8, opts) => rm(path8, opts), "rm"),
14478
15341
  mkdir,
14479
- open: /* @__PURE__ */ __name(async (path5, flags) => {
15342
+ open: /* @__PURE__ */ __name(async (path8, flags) => {
14480
15343
  if (!Deno.open) throw new Error("Deno.open is unavailable");
14481
- const file = await Deno.open(path5, flags);
15344
+ const file = await Deno.open(path8, flags);
14482
15345
  return {
14483
15346
  writeFile: /* @__PURE__ */ __name(async (data) => {
14484
15347
  const written = await file.write(data);
@@ -14501,6 +15364,7 @@ var init_durable_store = __esm({
14501
15364
  "core/memory/durable-store.ts"() {
14502
15365
  init_storage_coordinator();
14503
15366
  init_store_queue();
15367
+ init_text_encoding();
14504
15368
  DurableStorageUnavailableError = class extends Error {
14505
15369
  static {
14506
15370
  __name(this, "DurableStorageUnavailableError");
@@ -14529,8 +15393,8 @@ var init_durable_store = __esm({
14529
15393
  }
14530
15394
  /** Load all entries from disk. Throws on unreadable/corrupt store. */
14531
15395
  async load() {
14532
- const fs7 = await resolveFs();
14533
- if (!fs7) {
15396
+ const fs9 = await resolveFs();
15397
+ if (!fs9) {
14534
15398
  throw new DurableStorageUnavailableError(
14535
15399
  "Durable memory storage is unavailable in this runtime: no filesystem backend could be resolved."
14536
15400
  );
@@ -14540,7 +15404,7 @@ var init_durable_store = __esm({
14540
15404
  async () => {
14541
15405
  let raw;
14542
15406
  try {
14543
- raw = await fs7.readFile(this.filePath);
15407
+ raw = await fs9.readFile(this.filePath);
14544
15408
  } catch (error) {
14545
15409
  const code = error?.code;
14546
15410
  if (code === "ENOENT") {
@@ -14555,11 +15419,11 @@ var init_durable_store = __esm({
14555
15419
  }
14556
15420
  let parsed;
14557
15421
  try {
14558
- parsed = JSON.parse(new TextDecoder().decode(raw));
15422
+ parsed = JSON.parse(decodeText(raw, { source: this.filePath }));
14559
15423
  } catch {
14560
15424
  try {
14561
- const bakRaw = await fs7.readFile(`${this.filePath}.bak`);
14562
- parsed = JSON.parse(new TextDecoder().decode(bakRaw));
15425
+ const bakRaw = await fs9.readFile(`${this.filePath}.bak`);
15426
+ parsed = JSON.parse(decodeText(bakRaw, { source: `${this.filePath}.bak` }));
14563
15427
  } catch {
14564
15428
  throw new DurableStorageUnavailableError(
14565
15429
  "Durable memory store is corrupt and no backup is available."
@@ -14632,8 +15496,8 @@ var init_durable_store = __esm({
14632
15496
  await this.load();
14633
15497
  }
14634
15498
  async persist(entries2, nextVersion) {
14635
- const fs7 = await resolveFs();
14636
- if (!fs7) {
15499
+ const fs9 = await resolveFs();
15500
+ if (!fs9) {
14637
15501
  throw new DurableStorageUnavailableError(
14638
15502
  "Durable memory storage is unavailable: no filesystem backend could be resolved."
14639
15503
  );
@@ -14642,10 +15506,10 @@ var init_durable_store = __esm({
14642
15506
  version: nextVersion,
14643
15507
  entries: [...entries2.values()]
14644
15508
  };
14645
- await fs7.mkdir(parentDir(this.filePath), { recursive: true });
15509
+ await fs9.mkdir(parentDir(this.filePath), { recursive: true });
14646
15510
  const temporary = `${this.filePath}.${pidSuffix()}.${uniqueSuffix2()}.tmp`;
14647
15511
  try {
14648
- const handle = await fs7.open(temporary, "wx");
15512
+ const handle = await fs9.open(temporary, "wx");
14649
15513
  try {
14650
15514
  const bytes = new TextEncoder().encode(JSON.stringify(state2, null, 2) + "\n");
14651
15515
  await handle.writeFile(bytes);
@@ -14653,26 +15517,26 @@ var init_durable_store = __esm({
14653
15517
  } finally {
14654
15518
  await handle.close();
14655
15519
  }
14656
- await fs7.readFile(temporary);
14657
- await this.keepLastValidVersion(fs7);
14658
- await fs7.rename(temporary, this.filePath);
15520
+ await fs9.readFile(temporary);
15521
+ await this.keepLastValidVersion(fs9);
15522
+ await fs9.rename(temporary, this.filePath);
14659
15523
  await this.syncDirectory(parentDir(this.filePath));
14660
15524
  } catch (error) {
14661
- await fs7.rm(temporary, { force: true }).catch(() => void 0);
15525
+ await fs9.rm(temporary, { force: true }).catch(() => void 0);
14662
15526
  throw error;
14663
15527
  }
14664
15528
  }
14665
- async keepLastValidVersion(fs7) {
15529
+ async keepLastValidVersion(fs9) {
14666
15530
  try {
14667
- await fs7.copyFile(this.filePath, `${this.filePath}.bak`);
15531
+ await fs9.copyFile(this.filePath, `${this.filePath}.bak`);
14668
15532
  } catch {
14669
15533
  }
14670
15534
  }
14671
15535
  async syncDirectory(directoryPath) {
14672
- const fs7 = await resolveFs();
14673
- if (!fs7) return;
15536
+ const fs9 = await resolveFs();
15537
+ if (!fs9) return;
14674
15538
  try {
14675
- const handle = await fs7.open(directoryPath, "r");
15539
+ const handle = await fs9.open(directoryPath, "r");
14676
15540
  try {
14677
15541
  await handle.sync();
14678
15542
  } finally {
@@ -14783,9 +15647,9 @@ function computeRelevance(entry) {
14783
15647
  };
14784
15648
  return recencyScore * confidenceScore * accessScore * typeBoost[entry.type] * scopeBoost[entry.scope];
14785
15649
  }
14786
- function getNestedPath(obj, path5) {
14787
- if (!path5 || typeof path5 !== "string") return void 0;
14788
- const parts = path5.replace(/^state\./, "").split(".");
15650
+ function getNestedPath(obj, path8) {
15651
+ if (!path8 || typeof path8 !== "string") return void 0;
15652
+ const parts = path8.replace(/^state\./, "").split(".");
14789
15653
  let current = obj;
14790
15654
  for (const part of parts) {
14791
15655
  if (current === null || current === void 0) return void 0;
@@ -14793,9 +15657,9 @@ function getNestedPath(obj, path5) {
14793
15657
  }
14794
15658
  return current;
14795
15659
  }
14796
- function setNestedPath(obj, path5, value) {
14797
- if (!path5 || typeof path5 !== "string") return;
14798
- const parts = path5.replace(/^state\./, "").split(".");
15660
+ function setNestedPath(obj, path8, value) {
15661
+ if (!path8 || typeof path8 !== "string") return;
15662
+ const parts = path8.replace(/^state\./, "").split(".");
14799
15663
  let current = obj;
14800
15664
  for (let i2 = 0; i2 < parts.length - 1; i2++) {
14801
15665
  const part = parts[i2];
@@ -14806,9 +15670,9 @@ function setNestedPath(obj, path5, value) {
14806
15670
  }
14807
15671
  current[parts[parts.length - 1]] = value;
14808
15672
  }
14809
- function deleteNestedPath(obj, path5) {
14810
- if (!path5 || typeof path5 !== "string") return;
14811
- const parts = path5.replace(/^state\./, "").split(".");
15673
+ function deleteNestedPath(obj, path8) {
15674
+ if (!path8 || typeof path8 !== "string") return;
15675
+ const parts = path8.replace(/^state\./, "").split(".");
14812
15676
  let current = obj;
14813
15677
  for (let i2 = 0; i2 < parts.length - 1; i2++) {
14814
15678
  const part = parts[i2];
@@ -14976,7 +15840,6 @@ async function getEntry(key) {
14976
15840
  var MEMORY_INDEX_KEY, SUPERSEDED_PREFIX, durableStoreInstance, entries;
14977
15841
  var init_entries = __esm({
14978
15842
  "core/memory/entries.ts"() {
14979
- init_suppress_idb_warning();
14980
15843
  init_env();
14981
15844
  init_journal();
14982
15845
  init_durable_store();
@@ -15311,13 +16174,13 @@ async function findClaimAcrossAllSources(claimId, scope, sourceProject) {
15311
16174
  const matches2 = [];
15312
16175
  const scanDirectory = /* @__PURE__ */ __name(async (dir) => {
15313
16176
  try {
15314
- const fs7 = await import('fs/promises');
15315
- const entries2 = await fs7.readdir(dir, { withFileTypes: true });
16177
+ const fs9 = await import('fs/promises');
16178
+ const entries2 = await fs9.readdir(dir, { withFileTypes: true });
15316
16179
  for (const e of entries2) {
15317
16180
  if (e.isFile() && e.name.endsWith(".mem") && e.name !== "@brain.mem") {
15318
16181
  const filePath = `${dir}/${e.name}`;
15319
16182
  try {
15320
- const bytes = await fs7.readFile(filePath);
16183
+ const bytes = await fs9.readFile(filePath);
15321
16184
  const artifact = await decodeMemArtifact(bytes);
15322
16185
  const state2 = artifact.state;
15323
16186
  if (!state2) continue;
@@ -15354,7 +16217,6 @@ async function findClaimAcrossAllSources(claimId, scope, sourceProject) {
15354
16217
  var acquire;
15355
16218
  var init_acquire = __esm({
15356
16219
  "core/memory/acquire.ts"() {
15357
- init_suppress_idb_warning();
15358
16220
  init_env();
15359
16221
  init_built_in_context();
15360
16222
  init_project_identity();
@@ -15475,15 +16337,15 @@ var init_profile2 = __esm({
15475
16337
 
15476
16338
  // core/knowledge/note-types.ts
15477
16339
  async function sha256HexOfText(text) {
15478
- const encoder3 = new TextEncoder();
15479
- const bytes = encoder3.encode(text);
16340
+ const encoder4 = new TextEncoder();
16341
+ const bytes = encoder4.encode(text);
15480
16342
  const hashArray = await crypto.subtle.digest("SHA-256", bytes);
15481
16343
  return Array.from(new Uint8Array(hashArray)).map((b) => b.toString(16).padStart(2, "0")).join("");
15482
16344
  }
15483
16345
  async function buildNoteKnowledge(title, content, origin, tag) {
15484
16346
  const sha2563 = await sha256HexOfText(content);
15485
- const encoder3 = new TextEncoder();
15486
- const size = encoder3.encode(content).byteLength;
16347
+ const encoder4 = new TextEncoder();
16348
+ const size = encoder4.encode(content).byteLength;
15487
16349
  return {
15488
16350
  title,
15489
16351
  content,
@@ -16025,11 +16887,11 @@ var init_handshake_session = __esm({
16025
16887
  SESSION_FILE_NAME2 = "handshake-session.json";
16026
16888
  resolveHandshakeSessionPath = /* @__PURE__ */ __name(() => joinStoragePath(joinStoragePath(resolveUserDotMemPath(), RUNTIME_NAMESPACE_DIR), SESSION_FILE_NAME2), "resolveHandshakeSessionPath");
16027
16889
  loadHandshakeSessionRecord = /* @__PURE__ */ __name(() => {
16028
- const fs7 = getSyncFs();
16029
- if (!fs7) return null;
16890
+ const fs9 = getSyncFs();
16891
+ if (!fs9) return null;
16030
16892
  let raw;
16031
16893
  try {
16032
- raw = fs7.readFileSync(resolveHandshakeSessionPath(), "utf8");
16894
+ raw = fs9.readFileSync(resolveHandshakeSessionPath(), "utf8");
16033
16895
  } catch {
16034
16896
  return null;
16035
16897
  }
@@ -16041,26 +16903,26 @@ var init_handshake_session = __esm({
16041
16903
  }
16042
16904
  }, "loadHandshakeSessionRecord");
16043
16905
  saveHandshakeSessionRecord = /* @__PURE__ */ __name(async (record) => {
16044
- const fs7 = getSyncFs();
16045
- if (!fs7) {
16906
+ const fs9 = getSyncFs();
16907
+ if (!fs9) {
16046
16908
  throw new Error("Persisting the handshake session record requires filesystem access, unavailable in this runtime");
16047
16909
  }
16048
16910
  const filePath = resolveHandshakeSessionPath();
16049
- await fs7.promises.mkdir(parentStoragePath(filePath), { recursive: true });
16911
+ await fs9.promises.mkdir(parentStoragePath(filePath), { recursive: true });
16050
16912
  const temporary = `${filePath}.${process.pid}.${Date.now().toString(36)}.tmp`;
16051
16913
  try {
16052
- await fs7.promises.writeFile(temporary, `${JSON.stringify(record, null, 2)}
16914
+ await fs9.promises.writeFile(temporary, `${JSON.stringify(record, null, 2)}
16053
16915
  `, "utf8");
16054
- await fs7.promises.rename(temporary, filePath);
16916
+ await fs9.promises.rename(temporary, filePath);
16055
16917
  } catch (error) {
16056
- await fs7.promises.rm(temporary, { force: true }).catch(() => void 0);
16918
+ await fs9.promises.rm(temporary, { force: true }).catch(() => void 0);
16057
16919
  throw error;
16058
16920
  }
16059
16921
  }, "saveHandshakeSessionRecord");
16060
16922
  clearHandshakeSessionRecord = /* @__PURE__ */ __name(async () => {
16061
- const fs7 = getSyncFs();
16062
- if (!fs7) return;
16063
- await fs7.promises.rm(resolveHandshakeSessionPath(), { force: true }).catch(() => void 0);
16923
+ const fs9 = getSyncFs();
16924
+ if (!fs9) return;
16925
+ await fs9.promises.rm(resolveHandshakeSessionPath(), { force: true }).catch(() => void 0);
16064
16926
  }, "clearHandshakeSessionRecord");
16065
16927
  computeCurrentRuntimeId = /* @__PURE__ */ __name(() => computeRuntimeId({
16066
16928
  platform: process.platform,
@@ -16961,7 +17823,6 @@ async function bootstrapProject() {
16961
17823
  var pendingDetectionEvents, detectionFlushScheduled, flushDetectionEvents, memory;
16962
17824
  var init_memory = __esm({
16963
17825
  "core/memory/index.ts"() {
16964
- init_suppress_idb_warning();
16965
17826
  init_journal();
16966
17827
  init_brain();
16967
17828
  init_knowledge_runtime();
@@ -17085,7 +17946,7 @@ var init_memory = __esm({
17085
17946
  resetPolicyStoreCache();
17086
17947
  },
17087
17948
  // ----- namespaced surfaces -----
17088
- /** Local operation journal (namespaced). No-op substrate when sqlite/idb unavailable. */
17949
+ /** Local operation journal (namespaced). Persisted on `store`. */
17089
17950
  journal: journal_default,
17090
17951
  /** Configure the optional cloud-sync layer (namespace + provider). Chainable. */
17091
17952
  configure(opts) {
@@ -17220,7 +18081,7 @@ function readStdin() {
17220
18081
  });
17221
18082
  }
17222
18083
  function parseContextArgs(args) {
17223
- const options = { explain: false, json: false, full: false, claimsOnly: false };
18084
+ const options = { explain: false, json: false, full: false, claimsOnly: false, manifest: false };
17224
18085
  const positional = [];
17225
18086
  let i2 = 0;
17226
18087
  while (i2 < args.length) {
@@ -17229,7 +18090,16 @@ function parseContextArgs(args) {
17229
18090
  else if (arg === "--json") options.json = true;
17230
18091
  else if (arg === "--full") options.full = true;
17231
18092
  else if (arg === "--claims-only") options.claimsOnly = true;
17232
- else if (arg === "--limit") {
18093
+ else if (arg === "--manifest") options.manifest = true;
18094
+ else if (arg === "--claim") {
18095
+ i2++;
18096
+ const value = args[i2];
18097
+ if (!value) {
18098
+ console.error("Missing value for --claim");
18099
+ process14.exit(1);
18100
+ }
18101
+ options.claimId = value;
18102
+ } else if (arg === "--limit") {
17233
18103
  const value = args[i2 + 1];
17234
18104
  if (value === void 0 || value.startsWith("--")) {
17235
18105
  console.error("Missing value for --limit");
@@ -17244,6 +18114,21 @@ function parseContextArgs(args) {
17244
18114
  }
17245
18115
  options.limit = parsed;
17246
18116
  i2++;
18117
+ } else if (arg === "--offset") {
18118
+ const value = args[i2 + 1];
18119
+ if (value === void 0 || value.startsWith("--")) {
18120
+ console.error("Missing value for --offset");
18121
+ process14.exitCode = 1;
18122
+ process14.exit(1);
18123
+ }
18124
+ const parsed = parseInt(value, 10);
18125
+ if (Number.isNaN(parsed) || parsed < 0) {
18126
+ console.error(`Invalid --offset value: ${value}. Must be a non-negative integer.`);
18127
+ process14.exitCode = 1;
18128
+ process14.exit(1);
18129
+ }
18130
+ options.offset = parsed;
18131
+ i2++;
17247
18132
  } else if (arg === "--format") {
17248
18133
  const value = args[i2 + 1];
17249
18134
  if (value === void 0 || value.startsWith("--")) {
@@ -17261,7 +18146,7 @@ function parseContextArgs(args) {
17261
18146
  i2++;
17262
18147
  } else if (arg.startsWith("--")) {
17263
18148
  console.error(`Unknown context option: ${arg}`);
17264
- console.error('Usage: npx dotmem context "<situation>" [--explain] [--json] [--full] [--claims-only] [--limit <N>] [--format brief]');
18149
+ console.error('Usage: npx dotmem context "<situation>" [--explain] [--json] [--full] [--claims-only] [--limit <N>] [--offset <N>] [--format brief] [--manifest] [--claim <id>]');
17265
18150
  process14.exit(1);
17266
18151
  } else positional.push(arg);
17267
18152
  i2++;
@@ -17876,7 +18761,6 @@ var init_policy3 = __esm({
17876
18761
  });
17877
18762
 
17878
18763
  // core/cli/index.ts
17879
- init_suppress_idb_warning();
17880
18764
  init_memory();
17881
18765
 
17882
18766
  // core/continuity/freshness.ts
@@ -18078,33 +18962,33 @@ var validateContinuityDocument = /* @__PURE__ */ __name((value) => {
18078
18962
  snapshots: document.snapshots
18079
18963
  };
18080
18964
  }, "validateContinuityDocument");
18081
- var deleteContinuityArtifact = /* @__PURE__ */ __name(async (path5) => {
18082
- const fs7 = getSyncFs();
18083
- if (!fs7) return;
18084
- await fs7.promises.rm(path5, { force: true });
18965
+ var deleteContinuityArtifact = /* @__PURE__ */ __name(async (path8) => {
18966
+ const fs9 = getSyncFs();
18967
+ if (!fs9) return;
18968
+ await fs9.promises.rm(path8, { force: true });
18085
18969
  }, "deleteContinuityArtifact");
18086
- var loadContinuityDocument = /* @__PURE__ */ __name(async (path5) => {
18087
- const fs7 = getSyncFs();
18088
- if (!fs7) return emptyContinuityDocument();
18970
+ var loadContinuityDocument = /* @__PURE__ */ __name(async (path8) => {
18971
+ const fs9 = getSyncFs();
18972
+ if (!fs9) return emptyContinuityDocument();
18089
18973
  try {
18090
- const raw = await fs7.promises.readFile(path5, "utf8");
18974
+ const raw = await fs9.promises.readFile(path8, "utf8");
18091
18975
  return validateContinuityDocument(JSON.parse(raw));
18092
18976
  } catch {
18093
18977
  return emptyContinuityDocument();
18094
18978
  }
18095
18979
  }, "loadContinuityDocument");
18096
- var saveContinuityDocument = /* @__PURE__ */ __name(async (path5, document) => {
18097
- const fs7 = getSyncFs();
18098
- if (!fs7) return;
18980
+ var saveContinuityDocument = /* @__PURE__ */ __name(async (path8, document) => {
18981
+ const fs9 = getSyncFs();
18982
+ if (!fs9) return;
18099
18983
  const validated = validateContinuityDocument(document);
18100
- await fs7.promises.mkdir(resolveUserContinuityDir(), { recursive: true });
18101
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
18984
+ await fs9.promises.mkdir(resolveUserContinuityDir(), { recursive: true });
18985
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
18102
18986
  try {
18103
- await fs7.promises.writeFile(temporary, `${JSON.stringify(validated, null, 2)}
18987
+ await fs9.promises.writeFile(temporary, `${JSON.stringify(validated, null, 2)}
18104
18988
  `, "utf8");
18105
- await fs7.promises.rename(temporary, path5);
18989
+ await fs9.promises.rename(temporary, path8);
18106
18990
  } catch (error) {
18107
- await fs7.promises.rm(temporary, { force: true }).catch(() => void 0);
18991
+ await fs9.promises.rm(temporary, { force: true }).catch(() => void 0);
18108
18992
  throw error;
18109
18993
  }
18110
18994
  }, "saveContinuityDocument");
@@ -18738,48 +19622,48 @@ var HardRulesRegistry = class {
18738
19622
  return resolveRegistryFilePath(this.directory);
18739
19623
  }
18740
19624
  async load() {
18741
- const fs7 = await import('fs/promises');
19625
+ const fs9 = await import('fs/promises');
18742
19626
  try {
18743
- const raw = await fs7.readFile(this.filePath(), "utf8");
19627
+ const raw = await fs9.readFile(this.filePath(), "utf8");
18744
19628
  return validateDocument4(JSON.parse(raw));
18745
19629
  } catch (err2) {
18746
19630
  if (err2.code === "ENOENT") return emptyDocument3();
18747
19631
  throw err2;
18748
19632
  }
18749
19633
  }
18750
- async readDoc(fs7) {
19634
+ async readDoc(fs9) {
18751
19635
  try {
18752
- const raw = await fs7.readFile(this.filePath(), "utf8");
19636
+ const raw = await fs9.readFile(this.filePath(), "utf8");
18753
19637
  return validateDocument4(JSON.parse(raw));
18754
19638
  } catch (err2) {
18755
19639
  if (err2.code === "ENOENT") return emptyDocument3();
18756
19640
  throw err2;
18757
19641
  }
18758
19642
  }
18759
- async writeDoc(fs7, doc) {
18760
- await fs7.mkdir(this.dir(), { recursive: true });
19643
+ async writeDoc(fs9, doc) {
19644
+ await fs9.mkdir(this.dir(), { recursive: true });
18761
19645
  const fp = this.filePath();
18762
19646
  const tmp = `${fp}.${process.pid}.${Date.now().toString(36)}.tmp`;
18763
19647
  try {
18764
- await fs7.writeFile(tmp, `${JSON.stringify(doc, null, 2)}
19648
+ await fs9.writeFile(tmp, `${JSON.stringify(doc, null, 2)}
18765
19649
  `, "utf8");
18766
- const handle = await fs7.open(tmp, "r+");
19650
+ const handle = await fs9.open(tmp, "r+");
18767
19651
  try {
18768
19652
  await handle.sync();
18769
19653
  } finally {
18770
19654
  await handle.close();
18771
19655
  }
18772
- await fs7.rename(tmp, fp);
19656
+ await fs9.rename(tmp, fp);
18773
19657
  } catch (err2) {
18774
- await fs7.rm(tmp, { force: true }).catch(() => void 0);
19658
+ await fs9.rm(tmp, { force: true }).catch(() => void 0);
18775
19659
  throw err2;
18776
19660
  }
18777
19661
  }
18778
19662
  async mutate(operation, options = {}) {
18779
19663
  const directory = this.dir();
18780
19664
  return withPolicyNamespaceLock(async (session2) => {
18781
- const fs7 = await import('fs/promises');
18782
- const doc = await this.readDoc(fs7);
19665
+ const fs9 = await import('fs/promises');
19666
+ const doc = await this.readDoc(fs9);
18783
19667
  if (options.basedOnRevision !== void 0 && options.basedOnRevision !== doc.revision) {
18784
19668
  throw new HardRulesRegistryError(`Stale hard-rules revision: expected ${options.basedOnRevision}, current ${doc.revision}`);
18785
19669
  }
@@ -18787,7 +19671,7 @@ var HardRulesRegistry = class {
18787
19671
  let next = outcome.document;
18788
19672
  validateDocument4(next);
18789
19673
  await session2.assertOwnership();
18790
- await this.writeDoc(fs7, next);
19674
+ await this.writeDoc(fs9, next);
18791
19675
  return outcome.result;
18792
19676
  }, { directory });
18793
19677
  }
@@ -18947,15 +19831,15 @@ var HardRulesRegistry = class {
18947
19831
  // core/functions/bootstrap.ts
18948
19832
  async function checkProjectState(_cwd) {
18949
19833
  const userDotMemDir = resolveUserDotMemPath();
18950
- const userLogicMemPath = path2.join(userDotMemDir, "logic.mem");
19834
+ const userLogicMemPath = path3.join(userDotMemDir, "logic.mem");
18951
19835
  let logicMemValid = false;
18952
- if (fs2.existsSync(userLogicMemPath)) {
19836
+ if (fs3.existsSync(userLogicMemPath)) {
18953
19837
  logicMemValid = true;
18954
19838
  }
18955
19839
  const projectId = await resolveProjectIdentity(process.cwd());
18956
19840
  const projectAnchorPath = resolveUserProjectMemoryPath(projectId);
18957
- const projectAnchorPresent = fs2.existsSync(projectAnchorPath);
18958
- const initialized = fs2.existsSync(userDotMemDir) && logicMemValid && projectAnchorPresent;
19841
+ const projectAnchorPresent = fs3.existsSync(projectAnchorPath);
19842
+ const initialized = fs3.existsSync(userDotMemDir) && logicMemValid && projectAnchorPresent;
18959
19843
  return {
18960
19844
  initialized,
18961
19845
  dotmemDir: userDotMemDir,
@@ -18969,8 +19853,8 @@ async function checkProjectState(_cwd) {
18969
19853
  __name(checkProjectState, "checkProjectState");
18970
19854
  async function getMemoryReadiness(_cwd) {
18971
19855
  const userDotMemDir = resolveUserDotMemPath();
18972
- const userProjectsDir = path2.join(userDotMemDir, "projects");
18973
- if (!fs2.existsSync(userProjectsDir)) {
19856
+ const userProjectsDir = path3.join(userDotMemDir, "projects");
19857
+ if (!fs3.existsSync(userProjectsDir)) {
18974
19858
  return { ready: false, totalSources: 0, totalClaims: 0, sources: [] };
18975
19859
  }
18976
19860
  try {
@@ -19018,12 +19902,12 @@ async function detectAiEnvironment() {
19018
19902
  }
19019
19903
  if (process.platform !== "win32") {
19020
19904
  try {
19021
- const status = fs2.readFileSync("/proc/self/status", "utf8");
19905
+ const status = fs3.readFileSync("/proc/self/status", "utf8");
19022
19906
  const ppidMatch = status.match(/^PPid:\s*(\d+)$/m);
19023
19907
  if (ppidMatch) {
19024
19908
  const ppid = parseInt(ppidMatch[1], 10);
19025
19909
  try {
19026
- const comm = fs2.readFileSync(`/proc/${ppid}/comm`, "utf8").trim();
19910
+ const comm = fs3.readFileSync(`/proc/${ppid}/comm`, "utf8").trim();
19027
19911
  const knownAiParents = ["codex", "kilo", "claude", "aider", "continue", "cursor"];
19028
19912
  const matchedParent = knownAiParents.find((ai) => comm.toLowerCase().includes(ai));
19029
19913
  if (matchedParent) {
@@ -19052,33 +19936,33 @@ async function detectAiEnvironment() {
19052
19936
  __name(detectAiEnvironment, "detectAiEnvironment");
19053
19937
  async function ensureUserDotMemInitialized() {
19054
19938
  const userDotMemDir = resolveUserDotMemPath();
19055
- const userProjectsDir = path2.join(userDotMemDir, "projects");
19056
- const userLogicMemPath = path2.join(userDotMemDir, "logic.mem");
19939
+ const userProjectsDir = path3.join(userDotMemDir, "projects");
19940
+ const userLogicMemPath = path3.join(userDotMemDir, "logic.mem");
19057
19941
  const userContractPath = resolveUserContractPath();
19058
19942
  const userBrainPath = resolveUserBrainPath();
19059
19943
  try {
19060
- fs2.mkdirSync(userDotMemDir, { recursive: true });
19061
- fs2.mkdirSync(userProjectsDir, { recursive: true });
19944
+ fs3.mkdirSync(userDotMemDir, { recursive: true });
19945
+ fs3.mkdirSync(userProjectsDir, { recursive: true });
19062
19946
  } catch {
19063
19947
  }
19064
- if (!fs2.existsSync(userLogicMemPath)) {
19948
+ if (!fs3.existsSync(userLogicMemPath)) {
19065
19949
  const seedBytes = await encodeLogicSeed();
19066
- fs2.writeFileSync(userLogicMemPath, seedBytes);
19950
+ fs3.writeFileSync(userLogicMemPath, seedBytes);
19067
19951
  }
19068
- if (!fs2.existsSync(userContractPath)) {
19952
+ if (!fs3.existsSync(userContractPath)) {
19069
19953
  await ensureDotMemReadme();
19070
19954
  }
19071
- if (!fs2.existsSync(userBrainPath)) {
19955
+ if (!fs3.existsSync(userBrainPath)) {
19072
19956
  const emptyBrainDoc = {
19073
19957
  format: "dotmem.brain",
19074
19958
  version: 1,
19075
19959
  relationships: []
19076
19960
  };
19077
- fs2.writeFileSync(userBrainPath, JSON.stringify(emptyBrainDoc, null, 2));
19961
+ fs3.writeFileSync(userBrainPath, JSON.stringify(emptyBrainDoc, null, 2));
19078
19962
  }
19079
- const userLanguagePath = path2.join(userDotMemDir, "language.json");
19080
- if (!fs2.existsSync(userLanguagePath)) {
19081
- fs2.writeFileSync(userLanguagePath, JSON.stringify({ format: "dotmem.language", version: 1, language: "it-IT" }, null, 2));
19963
+ const userLanguagePath = path3.join(userDotMemDir, "language.json");
19964
+ if (!fs3.existsSync(userLanguagePath)) {
19965
+ fs3.writeFileSync(userLanguagePath, JSON.stringify({ format: "dotmem.language", version: 1, language: "it-IT" }, null, 2));
19082
19966
  }
19083
19967
  }
19084
19968
  __name(ensureUserDotMemInitialized, "ensureUserDotMemInitialized");
@@ -19487,7 +20371,8 @@ async function runContext(situation, _cwd, options = {}) {
19487
20371
  await getBrainDocument();
19488
20372
  const discovery = discoverAcquiredExperience(combined, situation, {
19489
20373
  currentProjectId: await resolveProjectIdentity(process.cwd()),
19490
- ...options.limit !== void 0 ? { maxCandidates: options.limit } : {}
20374
+ ...options.limit !== void 0 ? { maxCandidates: options.limit } : {},
20375
+ ...options.offset !== void 0 ? { cursor: { knowledgeVersion: combined.version, offset: options.offset } } : {}
19491
20376
  }, sources);
19492
20377
  if (options.explain) {
19493
20378
  const report = explainDiscovery(combined, discovery, situation);
@@ -19616,6 +20501,20 @@ async function runContext(situation, _cwd, options = {}) {
19616
20501
  claims: projection
19617
20502
  }, null, 2);
19618
20503
  }
20504
+ if (options.manifest) {
20505
+ return JSON.stringify({
20506
+ knowledgeVersion: projection.knowledgeVersion,
20507
+ totalCandidates: projection.totalCandidates,
20508
+ included: projection.experiences.length,
20509
+ omittedCandidates: projection.omittedCandidates,
20510
+ manifest: projection.manifest ?? {
20511
+ considered: projection.totalCandidates,
20512
+ included: projection.experiences.length,
20513
+ items: [],
20514
+ byReason: []
20515
+ }
20516
+ }, null, 2);
20517
+ }
19619
20518
  if (options.format === "brief") {
19620
20519
  const header = options.claimsOnly ? renderBriefClaimsHeader() : `${identityChannel.text}
19621
20520
  ${profileText}
@@ -19646,9 +20545,10 @@ ${projection.text}`;
19646
20545
  const sizeText = renderSizeDisclosure({
19647
20546
  totalCandidates: projection.totalCandidates,
19648
20547
  omittedCandidates: projection.omittedCandidates,
19649
- projectedBytes: projectedBody.length,
19650
- maxCharacters: options.full ? Infinity : DOTMEM_CONTEXT_DEFAULT_MAX_CHARACTERS,
19651
- hostCeilingBytes: DOTMEM_HOST_TRUNCATION_CEILING_BYTES
20548
+ projectedBytes: new TextEncoder().encode(projectedBody).length,
20549
+ maxCharacters: options.full ? Number.MAX_SAFE_INTEGER : DOTMEM_CONTEXT_DEFAULT_MAX_CHARACTERS,
20550
+ hostCeilingBytes: DOTMEM_HOST_TRUNCATION_CEILING_BYTES,
20551
+ manifest: projection.manifest
19652
20552
  });
19653
20553
  return `${identityChannel.text}
19654
20554
  ${profileText}
@@ -19746,6 +20646,8 @@ __name(topLevelUsage, "topLevelUsage");
19746
20646
 
19747
20647
  // core/cli/commands/context.ts
19748
20648
  init_memory();
20649
+ init_memory();
20650
+ init_project();
19749
20651
 
19750
20652
  // core/functions/profile-request.ts
19751
20653
  init_profile();
@@ -19808,6 +20710,17 @@ async function runContextCli(situation, options = {}) {
19808
20710
  console.info(gate.text);
19809
20711
  return;
19810
20712
  }
20713
+ if (options.claimId) {
20714
+ const state2 = await loadCombinedKnowledgeState();
20715
+ const claim = state2.claims.find((candidate) => candidate.id === options.claimId);
20716
+ if (!claim) {
20717
+ console.error(`No claim with id ${options.claimId} is present in the loaded stores.`);
20718
+ process.exitCode = 1;
20719
+ return;
20720
+ }
20721
+ console.info(renderExpandedClaim(claim));
20722
+ return;
20723
+ }
19811
20724
  const text = await runContext(situation ?? "", void 0, {
19812
20725
  ...options,
19813
20726
  handshake: gate.record ?? void 0,
@@ -20045,17 +20958,38 @@ __name(runStorageCli, "runStorageCli");
20045
20958
 
20046
20959
  // core/cli/commands/inspect.ts
20047
20960
  init_mem_package();
20048
- function runInspectCli(file) {
20961
+ init_inspect_report();
20962
+ var redactDefault = true;
20963
+ function runInspectCli(file, args) {
20049
20964
  if (!file) {
20050
- console.error("Usage: npx dotmem inspect FILE.mem");
20965
+ console.error("Usage: npx dotmem inspect FILE.mem [--format md|json] [--redact|--no-redact] [--limit N] [--offset N] [--claims]");
20051
20966
  process.exitCode = 1;
20052
20967
  return;
20053
20968
  }
20969
+ const format = args.includes("--format=json") || args.includes("--format json") ? "json" : "md";
20970
+ const redactArg = args.find((a) => a === "--no-redact" || a === "--redact");
20971
+ const redact = redactArg === "--no-redact" ? false : redactDefault;
20972
+ const limitIndex = args.findIndex((a) => a === "--limit");
20973
+ const limit = limitIndex >= 0 ? Number(args[limitIndex + 1]) : 50;
20974
+ const includeClaims = args.includes("--claims");
20054
20975
  void (async () => {
20055
20976
  try {
20056
- const bytes = await fs2.promises.readFile(path2.resolve(file));
20977
+ const bytes = await fs3.promises.readFile(path3.resolve(file));
20057
20978
  const result = await inspectMem(bytes);
20058
- console.info(JSON.stringify(result, null, 2));
20979
+ const report = renderInspectReport(result, {
20980
+ redact,
20981
+ includeKnowledge: includeClaims,
20982
+ limit: Number.isFinite(limit) && limit > 0 ? limit : 50
20983
+ });
20984
+ if (format === "json") {
20985
+ console.info(JSON.stringify(report.json, null, 2));
20986
+ } else {
20987
+ console.info(report.markdown);
20988
+ if (redact) {
20989
+ console.info("");
20990
+ console.info("Note: secret-shaped values are redacted. Use --no-redact for full local inspection.");
20991
+ }
20992
+ }
20059
20993
  if (result.status !== "valid") process.exitCode = 2;
20060
20994
  } catch (error) {
20061
20995
  console.error(`Unable to inspect ${file}: ${error instanceof Error ? error.message : String(error)}`);
@@ -20121,6 +21055,148 @@ async function runContinuityCli(args) {
20121
21055
  }
20122
21056
  }
20123
21057
  __name(runContinuityCli, "runContinuityCli");
21058
+
21059
+ // core/cli/commands/dump.ts
21060
+ init_read_only();
21061
+ init_inspect_report();
21062
+ async function runDumpCli(args) {
21063
+ const target = args[0];
21064
+ const format = args.includes("--format=json") || args.includes("--format json") ? "json" : "ndjson";
21065
+ const redactArg = args.find((a) => a === "--no-redact" || a === "--redact");
21066
+ const redact = redactArg === "--no-redact" ? false : true;
21067
+ const sinceIndex = args.findIndex((a) => a === "--since");
21068
+ const since = sinceIndex >= 0 ? Number(args[sinceIndex + 1]) : void 0;
21069
+ const root = target ? path3.resolve(target) : void 0;
21070
+ const listing = await listStore(root);
21071
+ const entries2 = listing.packages.filter((pkg) => since === void 0 || (pkg.inspection.memoryVersion ?? 0) >= since).map((pkg) => renderInspectReport(pkg.inspection, { redact, includeKnowledge: false, limit: 20 }));
21072
+ if (format === "json") {
21073
+ console.info(JSON.stringify({
21074
+ root: listing.root,
21075
+ redacted: redact,
21076
+ count: entries2.length,
21077
+ packages: entries2.map((e) => e.json)
21078
+ }, null, 2));
21079
+ return;
21080
+ }
21081
+ for (const entry of entries2) {
21082
+ const report = entry.json;
21083
+ console.info(`=== ${report.status === "valid" ? "" : "[corrupt] "}${report.packageVersion ? "package-v1" : report.representation}`);
21084
+ console.info(entry.markdown);
21085
+ }
21086
+ }
21087
+ __name(runDumpCli, "runDumpCli");
21088
+
21089
+ // core/cli/commands/diff.ts
21090
+ init_mem_package();
21091
+ var extractClaims = /* @__PURE__ */ __name((inspection) => {
21092
+ if (inspection.status !== "valid" || !inspection.knowledge) return [];
21093
+ const state2 = inspection.knowledge;
21094
+ if (!Array.isArray(state2.claims)) return [];
21095
+ return state2.claims.map((claim) => {
21096
+ const c = claim;
21097
+ return { id: String(c.id ?? ""), knowledge: c.knowledge, epistemicType: c.epistemicType };
21098
+ }).filter((c) => c.id.length > 0);
21099
+ }, "extractClaims");
21100
+ var knowledgeEqual = /* @__PURE__ */ __name((left, right) => JSON.stringify(stableValue2(left)) === JSON.stringify(stableValue2(right)), "knowledgeEqual");
21101
+ var stableValue2 = /* @__PURE__ */ __name((value) => {
21102
+ if (Array.isArray(value)) return value.map(stableValue2);
21103
+ if (value && typeof value === "object") {
21104
+ return Object.fromEntries(
21105
+ Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => [k, stableValue2(v)])
21106
+ );
21107
+ }
21108
+ return value;
21109
+ }, "stableValue");
21110
+ async function runDiffCli(args) {
21111
+ const [fileA, fileB] = args;
21112
+ if (!fileA || !fileB) {
21113
+ console.error("Usage: npx dotmem diff FILE_A.mem FILE_B.mem");
21114
+ process.exitCode = 1;
21115
+ return;
21116
+ }
21117
+ let inspectionA;
21118
+ let inspectionB;
21119
+ try {
21120
+ inspectionA = await inspectMem(await fs.readFile(path3.resolve(fileA)));
21121
+ } catch (error) {
21122
+ console.error(`Unable to read ${fileA}: ${error instanceof Error ? error.message : String(error)}`);
21123
+ process.exitCode = 1;
21124
+ return;
21125
+ }
21126
+ try {
21127
+ inspectionB = await inspectMem(await fs.readFile(path3.resolve(fileB)));
21128
+ } catch (error) {
21129
+ console.error(`Unable to read ${fileB}: ${error instanceof Error ? error.message : String(error)}`);
21130
+ process.exitCode = 1;
21131
+ return;
21132
+ }
21133
+ if (inspectionA.status !== "valid") {
21134
+ console.error(`Invalid input ${fileA}: ${inspectionA.status}`);
21135
+ process.exitCode = 1;
21136
+ return;
21137
+ }
21138
+ if (inspectionB.status !== "valid") {
21139
+ console.error(`Invalid input ${fileB}: ${inspectionB.status}`);
21140
+ process.exitCode = 1;
21141
+ return;
21142
+ }
21143
+ const claimsA = extractClaims(inspectionA);
21144
+ const claimsB = extractClaims(inspectionB);
21145
+ const mapA = new Map(claimsA.map((c) => [c.id, c]));
21146
+ const mapB = new Map(claimsB.map((c) => [c.id, c]));
21147
+ const added = [];
21148
+ const removed = [];
21149
+ const changed = [];
21150
+ for (const id of [...mapA.keys()].sort()) {
21151
+ if (!mapB.has(id)) removed.push(mapA.get(id));
21152
+ }
21153
+ for (const id of [...mapB.keys()].sort()) {
21154
+ if (!mapA.has(id)) added.push(mapB.get(id));
21155
+ else {
21156
+ const before = mapA.get(id);
21157
+ const after = mapB.get(id);
21158
+ if (!knowledgeEqual(before.knowledge, after.knowledge) || before.epistemicType !== after.epistemicType) {
21159
+ changed.push({ id, before, after });
21160
+ }
21161
+ }
21162
+ }
21163
+ const report = {
21164
+ fileA: path3.resolve(fileA),
21165
+ fileB: path3.resolve(fileB),
21166
+ countA: claimsA.length,
21167
+ countB: claimsB.length,
21168
+ added: added.map((c) => c.id),
21169
+ removed: removed.map((c) => c.id),
21170
+ changed: changed.map((c) => c.id),
21171
+ addedClaims: added,
21172
+ removedClaims: removed,
21173
+ changedClaims: changed,
21174
+ identical: added.length === 0 && removed.length === 0 && changed.length === 0
21175
+ };
21176
+ console.info(JSON.stringify(report, null, 2));
21177
+ }
21178
+ __name(runDiffCli, "runDiffCli");
21179
+
21180
+ // core/cli/commands/bootstrap.ts
21181
+ init_bootstrap();
21182
+ async function runBootstrapCli(args) {
21183
+ const sinceIndex = args.findIndex((a) => a === "--since");
21184
+ const since = sinceIndex >= 0 ? Number(args[sinceIndex + 1]) : void 0;
21185
+ const situationIndex = args.findIndex((a) => a === "--situation");
21186
+ const situation = situationIndex >= 0 ? args[situationIndex + 1] : void 0;
21187
+ try {
21188
+ const response = await composeBootstrap({
21189
+ sinceVersion: since,
21190
+ situation
21191
+ });
21192
+ console.info(response.text);
21193
+ if (response.unchanged) process.exitCode = 0;
21194
+ } catch (error) {
21195
+ console.error(`Bootstrap failed: ${error instanceof Error ? error.message : String(error)}`);
21196
+ process.exitCode = 1;
21197
+ }
21198
+ }
21199
+ __name(runBootstrapCli, "runBootstrapCli");
20124
21200
  async function runHandshakeCli(args) {
20125
21201
  const reset = args.includes("--reset");
20126
21202
  const status = args.includes("--status");
@@ -20367,8 +21443,8 @@ async function runRenderCli(args) {
20367
21443
  return;
20368
21444
  }
20369
21445
  if (outFile) {
20370
- const fs7 = await import('fs/promises');
20371
- await fs7.writeFile(outFile, result.markdown, "utf8");
21446
+ const fs9 = await import('fs/promises');
21447
+ await fs9.writeFile(outFile, result.markdown, "utf8");
20372
21448
  console.info(`Rendered ${view} view to ${outFile}: ${result.claimsWritten} claims`);
20373
21449
  } else {
20374
21450
  console.info(result.markdown);
@@ -20406,8 +21482,8 @@ async function runNoteCli(args) {
20406
21482
  content = await readStdin();
20407
21483
  origin = "stdin";
20408
21484
  } else {
20409
- const fs7 = await import('fs/promises');
20410
- content = await fs7.readFile(fileArg, "utf8");
21485
+ const fs9 = await import('fs/promises');
21486
+ content = await fs9.readFile(fileArg, "utf8");
20411
21487
  origin = fileArg.split(/[\\/]/).pop() ?? fileArg;
20412
21488
  }
20413
21489
  const titleIndex = args.indexOf("--title");
@@ -20491,8 +21567,8 @@ async function runNoteCli(args) {
20491
21567
  process14.exitCode = 1;
20492
21568
  return;
20493
21569
  }
20494
- const fs7 = await import('fs/promises');
20495
- await fs7.writeFile(outFile, content, "utf8");
21570
+ const fs9 = await import('fs/promises');
21571
+ await fs9.writeFile(outFile, content, "utf8");
20496
21572
  console.info(`Exported note ${id} to ${outFile}`);
20497
21573
  break;
20498
21574
  }
@@ -20589,9 +21665,9 @@ async function runSeedCli(args) {
20589
21665
  content = await readStdin();
20590
21666
  origin = "stdin";
20591
21667
  } else {
20592
- const fs7 = await import('fs/promises');
21668
+ const fs9 = await import('fs/promises');
20593
21669
  try {
20594
- content = await fs7.readFile(input, "utf8");
21670
+ content = await fs9.readFile(input, "utf8");
20595
21671
  } catch (error) {
20596
21672
  console.error(`Unable to read seed file: ${error instanceof Error ? error.message : String(error)}`);
20597
21673
  process14.exitCode = 1;
@@ -20720,12 +21796,34 @@ __name(runVaultCli, "runVaultCli");
20720
21796
 
20721
21797
  // core/cli/commands/verify.ts
20722
21798
  init_memory();
21799
+ init_memory();
20723
21800
  init_verify();
20724
21801
  async function runVerifyCli(args) {
20725
21802
  const json = args.includes("--json");
21803
+ const persist = args.includes("--persist");
20726
21804
  try {
20727
21805
  const state2 = await loadCombinedKnowledgeState();
20728
21806
  const result = await verifyDueClaims(state2);
21807
+ if (persist) {
21808
+ const { repository } = await getUserKnowledgeRuntime();
21809
+ const current = await repository.load();
21810
+ const { result: persistedResult, persisted } = await verifyAndPersistClaims(
21811
+ current,
21812
+ (next, expectedVersion) => repository.save(next, expectedVersion)
21813
+ );
21814
+ if (json) {
21815
+ console.info(JSON.stringify({ ...persistedResult, persisted }, null, 2));
21816
+ } else {
21817
+ console.info(formatVerifyResult(persistedResult));
21818
+ if (persisted.length > 0) {
21819
+ console.info(`Persisted verification metadata for: ${persisted.join(", ")}`);
21820
+ }
21821
+ }
21822
+ if (persistedResult.stale > 0) {
21823
+ process.exitCode = 2;
21824
+ }
21825
+ return;
21826
+ }
20729
21827
  if (json) {
20730
21828
  console.info(JSON.stringify(result, null, 2));
20731
21829
  return;
@@ -20819,6 +21917,7 @@ init_memory();
20819
21917
  init_rules_loader();
20820
21918
  async function runRulesCli(args) {
20821
21919
  const json = args.includes("--json");
21920
+ const expand = args.includes("--expand");
20822
21921
  try {
20823
21922
  const state2 = await loadCombinedKnowledgeState();
20824
21923
  const report = loadIronRules(state2);
@@ -20830,7 +21929,7 @@ async function runRulesCli(args) {
20830
21929
  console.info("No iron rules found.");
20831
21930
  return;
20832
21931
  }
20833
- console.info(formatRulesForSessionStart(report.rules));
21932
+ console.info(expand ? formatRulesForSessionStart(report.rules) : formatRulesReference(report.rules));
20834
21933
  } catch (error) {
20835
21934
  console.error(`Rules loading failed: ${error instanceof Error ? error.message : String(error)}`);
20836
21935
  process.exitCode = 1;
@@ -20929,7 +22028,7 @@ var collectStores = /* @__PURE__ */ __name(async () => {
20929
22028
  const files = [];
20930
22029
  for (const dir of sourceDirs) {
20931
22030
  try {
20932
- const entries2 = await fs4.readdir(dir, { withFileTypes: true });
22031
+ const entries2 = await fs.readdir(dir, { withFileTypes: true });
20933
22032
  for (const e of entries2) {
20934
22033
  if (e.isFile() && e.name.endsWith(".mem") && e.name !== "@brain.mem") {
20935
22034
  files.push({ sourceId: e.name, filePath: `${dir}/${e.name}` });
@@ -20941,7 +22040,7 @@ var collectStores = /* @__PURE__ */ __name(async () => {
20941
22040
  const stores = [];
20942
22041
  for (const { sourceId, filePath } of files) {
20943
22042
  try {
20944
- const bytes = await fs4.readFile(filePath);
22043
+ const bytes = await fs.readFile(filePath);
20945
22044
  const artifact = await decodeMemArtifact(bytes);
20946
22045
  stores.push({ sourceId, filePath, state: artifact.state, artifact });
20947
22046
  } catch (error) {
@@ -21164,7 +22263,7 @@ async function runDoctorCli(args) {
21164
22263
  }
21165
22264
  const filePath = store5.filePath;
21166
22265
  const expectedVersion = store5.state.version;
21167
- await withStorageLock(path2.dirname(filePath), async () => {
22266
+ await withStorageLock(path3.dirname(filePath), async () => {
21168
22267
  const fsMod = await import('fs/promises');
21169
22268
  let currentBytes;
21170
22269
  try {
@@ -21185,7 +22284,7 @@ async function runDoctorCli(args) {
21185
22284
  }
21186
22285
  const tmp = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
21187
22286
  try {
21188
- await fsMod.mkdir(path2.dirname(filePath), { recursive: true });
22287
+ await fsMod.mkdir(path3.dirname(filePath), { recursive: true });
21189
22288
  const encoded = await encodeMemPackage(newState, currentArtifact.preserved, currentArtifact.package);
21190
22289
  await fsMod.writeFile(tmp, encoded);
21191
22290
  await decodeMemArtifact(await fsMod.readFile(tmp));
@@ -21299,7 +22398,7 @@ Verify the AGENTS.md scintilla block matches SCINTILLA_SIGNAL_HASH.
21299
22398
  const agentsMd = fileIdx !== -1 && args[fileIdx + 1] !== void 0 ? args[fileIdx + 1] : "AGENTS.md";
21300
22399
  let content;
21301
22400
  try {
21302
- content = fs2.readFileSync(agentsMd, "utf8");
22401
+ content = fs3.readFileSync(agentsMd, "utf8");
21303
22402
  } catch {
21304
22403
  console.info(`scintilla block not found: ${agentsMd} does not exist (nothing to verify)`);
21305
22404
  return;
@@ -21386,7 +22485,7 @@ function dispatch4(command, args) {
21386
22485
  return;
21387
22486
  }
21388
22487
  if (command === "--version" || command === "-v") {
21389
- const pkg = JSON.parse(fs2.readFileSync(new URL("package.json", import.meta.url), "utf8"));
22488
+ const pkg = JSON.parse(fs3.readFileSync(new URL("package.json", import.meta.url), "utf8"));
21390
22489
  console.info(pkg.version);
21391
22490
  process14.exit(0);
21392
22491
  return;
@@ -21501,11 +22600,66 @@ Report or relocate the canonical dotmem storage location.
21501
22600
  }
21502
22601
  if (command === "inspect") {
21503
22602
  if (args[0] === "--help" || args[0] === "-h") {
21504
- console.info("Usage: npx dotmem inspect FILE.mem");
22603
+ console.info(`Usage: npx dotmem inspect FILE.mem [--format md|json] [--redact|--no-redact] [--limit N] [--offset N] [--claims]
22604
+
22605
+ Read-only inspection of a .mem package. Secret-shaped values are redacted by default.
22606
+
22607
+ FILE.mem the package to inspect
22608
+ --format md human-readable Markdown report (default)
22609
+ --format json structured JSON report
22610
+ --redact redact secret-shaped values (default)
22611
+ --no-redact disable redaction (local CLI inspection only)
22612
+ --limit N max claims to list (default 50)
22613
+ --offset N claims offset
22614
+ --claims include claim summaries in the report`);
22615
+ process14.exit(0);
22616
+ return;
22617
+ }
22618
+ void runInspectCli(args[0], args.slice(1));
22619
+ return;
22620
+ }
22621
+ if (command === "dump") {
22622
+ if (args[0] === "--help" || args[0] === "-h") {
22623
+ console.info(`Usage: npx dotmem dump [root|file] [--format json|ndjson] [--redact|--no-redact] [--since <version>]
22624
+
22625
+ Bounded, deterministic, read-only store-wide dump. Redacted by default.
22626
+
22627
+ (no target) dump the default storage root
22628
+ root|file dump a specific directory or package
22629
+ --format ndjson newline-delimited JSON (default)
22630
+ --format json single JSON document
22631
+ --redact redact secret-shaped values (default)
22632
+ --no-redact disable redaction (local CLI inspection only)
22633
+ --since <v> only packages at or above memory version`);
22634
+ process14.exit(0);
22635
+ return;
22636
+ }
22637
+ void runDumpCli(args);
22638
+ return;
22639
+ }
22640
+ if (command === "diff") {
22641
+ if (args[0] === "--help" || args[0] === "-h") {
22642
+ console.info(`Usage: npx dotmem diff FILE_A.mem FILE_B.mem
22643
+
22644
+ Deterministic, read-only diff between two MEM packages. Reports added,
22645
+ removed, and changed claims. Never mutates anything.`);
22646
+ process14.exit(0);
22647
+ return;
22648
+ }
22649
+ void runDiffCli(args);
22650
+ return;
22651
+ }
22652
+ if (command === "bootstrap") {
22653
+ if (args[0] === "--help" || args[0] === "-h") {
22654
+ console.info(`Usage: npx dotmem bootstrap [--since <version>] [--situation "<text>"]
22655
+
22656
+ Unified bootstrap: one call returns the initial context plus the rules
22657
+ reference. Pass --since to receive a small deterministic UNCHANGED response
22658
+ when the store has not changed since that version. Read-only; never mutates anything.`);
21505
22659
  process14.exit(0);
21506
22660
  return;
21507
22661
  }
21508
- void runInspectCli(args[0]);
22662
+ void runBootstrapCli(args);
21509
22663
  return;
21510
22664
  }
21511
22665
  if (command === "continuity") {
@@ -21652,9 +22806,12 @@ Record operator feedback about how an acquired claim performed.
21652
22806
  }
21653
22807
  if (command === "rules") {
21654
22808
  if (args[0] === "--help" || args[0] === "-h") {
21655
- console.info(`Usage: npx dotmem rules [--json]
22809
+ console.info(`Usage: npx dotmem rules [--json] [--expand]
22810
+
22811
+ Print iron rules (human-stated, kind: 'rule') sorted by violation frequency.
21656
22812
 
21657
- Print iron rules (human-stated, kind: 'rule') sorted by violation frequency.`);
22813
+ --json output structured report (count, signature, ids, rules)
22814
+ --expand print full rule bodies instead of the compact reference`);
21658
22815
  process14.exit(0);
21659
22816
  return;
21660
22817
  }