dotmem 0.1.8 → 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, { readFileSync } 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;
@@ -381,13 +381,13 @@ var init_storage_settings = __esm({
381
381
  return normalized || normalizeStoragePath(cwd);
382
382
  }, "projectRoot");
383
383
  findProjectSettingsFile = /* @__PURE__ */ __name((cwd) => {
384
- const fs7 = getSyncFs();
385
- if (!fs7) return null;
384
+ const fs9 = getSyncFs();
385
+ if (!fs9) return null;
386
386
  let current = projectRoot(cwd);
387
387
  for (; ; ) {
388
388
  const candidate = joinStoragePath(current, DOTMEM_STORAGE_SETTINGS_FILE_NAME);
389
389
  try {
390
- if (fs7.existsSync(candidate)) return candidate;
390
+ if (fs9.existsSync(candidate)) return candidate;
391
391
  } catch {
392
392
  return null;
393
393
  }
@@ -462,10 +462,10 @@ var init_storage_settings = __esm({
462
462
  }
463
463
  return { tier, file, root: normalizeStoragePath(declared), mode };
464
464
  }, "resolveSettingsEntry");
465
- readTextFile = /* @__PURE__ */ __name((fs7, file) => {
465
+ readTextFile = /* @__PURE__ */ __name((fs9, file) => {
466
466
  let raw;
467
467
  try {
468
- raw = fs7.readFileSync(file, "utf8");
468
+ raw = fs9.readFileSync(file, "utf8");
469
469
  } catch (error) {
470
470
  const code = error?.code;
471
471
  if (code === "ENOENT" || code === "ENOTDIR") return null;
@@ -477,9 +477,9 @@ var init_storage_settings = __esm({
477
477
  return raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw;
478
478
  }, "readTextFile");
479
479
  readStorageSettings = /* @__PURE__ */ __name((file, tier) => {
480
- const fs7 = getSyncFs();
481
- if (!fs7) return null;
482
- const raw = readTextFile(fs7, file);
480
+ const fs9 = getSyncFs();
481
+ if (!fs9) return null;
482
+ const raw = readTextFile(fs9, file);
483
483
  if (raw === null) return null;
484
484
  return resolveSettingsEntry(parseSettings(raw, file), tier, file);
485
485
  }, "readStorageSettings");
@@ -495,13 +495,13 @@ function resolveUserAnchor() {
495
495
  return joinStoragePath(stripTrailingSeparator(home.trim()), DOTMEM_USER_ANCHOR_DIR_NAME);
496
496
  }
497
497
  function readDotMemStorageLocator() {
498
- const fs7 = getSyncFs();
499
- if (!fs7) return null;
498
+ const fs9 = getSyncFs();
499
+ if (!fs9) return null;
500
500
  const anchor = resolveUserAnchor();
501
501
  const locatorFile = resolveLocatorFilePath(anchor);
502
502
  let raw;
503
503
  try {
504
- raw = decodeText(fs7.readFileSync(locatorFile), { source: locatorFile });
504
+ raw = decodeText(fs9.readFileSync(locatorFile), { source: locatorFile });
505
505
  } catch (error) {
506
506
  if (error instanceof UnsupportedEncodingError) {
507
507
  throw new DotMemStorageLocationError(
@@ -617,8 +617,8 @@ async function probeDotMemStorageCapabilities(root) {
617
617
  multiWriterSafety: "unsupported",
618
618
  notes
619
619
  };
620
- const fs7 = getSyncFs();
621
- if (!fs7) {
620
+ const fs9 = getSyncFs();
621
+ if (!fs9) {
622
622
  notes.push("no filesystem access in this runtime");
623
623
  return report;
624
624
  }
@@ -704,14 +704,14 @@ async function relocateDotMemStorage(targetRoot, options = {}) {
704
704
  `Storage relocation target ${target} and the active storage root ${current.storageRoot} must not contain each other.`
705
705
  );
706
706
  }
707
- const fs7 = getSyncFs();
708
- if (!fs7) {
707
+ const fs9 = getSyncFs();
708
+ if (!fs9) {
709
709
  throw new DotMemStorageLocationError("Storage relocation requires filesystem access, which is unavailable in this runtime.");
710
710
  }
711
711
  const fsPromises = await nodeFsPromises();
712
712
  await fsPromises.mkdir(target, { recursive: true });
713
713
  try {
714
- const access = fs7.statSync(target);
714
+ const access = fs9.statSync(target);
715
715
  if (!access.isDirectory()) throw new Error("not a directory");
716
716
  } catch (error) {
717
717
  if (error instanceof DotMemStorageLocationError) throw error;
@@ -720,7 +720,7 @@ async function relocateDotMemStorage(targetRoot, options = {}) {
720
720
  );
721
721
  }
722
722
  await migrateStorageData(current.storageRoot, target);
723
- if (!verifyMigratedData(fs7, current.storageRoot, target)) {
723
+ if (!verifyMigratedData(fs9, current.storageRoot, target)) {
724
724
  throw new DotMemStorageLocationError(
725
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}.`
726
726
  );
@@ -765,15 +765,15 @@ async function restoreDefaultDotMemStorage(options = {}) {
765
765
  if (current.source === "default") {
766
766
  return current;
767
767
  }
768
- const fs7 = getSyncFs();
769
- if (!fs7) {
768
+ const fs9 = getSyncFs();
769
+ if (!fs9) {
770
770
  throw new DotMemStorageLocationError("Restoring the default storage location requires filesystem access, which is unavailable in this runtime.");
771
771
  }
772
772
  const fsPromises = await nodeFsPromises();
773
773
  const target = current.anchor;
774
774
  await fsPromises.mkdir(target, { recursive: true });
775
775
  await migrateStorageData(current.storageRoot, target);
776
- if (!verifyMigratedData(fs7, current.storageRoot, target)) {
776
+ if (!verifyMigratedData(fs9, current.storageRoot, target)) {
777
777
  throw new DotMemStorageLocationError(
778
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}.`
779
779
  );
@@ -821,9 +821,9 @@ var init_storage_location = __esm({
821
821
  return proc && typeof proc.cwd === "function" ? proc.cwd() : ".";
822
822
  }, "currentWorkingDirectory");
823
823
  packageInstallPathHint = null;
824
- noteDotMemPackageInstallPath = /* @__PURE__ */ __name((path5) => {
825
- if (typeof path5 === "string" && path5.trim()) {
826
- packageInstallPathHint = normalizeStoragePath(path5.trim());
824
+ noteDotMemPackageInstallPath = /* @__PURE__ */ __name((path8) => {
825
+ if (typeof path8 === "string" && path8.trim()) {
826
+ packageInstallPathHint = normalizeStoragePath(path8.trim());
827
827
  }
828
828
  }, "noteDotMemPackageInstallPath");
829
829
  looksLikeDotMemInstallPath = /* @__PURE__ */ __name((value) => {
@@ -872,10 +872,10 @@ var init_storage_location = __esm({
872
872
  cliStorageRootOverride = null;
873
873
  }, "clearDotMemStorageRootOverride");
874
874
  hasRecognizableStore = /* @__PURE__ */ __name((root) => {
875
- const fs7 = getSyncFs();
876
- if (!fs7) return false;
875
+ const fs9 = getSyncFs();
876
+ if (!fs9) return false;
877
877
  try {
878
- const entries2 = fs7.readdirSync(root);
878
+ const entries2 = fs9.readdirSync(root);
879
879
  return entries2.some((name) => name.endsWith(".mem") || name === "policy" || name === "DOTMEM.md" || name === "projects");
880
880
  } catch {
881
881
  return false;
@@ -901,10 +901,10 @@ var init_storage_location = __esm({
901
901
  }
902
902
  const root = normalizeStoragePath(trimmed);
903
903
  assertNotInsidePackageInstall(root, source);
904
- const fs7 = getSyncFs();
905
- if (!fs7) return root;
904
+ const fs9 = getSyncFs();
905
+ if (!fs9) return root;
906
906
  try {
907
- const stats = fs7.statSync(root);
907
+ const stats = fs9.statSync(root);
908
908
  if (!stats.isDirectory()) {
909
909
  throw invalidConfiguredRoot(trimmed, source, "the path exists but is not a directory");
910
910
  }
@@ -918,11 +918,11 @@ var init_storage_location = __esm({
918
918
  __name(describeDotMemStorage, "describeDotMemStorage");
919
919
  __name(resolveDotMemStorageRoot, "resolveDotMemStorageRoot");
920
920
  __name(probeDotMemStorageCapabilities, "probeDotMemStorageCapabilities");
921
- collectRelativeEntries = /* @__PURE__ */ __name((fs7, root, prefix = "") => {
921
+ collectRelativeEntries = /* @__PURE__ */ __name((fs9, root, prefix = "") => {
922
922
  const entries2 = [];
923
923
  let dirents;
924
924
  try {
925
- dirents = fs7.readdirSync(root, { withFileTypes: true });
925
+ dirents = fs9.readdirSync(root, { withFileTypes: true });
926
926
  } catch {
927
927
  return entries2;
928
928
  }
@@ -930,23 +930,23 @@ var init_storage_location = __esm({
930
930
  const relative = prefix ? `${prefix}/${dirent.name}` : dirent.name;
931
931
  if (relative === DOTMEM_STORAGE_LOCATOR_FILE_NAME || relative === `${DOTMEM_STORAGE_LOCATOR_FILE_NAME}.tmp`) continue;
932
932
  if (dirent.isDirectory()) {
933
- entries2.push(...collectRelativeEntries(fs7, joinStoragePath(root, dirent.name), relative));
933
+ entries2.push(...collectRelativeEntries(fs9, joinStoragePath(root, dirent.name), relative));
934
934
  } else {
935
935
  entries2.push(relative);
936
936
  }
937
937
  }
938
938
  return entries2.sort();
939
939
  }, "collectRelativeEntries");
940
- verifyMigratedData = /* @__PURE__ */ __name((fs7, from, to) => {
941
- const expected = collectRelativeEntries(fs7, from);
942
- 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));
943
943
  return expected.every((relative) => migrated.has(relative));
944
944
  }, "verifyMigratedData");
945
945
  migrateStorageData = /* @__PURE__ */ __name(async (from, to) => {
946
- const fs7 = getSyncFs();
947
- 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.");
948
948
  const fsPromises = await nodeFsPromises();
949
- for (const relative of collectRelativeEntries(fs7, from)) {
949
+ for (const relative of collectRelativeEntries(fs9, from)) {
950
950
  const source = joinStoragePath(from, ...relative.split("/"));
951
951
  const destination = joinStoragePath(to, ...relative.split("/"));
952
952
  await fsPromises.mkdir(parentStoragePath(destination), { recursive: true });
@@ -967,10 +967,10 @@ var init_storage_location = __esm({
967
967
  await fsPromises.rename(temporary, locatorFile);
968
968
  }, "writeStorageLocator");
969
969
  clearMigratedSource = /* @__PURE__ */ __name(async (root, removeRoot) => {
970
- const fs7 = getSyncFs();
971
- if (!fs7) return;
970
+ const fs9 = getSyncFs();
971
+ if (!fs9) return;
972
972
  const fsPromises = await nodeFsPromises();
973
- for (const relative of collectRelativeEntries(fs7, root)) {
973
+ for (const relative of collectRelativeEntries(fs9, root)) {
974
974
  await fsPromises.rm(joinStoragePath(root, ...relative.split("/")), { recursive: true, force: true }).catch(() => void 0);
975
975
  }
976
976
  if (removeRoot && root !== resolveUserAnchor()) {
@@ -978,11 +978,11 @@ var init_storage_location = __esm({
978
978
  }
979
979
  }, "clearMigratedSource");
980
980
  writeSettingsFile = /* @__PURE__ */ __name(async (file, transform) => {
981
- const fs7 = getSyncFs();
982
- 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.");
983
983
  let document = {};
984
984
  try {
985
- const raw = fs7.readFileSync(file, "utf8");
985
+ const raw = fs9.readFileSync(file, "utf8");
986
986
  const parsed = JSON.parse(raw);
987
987
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("not an object");
988
988
  document = parsed;
@@ -1737,8 +1737,8 @@ __export(brain_exports, {
1737
1737
  });
1738
1738
  async function brainLoad(brainPath) {
1739
1739
  try {
1740
- const fs7 = await nodeFs();
1741
- const raw = await fs7.readFile(brainPath, "utf8");
1740
+ const fs9 = await nodeFs();
1741
+ const raw = await fs9.readFile(brainPath, "utf8");
1742
1742
  const doc = JSON.parse(raw);
1743
1743
  if (doc.format !== "dotmem.brain" || doc.version !== 1) return emptyBrain();
1744
1744
  if (!Array.isArray(doc.relationships)) return emptyBrain();
@@ -1748,26 +1748,26 @@ async function brainLoad(brainPath) {
1748
1748
  }
1749
1749
  }
1750
1750
  async function brainSave(brainPath, document) {
1751
- const fs7 = await nodeFs();
1751
+ const fs9 = await nodeFs();
1752
1752
  const dir = brainPath.includes("/") ? brainPath.slice(0, brainPath.lastIndexOf("/")) : brainPath.includes("\\") ? brainPath.slice(0, brainPath.lastIndexOf("\\")) : ".";
1753
- await fs7.mkdir(dir, { recursive: true });
1753
+ await fs9.mkdir(dir, { recursive: true });
1754
1754
  const tmp = `${brainPath}.${process.pid}.${Date.now().toString(36)}.tmp`;
1755
1755
  try {
1756
- await fs7.writeFile(tmp, JSON.stringify(document, null, 2));
1757
- await fs7.rename(tmp, brainPath);
1756
+ await fs9.writeFile(tmp, JSON.stringify(document, null, 2));
1757
+ await fs9.rename(tmp, brainPath);
1758
1758
  } catch (error) {
1759
- await fs7.rm(tmp, { force: true }).catch(() => void 0);
1759
+ await fs9.rm(tmp, { force: true }).catch(() => void 0);
1760
1760
  throw error;
1761
1761
  }
1762
1762
  }
1763
1763
  async function getBrainDocument() {
1764
- const path5 = getBrainPath();
1765
- cachedBrainPath = path5;
1766
- return brainLoad(path5);
1764
+ const path8 = getBrainPath();
1765
+ cachedBrainPath = path8;
1766
+ return brainLoad(path8);
1767
1767
  }
1768
1768
  async function saveBrainDocument(document) {
1769
- const path5 = cachedBrainPath || getBrainPath();
1770
- await brainSave(path5, document);
1769
+ const path8 = cachedBrainPath || getBrainPath();
1770
+ await brainSave(path8, document);
1771
1771
  }
1772
1772
  function resetBrainPathCache() {
1773
1773
  cachedBrainPath = null;
@@ -1923,11 +1923,11 @@ var init_state = __esm({
1923
1923
  }
1924
1924
  for (let index = 0; index < evidence.length; index++) {
1925
1925
  const entry = evidence[index];
1926
- const path5 = `evidence[${index}]`;
1926
+ const path8 = `evidence[${index}]`;
1927
1927
  if (Array.isArray(entry)) {
1928
1928
  throw canonicalEvidenceError({
1929
1929
  claimId: claim.id,
1930
- path: path5,
1930
+ path: path8,
1931
1931
  problem: CANONICAL_EVIDENCE_PROBLEMS.tupleEntry,
1932
1932
  received: entry,
1933
1933
  fix: CANONICAL_EVIDENCE_FIX.tupleEntry
@@ -1936,7 +1936,7 @@ var init_state = __esm({
1936
1936
  if (!entry || typeof entry !== "object") {
1937
1937
  throw canonicalEvidenceError({
1938
1938
  claimId: claim.id,
1939
- path: path5,
1939
+ path: path8,
1940
1940
  problem: CANONICAL_EVIDENCE_PROBLEMS.nonObjectEntry,
1941
1941
  received: entry,
1942
1942
  fix: CANONICAL_EVIDENCE_FIX.nonObjectEntry
@@ -1945,7 +1945,7 @@ var init_state = __esm({
1945
1945
  if (!requiredText(entry.id)) {
1946
1946
  throw canonicalEvidenceError({
1947
1947
  claimId: claim.id,
1948
- path: `${path5}.id`,
1948
+ path: `${path8}.id`,
1949
1949
  problem: CANONICAL_EVIDENCE_PROBLEMS.missingId,
1950
1950
  received: entry,
1951
1951
  fix: CANONICAL_EVIDENCE_FIX.missingId
@@ -1956,7 +1956,7 @@ var init_state = __esm({
1956
1956
  if (fieldValue !== void 0 && !requiredText(fieldValue)) {
1957
1957
  throw canonicalEvidenceError({
1958
1958
  claimId: claim.id,
1959
- path: `${path5}.${field}`,
1959
+ path: `${path8}.${field}`,
1960
1960
  problem: CANONICAL_EVIDENCE_PROBLEMS.invalidOptionalField(field),
1961
1961
  received: fieldValue,
1962
1962
  fix: CANONICAL_EVIDENCE_FIX.invalidOptionalField(field)
@@ -2001,12 +2001,6 @@ var init_state = __esm({
2001
2001
  if (claim.sourceProject !== void 0 && !requiredText(claim.sourceProject)) {
2002
2002
  throw new Error(`Claim ${claim.id} has an invalid sourceProject`);
2003
2003
  }
2004
- if (claim.check !== void 0) {
2005
- const check = claim.check;
2006
- if (!check || typeof check !== "object" || Array.isArray(check) || check.kind !== "regex" || !requiredText(check.pattern) || !["staged", "committed", "working-tree"].includes(check.on) || check.description !== void 0 && !requiredText(check.description)) {
2007
- throw new Error(`Claim ${claim.id} has an invalid check`);
2008
- }
2009
- }
2010
2004
  return claim;
2011
2005
  }, "validateClaim");
2012
2006
  validateKnowledgeState = /* @__PURE__ */ __name((value) => {
@@ -2538,6 +2532,10 @@ var init_discover = __esm({
2538
2532
  freshEligible.map((claim) => [claim.id, isEligibleByApplicability(claim, situationApplicability)])
2539
2533
  );
2540
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
+ });
2541
2539
  const applicabilityOmissions = freshEligible.filter((claim) => !applicabilityMatches.get(claim.id).eligible).map((claim) => {
2542
2540
  const match = applicabilityMatches.get(claim.id);
2543
2541
  const mismatched = Object.entries(match.dimensions).filter(([, state3]) => state3 === "MISMATCH").map(([dimension]) => dimension);
@@ -2561,7 +2559,7 @@ var init_discover = __esm({
2561
2559
  }
2562
2560
  const currentnessOf = /* @__PURE__ */ __name((claim) => deriveCurrentness(claim, { retractedIds, supersededIds, contestedIds }), "currentnessOf");
2563
2561
  if (queryTerms.length === 0) {
2564
- const baselineAll = 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) => {
2565
2563
  const leftTime = acquiredTime(left);
2566
2564
  const rightTime = acquiredTime(right);
2567
2565
  return rightTime - leftTime || Number(right.scope === "project") - Number(left.scope === "project") || left.id.localeCompare(right.id);
@@ -2605,7 +2603,7 @@ var init_discover = __esm({
2605
2603
  ]
2606
2604
  };
2607
2605
  }
2608
- const ranked = eligible.map(
2606
+ const ranked = eligibleForContext.map(
2609
2607
  (candidate) => rankCandidate(
2610
2608
  candidate.claim,
2611
2609
  situation,
@@ -2620,7 +2618,7 @@ var init_discover = __esm({
2620
2618
  );
2621
2619
  const rankedIds = new Set(ranked.map((candidate) => candidate.claim.id));
2622
2620
  const rankingOmissions = [
2623
- ...eligible.filter((candidate) => !rankedIds.has(candidate.claim.id)).map((candidate) => ({
2621
+ ...eligibleForContext.filter((candidate) => !rankedIds.has(candidate.claim.id)).map((candidate) => ({
2624
2622
  id: candidate.claim.id,
2625
2623
  reason: "no-term-match",
2626
2624
  gate: "ranking",
@@ -2919,9 +2917,9 @@ var init_policy_namespace_lock = __esm({
2919
2917
  acquiredAt: (/* @__PURE__ */ new Date()).toISOString(),
2920
2918
  token: `lock-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`
2921
2919
  }), "createOwner");
2922
- readLockOwner = /* @__PURE__ */ __name(async (fs7, lockPath) => {
2920
+ readLockOwner = /* @__PURE__ */ __name(async (fs9, lockPath) => {
2923
2921
  try {
2924
- const raw = await fs7.readFile(lockPath, "utf8");
2922
+ const raw = await fs9.readFile(lockPath, "utf8");
2925
2923
  const parsed = JSON.parse(raw);
2926
2924
  if (!parsed || typeof parsed !== "object") return null;
2927
2925
  return {
@@ -2934,11 +2932,11 @@ var init_policy_namespace_lock = __esm({
2934
2932
  return null;
2935
2933
  }
2936
2934
  }, "readLockOwner");
2937
- acquireLock = /* @__PURE__ */ __name(async (fs7, lockPath, owner) => {
2935
+ acquireLock = /* @__PURE__ */ __name(async (fs9, lockPath, owner) => {
2938
2936
  let brokenOwner = null;
2939
2937
  for (let attempt = 0; attempt <= POLICY_LOCK_RETRY_ATTEMPTS; attempt++) {
2940
2938
  try {
2941
- await fs7.writeFile(lockPath, JSON.stringify(owner), { encoding: "utf8", flag: "wx" });
2939
+ await fs9.writeFile(lockPath, JSON.stringify(owner), { encoding: "utf8", flag: "wx" });
2942
2940
  return brokenOwner;
2943
2941
  } catch (error) {
2944
2942
  const code = error?.code;
@@ -2947,12 +2945,12 @@ var init_policy_namespace_lock = __esm({
2947
2945
  `Policy namespace exclusive creation is not verifiable on this substrate (${String(code)}); policy mutation fails closed`
2948
2946
  );
2949
2947
  }
2950
- const held = await readLockOwner(fs7, lockPath);
2948
+ const held = await readLockOwner(fs9, lockPath);
2951
2949
  const acquiredAt = held ? Date.parse(held.acquiredAt) : Number.NaN;
2952
2950
  const age = Number.isFinite(acquiredAt) ? Date.now() - acquiredAt : Number.POSITIVE_INFINITY;
2953
2951
  if (age > POLICY_LOCK_TTL_MS) {
2954
2952
  const stale = held ?? { pid: 0, host: "unknown", acquiredAt: "", token: "" };
2955
- const outcome = await breakStalePolicyLock(fs7, lockPath, stale);
2953
+ const outcome = await breakStalePolicyLock(fs9, lockPath, stale);
2956
2954
  if (outcome === "broken") {
2957
2955
  brokenOwner = stale;
2958
2956
  }
@@ -2971,21 +2969,21 @@ var init_policy_namespace_lock = __esm({
2971
2969
  `Policy namespace lock could not be acquired after ${POLICY_LOCK_RETRY_ATTEMPTS} bounded retries; policy mutation fails closed`
2972
2970
  );
2973
2971
  }, "acquireLock");
2974
- breakStalePolicyLock = /* @__PURE__ */ __name(async (fs7, lockPath, staleOwner) => {
2972
+ breakStalePolicyLock = /* @__PURE__ */ __name(async (fs9, lockPath, staleOwner) => {
2975
2973
  const candidate = `${lockPath}.breaking-${staleOwner.token || "unknown"}`;
2976
2974
  try {
2977
- await fs7.rename(lockPath, candidate);
2975
+ await fs9.rename(lockPath, candidate);
2978
2976
  } catch (error) {
2979
2977
  if (error.code === "ENOENT") return "lost";
2980
2978
  throw error;
2981
2979
  }
2982
- const moved = await readLockOwner(fs7, candidate);
2980
+ const moved = await readLockOwner(fs9, candidate);
2983
2981
  if (moved && moved.token === staleOwner.token) {
2984
- await fs7.rm(candidate, { force: true }).catch(() => void 0);
2982
+ await fs9.rm(candidate, { force: true }).catch(() => void 0);
2985
2983
  return "broken";
2986
2984
  }
2987
2985
  try {
2988
- await fs7.link(candidate, lockPath);
2986
+ await fs9.link(candidate, lockPath);
2989
2987
  } catch (error) {
2990
2988
  const code = error?.code;
2991
2989
  if (code !== "EEXIST") {
@@ -2994,22 +2992,22 @@ var init_policy_namespace_lock = __esm({
2994
2992
  );
2995
2993
  }
2996
2994
  }
2997
- await fs7.rm(candidate, { force: true }).catch(() => void 0);
2995
+ await fs9.rm(candidate, { force: true }).catch(() => void 0);
2998
2996
  return "lost";
2999
2997
  }, "breakStalePolicyLock");
3000
- releaseLock = /* @__PURE__ */ __name(async (fs7, lockPath, owner) => {
3001
- const held = await readLockOwner(fs7, lockPath);
2998
+ releaseLock = /* @__PURE__ */ __name(async (fs9, lockPath, owner) => {
2999
+ const held = await readLockOwner(fs9, lockPath);
3002
3000
  if (!held || held.token !== owner.token) return;
3003
- await fs7.rm(lockPath, { force: true }).catch(() => void 0);
3001
+ await fs9.rm(lockPath, { force: true }).catch(() => void 0);
3004
3002
  }, "releaseLock");
3005
3003
  withPolicyNamespaceLock = /* @__PURE__ */ __name(async (operation, options = {}) => {
3006
3004
  const directory = options.directory ?? resolveUserPolicyDir();
3007
3005
  const lockPath = resolvePolicyNamespaceLockPath(directory);
3008
3006
  return enqueue(directory, async () => {
3009
- const fs7 = await nodeFs2();
3007
+ const fs9 = await nodeFs2();
3010
3008
  const owner = await createOwner();
3011
- await fs7.mkdir(parentDirectoryOf(lockPath), { recursive: true }).catch(() => void 0);
3012
- 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);
3013
3011
  if (brokenOwner && options.onLockBreak) {
3014
3012
  options.onLockBreak({
3015
3013
  at: (/* @__PURE__ */ new Date()).toISOString(),
@@ -3020,7 +3018,7 @@ var init_policy_namespace_lock = __esm({
3020
3018
  try {
3021
3019
  return await operation({
3022
3020
  assertOwnership: /* @__PURE__ */ __name(async () => {
3023
- const held = await readLockOwner(fs7, lockPath);
3021
+ const held = await readLockOwner(fs9, lockPath);
3024
3022
  if (!held || held.token !== owner.token) {
3025
3023
  throw new PolicyNamespaceLockError(
3026
3024
  "Policy namespace lock ownership was lost before commit; policy mutation fails closed"
@@ -3029,7 +3027,7 @@ var init_policy_namespace_lock = __esm({
3029
3027
  }, "assertOwnership")
3030
3028
  });
3031
3029
  } finally {
3032
- await releaseLock(fs7, lockPath, owner);
3030
+ await releaseLock(fs9, lockPath, owner);
3033
3031
  }
3034
3032
  });
3035
3033
  }, "withPolicyNamespaceLock");
@@ -3357,35 +3355,35 @@ var init_policy_store = __esm({
3357
3355
  }
3358
3356
  /** Read one namespace document: always fresh, always validated. */
3359
3357
  async load(namespace2) {
3360
- const fs7 = await nodeFs3();
3361
- return this.readDocument(fs7, namespace2);
3358
+ const fs9 = await nodeFs3();
3359
+ return this.readDocument(fs9, namespace2);
3362
3360
  }
3363
- async readDocument(fs7, namespace2) {
3361
+ async readDocument(fs9, namespace2) {
3364
3362
  let raw;
3365
3363
  try {
3366
- raw = await fs7.readFile(this.filePath(namespace2), "utf8");
3364
+ raw = await fs9.readFile(this.filePath(namespace2), "utf8");
3367
3365
  } catch (error) {
3368
3366
  if (error.code === "ENOENT") return emptyPolicyDocument();
3369
3367
  throw error;
3370
3368
  }
3371
3369
  return validatePolicyDocument(JSON.parse(raw));
3372
3370
  }
3373
- async writeDocument(fs7, namespace2, document) {
3374
- await fs7.mkdir(this.dir(), { recursive: true });
3371
+ async writeDocument(fs9, namespace2, document) {
3372
+ await fs9.mkdir(this.dir(), { recursive: true });
3375
3373
  const filePath = this.filePath(namespace2);
3376
3374
  const temporary = `${filePath}.${process.pid}.${Date.now().toString(36)}.tmp`;
3377
3375
  try {
3378
- await fs7.writeFile(temporary, `${JSON.stringify(document, null, 2)}
3376
+ await fs9.writeFile(temporary, `${JSON.stringify(document, null, 2)}
3379
3377
  `, "utf8");
3380
- const handle = await fs7.open(temporary, "r+");
3378
+ const handle = await fs9.open(temporary, "r+");
3381
3379
  try {
3382
3380
  await handle.sync();
3383
3381
  } finally {
3384
3382
  await handle.close();
3385
3383
  }
3386
- await fs7.rename(temporary, filePath);
3384
+ await fs9.rename(temporary, filePath);
3387
3385
  } catch (error) {
3388
- await fs7.rm(temporary, { force: true }).catch(() => void 0);
3386
+ await fs9.rm(temporary, { force: true }).catch(() => void 0);
3389
3387
  throw error;
3390
3388
  }
3391
3389
  }
@@ -3404,8 +3402,8 @@ var init_policy_store = __esm({
3404
3402
  const lockBreaks = [];
3405
3403
  try {
3406
3404
  return await withPolicyNamespaceLock(async (session2) => {
3407
- const fs7 = await nodeFs3();
3408
- const document = await this.readDocument(fs7, namespace2);
3405
+ const fs9 = await nodeFs3();
3406
+ const document = await this.readDocument(fs9, namespace2);
3409
3407
  if (options.basedOnRevision !== void 0 && options.basedOnRevision !== document.revision) {
3410
3408
  throw new PolicyStoreError(
3411
3409
  `Stale policy revision: caller expected ${options.basedOnRevision}, current document revision is ${document.revision}`
@@ -3426,7 +3424,7 @@ var init_policy_store = __esm({
3426
3424
  }
3427
3425
  validatePolicyDocument(next);
3428
3426
  await session2.assertOwnership();
3429
- await this.writeDocument(fs7, namespace2, next);
3427
+ await this.writeDocument(fs9, namespace2, next);
3430
3428
  return outcome.result;
3431
3429
  }, { directory, onLockBreak: /* @__PURE__ */ __name((lockBreak) => {
3432
3430
  lockBreaks.push(lockBreak);
@@ -3800,6 +3798,74 @@ var init_acquisition_limits = __esm({
3800
3798
  }
3801
3799
  });
3802
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
+
3803
3869
  // core/knowledge/acquisition-boundary.ts
3804
3870
  var MEMORY_ACQUIRE_EVENT, crossAcquisitionBoundary;
3805
3871
  var init_acquisition_boundary = __esm({
@@ -3809,6 +3875,7 @@ var init_acquisition_boundary = __esm({
3809
3875
  init_policy_store();
3810
3876
  init_applicability();
3811
3877
  init_acquisition_limits();
3878
+ init_verification();
3812
3879
  MEMORY_ACQUIRE_EVENT = "memory.acquire";
3813
3880
  if (!(MEMORY_ACQUIRE_EVENT in CANONICAL_EVENTS)) {
3814
3881
  throw new Error(
@@ -3818,6 +3885,12 @@ var init_acquisition_boundary = __esm({
3818
3885
  crossAcquisitionBoundary = /* @__PURE__ */ __name(async (opts, dependencies = {}) => {
3819
3886
  const limits = dependencies.limits ?? MEMORY_ACQUIRE_LIMITS;
3820
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
+ }
3821
3894
  const sanitized = sanitizeKnowledge(opts.knowledge);
3822
3895
  if (sanitized.disposition === "reject") {
3823
3896
  throw new Error(
@@ -3868,6 +3941,7 @@ var FORMAT, STATUS, NOTICE, DEFAULT_MAX_CANDIDATES, DEFAULT_MAX_CHARACTERS, MIN_
3868
3941
  var init_project = __esm({
3869
3942
  "core/knowledge/project.ts"() {
3870
3943
  init_state();
3944
+ init_verification();
3871
3945
  init_user_paths();
3872
3946
  init_discover();
3873
3947
  init_context_constants();
@@ -3879,18 +3953,36 @@ var init_project = __esm({
3879
3953
  MIN_MAX_CHARACTERS = DOTMEM_CONTEXT_DEFAULT_MIN_MAX__CHARACTERS;
3880
3954
  projectCandidate = /* @__PURE__ */ __name((candidate) => {
3881
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
+ };
3882
3973
  return structuredClone({
3883
3974
  id: claim.id,
3884
3975
  status: "prior-acquired-experience-candidate",
3885
3976
  experience: claim.knowledge,
3886
3977
  applicability: claim.applicability,
3887
- evidence: claim.evidence,
3978
+ evidence: claim.evidence.map((evidence) => ({ ...evidence, resolved: false })),
3888
3979
  ...claim.epistemicType ? { epistemicType: claim.epistemicType } : {},
3889
3980
  ...claim.provenance ? { provenance: claim.provenance } : {},
3890
3981
  ...claim.acquiredAt ? { acquiredAt: claim.acquiredAt } : {},
3891
3982
  ...claim.revision ? { revision: claim.revision } : {},
3892
3983
  ...candidate.explanation.sourceId ? { sourceId: candidate.explanation.sourceId } : {},
3893
- ...candidate.currentness ? { currentness: candidate.currentness } : {}
3984
+ ...candidate.currentness ? { currentness: candidate.currentness } : {},
3985
+ trustBasis
3894
3986
  });
3895
3987
  }, "projectCandidate");
3896
3988
  GIST_MAX_LENGTH = 80;
@@ -3949,7 +4041,8 @@ var init_project = __esm({
3949
4041
  ...experience.provenance ? { provenance: [experience.provenance.source, experience.provenance.detail ?? null] } : {},
3950
4042
  ...experience.acquiredAt ? { acquiredAt: experience.acquiredAt } : {},
3951
4043
  ...experience.revision ? { revision: experience.revision } : {},
3952
- ...experience.sourceId ? { source: experience.sourceId } : {}
4044
+ ...experience.sourceId ? { source: experience.sourceId } : {},
4045
+ ...experience.trustBasis ? { trustBasis: experience.trustBasis } : {}
3953
4046
  }), "renderExperience");
3954
4047
  renderText = /* @__PURE__ */ __name((header, experiences, omittedCandidates, manifest, render = renderExperience, currentnessSummary) => {
3955
4048
  const lines = [header];
@@ -3987,6 +4080,7 @@ var init_project = __esm({
3987
4080
  gist: deriveGist(experience.experience),
3988
4081
  epistemic: experience.epistemicType ?? null,
3989
4082
  currentness: experience.currentness ?? null,
4083
+ trustBasis: experience.trustBasis?.trustBasis ?? null,
3990
4084
  ...experience.revision ? { revision: experience.revision.kind } : {}
3991
4085
  }), "renderCompactExperience");
3992
4086
  projectDiscoveredExperience = /* @__PURE__ */ __name((discovery, options = {}) => {
@@ -6017,8 +6111,8 @@ async function signMemPackage(input, privateKey, publicKey) {
6017
6111
  const artifact = await decodePackage(input);
6018
6112
  const rawPublicKey = new Uint8Array(await crypto.subtle.exportKey("raw", publicKey));
6019
6113
  const keyId = await keyIdentity(rawPublicKey);
6020
- const path5 = signaturePath(keyId);
6021
- const existingSignatures = { ...artifact.package?.signatures, [path5]: jsonBytes({}) };
6114
+ const path8 = signaturePath(keyId);
6115
+ const existingSignatures = { ...artifact.package?.signatures, [path8]: jsonBytes({}) };
6022
6116
  const declaredPackage = await encodePackage(artifact.state, artifact.preserved, artifact.package, existingSignatures);
6023
6117
  const declaredArtifact = await decodePackage(declaredPackage);
6024
6118
  const signature = new Uint8Array(await crypto.subtle.sign(
@@ -6037,7 +6131,7 @@ async function signMemPackage(input, privateKey, publicKey) {
6037
6131
  };
6038
6132
  return encodePackage(artifact.state, artifact.preserved, artifact.package, {
6039
6133
  ...artifact.package?.signatures,
6040
- [path5]: jsonBytes(document)
6134
+ [path8]: jsonBytes(document)
6041
6135
  });
6042
6136
  }
6043
6137
  async function decodeMemArtifact(input) {
@@ -6069,7 +6163,7 @@ async function inspectMem(input) {
6069
6163
  const knownMapKeys = /* @__PURE__ */ new Set(["state", "claim", "evidence", "provenance", "revision", "epistemicType", "revisionKind"]);
6070
6164
  const unknownMapEntries = Object.keys(artifact2.preserved?.map ?? {}).filter((key) => !knownMapKeys.has(key)).length;
6071
6165
  const vocabularyEntries = Math.max(0, (artifact2.preserved?.map.epistemicType.length ?? 4) - 4) + Math.max(0, (artifact2.preserved?.map.revisionKind.length ?? 3) - 3);
6072
- 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)));
6073
6167
  const authenticityStatus = signatures.length === 0 ? "unsigned" : signatures.some((signature) => signature.status === "invalid") ? "invalid" : signatures.some((signature) => signature.status === "unsupported") ? "unsupported" : "valid";
6074
6168
  return {
6075
6169
  status: "valid",
@@ -6078,10 +6172,10 @@ async function inspectMem(input) {
6078
6172
  packageVersion: MEM_PACKAGE_VERSION,
6079
6173
  memoryVersion: MEM_FORMAT_VERSION,
6080
6174
  contentId: artifact2.integrity.contentId,
6081
- parts: Object.entries(artifact2.parts).sort(([a], [b]) => a.localeCompare(b)).map(([path5, part]) => ({
6082
- path: path5,
6175
+ parts: Object.entries(artifact2.parts).sort(([a], [b]) => a.localeCompare(b)).map(([path8, part]) => ({
6176
+ path: path8,
6083
6177
  bytes: part.length,
6084
- protected: path5 !== INTEGRITY_PATH && !path5.startsWith("security/signatures/")
6178
+ protected: path8 !== INTEGRITY_PATH && !path8.startsWith("security/signatures/")
6085
6179
  })),
6086
6180
  knowledge: artifact2.state,
6087
6181
  unknownSemantics: { mapEntries: unknownMapEntries, vocabularyEntries, extensionParts: Object.keys(artifact2.package?.extensions ?? {}).sort() },
@@ -6159,14 +6253,14 @@ var init_mem_package = __esm({
6159
6253
  const digest = await globalThis.crypto.subtle.digest("SHA-256", data);
6160
6254
  return `sha256:${[...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
6161
6255
  }, "sha256");
6162
- parseJson = /* @__PURE__ */ __name((bytes, path5) => {
6256
+ parseJson = /* @__PURE__ */ __name((bytes, path8) => {
6163
6257
  try {
6164
6258
  return JSON.parse(decodeText(bytes));
6165
6259
  } catch (error) {
6166
- 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}`);
6167
6261
  }
6168
6262
  }, "parseJson");
6169
- 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");
6170
6264
  concatenate = /* @__PURE__ */ __name((chunks, size) => {
6171
6265
  const result = new Uint8Array(size);
6172
6266
  let offset = 0;
@@ -6258,31 +6352,31 @@ ${contentId}
6258
6352
  [DATA_PATH]: jsonBytes(memory2.data),
6259
6353
  ...structuredClone(preservedPackage?.extensions ?? {})
6260
6354
  };
6261
- for (const path5 of Object.keys(protectedParts)) {
6262
- if (!requiredParts.includes(path5) && !path5.startsWith("extensions/")) {
6263
- 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}`);
6264
6358
  }
6265
- 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}`);
6266
6360
  }
6267
- for (const path5 of Object.keys(signatures)) {
6268
- if (!/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path5)) {
6269
- 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}`);
6270
6364
  }
6271
6365
  }
6272
6366
  const files = {};
6273
- 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]);
6274
6368
  const integrity = { algorithm: "sha256", files, contentId: await digestTableIdentity(files) };
6275
6369
  const parts = { ...protectedParts, [INTEGRITY_PATH]: jsonBytes(integrity), ...signatures };
6276
- for (const [path5, bytes] of Object.entries(parts)) {
6370
+ for (const [path8, bytes] of Object.entries(parts)) {
6277
6371
  if (bytes.length > MEM_PACKAGE_WRITE_LIMITS.maximumEntryBytes) {
6278
- 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}`);
6279
6373
  }
6280
6374
  }
6281
6375
  const uncompressedBytes = Object.values(parts).reduce((total, bytes) => total + bytes.length, 0);
6282
6376
  if (uncompressedBytes > MEM_PACKAGE_WRITE_LIMITS.maximumUncompressedBytes) {
6283
6377
  throw new MemArtifactError("invalid", "MEM package exceeds the write limit for uncompressed content");
6284
6378
  }
6285
- 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], {
6286
6380
  level: 6,
6287
6381
  mtime: /* @__PURE__ */ new Date("1980-01-02T00:00:00.000Z")
6288
6382
  }]]));
@@ -6297,8 +6391,8 @@ ${contentId}
6297
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");
6298
6392
  decodePackage = /* @__PURE__ */ __name(async (bytes) => {
6299
6393
  const parts = readZipParts(bytes);
6300
- for (const path5 of [...requiredParts, INTEGRITY_PATH]) {
6301
- 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}`);
6302
6396
  }
6303
6397
  const manifest = parseJson(parts[MANIFEST_PATH], MANIFEST_PATH);
6304
6398
  if (manifest.format !== MEM_PACKAGE_FORMAT && manifest.format !== MEM_PACKAGE_FORMAT_LEGACY || manifest.version !== MEM_PACKAGE_VERSION) {
@@ -6309,8 +6403,8 @@ ${contentId}
6309
6403
  }
6310
6404
  const integrity = parseJson(parts[INTEGRITY_PATH], INTEGRITY_PATH);
6311
6405
  if (integrity.algorithm !== "sha256") throw new MemArtifactError("unsupported", "Unsupported MEM package integrity algorithm");
6312
- const signaturePaths = Object.keys(parts).filter((path5) => path5.startsWith("security/signatures/")).sort();
6313
- 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))) {
6314
6408
  throw new MemArtifactError("invalid", "Invalid MEM signature entry path");
6315
6409
  }
6316
6410
  if (manifest.authenticity !== void 0 && manifest.authenticity.signed !== true) {
@@ -6319,14 +6413,14 @@ ${contentId}
6319
6413
  if (manifest.authenticity?.signed === true !== signaturePaths.length > 0) {
6320
6414
  throw new MemArtifactError("invalid", "Declared MEM signatures do not match package entries");
6321
6415
  }
6322
- 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();
6323
6417
  const protectedPaths = Object.keys(integrity.files ?? {}).sort();
6324
6418
  if (JSON.stringify(archivePaths) !== JSON.stringify(protectedPaths)) {
6325
6419
  throw new MemArtifactError("invalid", "MEM package protected-parts table does not match archive contents");
6326
6420
  }
6327
- for (const path5 of protectedPaths) {
6328
- const actual = await sha256(parts[path5]);
6329
- 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}`);
6330
6424
  }
6331
6425
  if (integrity.contentId !== await digestTableIdentity(integrity.files)) {
6332
6426
  throw new MemArtifactError("checksum_mismatch", "MEM package content identity mismatch");
@@ -6339,14 +6433,14 @@ ${contentId}
6339
6433
  } catch (error) {
6340
6434
  throw new MemArtifactError("invalid", `Invalid packaged MEM semantics: ${error.message}`);
6341
6435
  }
6342
- const extensions = Object.fromEntries(Object.entries(parts).filter(([path5]) => path5.startsWith("extensions/")));
6343
- 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]]));
6344
6438
  return { ...decoded, representation: "package-v1", package: { manifest, extensions, signatures }, parts, integrity };
6345
6439
  }, "decodePackage");
6346
- verifySignature = /* @__PURE__ */ __name(async (path5, bytes, contentId) => {
6440
+ verifySignature = /* @__PURE__ */ __name(async (path8, bytes, contentId) => {
6347
6441
  let document;
6348
6442
  try {
6349
- document = parseJson(bytes, path5);
6443
+ document = parseJson(bytes, path8);
6350
6444
  } catch (error) {
6351
6445
  return { status: "invalid", message: error.message };
6352
6446
  }
@@ -6378,7 +6472,7 @@ ${contentId}
6378
6472
  const publicKeyBytes = base64UrlDecode(document.publicKey.value);
6379
6473
  const signatureBytes = base64UrlDecode(document.signature.value);
6380
6474
  const derivedKeyId = await keyIdentity(publicKeyBytes);
6381
- if (derivedKeyId !== document.keyId || signaturePath(derivedKeyId) !== path5) {
6475
+ if (derivedKeyId !== document.keyId || signaturePath(derivedKeyId) !== path8) {
6382
6476
  return {
6383
6477
  status: "invalid",
6384
6478
  algorithm: document.algorithm,
@@ -6430,7 +6524,7 @@ var init_storage_coordinator = __esm({
6430
6524
  const staleMs = opts.staleMs ?? 6e4;
6431
6525
  const lockName = opts.lockName ?? ".storage.lock";
6432
6526
  const lockPath = `${directoryPath}/${lockName}`;
6433
- const fs7 = await nodeFs4();
6527
+ const fs9 = await nodeFs4();
6434
6528
  const started = Date.now();
6435
6529
  const heldDepth = heldLocks.get(lockPath) ?? 0;
6436
6530
  if (heldDepth > 0) {
@@ -6441,12 +6535,12 @@ var init_storage_coordinator = __esm({
6441
6535
  heldLocks.set(lockPath, heldDepth);
6442
6536
  }
6443
6537
  }
6444
- await fs7.mkdir(directoryPath, { recursive: true });
6538
+ await fs9.mkdir(directoryPath, { recursive: true });
6445
6539
  while (true) {
6446
6540
  try {
6447
- await fs7.mkdir(lockPath);
6541
+ await fs9.mkdir(lockPath);
6448
6542
  const token2 = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
6449
- 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" });
6450
6544
  break;
6451
6545
  } catch (error) {
6452
6546
  const code = error.code;
@@ -6454,7 +6548,7 @@ var init_storage_coordinator = __esm({
6454
6548
  let stale = false;
6455
6549
  let processDead = false;
6456
6550
  try {
6457
- const raw = await fs7.readFile(`${lockPath}/owner.json`);
6551
+ const raw = await fs9.readFile(`${lockPath}/owner.json`);
6458
6552
  const parsed = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` }));
6459
6553
  const ageStale = typeof parsed.createdAt === "number" && Date.now() - parsed.createdAt > staleMs;
6460
6554
  if (typeof parsed.pid === "number") {
@@ -6473,13 +6567,13 @@ var init_storage_coordinator = __esm({
6473
6567
  if (stale) {
6474
6568
  if (processDead) {
6475
6569
  try {
6476
- await fs7.rm(lockPath, { recursive: true, force: true });
6570
+ await fs9.rm(lockPath, { recursive: true, force: true });
6477
6571
  continue;
6478
6572
  } catch {
6479
6573
  }
6480
6574
  }
6481
6575
  try {
6482
- await fs7.rmdir(lockPath);
6576
+ await fs9.rmdir(lockPath);
6483
6577
  continue;
6484
6578
  } catch {
6485
6579
  }
@@ -6492,7 +6586,7 @@ var init_storage_coordinator = __esm({
6492
6586
  }
6493
6587
  let token = "";
6494
6588
  try {
6495
- const raw = await fs7.readFile(`${lockPath}/owner.json`);
6589
+ const raw = await fs9.readFile(`${lockPath}/owner.json`);
6496
6590
  token = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` })).token ?? "";
6497
6591
  } catch {
6498
6592
  token = "";
@@ -6503,19 +6597,19 @@ var init_storage_coordinator = __esm({
6503
6597
  } finally {
6504
6598
  heldLocks.delete(lockPath);
6505
6599
  try {
6506
- const raw = await fs7.readFile(`${lockPath}/owner.json`);
6600
+ const raw = await fs9.readFile(`${lockPath}/owner.json`);
6507
6601
  const parsed = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` }));
6508
6602
  if (parsed.token === token && token) {
6509
- await fs7.rm(lockPath, { recursive: true, force: true });
6603
+ await fs9.rm(lockPath, { recursive: true, force: true });
6510
6604
  }
6511
6605
  } catch {
6512
6606
  }
6513
6607
  }
6514
6608
  }, "withStorageLock");
6515
6609
  readStorageGeneration = /* @__PURE__ */ __name(async (directoryPath) => {
6516
- const fs7 = await nodeFs4();
6610
+ const fs9 = await nodeFs4();
6517
6611
  try {
6518
- const raw = await fs7.readFile(`${directoryPath}/.storage.generation`);
6612
+ const raw = await fs9.readFile(`${directoryPath}/.storage.generation`);
6519
6613
  const value = Number(decodeText(raw, { source: `${directoryPath}/.storage.generation` }).trim());
6520
6614
  return Number.isFinite(value) && value >= 0 ? value : 0;
6521
6615
  } catch {
@@ -6523,11 +6617,11 @@ var init_storage_coordinator = __esm({
6523
6617
  }
6524
6618
  }, "readStorageGeneration");
6525
6619
  writeStorageGeneration = /* @__PURE__ */ __name(async (directoryPath, value) => {
6526
- const fs7 = await nodeFs4();
6527
- await fs7.mkdir(directoryPath, { recursive: true });
6620
+ const fs9 = await nodeFs4();
6621
+ await fs9.mkdir(directoryPath, { recursive: true });
6528
6622
  const temp = `${directoryPath}/.storage.generation.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
6529
- await fs7.writeFile(temp, String(value));
6530
- await fs7.rename(temp, `${directoryPath}/.storage.generation`);
6623
+ await fs9.writeFile(temp, String(value));
6624
+ await fs9.rename(temp, `${directoryPath}/.storage.generation`);
6531
6625
  }, "writeStorageGeneration");
6532
6626
  }
6533
6627
  });
@@ -7040,12 +7134,12 @@ function resolveLanguagePath() {
7040
7134
  function resolveLanguagePreferencePath() {
7041
7135
  return resolveUserLanguagePath();
7042
7136
  }
7043
- function readJsonFile(path5) {
7044
- const fs7 = getSyncFs();
7045
- if (!fs7) return null;
7137
+ function readJsonFile(path8) {
7138
+ const fs9 = getSyncFs();
7139
+ if (!fs9) return null;
7046
7140
  let raw;
7047
7141
  try {
7048
- raw = decodeText(fs7.readFileSync(path5), { source: path5 });
7142
+ raw = decodeText(fs9.readFileSync(path8), { source: path8 });
7049
7143
  } catch {
7050
7144
  return null;
7051
7145
  }
@@ -7078,9 +7172,9 @@ function extractLanguage(value) {
7078
7172
  return null;
7079
7173
  }
7080
7174
  function loadUserLanguage() {
7081
- const fs7 = getSyncFs();
7175
+ const fs9 = getSyncFs();
7082
7176
  const anchor = resolveUserDotMemPath();
7083
- if (fs7) {
7177
+ if (fs9) {
7084
7178
  for (const name of LANGUAGE_FILE_NAMES) {
7085
7179
  const candidatePath = joinPath3(anchor, name);
7086
7180
  const parsed = readJsonFile(candidatePath);
@@ -7142,14 +7236,14 @@ function getResponseLanguage() {
7142
7236
  }
7143
7237
  async function setUserLanguage(language2) {
7144
7238
  const fsMod = await import('fs/promises');
7145
- const path5 = resolveUserLanguagePath();
7146
- const dir = parentStoragePath(path5);
7239
+ const path8 = resolveUserLanguagePath();
7240
+ const dir = parentStoragePath(path8);
7147
7241
  await fsMod.mkdir(dir, { recursive: true });
7148
7242
  const payload = { format: "dotmem.language", version: 1, language: String(language2).trim() };
7149
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
7243
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
7150
7244
  await fsMod.writeFile(temporary, `${JSON.stringify(payload, null, 2)}
7151
7245
  `, "utf8");
7152
- await fsMod.rename(temporary, path5);
7246
+ await fsMod.rename(temporary, path8);
7153
7247
  return payload.language;
7154
7248
  }
7155
7249
  async function saveUserLanguage(language2) {
@@ -10724,11 +10818,11 @@ var init_identity_governance = __esm({
10724
10818
  updatedAt: (/* @__PURE__ */ new Date(0)).toISOString()
10725
10819
  }), "defaultIdentityGovernance");
10726
10820
  loadIdentityGovernance = /* @__PURE__ */ __name((canonicalAgentName) => {
10727
- const fs7 = getSyncFs();
10728
- if (!fs7) return defaultIdentityGovernance(canonicalAgentName);
10821
+ const fs9 = getSyncFs();
10822
+ if (!fs9) return defaultIdentityGovernance(canonicalAgentName);
10729
10823
  let raw;
10730
10824
  try {
10731
- raw = fs7.readFileSync(resolveUserIdentityGovernancePath(), "utf8");
10825
+ raw = fs9.readFileSync(resolveUserIdentityGovernancePath(), "utf8");
10732
10826
  } catch {
10733
10827
  return defaultIdentityGovernance(canonicalAgentName);
10734
10828
  }
@@ -10748,19 +10842,19 @@ var init_identity_governance = __esm({
10748
10842
  authority,
10749
10843
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
10750
10844
  });
10751
- const fs7 = getSyncFs();
10752
- if (!fs7) {
10845
+ const fs9 = getSyncFs();
10846
+ if (!fs9) {
10753
10847
  throw new IdentityGovernanceError("Identity governance write requires filesystem access, unavailable in this runtime");
10754
10848
  }
10755
10849
  const filePath = resolveUserIdentityGovernancePath();
10756
- await fs7.promises.mkdir(parentStoragePath(filePath), { recursive: true });
10850
+ await fs9.promises.mkdir(parentStoragePath(filePath), { recursive: true });
10757
10851
  const temporary = `${filePath}.${process.pid}.${Date.now().toString(36)}.tmp`;
10758
10852
  try {
10759
- await fs7.promises.writeFile(temporary, `${JSON.stringify(document, null, 2)}
10853
+ await fs9.promises.writeFile(temporary, `${JSON.stringify(document, null, 2)}
10760
10854
  `, "utf8");
10761
- await fs7.promises.rename(temporary, filePath);
10855
+ await fs9.promises.rename(temporary, filePath);
10762
10856
  } catch (error) {
10763
- await fs7.promises.rm(temporary, { force: true }).catch(() => void 0);
10857
+ await fs9.promises.rm(temporary, { force: true }).catch(() => void 0);
10764
10858
  throw error;
10765
10859
  }
10766
10860
  return document;
@@ -10957,20 +11051,20 @@ var init_detection_journal = __esm({
10957
11051
  }, "validateDetectionJournalDocument");
10958
11052
  appendDetectionJournal = /* @__PURE__ */ __name(async (events) => {
10959
11053
  if (events.length === 0) return;
10960
- const fs7 = getSyncFs();
10961
- if (!fs7) return;
11054
+ const fs9 = getSyncFs();
11055
+ if (!fs9) return;
10962
11056
  await withPolicyNamespaceLock(async () => {
10963
11057
  await appendDetectionJournalUnlocked(events);
10964
11058
  }, { directory: resolveUserPolicyDir() });
10965
11059
  }, "appendDetectionJournal");
10966
11060
  appendDetectionJournalUnlocked = /* @__PURE__ */ __name(async (events) => {
10967
11061
  if (events.length === 0) return;
10968
- const fs7 = getSyncFs();
10969
- if (!fs7) return;
11062
+ const fs9 = getSyncFs();
11063
+ if (!fs9) return;
10970
11064
  const filePath = resolveUserDetectionJournalPath();
10971
11065
  let document = emptyDetectionJournal();
10972
11066
  try {
10973
- const raw = await fs7.promises.readFile(filePath, "utf8");
11067
+ const raw = await fs9.promises.readFile(filePath, "utf8");
10974
11068
  document = validateDetectionJournalDocument(JSON.parse(raw));
10975
11069
  } catch (error) {
10976
11070
  const code = error?.code;
@@ -10984,22 +11078,22 @@ var init_detection_journal = __esm({
10984
11078
  }
10985
11079
  const merged = [...document.events, ...events].slice(-DETECTION_JOURNAL_RETENTION);
10986
11080
  const dir = filePath.slice(0, Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\")));
10987
- await fs7.promises.mkdir(dir, { recursive: true });
11081
+ await fs9.promises.mkdir(dir, { recursive: true });
10988
11082
  const temporary = `${filePath}.${process.pid}.${Date.now().toString(36)}.tmp`;
10989
11083
  try {
10990
- 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)}
10991
11085
  `, "utf8");
10992
- await fs7.promises.rename(temporary, filePath);
11086
+ await fs9.promises.rename(temporary, filePath);
10993
11087
  } catch (error) {
10994
- await fs7.promises.rm(temporary, { force: true }).catch(() => void 0);
11088
+ await fs9.promises.rm(temporary, { force: true }).catch(() => void 0);
10995
11089
  throw error;
10996
11090
  }
10997
11091
  }, "appendDetectionJournalUnlocked");
10998
11092
  loadDetectionJournal = /* @__PURE__ */ __name(async () => {
10999
- const fs7 = getSyncFs();
11000
- if (!fs7) return emptyDetectionJournal();
11093
+ const fs9 = getSyncFs();
11094
+ if (!fs9) return emptyDetectionJournal();
11001
11095
  try {
11002
- const raw = await fs7.promises.readFile(resolveUserDetectionJournalPath(), "utf8");
11096
+ const raw = await fs9.promises.readFile(resolveUserDetectionJournalPath(), "utf8");
11003
11097
  return validateDetectionJournalDocument(JSON.parse(raw));
11004
11098
  } catch {
11005
11099
  return emptyDetectionJournal();
@@ -11075,11 +11169,11 @@ var init_store_queue = __esm({
11075
11169
  async function resolveProjectIdentity(cwd, hints) {
11076
11170
  const explicit = sanitizeIdentity(process.env.DOTMEM_PROJECT_ID);
11077
11171
  if (explicit) return explicit;
11078
- const fs7 = await import('fs/promises');
11172
+ const fs9 = await import('fs/promises');
11079
11173
  const pkgPath = cwd.endsWith("/") || cwd.endsWith("\\") ? `${cwd}package.json` : `${cwd}/package.json`;
11080
11174
  let pkgJson;
11081
11175
  try {
11082
- const content = await fs7.readFile(pkgPath, "utf8");
11176
+ const content = await fs9.readFile(pkgPath, "utf8");
11083
11177
  pkgJson = JSON.parse(content);
11084
11178
  } catch {
11085
11179
  }
@@ -11224,8 +11318,8 @@ var init_staging = __esm({
11224
11318
  };
11225
11319
  const requestId = generateRequestId();
11226
11320
  const stagePath = stagePathFor(requestId);
11227
- const fs7 = await nodeFs6();
11228
- await fs7.mkdir(resolveStagingDirectory(), { recursive: true });
11321
+ const fs9 = await nodeFs6();
11322
+ await fs9.mkdir(resolveStagingDirectory(), { recursive: true });
11229
11323
  const stageFile = {
11230
11324
  format: DOTMEM_STAGE_FORMAT,
11231
11325
  version: DOTMEM_STAGE_VERSION,
@@ -11234,9 +11328,9 @@ var init_staging = __esm({
11234
11328
  ...sourceProject ? { sourceProject } : {},
11235
11329
  claim: sanitizedClaim
11236
11330
  };
11237
- await fs7.writeFile(stagePath, JSON.stringify(stageFile), { mode: 384 });
11331
+ await fs9.writeFile(stagePath, JSON.stringify(stageFile), { mode: 384 });
11238
11332
  try {
11239
- await fs7.access(stagePath);
11333
+ await fs9.access(stagePath);
11240
11334
  } catch {
11241
11335
  throw new StageFileError(`Stage file write verification failed: ${requestId} does not exist on disk`, requestId);
11242
11336
  }
@@ -11244,9 +11338,9 @@ var init_staging = __esm({
11244
11338
  }, "writeStageFile");
11245
11339
  readStageFile = /* @__PURE__ */ __name(async (requestId) => {
11246
11340
  const stagePath = stagePathFor(requestId);
11247
- const fs7 = await nodeFs6();
11341
+ const fs9 = await nodeFs6();
11248
11342
  try {
11249
- const content = await fs7.readFile(stagePath, "utf8");
11343
+ const content = await fs9.readFile(stagePath, "utf8");
11250
11344
  return JSON.parse(content);
11251
11345
  } catch (error) {
11252
11346
  if (error.code === "ENOENT") {
@@ -11359,9 +11453,9 @@ var init_staging = __esm({
11359
11453
  }, "commitStageFile");
11360
11454
  cleanupStageFile = /* @__PURE__ */ __name(async (requestId) => {
11361
11455
  const stagePath = stagePathFor(requestId);
11362
- const fs7 = await nodeFs6();
11456
+ const fs9 = await nodeFs6();
11363
11457
  try {
11364
- await fs7.unlink(stagePath);
11458
+ await fs9.unlink(stagePath);
11365
11459
  } catch (error) {
11366
11460
  if (error.code !== "ENOENT") {
11367
11461
  throw error;
@@ -11370,19 +11464,19 @@ var init_staging = __esm({
11370
11464
  }, "cleanupStageFile");
11371
11465
  cleanupStaleStages = /* @__PURE__ */ __name(async (maxAgeMs = 24 * 60 * 60 * 1e3) => {
11372
11466
  const stagingDir = resolveStagingDirectory();
11373
- const fs7 = await nodeFs6();
11467
+ const fs9 = await nodeFs6();
11374
11468
  let count = 0;
11375
11469
  try {
11376
- const entries2 = await fs7.readdir(stagingDir, { withFileTypes: true });
11470
+ const entries2 = await fs9.readdir(stagingDir, { withFileTypes: true });
11377
11471
  const now2 = Date.now();
11378
11472
  for (const entry of entries2) {
11379
11473
  if (!entry.isFile() || !entry.name.endsWith(".stage")) continue;
11380
11474
  const filePath = `${stagingDir}/${entry.name}`;
11381
11475
  try {
11382
- const stat = await fs7.stat(filePath);
11476
+ const stat = await fs9.stat(filePath);
11383
11477
  const age = now2 - stat.mtimeMs;
11384
11478
  if (age > maxAgeMs) {
11385
- await fs7.unlink(filePath);
11479
+ await fs9.unlink(filePath);
11386
11480
  count++;
11387
11481
  }
11388
11482
  } catch {
@@ -11406,25 +11500,25 @@ function joinPath4(base, child) {
11406
11500
  function resolveLoopsFilePath() {
11407
11501
  return joinPath4(resolveUserDotMemPath(), LOOPS_FILE_NAME);
11408
11502
  }
11409
- async function readFile(path5) {
11503
+ async function readFile(path8) {
11410
11504
  try {
11411
- const fs7 = await import('fs/promises');
11412
- return await fs7.readFile(path5, "utf8");
11505
+ const fs9 = await import('fs/promises');
11506
+ return await fs9.readFile(path8, "utf8");
11413
11507
  } catch {
11414
11508
  return null;
11415
11509
  }
11416
11510
  }
11417
- async function writeFile(path5, content) {
11418
- const fs7 = await import('fs/promises');
11419
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
11420
- await fs7.mkdir(dir, { recursive: true });
11421
- 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`;
11422
11516
  try {
11423
- await fs7.writeFile(temporary, content, "utf8");
11424
- await fs7.rename(temporary, path5);
11517
+ await fs9.writeFile(temporary, content, "utf8");
11518
+ await fs9.rename(temporary, path8);
11425
11519
  } catch {
11426
- await fs7.rm(temporary, { force: true }).catch(() => void 0);
11427
- 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}`);
11428
11522
  }
11429
11523
  }
11430
11524
  function emptyDocument() {
@@ -11845,9 +11939,9 @@ async function getCommittedFiles() {
11845
11939
  return result.stdout.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
11846
11940
  }
11847
11941
  async function getFileContent(filePath) {
11848
- const fs7 = await import('fs/promises');
11942
+ const fs9 = await import('fs/promises');
11849
11943
  try {
11850
- return await fs7.readFile(filePath, "utf8");
11944
+ return await fs9.readFile(filePath, "utf8");
11851
11945
  } catch {
11852
11946
  return null;
11853
11947
  }
@@ -11963,25 +12057,25 @@ function joinPath5(base, child) {
11963
12057
  function resolveVaultFilePath() {
11964
12058
  return joinPath5(resolveUserDotMemPath(), VAULT_FILE_NAME);
11965
12059
  }
11966
- async function readFile2(path5) {
12060
+ async function readFile2(path8) {
11967
12061
  try {
11968
- const fs7 = await import('fs/promises');
11969
- return await fs7.readFile(path5, "utf8");
12062
+ const fs9 = await import('fs/promises');
12063
+ return await fs9.readFile(path8, "utf8");
11970
12064
  } catch {
11971
12065
  return null;
11972
12066
  }
11973
12067
  }
11974
- async function writeFile2(path5, content) {
11975
- const fs7 = await import('fs/promises');
11976
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
11977
- await fs7.mkdir(dir, { recursive: true });
11978
- 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`;
11979
12073
  try {
11980
- await fs7.writeFile(temporary, content, "utf8");
11981
- await fs7.rename(temporary, path5);
12074
+ await fs9.writeFile(temporary, content, "utf8");
12075
+ await fs9.rename(temporary, path8);
11982
12076
  } catch {
11983
- await fs7.rm(temporary, { force: true }).catch(() => void 0);
11984
- 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}`);
11985
12079
  }
11986
12080
  }
11987
12081
  function emptyDocument2() {
@@ -12099,9 +12193,9 @@ function joinPath6(base, child) {
12099
12193
  return `${base.replace(/[\\/]+/g, separator3)}${separator3}${child}`;
12100
12194
  }
12101
12195
  async function readJsonFile2(filePath, pointer) {
12102
- const fs7 = await import('fs/promises');
12196
+ const fs9 = await import('fs/promises');
12103
12197
  try {
12104
- const content = await fs7.readFile(filePath, "utf8");
12198
+ const content = await fs9.readFile(filePath, "utf8");
12105
12199
  const data = JSON.parse(content);
12106
12200
  const pathParts = pointer.replace(/^\//, "").split("/").filter((p) => p.length > 0);
12107
12201
  let current = data;
@@ -12164,6 +12258,39 @@ async function evaluateClaim(claim) {
12164
12258
  detail: `Value is ${result.valueStr}, expected ${expected}`
12165
12259
  };
12166
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
+ }
12167
12294
  return {
12168
12295
  claimId: claim.id,
12169
12296
  probe,
@@ -12249,214 +12376,748 @@ function formatVerifyResult(result) {
12249
12376
  }
12250
12377
  return lines.join("\n");
12251
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
+ }
12252
12423
  var init_verify = __esm({
12253
12424
  "core/knowledge/verify.ts"() {
12254
12425
  init_state();
12426
+ init_verification();
12255
12427
  __name(joinPath6, "joinPath");
12256
12428
  __name(readJsonFile2, "readJsonFile");
12257
12429
  __name(evaluateClaim, "evaluateClaim");
12258
12430
  __name(isDue, "isDue");
12259
12431
  __name(verifyDueClaims, "verifyDueClaims");
12260
12432
  __name(formatVerifyResult, "formatVerifyResult");
12433
+ __name(applyVerification, "applyVerification");
12434
+ __name(verifyAndPersistClaims, "verifyAndPersistClaims");
12261
12435
  }
12262
12436
  });
12263
12437
 
12264
- // core/knowledge/context-budget.ts
12265
- function estimateTokens(text) {
12266
- return Math.ceil(text.length / 4);
12267
- }
12268
- function estimateClaimSize(claim) {
12269
- const serialized = JSON.stringify(claim.knowledge ?? {});
12270
- const characters = serialized.length;
12271
- return { tokens: estimateTokens(serialized), characters };
12272
- }
12273
- function calculateBudgetUsage(claims, budget) {
12274
- let totalChars = 0;
12275
- for (const claim of claims) {
12276
- totalChars += estimateClaimSize(claim).characters;
12277
- }
12278
- const tokens = estimateTokens(String(totalChars));
12279
- const utilization = budget === "unlimited" || budget === 0 ? 1 : Math.min(totalChars / (budget * 4), 1);
12280
- return {
12281
- tokens,
12282
- characters: totalChars,
12283
- claimCount: claims.length,
12284
- budget,
12285
- utilization
12286
- };
12287
- }
12288
- function explainBudgetAllocation(included, excluded, budget) {
12289
- const result = {
12290
- included: included.map((claim) => {
12291
- const size = estimateClaimSize(claim);
12292
- return {
12293
- claimId: claim.id,
12294
- reason: "matched discovery",
12295
- estimatedTokens: size.tokens,
12296
- estimatedCharacters: size.characters
12297
- };
12298
- }),
12299
- excluded: excluded.map((item) => ({
12300
- claimId: item.id,
12301
- reason: item.reason
12302
- })),
12303
- total: calculateBudgetUsage(included, budget)
12304
- };
12305
- if (result.total.utilization >= 0.9 && budget !== "unlimited") {
12306
- result.excluded.push({
12307
- claimId: "__budget__",
12308
- reason: `Budget at ${Math.round(result.total.utilization * 100)}% utilization (${result.total.tokens} tokens of ${budget})`
12309
- });
12310
- }
12311
- return result;
12312
- }
12313
- function formatBudgetExplanation(explanation) {
12314
- const lines = [
12315
- "Context Budget Report",
12316
- "",
12317
- `Total claims included: ${explanation.total.claimCount}`,
12318
- `Estimated tokens: ${explanation.total.tokens}`,
12319
- `Budget: ${explanation.total.budget === "unlimited" ? "unlimited" : explanation.total.budget}`,
12320
- `Utilization: ${Math.round(explanation.total.utilization * 100)}%`,
12321
- ""
12322
- ];
12323
- if (explanation.included.length > 0) {
12324
- lines.push("Included claims:");
12325
- for (const item of explanation.included) {
12326
- lines.push(` [${item.claimId}] ${item.estimatedTokens} tokens \u2014 ${item.reason}`);
12327
- }
12328
- lines.push("");
12329
- }
12330
- if (explanation.excluded.length > 0) {
12331
- lines.push("Excluded claims:");
12332
- for (const item of explanation.excluded) {
12333
- lines.push(` [${item.claimId}] ${item.reason}`);
12334
- }
12335
- lines.push("");
12336
- }
12337
- return lines.join("\n");
12338
- }
12339
- var init_context_budget = __esm({
12340
- "core/knowledge/context-budget.ts"() {
12341
- __name(estimateTokens, "estimateTokens");
12342
- __name(estimateClaimSize, "estimateClaimSize");
12343
- __name(calculateBudgetUsage, "calculateBudgetUsage");
12344
- __name(explainBudgetAllocation, "explainBudgetAllocation");
12345
- __name(formatBudgetExplanation, "formatBudgetExplanation");
12346
- }
12347
- });
12348
-
12349
- // core/knowledge/feedback.ts
12438
+ // core/knowledge/violations.ts
12350
12439
  function joinPath7(base, child) {
12351
12440
  const separator3 = process.platform === "win32" ? "\\" : "/";
12352
12441
  return `${base.replace(/[\\/]+/g, separator3)}${separator3}${child}`;
12353
12442
  }
12354
- function resolveFeedbackFilePath() {
12355
- return joinPath7(resolveUserDotMemPath(), FEEDBACK_FILE_NAME);
12443
+ function resolveViolationFilePath() {
12444
+ return joinPath7(resolveUserDotMemPath(), VIOLATION_FILE_NAME);
12356
12445
  }
12357
- async function readFile3(path5) {
12446
+ async function readFile3(path8) {
12358
12447
  try {
12359
- const fs7 = await import('fs/promises');
12360
- return await fs7.readFile(path5, "utf8");
12448
+ const fs9 = await import('fs/promises');
12449
+ return await fs9.readFile(path8, "utf8");
12361
12450
  } catch {
12362
12451
  return null;
12363
12452
  }
12364
12453
  }
12365
- async function writeFile3(path5, content) {
12366
- const fs7 = await import('fs/promises');
12367
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
12368
- await fs7.mkdir(dir, { recursive: true });
12369
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
12370
- await fs7.writeFile(temporary, content, "utf8");
12371
- 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);
12372
12461
  }
12373
- async function loadFeedback() {
12374
- const raw = await readFile3(resolveFeedbackFilePath());
12375
- 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: [] };
12376
12465
  try {
12377
12466
  const parsed = JSON.parse(raw);
12378
- if (parsed.version === FEEDBACK_FORMAT_VERSION && Array.isArray(parsed.entries)) {
12379
- 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 };
12380
12469
  }
12381
12470
  } catch {
12382
12471
  }
12383
- return { version: FEEDBACK_FORMAT_VERSION, entries: [] };
12472
+ return { version: VIOLATION_FORMAT_VERSION, entries: [] };
12384
12473
  }
12385
- async function saveFeedback(document) {
12386
- await writeFile3(resolveFeedbackFilePath(), JSON.stringify(document, null, 2) + "\n");
12474
+ async function saveViolations(document) {
12475
+ await writeFile3(resolveViolationFilePath(), JSON.stringify(document, null, 2) + "\n");
12387
12476
  }
12388
- function validateFeedbackEntry(entry) {
12389
- if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
12390
- throw new Error("Feedback entry must be an object");
12391
- }
12392
- const feedback = entry;
12393
- if (typeof feedback.claimId !== "string" || !feedback.claimId) {
12394
- throw new Error("Feedback entry requires a claimId");
12395
- }
12396
- if (typeof feedback.kind !== "string" || !VALID_KINDS.has(feedback.kind)) {
12397
- throw new Error(`Feedback entry has invalid kind: ${String(feedback.kind)}`);
12398
- }
12399
- if (typeof feedback.recordedAt !== "string") {
12400
- throw new Error("Feedback entry requires a recordedAt timestamp");
12401
- }
12402
- return {
12403
- claimId: feedback.claimId,
12404
- kind: feedback.kind,
12405
- note: typeof feedback.note === "string" ? feedback.note : void 0,
12406
- recordedAt: feedback.recordedAt
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
12407
12484
  };
12485
+ document.entries.push(record);
12486
+ await saveViolations(document);
12487
+ return record;
12408
12488
  }
12409
- async function recordFeedback(claimId, kind, note) {
12410
- if (!VALID_KINDS.has(kind)) {
12411
- throw new Error(`Invalid feedback kind: ${kind}`);
12412
- }
12413
- const document = await loadFeedback();
12414
- const entry = {
12415
- claimId,
12416
- kind,
12417
- note,
12418
- recordedAt: (/* @__PURE__ */ new Date()).toISOString()
12419
- };
12420
- document.entries.push(entry);
12421
- await saveFeedback(document);
12422
- return entry;
12489
+ async function countViolations(ruleId) {
12490
+ const document = await loadViolations();
12491
+ return document.entries.filter((e) => e.ruleId === ruleId).length;
12423
12492
  }
12424
- async function getFeedbackForClaim(claimId) {
12425
- const document = await loadFeedback();
12426
- return document.entries.filter((e) => e.claimId === claimId);
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;
12427
12497
  }
12428
- async function getFeedbackSummary() {
12429
- const document = await loadFeedback();
12430
- const summary = { helped: 0, misled: 0, ignored: 0 };
12431
- for (const entry of document.entries) {
12432
- summary[entry.kind]++;
12433
- }
12434
- return summary;
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);
12435
12502
  }
12436
- function summarizeFeedbackWeights(feedback) {
12437
- return {
12438
- helpedWeight: feedback.filter((e) => e.kind === "helped").length,
12439
- misledWeight: feedback.filter((e) => e.kind === "misled").length,
12440
- ignoredWeight: feedback.filter((e) => e.kind === "ignored").length
12441
- };
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;
12442
12513
  }
12443
- var FEEDBACK_FILE_NAME, FEEDBACK_FORMAT_VERSION, VALID_KINDS;
12444
- var init_feedback = __esm({
12445
- "core/knowledge/feedback.ts"() {
12514
+ var VIOLATION_FILE_NAME, VIOLATION_FORMAT_VERSION;
12515
+ var init_violations = __esm({
12516
+ "core/knowledge/violations.ts"() {
12446
12517
  init_user_paths();
12447
- FEEDBACK_FILE_NAME = "feedback.json";
12448
- FEEDBACK_FORMAT_VERSION = 1;
12518
+ VIOLATION_FILE_NAME = "violations.json";
12519
+ VIOLATION_FORMAT_VERSION = 1;
12449
12520
  __name(joinPath7, "joinPath");
12450
- __name(resolveFeedbackFilePath, "resolveFeedbackFilePath");
12521
+ __name(resolveViolationFilePath, "resolveViolationFilePath");
12451
12522
  __name(readFile3, "readFile");
12452
12523
  __name(writeFile3, "writeFile");
12453
- VALID_KINDS = /* @__PURE__ */ new Set(["helped", "misled", "ignored"]);
12454
- __name(loadFeedback, "loadFeedback");
12455
- __name(saveFeedback, "saveFeedback");
12456
- __name(validateFeedbackEntry, "validateFeedbackEntry");
12457
- __name(recordFeedback, "recordFeedback");
12458
- __name(getFeedbackForClaim, "getFeedbackForClaim");
12459
- __name(getFeedbackSummary, "getFeedbackSummary");
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)) {
13051
+ throw new Error("Feedback entry must be an object");
13052
+ }
13053
+ const feedback = entry;
13054
+ if (typeof feedback.claimId !== "string" || !feedback.claimId) {
13055
+ throw new Error("Feedback entry requires a claimId");
13056
+ }
13057
+ if (typeof feedback.kind !== "string" || !VALID_KINDS.has(feedback.kind)) {
13058
+ throw new Error(`Feedback entry has invalid kind: ${String(feedback.kind)}`);
13059
+ }
13060
+ if (typeof feedback.recordedAt !== "string") {
13061
+ throw new Error("Feedback entry requires a recordedAt timestamp");
13062
+ }
13063
+ return {
13064
+ claimId: feedback.claimId,
13065
+ kind: feedback.kind,
13066
+ note: typeof feedback.note === "string" ? feedback.note : void 0,
13067
+ recordedAt: feedback.recordedAt
13068
+ };
13069
+ }
13070
+ async function recordFeedback(claimId, kind, note) {
13071
+ if (!VALID_KINDS.has(kind)) {
13072
+ throw new Error(`Invalid feedback kind: ${kind}`);
13073
+ }
13074
+ const document = await loadFeedback();
13075
+ const entry = {
13076
+ claimId,
13077
+ kind,
13078
+ note,
13079
+ recordedAt: (/* @__PURE__ */ new Date()).toISOString()
13080
+ };
13081
+ document.entries.push(entry);
13082
+ await saveFeedback(document);
13083
+ return entry;
13084
+ }
13085
+ async function getFeedbackForClaim(claimId) {
13086
+ const document = await loadFeedback();
13087
+ return document.entries.filter((e) => e.claimId === claimId);
13088
+ }
13089
+ async function getFeedbackSummary() {
13090
+ const document = await loadFeedback();
13091
+ const summary = { helped: 0, misled: 0, ignored: 0 };
13092
+ for (const entry of document.entries) {
13093
+ summary[entry.kind]++;
13094
+ }
13095
+ return summary;
13096
+ }
13097
+ function summarizeFeedbackWeights(feedback) {
13098
+ return {
13099
+ helpedWeight: feedback.filter((e) => e.kind === "helped").length,
13100
+ misledWeight: feedback.filter((e) => e.kind === "misled").length,
13101
+ ignoredWeight: feedback.filter((e) => e.kind === "ignored").length
13102
+ };
13103
+ }
13104
+ var FEEDBACK_FILE_NAME, FEEDBACK_FORMAT_VERSION, VALID_KINDS;
13105
+ var init_feedback = __esm({
13106
+ "core/knowledge/feedback.ts"() {
13107
+ init_user_paths();
13108
+ FEEDBACK_FILE_NAME = "feedback.json";
13109
+ FEEDBACK_FORMAT_VERSION = 1;
13110
+ __name(joinPath8, "joinPath");
13111
+ __name(resolveFeedbackFilePath, "resolveFeedbackFilePath");
13112
+ __name(readFile4, "readFile");
13113
+ __name(writeFile4, "writeFile");
13114
+ VALID_KINDS = /* @__PURE__ */ new Set(["helped", "misled", "ignored"]);
13115
+ __name(loadFeedback, "loadFeedback");
13116
+ __name(saveFeedback, "saveFeedback");
13117
+ __name(validateFeedbackEntry, "validateFeedbackEntry");
13118
+ __name(recordFeedback, "recordFeedback");
13119
+ __name(getFeedbackForClaim, "getFeedbackForClaim");
13120
+ __name(getFeedbackSummary, "getFeedbackSummary");
12460
13121
  __name(summarizeFeedbackWeights, "summarizeFeedbackWeights");
12461
13122
  }
12462
13123
  });
@@ -12512,332 +13173,120 @@ var init_correction = __esm({
12512
13173
  function findIncidentById(id) {
12513
13174
  return INCIDENT_EVAL_TEST_SET.find((incident) => incident.id === id);
12514
13175
  }
12515
- function listIncidents() {
12516
- return [...INCIDENT_EVAL_TEST_SET];
12517
- }
12518
- function buildIncidentState(overrides = {}) {
12519
- const baseClaims = [
12520
- {
12521
- id: "behavior:watch-files",
12522
- epistemicType: "observed",
12523
- applicability: { verified: true },
12524
- evidence: [{ id: "ev-watch-1", observedAt: "2026-01-01T00:00:00Z" }],
12525
- knowledge: { trigger: "file watching", rule: "watch files with watch tool" },
12526
- acquiredAt: "2026-01-01T00:00:00Z"
12527
- },
12528
- {
12529
- id: "behavior:state-engine",
12530
- epistemicType: "observed",
12531
- applicability: { verified: true },
12532
- evidence: [{ id: "ev-state-1", observedAt: "2026-01-01T00:00:00Z" }],
12533
- knowledge: { trigger: "state engine", rule: "state is foundation" },
12534
- acquiredAt: "2026-01-01T00:00:00Z"
12535
- },
12536
- {
12537
- id: "behavior:git-push-guard",
12538
- epistemicType: "observed",
12539
- applicability: { verified: true },
12540
- evidence: [{ id: "ev-push-1", observedAt: "2026-01-01T00:00:00Z" }],
12541
- knowledge: { trigger: "git push", rule: "guard git operations" },
12542
- acquiredAt: "2026-01-01T00:00:00Z"
12543
- },
12544
- {
12545
- id: "behavior:memory-layer",
12546
- epistemicType: "observed",
12547
- applicability: { verified: true },
12548
- evidence: [{ id: "ev-mem-1", observedAt: "2026-01-01T00:00:00Z" }],
12549
- knowledge: { trigger: "memory", rule: "memory is state plus store" },
12550
- acquiredAt: "2026-01-01T00:00:00Z"
12551
- },
12552
- {
12553
- id: "project:current-project",
12554
- epistemicType: "observed",
12555
- applicability: { scope: "project", verified: true },
12556
- evidence: [{ id: "ev-proj-1", observedAt: "2026-01-01T00:00:00Z" }],
12557
- knowledge: { trigger: "current project", anchor: "project root" },
12558
- acquiredAt: "2026-01-01T00:00:00Z"
12559
- }
12560
- ];
12561
- return {
12562
- version: 1,
12563
- claims: [...baseClaims, ...overrides.claims ?? []]
12564
- };
12565
- }
12566
- function evaluateIncident(incident, matchedClaims) {
12567
- const got = matchedClaims;
12568
- const missing = incident.expectedClaimIds.filter((id) => !got.includes(id));
12569
- const unexpected = got.filter((id) => !incident.expectedClaimIds.includes(id));
12570
- return {
12571
- incidentId: incident.id,
12572
- passed: missing.length === 0 && unexpected.length === 0,
12573
- expected: incident.expectedClaimIds,
12574
- got,
12575
- missing,
12576
- unexpected
12577
- };
12578
- }
12579
- function formatIncidentReport(report) {
12580
- const lines = [
12581
- `Incident Eval Report: ${report.passed}/${report.total} passed`,
12582
- ""
12583
- ];
12584
- for (const result of report.results) {
12585
- const status = result.passed ? "PASS" : "FAIL";
12586
- lines.push(`[${status}] ${result.incidentId}`);
12587
- if (!result.passed) {
12588
- if (result.missing.length > 0) {
12589
- lines.push(` Missing: ${result.missing.join(", ")}`);
12590
- }
12591
- if (result.unexpected.length > 0) {
12592
- lines.push(` Unexpected: ${result.unexpected.join(", ")}`);
12593
- }
12594
- }
12595
- }
12596
- return lines.join("\n");
12597
- }
12598
- var INCIDENT_EVAL_TEST_SET;
12599
- var init_incidents = __esm({
12600
- "core/knowledge/incidents.ts"() {
12601
- INCIDENT_EVAL_TEST_SET = [
12602
- {
12603
- id: "incident-001",
12604
- situation: "user asks about file watching",
12605
- expectedClaimIds: ["behavior:watch-files"],
12606
- excludedIds: ["behavior:state-engine"],
12607
- description: "File watching should pull the watch-files rule, not the state engine rule"
12608
- },
12609
- {
12610
- id: "incident-002",
12611
- situation: "user asks about git push",
12612
- expectedClaimIds: ["behavior:git-push-guard"],
12613
- excludedIds: ["behavior:memory-layer"],
12614
- description: "Git push should trigger the push guard, not the memory layer"
12615
- },
12616
- {
12617
- id: "incident-003",
12618
- situation: "current project context",
12619
- expectedClaimIds: ["project:current-project"],
12620
- excludedIds: ["behavior:state-engine"],
12621
- description: "Current project situation should surface the project anchor claim"
12622
- }
12623
- ];
12624
- __name(findIncidentById, "findIncidentById");
12625
- __name(listIncidents, "listIncidents");
12626
- __name(buildIncidentState, "buildIncidentState");
12627
- __name(evaluateIncident, "evaluateIncident");
12628
- __name(formatIncidentReport, "formatIncidentReport");
12629
- }
12630
- });
12631
-
12632
- // core/knowledge/violations.ts
12633
- function joinPath8(base, child) {
12634
- const separator3 = process.platform === "win32" ? "\\" : "/";
12635
- return `${base.replace(/[\\/]+/g, separator3)}${separator3}${child}`;
12636
- }
12637
- function resolveViolationFilePath() {
12638
- return joinPath8(resolveUserDotMemPath(), VIOLATION_FILE_NAME);
12639
- }
12640
- async function readFile4(path5) {
12641
- try {
12642
- const fs7 = await import('fs/promises');
12643
- return await fs7.readFile(path5, "utf8");
12644
- } catch {
12645
- return null;
12646
- }
12647
- }
12648
- async function writeFile4(path5, content) {
12649
- const fs7 = await import('fs/promises');
12650
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
12651
- await fs7.mkdir(dir, { recursive: true });
12652
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
12653
- await fs7.writeFile(temporary, content, "utf8");
12654
- await fs7.rename(temporary, path5);
12655
- }
12656
- async function loadViolations() {
12657
- const raw = await readFile4(resolveViolationFilePath());
12658
- if (!raw) return { version: VIOLATION_FORMAT_VERSION, entries: [] };
12659
- try {
12660
- const parsed = JSON.parse(raw);
12661
- if (parsed.version === VIOLATION_FORMAT_VERSION && Array.isArray(parsed.entries)) {
12662
- return { version: VIOLATION_FORMAT_VERSION, entries: parsed.entries };
12663
- }
12664
- } catch {
12665
- }
12666
- return { version: VIOLATION_FORMAT_VERSION, entries: [] };
12667
- }
12668
- async function saveViolations(document) {
12669
- await writeFile4(resolveViolationFilePath(), JSON.stringify(document, null, 2) + "\n");
12670
- }
12671
- async function logViolation(ruleId, situation, description = "") {
12672
- const document = await loadViolations();
12673
- const record = {
12674
- ruleId,
12675
- violatedAt: (/* @__PURE__ */ new Date()).toISOString(),
12676
- description,
12677
- situation
12678
- };
12679
- document.entries.push(record);
12680
- await saveViolations(document);
12681
- return record;
12682
- }
12683
- async function countViolations(ruleId) {
12684
- const document = await loadViolations();
12685
- return document.entries.filter((e) => e.ruleId === ruleId).length;
12686
- }
12687
- async function lastViolation(ruleId) {
12688
- const document = await loadViolations();
12689
- const entries2 = document.entries.filter((e) => e.ruleId === ruleId).sort((a, b) => b.violatedAt.localeCompare(a.violatedAt));
12690
- return entries2[0]?.violatedAt;
12691
- }
12692
- async function listViolations(ruleId) {
12693
- const document = await loadViolations();
12694
- if (!ruleId) return document.entries;
12695
- return document.entries.filter((e) => e.ruleId === ruleId);
12696
- }
12697
- async function clearViolations(ruleId) {
12698
- const document = await loadViolations();
12699
- const beforeCount = document.entries.length;
12700
- if (ruleId) {
12701
- document.entries = document.entries.filter((e) => e.ruleId !== ruleId);
12702
- } else {
12703
- document.entries = [];
12704
- }
12705
- await saveViolations(document);
12706
- return beforeCount - document.entries.length;
12707
- }
12708
- var VIOLATION_FILE_NAME, VIOLATION_FORMAT_VERSION;
12709
- var init_violations = __esm({
12710
- "core/knowledge/violations.ts"() {
12711
- init_user_paths();
12712
- VIOLATION_FILE_NAME = "violations.json";
12713
- VIOLATION_FORMAT_VERSION = 1;
12714
- __name(joinPath8, "joinPath");
12715
- __name(resolveViolationFilePath, "resolveViolationFilePath");
12716
- __name(readFile4, "readFile");
12717
- __name(writeFile4, "writeFile");
12718
- __name(loadViolations, "loadViolations");
12719
- __name(saveViolations, "saveViolations");
12720
- __name(logViolation, "logViolation");
12721
- __name(countViolations, "countViolations");
12722
- __name(lastViolation, "lastViolation");
12723
- __name(listViolations, "listViolations");
12724
- __name(clearViolations, "clearViolations");
12725
- }
12726
- });
12727
- function isRuleClaim(claim) {
12728
- const knowledge = claim.knowledge;
12729
- return knowledge?.kind === "rule";
12730
- }
12731
- function isIronRule(claim) {
12732
- return claim.epistemicType === "human-stated" && isRuleClaim(claim);
12733
- }
12734
- function extractIronRules(state2, violations = {}) {
12735
- const validated = validateKnowledgeState(state2);
12736
- const claims = activeClaims(validated);
12737
- const rules = [];
12738
- for (const claim of claims) {
12739
- if (!isIronRule(claim)) continue;
12740
- const knowledge = claim.knowledge;
12741
- const applicability = claim.applicability;
12742
- const iron = applicability.iron === true || applicability.priority === "iron";
12743
- if (!iron) continue;
12744
- rules.push({
12745
- id: claim.id,
12746
- text: String(knowledge.text ?? knowledge.rule ?? claim.id),
12747
- why: String(knowledge.why ?? knowledge.reason ?? ""),
12748
- appliesWhen: String(knowledge.appliesWhen ?? knowledge.when ?? ""),
12749
- violatedOn: Array.isArray(knowledge.violatedOn) ? knowledge.violatedOn : void 0,
12750
- lastViolation: typeof knowledge.lastViolation === "string" ? knowledge.lastViolation : void 0,
12751
- frequency: typeof knowledge.frequency === "number" ? knowledge.frequency : violations[claim.id] ?? 0
12752
- });
12753
- }
12754
- return rules;
12755
- }
12756
- function sortRulesByViolationFrequency(rules) {
12757
- return [...rules].sort((a, b) => {
12758
- if (b.frequency !== a.frequency) return b.frequency - a.frequency;
12759
- if (a.lastViolation && b.lastViolation) {
12760
- return b.lastViolation.localeCompare(a.lastViolation);
13176
+ function listIncidents() {
13177
+ return [...INCIDENT_EVAL_TEST_SET];
13178
+ }
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"
12761
13220
  }
12762
- return 0;
12763
- });
13221
+ ];
13222
+ return {
13223
+ version: 1,
13224
+ claims: [...baseClaims, ...overrides.claims ?? []]
13225
+ };
12764
13226
  }
12765
- function loadIronRules(state2) {
12766
- const rules = sortRulesByViolationFrequency(
12767
- extractIronRules(state2, readViolationCounts(`${resolveUserDotMemPath()}/${VIOLATION_FILE_NAME}`))
12768
- );
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));
12769
13231
  return {
12770
- rules,
12771
- count: rules.length,
12772
- sortedBy: "violation-frequency"
13232
+ incidentId: incident.id,
13233
+ passed: missing.length === 0 && unexpected.length === 0,
13234
+ expected: incident.expectedClaimIds,
13235
+ got,
13236
+ missing,
13237
+ unexpected
12773
13238
  };
12774
13239
  }
12775
- function formatRulesForSessionStart(rules) {
12776
- if (rules.length === 0) {
12777
- return "";
12778
- }
12779
- const lines = ["---", "IRON RULES (must always arrive)", "---"];
12780
- for (const rule of rules) {
12781
- lines.push(`${rule.id}: ${rule.text}`);
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
+ }
12782
13256
  }
12783
13257
  return lines.join("\n");
12784
13258
  }
12785
- function formatRuleWithExplanation(rule) {
12786
- const parts = [];
12787
- parts.push(`[${rule.id}] ${rule.text}`);
12788
- if (rule.why) parts.push(` WHY: ${rule.why}`);
12789
- if (rule.appliesWhen) parts.push(` APPLIES WHEN: ${rule.appliesWhen}`);
12790
- if (rule.violatedOn && rule.violatedOn.length > 0) {
12791
- parts.push(` VIOLATED ${rule.violatedOn.length} TIME(S)`);
12792
- if (rule.lastViolation) parts.push(` Last: ${rule.lastViolation}`);
12793
- }
12794
- return parts.join("\n");
12795
- }
12796
- var readViolationCounts, ruleSetSignature, formatRulesReference;
12797
- var init_rules_loader = __esm({
12798
- "core/knowledge/rules-loader.ts"() {
12799
- init_state();
12800
- init_user_paths();
12801
- init_violations();
12802
- __name(isRuleClaim, "isRuleClaim");
12803
- __name(isIronRule, "isIronRule");
12804
- __name(extractIronRules, "extractIronRules");
12805
- readViolationCounts = /* @__PURE__ */ __name((file) => {
12806
- try {
12807
- const parsed = JSON.parse(readFileSync(file, "utf8"));
12808
- const counts = {};
12809
- for (const violation of Array.isArray(parsed.violations) ? parsed.violations : []) {
12810
- const ruleId = typeof violation?.ruleId === "string" ? violation.ruleId : "";
12811
- if (!ruleId) continue;
12812
- counts[ruleId] = (counts[ruleId] ?? 0) + 1;
12813
- }
12814
- return counts;
12815
- } catch {
12816
- return {};
12817
- }
12818
- }, "readViolationCounts");
12819
- __name(sortRulesByViolationFrequency, "sortRulesByViolationFrequency");
12820
- __name(loadIronRules, "loadIronRules");
12821
- ruleSetSignature = /* @__PURE__ */ __name((rules) => {
12822
- const material = rules.map((rule) => `${rule.id}\0${rule.text}`).join("");
12823
- let hash = 2166136261;
12824
- for (let index = 0; index < material.length; index += 1) {
12825
- hash ^= material.charCodeAt(index);
12826
- hash = Math.imul(hash, 16777619) >>> 0;
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"
12827
13283
  }
12828
- return hash.toString(16).padStart(8, "0");
12829
- }, "ruleSetSignature");
12830
- formatRulesReference = /* @__PURE__ */ __name((rules) => {
12831
- if (rules.length === 0) return "DOTMEM_IRON_RULES_V1\ncount=0";
12832
- return [
12833
- "DOTMEM_IRON_RULES_V1",
12834
- `count=${rules.length}`,
12835
- `signature=${ruleSetSignature(rules)}`,
12836
- `ids=${rules.map((rule) => rule.id).join(",")}`
12837
- ].join("\n");
12838
- }, "formatRulesReference");
12839
- __name(formatRulesForSessionStart, "formatRulesForSessionStart");
12840
- __name(formatRuleWithExplanation, "formatRuleWithExplanation");
13284
+ ];
13285
+ __name(findIncidentById, "findIncidentById");
13286
+ __name(listIncidents, "listIncidents");
13287
+ __name(buildIncidentState, "buildIncidentState");
13288
+ __name(evaluateIncident, "evaluateIncident");
13289
+ __name(formatIncidentReport, "formatIncidentReport");
12841
13290
  }
12842
13291
  });
12843
13292
 
@@ -12849,21 +13298,21 @@ function joinPath9(base, child) {
12849
13298
  function resolveSessionFilePath() {
12850
13299
  return joinPath9(resolveUserDotMemPath(), SESSION_FILE_NAME);
12851
13300
  }
12852
- async function readFile5(path5) {
13301
+ async function readFile5(path8) {
12853
13302
  try {
12854
- const fs7 = await import('fs/promises');
12855
- return await fs7.readFile(path5, "utf8");
13303
+ const fs9 = await import('fs/promises');
13304
+ return await fs9.readFile(path8, "utf8");
12856
13305
  } catch {
12857
13306
  return null;
12858
13307
  }
12859
13308
  }
12860
- async function writeFile5(path5, content) {
12861
- const fs7 = await import('fs/promises');
12862
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
12863
- await fs7.mkdir(dir, { recursive: true });
12864
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
12865
- await fs7.writeFile(temporary, content, "utf8");
12866
- 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);
12867
13316
  }
12868
13317
  async function loadSession() {
12869
13318
  const raw = await readFile5(resolveSessionFilePath());
@@ -12965,25 +13414,25 @@ function joinPath10(base, child) {
12965
13414
  function resolveExemplarsPath() {
12966
13415
  return joinPath10(resolveUserDotMemPath(), EXEMPLARS_FILE_NAME);
12967
13416
  }
12968
- async function readFile6(path5) {
13417
+ async function readFile6(path8) {
12969
13418
  try {
12970
- const fs7 = await import('fs/promises');
12971
- return await fs7.readFile(path5, "utf8");
13419
+ const fs9 = await import('fs/promises');
13420
+ return await fs9.readFile(path8, "utf8");
12972
13421
  } catch {
12973
13422
  return null;
12974
13423
  }
12975
13424
  }
12976
- async function writeFile6(path5, content) {
12977
- const fs7 = await import('fs/promises');
12978
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
12979
- await fs7.mkdir(dir, { recursive: true });
12980
- 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`;
12981
13430
  try {
12982
- await fs7.writeFile(temporary, content, "utf8");
12983
- await fs7.rename(temporary, path5);
13431
+ await fs9.writeFile(temporary, content, "utf8");
13432
+ await fs9.rename(temporary, path8);
12984
13433
  } catch {
12985
- await fs7.rm(temporary, { force: true }).catch(() => void 0);
12986
- 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}`);
12987
13436
  }
12988
13437
  }
12989
13438
  function emptyStore() {
@@ -13197,25 +13646,25 @@ function joinPath11(base, child) {
13197
13646
  function resolvePersonalityAnchorPath() {
13198
13647
  return joinPath11(resolveUserDotMemPath(), PERSONALITY_ANCHOR_FILE_NAME);
13199
13648
  }
13200
- async function readFile7(path5) {
13649
+ async function readFile7(path8) {
13201
13650
  try {
13202
- const fs7 = await import('fs/promises');
13203
- return await fs7.readFile(path5, "utf8");
13651
+ const fs9 = await import('fs/promises');
13652
+ return await fs9.readFile(path8, "utf8");
13204
13653
  } catch {
13205
13654
  return null;
13206
13655
  }
13207
13656
  }
13208
- async function writeFile7(path5, content) {
13209
- const fs7 = await import('fs/promises');
13210
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
13211
- await fs7.mkdir(dir, { recursive: true });
13212
- 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`;
13213
13662
  try {
13214
- await fs7.writeFile(temporary, content, "utf8");
13215
- await fs7.rename(temporary, path5);
13663
+ await fs9.writeFile(temporary, content, "utf8");
13664
+ await fs9.rename(temporary, path8);
13216
13665
  } catch {
13217
- await fs7.rm(temporary, { force: true }).catch(() => void 0);
13218
- 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}`);
13219
13668
  }
13220
13669
  }
13221
13670
  function emptyAnchor() {
@@ -13353,8 +13802,8 @@ async function loadPersonalityAnchor() {
13353
13802
  async function savePersonalityAnchor(anchor) {
13354
13803
  const validated = validateAnchor(anchor);
13355
13804
  const dirPath = resolveUserDotMemPath();
13356
- const fs7 = await import('fs/promises');
13357
- await fs7.mkdir(dirPath, { recursive: true });
13805
+ const fs9 = await import('fs/promises');
13806
+ await fs9.mkdir(dirPath, { recursive: true });
13358
13807
  await writeFile7(resolvePersonalityAnchorPath(), JSON.stringify(validated, null, 2));
13359
13808
  }
13360
13809
  async function updatePersonalityAnchor(updates) {
@@ -13456,7 +13905,7 @@ function pkgDirname() {
13456
13905
  return __dirname;
13457
13906
  }
13458
13907
  try {
13459
- return path2.dirname(fileURLToPath(import.meta.url));
13908
+ return path3.dirname(fileURLToPath(import.meta.url));
13460
13909
  } catch {
13461
13910
  return process.cwd();
13462
13911
  }
@@ -13464,7 +13913,7 @@ function pkgDirname() {
13464
13913
  function candidatePaths() {
13465
13914
  const paths = [];
13466
13915
  try {
13467
- paths.push(path2.join(pkgDirname(), "built-in-context.json"));
13916
+ paths.push(path3.join(pkgDirname(), "built-in-context.json"));
13468
13917
  } catch {
13469
13918
  }
13470
13919
  return paths;
@@ -13533,9 +13982,9 @@ function loadBuiltInContext() {
13533
13982
  let lastError = "Built-in context artifact not found";
13534
13983
  const candidates = _artifactPathOverride ? [_artifactPathOverride] : candidatePaths();
13535
13984
  for (const candidate of candidates) {
13536
- if (!fs2.existsSync(candidate)) continue;
13985
+ if (!fs3.existsSync(candidate)) continue;
13537
13986
  try {
13538
- const raw = fs2.readFileSync(candidate);
13987
+ const raw = fs3.readFileSync(candidate);
13539
13988
  const parsed = JSON.parse(decodeText(raw, { source: candidate }));
13540
13989
  const artifact = validateArtifact(parsed);
13541
13990
  cached = artifact;
@@ -13566,14 +14015,14 @@ function loadBuiltInContext() {
13566
14015
  }
13567
14016
  let attemptedPath = "";
13568
14017
  try {
13569
- attemptedPath = path2.join(pkgDirname(), "built-in-context.json");
14018
+ attemptedPath = path3.join(pkgDirname(), "built-in-context.json");
13570
14019
  } catch {
13571
14020
  }
13572
14021
  let packageVersion = "unknown";
13573
14022
  try {
13574
- const pkgPath = path2.join(pkgDirname(), "package.json");
13575
- if (fs2.existsSync(pkgPath)) {
13576
- 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"));
13577
14026
  packageVersion = typeof pkg.version === "string" ? pkg.version : "unknown";
13578
14027
  }
13579
14028
  } catch {
@@ -13786,14 +14235,17 @@ __export(knowledge_exports, {
13786
14235
  addLoop: () => addLoop,
13787
14236
  addWaitingForUser: () => addWaitingForUser,
13788
14237
  appendDetectionJournal: () => appendDetectionJournal,
14238
+ applyVerification: () => applyVerification,
13789
14239
  assertBuiltInContextAvailable: () => assertBuiltInContextAvailable,
13790
14240
  assertNoConversationalOverride: () => assertNoConversationalOverride,
13791
14241
  authorityRelaxationPermitted: () => authorityRelaxationPermitted,
13792
14242
  authorityRevocationPermitted: () => authorityRevocationPermitted,
13793
14243
  buildIncidentState: () => buildIncidentState,
14244
+ buildVerificationRecord: () => buildVerificationRecord,
13794
14245
  builtInContextRulesMapped: () => builtInContextRulesMapped,
13795
14246
  calculateAnchorBudget: () => calculateAnchorBudget,
13796
14247
  calculateBudgetUsage: () => calculateBudgetUsage,
14248
+ callerInjectedVerificationMetadata: () => callerInjectedVerificationMetadata,
13797
14249
  canonicalApplicabilityValue: () => canonicalApplicabilityValue,
13798
14250
  canonicalEvent: () => canonicalEvent,
13799
14251
  canonicalEvidenceError: () => canonicalEvidenceError,
@@ -13812,6 +14264,7 @@ __export(knowledge_exports, {
13812
14264
  clearViolations: () => clearViolations,
13813
14265
  closeLoop: () => closeLoop,
13814
14266
  commitStageFile: () => commitStageFile,
14267
+ composeBootstrap: () => composeBootstrap,
13815
14268
  constructEffectiveAgentContract: () => constructEffectiveAgentContract,
13816
14269
  countViolations: () => countViolations,
13817
14270
  crossAcquisitionBoundary: () => crossAcquisitionBoundary,
@@ -13821,6 +14274,7 @@ __export(knowledge_exports, {
13821
14274
  defaultPolicyId: () => defaultPolicyId,
13822
14275
  deriveCurrentness: () => deriveCurrentness,
13823
14276
  deriveSituationApplicability: () => deriveSituationApplicability,
14277
+ deriveTrustBasis: () => deriveTrustBasis,
13824
14278
  describeDotMemStorage: () => describeDotMemStorage,
13825
14279
  detectAuthorityEscalationAttempt: () => detectAuthorityEscalationAttempt,
13826
14280
  detectBehaviorCoreMutationAttempt: () => detectBehaviorCoreMutationAttempt,
@@ -13873,6 +14327,7 @@ __export(knowledge_exports, {
13873
14327
  inspectMem: () => inspectMem,
13874
14328
  isBaselineClaim: () => isBaselineClaim,
13875
14329
  isBuiltInContextAvailable: () => isBuiltInContextAvailable,
14330
+ isCallerDeclaredVerified: () => isCallerDeclaredVerified,
13876
14331
  isEligibleByApplicability: () => isEligibleByApplicability,
13877
14332
  isIronRule: () => isIronRule,
13878
14333
  isItalian: () => isItalian,
@@ -13884,6 +14339,7 @@ __export(knowledge_exports, {
13884
14339
  listExemplars: () => listExemplars,
13885
14340
  listIncidents: () => listIncidents,
13886
14341
  listLoops: () => listLoops,
14342
+ listStore: () => listStore,
13887
14343
  listViews: () => listViews,
13888
14344
  listViolations: () => listViolations,
13889
14345
  loadBuiltInContext: () => loadBuiltInContext,
@@ -13913,6 +14369,7 @@ __export(knowledge_exports, {
13913
14369
  projectExemplarContext: () => projectExemplarContext,
13914
14370
  projectPersonalityAnchor: () => projectPersonalityAnchor,
13915
14371
  readDotMemStorageLocator: () => readDotMemStorageLocator,
14372
+ readPackage: () => readPackage,
13916
14373
  readStageFile: () => readStageFile,
13917
14374
  readStorageSettings: () => readStorageSettings,
13918
14375
  readUserLanguage: () => readUserLanguage,
@@ -13924,6 +14381,7 @@ __export(knowledge_exports, {
13924
14381
  renderAgentRules: () => renderAgentRules,
13925
14382
  renderExpandedClaim: () => renderExpandedClaim,
13926
14383
  renderExplanation: () => renderExplanation,
14384
+ renderInspectReport: () => renderInspectReport,
13927
14385
  renderMarkdownIndex: () => renderMarkdownIndex,
13928
14386
  renderOperatorContract: () => renderOperatorContract,
13929
14387
  renderView: () => renderView,
@@ -14011,6 +14469,7 @@ __export(knowledge_exports, {
14011
14469
  vaultList: () => vaultList,
14012
14470
  vaultPut: () => vaultPut,
14013
14471
  vaultResolve: () => vaultResolve,
14472
+ verifyAndPersistClaims: () => verifyAndPersistClaims,
14014
14473
  verifyDueClaims: () => verifyDueClaims,
14015
14474
  withPolicyNamespaceLock: () => withPolicyNamespaceLock,
14016
14475
  withoutOverlays: () => withoutOverlays,
@@ -14060,6 +14519,10 @@ var init_knowledge = __esm({
14060
14519
  init_rule_checker();
14061
14520
  init_vault();
14062
14521
  init_verify();
14522
+ init_verification();
14523
+ init_bootstrap();
14524
+ init_inspect_report();
14525
+ init_read_only();
14063
14526
  init_context_budget();
14064
14527
  init_feedback();
14065
14528
  init_correction();
@@ -14288,16 +14751,16 @@ function detectLineEnding(content) {
14288
14751
  return content.includes("\r\n") ? "\r\n" : "\n";
14289
14752
  }
14290
14753
  async function ensureDotMemReadme(_projectRoot, readmeSource) {
14291
- const fs7 = await import('fs/promises');
14754
+ const fs9 = await import('fs/promises');
14292
14755
  const dotmemDir = resolveUserDotMemPath();
14293
14756
  try {
14294
- await fs7.mkdir(dotmemDir, { recursive: true });
14757
+ await fs9.mkdir(dotmemDir, { recursive: true });
14295
14758
  } catch {
14296
14759
  }
14297
14760
  const contractDestination = resolveUserContractPath();
14298
14761
  const readmeDestination = resolveUserReadmePath();
14299
14762
  try {
14300
- await fs7.access(contractDestination);
14763
+ await fs9.access(contractDestination);
14301
14764
  } catch {
14302
14765
  let source = readmeSource;
14303
14766
  if (!source) {
@@ -14315,7 +14778,7 @@ async function ensureDotMemReadme(_projectRoot, readmeSource) {
14315
14778
  return pathname.startsWith("/") && pathname.length > 3 && pathname[2] === ":" ? pathname.slice(1) : pathname;
14316
14779
  });
14317
14780
  for (const candidate of sourceCandidates) {
14318
- if (await fs7.access(candidate).then(() => true).catch(() => false)) {
14781
+ if (await fs9.access(candidate).then(() => true).catch(() => false)) {
14319
14782
  source = candidate;
14320
14783
  break;
14321
14784
  }
@@ -14323,22 +14786,22 @@ async function ensureDotMemReadme(_projectRoot, readmeSource) {
14323
14786
  source ??= sourceCandidates.at(-1);
14324
14787
  }
14325
14788
  try {
14326
- const contractContent = await fs7.readFile(source, "utf8");
14789
+ const contractContent = await fs9.readFile(source, "utf8");
14327
14790
  if (!contractContent.trim()) {
14328
14791
  throw new Error(`Refusing to install ${source} as the dotmem contract: the file is empty`);
14329
14792
  }
14330
- await fs7.writeFile(contractDestination, contractContent, "utf8");
14793
+ await fs9.writeFile(contractDestination, contractContent, "utf8");
14331
14794
  } catch (error) {
14332
14795
  throw new Error(`Failed to install dotmem contract from ${source} to ${contractDestination}: ${error instanceof Error ? error.message : String(error)}`);
14333
14796
  }
14334
14797
  }
14335
14798
  try {
14336
- await fs7.access(readmeDestination);
14799
+ await fs9.access(readmeDestination);
14337
14800
  return { action: "already-present", path: readmeDestination };
14338
14801
  } catch {
14339
14802
  }
14340
14803
  try {
14341
- await fs7.writeFile(readmeDestination, DEFAULT_README_CONTENT, "utf8");
14804
+ await fs9.writeFile(readmeDestination, DEFAULT_README_CONTENT, "utf8");
14342
14805
  return { action: "created", path: readmeDestination };
14343
14806
  } catch (error) {
14344
14807
  throw new Error(`Failed to write dotmem README at ${readmeDestination}: ${error instanceof Error ? error.message : String(error)}`);
@@ -14874,11 +15337,11 @@ function denoFs() {
14874
15337
  writeFile: writeFile8,
14875
15338
  rename,
14876
15339
  copyFile,
14877
- rm: /* @__PURE__ */ __name((path5, opts) => rm(path5, opts), "rm"),
15340
+ rm: /* @__PURE__ */ __name((path8, opts) => rm(path8, opts), "rm"),
14878
15341
  mkdir,
14879
- open: /* @__PURE__ */ __name(async (path5, flags) => {
15342
+ open: /* @__PURE__ */ __name(async (path8, flags) => {
14880
15343
  if (!Deno.open) throw new Error("Deno.open is unavailable");
14881
- const file = await Deno.open(path5, flags);
15344
+ const file = await Deno.open(path8, flags);
14882
15345
  return {
14883
15346
  writeFile: /* @__PURE__ */ __name(async (data) => {
14884
15347
  const written = await file.write(data);
@@ -14930,8 +15393,8 @@ var init_durable_store = __esm({
14930
15393
  }
14931
15394
  /** Load all entries from disk. Throws on unreadable/corrupt store. */
14932
15395
  async load() {
14933
- const fs7 = await resolveFs();
14934
- if (!fs7) {
15396
+ const fs9 = await resolveFs();
15397
+ if (!fs9) {
14935
15398
  throw new DurableStorageUnavailableError(
14936
15399
  "Durable memory storage is unavailable in this runtime: no filesystem backend could be resolved."
14937
15400
  );
@@ -14941,7 +15404,7 @@ var init_durable_store = __esm({
14941
15404
  async () => {
14942
15405
  let raw;
14943
15406
  try {
14944
- raw = await fs7.readFile(this.filePath);
15407
+ raw = await fs9.readFile(this.filePath);
14945
15408
  } catch (error) {
14946
15409
  const code = error?.code;
14947
15410
  if (code === "ENOENT") {
@@ -14959,7 +15422,7 @@ var init_durable_store = __esm({
14959
15422
  parsed = JSON.parse(decodeText(raw, { source: this.filePath }));
14960
15423
  } catch {
14961
15424
  try {
14962
- const bakRaw = await fs7.readFile(`${this.filePath}.bak`);
15425
+ const bakRaw = await fs9.readFile(`${this.filePath}.bak`);
14963
15426
  parsed = JSON.parse(decodeText(bakRaw, { source: `${this.filePath}.bak` }));
14964
15427
  } catch {
14965
15428
  throw new DurableStorageUnavailableError(
@@ -15033,8 +15496,8 @@ var init_durable_store = __esm({
15033
15496
  await this.load();
15034
15497
  }
15035
15498
  async persist(entries2, nextVersion) {
15036
- const fs7 = await resolveFs();
15037
- if (!fs7) {
15499
+ const fs9 = await resolveFs();
15500
+ if (!fs9) {
15038
15501
  throw new DurableStorageUnavailableError(
15039
15502
  "Durable memory storage is unavailable: no filesystem backend could be resolved."
15040
15503
  );
@@ -15043,10 +15506,10 @@ var init_durable_store = __esm({
15043
15506
  version: nextVersion,
15044
15507
  entries: [...entries2.values()]
15045
15508
  };
15046
- await fs7.mkdir(parentDir(this.filePath), { recursive: true });
15509
+ await fs9.mkdir(parentDir(this.filePath), { recursive: true });
15047
15510
  const temporary = `${this.filePath}.${pidSuffix()}.${uniqueSuffix2()}.tmp`;
15048
15511
  try {
15049
- const handle = await fs7.open(temporary, "wx");
15512
+ const handle = await fs9.open(temporary, "wx");
15050
15513
  try {
15051
15514
  const bytes = new TextEncoder().encode(JSON.stringify(state2, null, 2) + "\n");
15052
15515
  await handle.writeFile(bytes);
@@ -15054,26 +15517,26 @@ var init_durable_store = __esm({
15054
15517
  } finally {
15055
15518
  await handle.close();
15056
15519
  }
15057
- await fs7.readFile(temporary);
15058
- await this.keepLastValidVersion(fs7);
15059
- await fs7.rename(temporary, this.filePath);
15520
+ await fs9.readFile(temporary);
15521
+ await this.keepLastValidVersion(fs9);
15522
+ await fs9.rename(temporary, this.filePath);
15060
15523
  await this.syncDirectory(parentDir(this.filePath));
15061
15524
  } catch (error) {
15062
- await fs7.rm(temporary, { force: true }).catch(() => void 0);
15525
+ await fs9.rm(temporary, { force: true }).catch(() => void 0);
15063
15526
  throw error;
15064
15527
  }
15065
15528
  }
15066
- async keepLastValidVersion(fs7) {
15529
+ async keepLastValidVersion(fs9) {
15067
15530
  try {
15068
- await fs7.copyFile(this.filePath, `${this.filePath}.bak`);
15531
+ await fs9.copyFile(this.filePath, `${this.filePath}.bak`);
15069
15532
  } catch {
15070
15533
  }
15071
15534
  }
15072
15535
  async syncDirectory(directoryPath) {
15073
- const fs7 = await resolveFs();
15074
- if (!fs7) return;
15536
+ const fs9 = await resolveFs();
15537
+ if (!fs9) return;
15075
15538
  try {
15076
- const handle = await fs7.open(directoryPath, "r");
15539
+ const handle = await fs9.open(directoryPath, "r");
15077
15540
  try {
15078
15541
  await handle.sync();
15079
15542
  } finally {
@@ -15184,9 +15647,9 @@ function computeRelevance(entry) {
15184
15647
  };
15185
15648
  return recencyScore * confidenceScore * accessScore * typeBoost[entry.type] * scopeBoost[entry.scope];
15186
15649
  }
15187
- function getNestedPath(obj, path5) {
15188
- if (!path5 || typeof path5 !== "string") return void 0;
15189
- 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(".");
15190
15653
  let current = obj;
15191
15654
  for (const part of parts) {
15192
15655
  if (current === null || current === void 0) return void 0;
@@ -15194,9 +15657,9 @@ function getNestedPath(obj, path5) {
15194
15657
  }
15195
15658
  return current;
15196
15659
  }
15197
- function setNestedPath(obj, path5, value) {
15198
- if (!path5 || typeof path5 !== "string") return;
15199
- 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(".");
15200
15663
  let current = obj;
15201
15664
  for (let i2 = 0; i2 < parts.length - 1; i2++) {
15202
15665
  const part = parts[i2];
@@ -15207,9 +15670,9 @@ function setNestedPath(obj, path5, value) {
15207
15670
  }
15208
15671
  current[parts[parts.length - 1]] = value;
15209
15672
  }
15210
- function deleteNestedPath(obj, path5) {
15211
- if (!path5 || typeof path5 !== "string") return;
15212
- 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(".");
15213
15676
  let current = obj;
15214
15677
  for (let i2 = 0; i2 < parts.length - 1; i2++) {
15215
15678
  const part = parts[i2];
@@ -15711,13 +16174,13 @@ async function findClaimAcrossAllSources(claimId, scope, sourceProject) {
15711
16174
  const matches2 = [];
15712
16175
  const scanDirectory = /* @__PURE__ */ __name(async (dir) => {
15713
16176
  try {
15714
- const fs7 = await import('fs/promises');
15715
- const entries2 = await fs7.readdir(dir, { withFileTypes: true });
16177
+ const fs9 = await import('fs/promises');
16178
+ const entries2 = await fs9.readdir(dir, { withFileTypes: true });
15716
16179
  for (const e of entries2) {
15717
16180
  if (e.isFile() && e.name.endsWith(".mem") && e.name !== "@brain.mem") {
15718
16181
  const filePath = `${dir}/${e.name}`;
15719
16182
  try {
15720
- const bytes = await fs7.readFile(filePath);
16183
+ const bytes = await fs9.readFile(filePath);
15721
16184
  const artifact = await decodeMemArtifact(bytes);
15722
16185
  const state2 = artifact.state;
15723
16186
  if (!state2) continue;
@@ -16424,11 +16887,11 @@ var init_handshake_session = __esm({
16424
16887
  SESSION_FILE_NAME2 = "handshake-session.json";
16425
16888
  resolveHandshakeSessionPath = /* @__PURE__ */ __name(() => joinStoragePath(joinStoragePath(resolveUserDotMemPath(), RUNTIME_NAMESPACE_DIR), SESSION_FILE_NAME2), "resolveHandshakeSessionPath");
16426
16889
  loadHandshakeSessionRecord = /* @__PURE__ */ __name(() => {
16427
- const fs7 = getSyncFs();
16428
- if (!fs7) return null;
16890
+ const fs9 = getSyncFs();
16891
+ if (!fs9) return null;
16429
16892
  let raw;
16430
16893
  try {
16431
- raw = fs7.readFileSync(resolveHandshakeSessionPath(), "utf8");
16894
+ raw = fs9.readFileSync(resolveHandshakeSessionPath(), "utf8");
16432
16895
  } catch {
16433
16896
  return null;
16434
16897
  }
@@ -16440,26 +16903,26 @@ var init_handshake_session = __esm({
16440
16903
  }
16441
16904
  }, "loadHandshakeSessionRecord");
16442
16905
  saveHandshakeSessionRecord = /* @__PURE__ */ __name(async (record) => {
16443
- const fs7 = getSyncFs();
16444
- if (!fs7) {
16906
+ const fs9 = getSyncFs();
16907
+ if (!fs9) {
16445
16908
  throw new Error("Persisting the handshake session record requires filesystem access, unavailable in this runtime");
16446
16909
  }
16447
16910
  const filePath = resolveHandshakeSessionPath();
16448
- await fs7.promises.mkdir(parentStoragePath(filePath), { recursive: true });
16911
+ await fs9.promises.mkdir(parentStoragePath(filePath), { recursive: true });
16449
16912
  const temporary = `${filePath}.${process.pid}.${Date.now().toString(36)}.tmp`;
16450
16913
  try {
16451
- await fs7.promises.writeFile(temporary, `${JSON.stringify(record, null, 2)}
16914
+ await fs9.promises.writeFile(temporary, `${JSON.stringify(record, null, 2)}
16452
16915
  `, "utf8");
16453
- await fs7.promises.rename(temporary, filePath);
16916
+ await fs9.promises.rename(temporary, filePath);
16454
16917
  } catch (error) {
16455
- await fs7.promises.rm(temporary, { force: true }).catch(() => void 0);
16918
+ await fs9.promises.rm(temporary, { force: true }).catch(() => void 0);
16456
16919
  throw error;
16457
16920
  }
16458
16921
  }, "saveHandshakeSessionRecord");
16459
16922
  clearHandshakeSessionRecord = /* @__PURE__ */ __name(async () => {
16460
- const fs7 = getSyncFs();
16461
- if (!fs7) return;
16462
- 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);
16463
16926
  }, "clearHandshakeSessionRecord");
16464
16927
  computeCurrentRuntimeId = /* @__PURE__ */ __name(() => computeRuntimeId({
16465
16928
  platform: process.platform,
@@ -18499,33 +18962,33 @@ var validateContinuityDocument = /* @__PURE__ */ __name((value) => {
18499
18962
  snapshots: document.snapshots
18500
18963
  };
18501
18964
  }, "validateContinuityDocument");
18502
- var deleteContinuityArtifact = /* @__PURE__ */ __name(async (path5) => {
18503
- const fs7 = getSyncFs();
18504
- if (!fs7) return;
18505
- 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 });
18506
18969
  }, "deleteContinuityArtifact");
18507
- var loadContinuityDocument = /* @__PURE__ */ __name(async (path5) => {
18508
- const fs7 = getSyncFs();
18509
- if (!fs7) return emptyContinuityDocument();
18970
+ var loadContinuityDocument = /* @__PURE__ */ __name(async (path8) => {
18971
+ const fs9 = getSyncFs();
18972
+ if (!fs9) return emptyContinuityDocument();
18510
18973
  try {
18511
- const raw = await fs7.promises.readFile(path5, "utf8");
18974
+ const raw = await fs9.promises.readFile(path8, "utf8");
18512
18975
  return validateContinuityDocument(JSON.parse(raw));
18513
18976
  } catch {
18514
18977
  return emptyContinuityDocument();
18515
18978
  }
18516
18979
  }, "loadContinuityDocument");
18517
- var saveContinuityDocument = /* @__PURE__ */ __name(async (path5, document) => {
18518
- const fs7 = getSyncFs();
18519
- if (!fs7) return;
18980
+ var saveContinuityDocument = /* @__PURE__ */ __name(async (path8, document) => {
18981
+ const fs9 = getSyncFs();
18982
+ if (!fs9) return;
18520
18983
  const validated = validateContinuityDocument(document);
18521
- await fs7.promises.mkdir(resolveUserContinuityDir(), { recursive: true });
18522
- 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`;
18523
18986
  try {
18524
- await fs7.promises.writeFile(temporary, `${JSON.stringify(validated, null, 2)}
18987
+ await fs9.promises.writeFile(temporary, `${JSON.stringify(validated, null, 2)}
18525
18988
  `, "utf8");
18526
- await fs7.promises.rename(temporary, path5);
18989
+ await fs9.promises.rename(temporary, path8);
18527
18990
  } catch (error) {
18528
- await fs7.promises.rm(temporary, { force: true }).catch(() => void 0);
18991
+ await fs9.promises.rm(temporary, { force: true }).catch(() => void 0);
18529
18992
  throw error;
18530
18993
  }
18531
18994
  }, "saveContinuityDocument");
@@ -19159,48 +19622,48 @@ var HardRulesRegistry = class {
19159
19622
  return resolveRegistryFilePath(this.directory);
19160
19623
  }
19161
19624
  async load() {
19162
- const fs7 = await import('fs/promises');
19625
+ const fs9 = await import('fs/promises');
19163
19626
  try {
19164
- const raw = await fs7.readFile(this.filePath(), "utf8");
19627
+ const raw = await fs9.readFile(this.filePath(), "utf8");
19165
19628
  return validateDocument4(JSON.parse(raw));
19166
19629
  } catch (err2) {
19167
19630
  if (err2.code === "ENOENT") return emptyDocument3();
19168
19631
  throw err2;
19169
19632
  }
19170
19633
  }
19171
- async readDoc(fs7) {
19634
+ async readDoc(fs9) {
19172
19635
  try {
19173
- const raw = await fs7.readFile(this.filePath(), "utf8");
19636
+ const raw = await fs9.readFile(this.filePath(), "utf8");
19174
19637
  return validateDocument4(JSON.parse(raw));
19175
19638
  } catch (err2) {
19176
19639
  if (err2.code === "ENOENT") return emptyDocument3();
19177
19640
  throw err2;
19178
19641
  }
19179
19642
  }
19180
- async writeDoc(fs7, doc) {
19181
- await fs7.mkdir(this.dir(), { recursive: true });
19643
+ async writeDoc(fs9, doc) {
19644
+ await fs9.mkdir(this.dir(), { recursive: true });
19182
19645
  const fp = this.filePath();
19183
19646
  const tmp = `${fp}.${process.pid}.${Date.now().toString(36)}.tmp`;
19184
19647
  try {
19185
- await fs7.writeFile(tmp, `${JSON.stringify(doc, null, 2)}
19648
+ await fs9.writeFile(tmp, `${JSON.stringify(doc, null, 2)}
19186
19649
  `, "utf8");
19187
- const handle = await fs7.open(tmp, "r+");
19650
+ const handle = await fs9.open(tmp, "r+");
19188
19651
  try {
19189
19652
  await handle.sync();
19190
19653
  } finally {
19191
19654
  await handle.close();
19192
19655
  }
19193
- await fs7.rename(tmp, fp);
19656
+ await fs9.rename(tmp, fp);
19194
19657
  } catch (err2) {
19195
- await fs7.rm(tmp, { force: true }).catch(() => void 0);
19658
+ await fs9.rm(tmp, { force: true }).catch(() => void 0);
19196
19659
  throw err2;
19197
19660
  }
19198
19661
  }
19199
19662
  async mutate(operation, options = {}) {
19200
19663
  const directory = this.dir();
19201
19664
  return withPolicyNamespaceLock(async (session2) => {
19202
- const fs7 = await import('fs/promises');
19203
- const doc = await this.readDoc(fs7);
19665
+ const fs9 = await import('fs/promises');
19666
+ const doc = await this.readDoc(fs9);
19204
19667
  if (options.basedOnRevision !== void 0 && options.basedOnRevision !== doc.revision) {
19205
19668
  throw new HardRulesRegistryError(`Stale hard-rules revision: expected ${options.basedOnRevision}, current ${doc.revision}`);
19206
19669
  }
@@ -19208,7 +19671,7 @@ var HardRulesRegistry = class {
19208
19671
  let next = outcome.document;
19209
19672
  validateDocument4(next);
19210
19673
  await session2.assertOwnership();
19211
- await this.writeDoc(fs7, next);
19674
+ await this.writeDoc(fs9, next);
19212
19675
  return outcome.result;
19213
19676
  }, { directory });
19214
19677
  }
@@ -19368,15 +19831,15 @@ var HardRulesRegistry = class {
19368
19831
  // core/functions/bootstrap.ts
19369
19832
  async function checkProjectState(_cwd) {
19370
19833
  const userDotMemDir = resolveUserDotMemPath();
19371
- const userLogicMemPath = path2.join(userDotMemDir, "logic.mem");
19834
+ const userLogicMemPath = path3.join(userDotMemDir, "logic.mem");
19372
19835
  let logicMemValid = false;
19373
- if (fs2.existsSync(userLogicMemPath)) {
19836
+ if (fs3.existsSync(userLogicMemPath)) {
19374
19837
  logicMemValid = true;
19375
19838
  }
19376
19839
  const projectId = await resolveProjectIdentity(process.cwd());
19377
19840
  const projectAnchorPath = resolveUserProjectMemoryPath(projectId);
19378
- const projectAnchorPresent = fs2.existsSync(projectAnchorPath);
19379
- const initialized = fs2.existsSync(userDotMemDir) && logicMemValid && projectAnchorPresent;
19841
+ const projectAnchorPresent = fs3.existsSync(projectAnchorPath);
19842
+ const initialized = fs3.existsSync(userDotMemDir) && logicMemValid && projectAnchorPresent;
19380
19843
  return {
19381
19844
  initialized,
19382
19845
  dotmemDir: userDotMemDir,
@@ -19390,8 +19853,8 @@ async function checkProjectState(_cwd) {
19390
19853
  __name(checkProjectState, "checkProjectState");
19391
19854
  async function getMemoryReadiness(_cwd) {
19392
19855
  const userDotMemDir = resolveUserDotMemPath();
19393
- const userProjectsDir = path2.join(userDotMemDir, "projects");
19394
- if (!fs2.existsSync(userProjectsDir)) {
19856
+ const userProjectsDir = path3.join(userDotMemDir, "projects");
19857
+ if (!fs3.existsSync(userProjectsDir)) {
19395
19858
  return { ready: false, totalSources: 0, totalClaims: 0, sources: [] };
19396
19859
  }
19397
19860
  try {
@@ -19439,12 +19902,12 @@ async function detectAiEnvironment() {
19439
19902
  }
19440
19903
  if (process.platform !== "win32") {
19441
19904
  try {
19442
- const status = fs2.readFileSync("/proc/self/status", "utf8");
19905
+ const status = fs3.readFileSync("/proc/self/status", "utf8");
19443
19906
  const ppidMatch = status.match(/^PPid:\s*(\d+)$/m);
19444
19907
  if (ppidMatch) {
19445
19908
  const ppid = parseInt(ppidMatch[1], 10);
19446
19909
  try {
19447
- const comm = fs2.readFileSync(`/proc/${ppid}/comm`, "utf8").trim();
19910
+ const comm = fs3.readFileSync(`/proc/${ppid}/comm`, "utf8").trim();
19448
19911
  const knownAiParents = ["codex", "kilo", "claude", "aider", "continue", "cursor"];
19449
19912
  const matchedParent = knownAiParents.find((ai) => comm.toLowerCase().includes(ai));
19450
19913
  if (matchedParent) {
@@ -19473,33 +19936,33 @@ async function detectAiEnvironment() {
19473
19936
  __name(detectAiEnvironment, "detectAiEnvironment");
19474
19937
  async function ensureUserDotMemInitialized() {
19475
19938
  const userDotMemDir = resolveUserDotMemPath();
19476
- const userProjectsDir = path2.join(userDotMemDir, "projects");
19477
- const userLogicMemPath = path2.join(userDotMemDir, "logic.mem");
19939
+ const userProjectsDir = path3.join(userDotMemDir, "projects");
19940
+ const userLogicMemPath = path3.join(userDotMemDir, "logic.mem");
19478
19941
  const userContractPath = resolveUserContractPath();
19479
19942
  const userBrainPath = resolveUserBrainPath();
19480
19943
  try {
19481
- fs2.mkdirSync(userDotMemDir, { recursive: true });
19482
- fs2.mkdirSync(userProjectsDir, { recursive: true });
19944
+ fs3.mkdirSync(userDotMemDir, { recursive: true });
19945
+ fs3.mkdirSync(userProjectsDir, { recursive: true });
19483
19946
  } catch {
19484
19947
  }
19485
- if (!fs2.existsSync(userLogicMemPath)) {
19948
+ if (!fs3.existsSync(userLogicMemPath)) {
19486
19949
  const seedBytes = await encodeLogicSeed();
19487
- fs2.writeFileSync(userLogicMemPath, seedBytes);
19950
+ fs3.writeFileSync(userLogicMemPath, seedBytes);
19488
19951
  }
19489
- if (!fs2.existsSync(userContractPath)) {
19952
+ if (!fs3.existsSync(userContractPath)) {
19490
19953
  await ensureDotMemReadme();
19491
19954
  }
19492
- if (!fs2.existsSync(userBrainPath)) {
19955
+ if (!fs3.existsSync(userBrainPath)) {
19493
19956
  const emptyBrainDoc = {
19494
19957
  format: "dotmem.brain",
19495
19958
  version: 1,
19496
19959
  relationships: []
19497
19960
  };
19498
- fs2.writeFileSync(userBrainPath, JSON.stringify(emptyBrainDoc, null, 2));
19961
+ fs3.writeFileSync(userBrainPath, JSON.stringify(emptyBrainDoc, null, 2));
19499
19962
  }
19500
- const userLanguagePath = path2.join(userDotMemDir, "language.json");
19501
- if (!fs2.existsSync(userLanguagePath)) {
19502
- 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));
19503
19966
  }
19504
19967
  }
19505
19968
  __name(ensureUserDotMemInitialized, "ensureUserDotMemInitialized");
@@ -20495,17 +20958,38 @@ __name(runStorageCli, "runStorageCli");
20495
20958
 
20496
20959
  // core/cli/commands/inspect.ts
20497
20960
  init_mem_package();
20498
- function runInspectCli(file) {
20961
+ init_inspect_report();
20962
+ var redactDefault = true;
20963
+ function runInspectCli(file, args) {
20499
20964
  if (!file) {
20500
- 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]");
20501
20966
  process.exitCode = 1;
20502
20967
  return;
20503
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");
20504
20975
  void (async () => {
20505
20976
  try {
20506
- const bytes = await fs2.promises.readFile(path2.resolve(file));
20977
+ const bytes = await fs3.promises.readFile(path3.resolve(file));
20507
20978
  const result = await inspectMem(bytes);
20508
- 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
+ }
20509
20993
  if (result.status !== "valid") process.exitCode = 2;
20510
20994
  } catch (error) {
20511
20995
  console.error(`Unable to inspect ${file}: ${error instanceof Error ? error.message : String(error)}`);
@@ -20571,6 +21055,148 @@ async function runContinuityCli(args) {
20571
21055
  }
20572
21056
  }
20573
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");
20574
21200
  async function runHandshakeCli(args) {
20575
21201
  const reset = args.includes("--reset");
20576
21202
  const status = args.includes("--status");
@@ -20817,8 +21443,8 @@ async function runRenderCli(args) {
20817
21443
  return;
20818
21444
  }
20819
21445
  if (outFile) {
20820
- const fs7 = await import('fs/promises');
20821
- await fs7.writeFile(outFile, result.markdown, "utf8");
21446
+ const fs9 = await import('fs/promises');
21447
+ await fs9.writeFile(outFile, result.markdown, "utf8");
20822
21448
  console.info(`Rendered ${view} view to ${outFile}: ${result.claimsWritten} claims`);
20823
21449
  } else {
20824
21450
  console.info(result.markdown);
@@ -20856,8 +21482,8 @@ async function runNoteCli(args) {
20856
21482
  content = await readStdin();
20857
21483
  origin = "stdin";
20858
21484
  } else {
20859
- const fs7 = await import('fs/promises');
20860
- content = await fs7.readFile(fileArg, "utf8");
21485
+ const fs9 = await import('fs/promises');
21486
+ content = await fs9.readFile(fileArg, "utf8");
20861
21487
  origin = fileArg.split(/[\\/]/).pop() ?? fileArg;
20862
21488
  }
20863
21489
  const titleIndex = args.indexOf("--title");
@@ -20941,8 +21567,8 @@ async function runNoteCli(args) {
20941
21567
  process14.exitCode = 1;
20942
21568
  return;
20943
21569
  }
20944
- const fs7 = await import('fs/promises');
20945
- await fs7.writeFile(outFile, content, "utf8");
21570
+ const fs9 = await import('fs/promises');
21571
+ await fs9.writeFile(outFile, content, "utf8");
20946
21572
  console.info(`Exported note ${id} to ${outFile}`);
20947
21573
  break;
20948
21574
  }
@@ -21039,9 +21665,9 @@ async function runSeedCli(args) {
21039
21665
  content = await readStdin();
21040
21666
  origin = "stdin";
21041
21667
  } else {
21042
- const fs7 = await import('fs/promises');
21668
+ const fs9 = await import('fs/promises');
21043
21669
  try {
21044
- content = await fs7.readFile(input, "utf8");
21670
+ content = await fs9.readFile(input, "utf8");
21045
21671
  } catch (error) {
21046
21672
  console.error(`Unable to read seed file: ${error instanceof Error ? error.message : String(error)}`);
21047
21673
  process14.exitCode = 1;
@@ -21170,12 +21796,34 @@ __name(runVaultCli, "runVaultCli");
21170
21796
 
21171
21797
  // core/cli/commands/verify.ts
21172
21798
  init_memory();
21799
+ init_memory();
21173
21800
  init_verify();
21174
21801
  async function runVerifyCli(args) {
21175
21802
  const json = args.includes("--json");
21803
+ const persist = args.includes("--persist");
21176
21804
  try {
21177
21805
  const state2 = await loadCombinedKnowledgeState();
21178
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
+ }
21179
21827
  if (json) {
21180
21828
  console.info(JSON.stringify(result, null, 2));
21181
21829
  return;
@@ -21380,7 +22028,7 @@ var collectStores = /* @__PURE__ */ __name(async () => {
21380
22028
  const files = [];
21381
22029
  for (const dir of sourceDirs) {
21382
22030
  try {
21383
- const entries2 = await fs4.readdir(dir, { withFileTypes: true });
22031
+ const entries2 = await fs.readdir(dir, { withFileTypes: true });
21384
22032
  for (const e of entries2) {
21385
22033
  if (e.isFile() && e.name.endsWith(".mem") && e.name !== "@brain.mem") {
21386
22034
  files.push({ sourceId: e.name, filePath: `${dir}/${e.name}` });
@@ -21392,7 +22040,7 @@ var collectStores = /* @__PURE__ */ __name(async () => {
21392
22040
  const stores = [];
21393
22041
  for (const { sourceId, filePath } of files) {
21394
22042
  try {
21395
- const bytes = await fs4.readFile(filePath);
22043
+ const bytes = await fs.readFile(filePath);
21396
22044
  const artifact = await decodeMemArtifact(bytes);
21397
22045
  stores.push({ sourceId, filePath, state: artifact.state, artifact });
21398
22046
  } catch (error) {
@@ -21615,7 +22263,7 @@ async function runDoctorCli(args) {
21615
22263
  }
21616
22264
  const filePath = store5.filePath;
21617
22265
  const expectedVersion = store5.state.version;
21618
- await withStorageLock(path2.dirname(filePath), async () => {
22266
+ await withStorageLock(path3.dirname(filePath), async () => {
21619
22267
  const fsMod = await import('fs/promises');
21620
22268
  let currentBytes;
21621
22269
  try {
@@ -21636,7 +22284,7 @@ async function runDoctorCli(args) {
21636
22284
  }
21637
22285
  const tmp = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
21638
22286
  try {
21639
- await fsMod.mkdir(path2.dirname(filePath), { recursive: true });
22287
+ await fsMod.mkdir(path3.dirname(filePath), { recursive: true });
21640
22288
  const encoded = await encodeMemPackage(newState, currentArtifact.preserved, currentArtifact.package);
21641
22289
  await fsMod.writeFile(tmp, encoded);
21642
22290
  await decodeMemArtifact(await fsMod.readFile(tmp));
@@ -21750,7 +22398,7 @@ Verify the AGENTS.md scintilla block matches SCINTILLA_SIGNAL_HASH.
21750
22398
  const agentsMd = fileIdx !== -1 && args[fileIdx + 1] !== void 0 ? args[fileIdx + 1] : "AGENTS.md";
21751
22399
  let content;
21752
22400
  try {
21753
- content = fs2.readFileSync(agentsMd, "utf8");
22401
+ content = fs3.readFileSync(agentsMd, "utf8");
21754
22402
  } catch {
21755
22403
  console.info(`scintilla block not found: ${agentsMd} does not exist (nothing to verify)`);
21756
22404
  return;
@@ -21837,7 +22485,7 @@ function dispatch4(command, args) {
21837
22485
  return;
21838
22486
  }
21839
22487
  if (command === "--version" || command === "-v") {
21840
- 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"));
21841
22489
  console.info(pkg.version);
21842
22490
  process14.exit(0);
21843
22491
  return;
@@ -21952,11 +22600,66 @@ Report or relocate the canonical dotmem storage location.
21952
22600
  }
21953
22601
  if (command === "inspect") {
21954
22602
  if (args[0] === "--help" || args[0] === "-h") {
21955
- 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.`);
21956
22659
  process14.exit(0);
21957
22660
  return;
21958
22661
  }
21959
- void runInspectCli(args[0]);
22662
+ void runBootstrapCli(args);
21960
22663
  return;
21961
22664
  }
21962
22665
  if (command === "continuity") {