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.cjs CHANGED
@@ -1,21 +1,21 @@
1
1
  'use strict';
2
2
 
3
3
  var memorio = require('memorio');
4
- var fs2 = require('fs');
5
- var path2 = require('path');
4
+ var fs3 = require('fs');
5
+ var fs = require('fs/promises');
6
+ var path3 = require('path');
6
7
  var url = require('url');
7
8
  var crypto2 = require('crypto');
8
9
  var process14 = require('process');
9
- var fs4 = require('fs/promises');
10
10
 
11
11
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
12
12
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
13
13
 
14
- var fs2__default = /*#__PURE__*/_interopDefault(fs2);
15
- var path2__default = /*#__PURE__*/_interopDefault(path2);
14
+ var fs3__default = /*#__PURE__*/_interopDefault(fs3);
15
+ var fs__default = /*#__PURE__*/_interopDefault(fs);
16
+ var path3__default = /*#__PURE__*/_interopDefault(path3);
16
17
  var crypto2__default = /*#__PURE__*/_interopDefault(crypto2);
17
18
  var process14__default = /*#__PURE__*/_interopDefault(process14);
18
- var fs4__default = /*#__PURE__*/_interopDefault(fs4);
19
19
 
20
20
  var __defProp = Object.defineProperty;
21
21
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -392,13 +392,13 @@ var init_storage_settings = __esm({
392
392
  return normalized || normalizeStoragePath(cwd);
393
393
  }, "projectRoot");
394
394
  findProjectSettingsFile = /* @__PURE__ */ __name((cwd) => {
395
- const fs7 = getSyncFs();
396
- if (!fs7) return null;
395
+ const fs9 = getSyncFs();
396
+ if (!fs9) return null;
397
397
  let current = projectRoot(cwd);
398
398
  for (; ; ) {
399
399
  const candidate = joinStoragePath(current, exports.DOTMEM_STORAGE_SETTINGS_FILE_NAME);
400
400
  try {
401
- if (fs7.existsSync(candidate)) return candidate;
401
+ if (fs9.existsSync(candidate)) return candidate;
402
402
  } catch {
403
403
  return null;
404
404
  }
@@ -473,10 +473,10 @@ var init_storage_settings = __esm({
473
473
  }
474
474
  return { tier, file, root: normalizeStoragePath(declared), mode };
475
475
  }, "resolveSettingsEntry");
476
- readTextFile = /* @__PURE__ */ __name((fs7, file) => {
476
+ readTextFile = /* @__PURE__ */ __name((fs9, file) => {
477
477
  let raw;
478
478
  try {
479
- raw = fs7.readFileSync(file, "utf8");
479
+ raw = fs9.readFileSync(file, "utf8");
480
480
  } catch (error) {
481
481
  const code = error?.code;
482
482
  if (code === "ENOENT" || code === "ENOTDIR") return null;
@@ -488,9 +488,9 @@ var init_storage_settings = __esm({
488
488
  return raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw;
489
489
  }, "readTextFile");
490
490
  exports.readStorageSettings = /* @__PURE__ */ __name((file, tier) => {
491
- const fs7 = getSyncFs();
492
- if (!fs7) return null;
493
- const raw = readTextFile(fs7, file);
491
+ const fs9 = getSyncFs();
492
+ if (!fs9) return null;
493
+ const raw = readTextFile(fs9, file);
494
494
  if (raw === null) return null;
495
495
  return resolveSettingsEntry(parseSettings(raw, file), tier, file);
496
496
  }, "readStorageSettings");
@@ -506,13 +506,13 @@ function resolveUserAnchor() {
506
506
  return joinStoragePath(stripTrailingSeparator(home.trim()), DOTMEM_USER_ANCHOR_DIR_NAME);
507
507
  }
508
508
  function readDotMemStorageLocator() {
509
- const fs7 = getSyncFs();
510
- if (!fs7) return null;
509
+ const fs9 = getSyncFs();
510
+ if (!fs9) return null;
511
511
  const anchor = resolveUserAnchor();
512
512
  const locatorFile = resolveLocatorFilePath(anchor);
513
513
  let raw;
514
514
  try {
515
- raw = decodeText(fs7.readFileSync(locatorFile), { source: locatorFile });
515
+ raw = decodeText(fs9.readFileSync(locatorFile), { source: locatorFile });
516
516
  } catch (error) {
517
517
  if (error instanceof UnsupportedEncodingError) {
518
518
  throw new exports.DotMemStorageLocationError(
@@ -628,8 +628,8 @@ async function probeDotMemStorageCapabilities(root) {
628
628
  multiWriterSafety: "unsupported",
629
629
  notes
630
630
  };
631
- const fs7 = getSyncFs();
632
- if (!fs7) {
631
+ const fs9 = getSyncFs();
632
+ if (!fs9) {
633
633
  notes.push("no filesystem access in this runtime");
634
634
  return report;
635
635
  }
@@ -715,14 +715,14 @@ async function relocateDotMemStorage(targetRoot, options = {}) {
715
715
  `Storage relocation target ${target} and the active storage root ${current.storageRoot} must not contain each other.`
716
716
  );
717
717
  }
718
- const fs7 = getSyncFs();
719
- if (!fs7) {
718
+ const fs9 = getSyncFs();
719
+ if (!fs9) {
720
720
  throw new exports.DotMemStorageLocationError("Storage relocation requires filesystem access, which is unavailable in this runtime.");
721
721
  }
722
722
  const fsPromises = await nodeFsPromises();
723
723
  await fsPromises.mkdir(target, { recursive: true });
724
724
  try {
725
- const access = fs7.statSync(target);
725
+ const access = fs9.statSync(target);
726
726
  if (!access.isDirectory()) throw new Error("not a directory");
727
727
  } catch (error) {
728
728
  if (error instanceof exports.DotMemStorageLocationError) throw error;
@@ -731,7 +731,7 @@ async function relocateDotMemStorage(targetRoot, options = {}) {
731
731
  );
732
732
  }
733
733
  await migrateStorageData(current.storageRoot, target);
734
- if (!verifyMigratedData(fs7, current.storageRoot, target)) {
734
+ if (!verifyMigratedData(fs9, current.storageRoot, target)) {
735
735
  throw new exports.DotMemStorageLocationError(
736
736
  `Storage relocation to ${target} could not be verified: migrated data is incomplete. The locator at ${current.locatorFile} was not updated and the storage root remains ${current.storageRoot}.`
737
737
  );
@@ -776,15 +776,15 @@ async function restoreDefaultDotMemStorage(options = {}) {
776
776
  if (current.source === "default") {
777
777
  return current;
778
778
  }
779
- const fs7 = getSyncFs();
780
- if (!fs7) {
779
+ const fs9 = getSyncFs();
780
+ if (!fs9) {
781
781
  throw new exports.DotMemStorageLocationError("Restoring the default storage location requires filesystem access, which is unavailable in this runtime.");
782
782
  }
783
783
  const fsPromises = await nodeFsPromises();
784
784
  const target = current.anchor;
785
785
  await fsPromises.mkdir(target, { recursive: true });
786
786
  await migrateStorageData(current.storageRoot, target);
787
- if (!verifyMigratedData(fs7, current.storageRoot, target)) {
787
+ if (!verifyMigratedData(fs9, current.storageRoot, target)) {
788
788
  throw new exports.DotMemStorageLocationError(
789
789
  `Restoring the default location ${target} could not be verified: migrated data is incomplete. The locator at ${current.locatorFile} was not removed and still points to ${current.storageRoot}.`
790
790
  );
@@ -832,9 +832,9 @@ var init_storage_location = __esm({
832
832
  return proc && typeof proc.cwd === "function" ? proc.cwd() : ".";
833
833
  }, "currentWorkingDirectory");
834
834
  packageInstallPathHint = null;
835
- exports.noteDotMemPackageInstallPath = /* @__PURE__ */ __name((path5) => {
836
- if (typeof path5 === "string" && path5.trim()) {
837
- packageInstallPathHint = normalizeStoragePath(path5.trim());
835
+ exports.noteDotMemPackageInstallPath = /* @__PURE__ */ __name((path8) => {
836
+ if (typeof path8 === "string" && path8.trim()) {
837
+ packageInstallPathHint = normalizeStoragePath(path8.trim());
838
838
  }
839
839
  }, "noteDotMemPackageInstallPath");
840
840
  looksLikeDotMemInstallPath = /* @__PURE__ */ __name((value) => {
@@ -883,10 +883,10 @@ var init_storage_location = __esm({
883
883
  cliStorageRootOverride = null;
884
884
  }, "clearDotMemStorageRootOverride");
885
885
  hasRecognizableStore = /* @__PURE__ */ __name((root) => {
886
- const fs7 = getSyncFs();
887
- if (!fs7) return false;
886
+ const fs9 = getSyncFs();
887
+ if (!fs9) return false;
888
888
  try {
889
- const entries2 = fs7.readdirSync(root);
889
+ const entries2 = fs9.readdirSync(root);
890
890
  return entries2.some((name) => name.endsWith(".mem") || name === "policy" || name === "DOTMEM.md" || name === "projects");
891
891
  } catch {
892
892
  return false;
@@ -912,10 +912,10 @@ var init_storage_location = __esm({
912
912
  }
913
913
  const root = normalizeStoragePath(trimmed);
914
914
  assertNotInsidePackageInstall(root, source);
915
- const fs7 = getSyncFs();
916
- if (!fs7) return root;
915
+ const fs9 = getSyncFs();
916
+ if (!fs9) return root;
917
917
  try {
918
- const stats = fs7.statSync(root);
918
+ const stats = fs9.statSync(root);
919
919
  if (!stats.isDirectory()) {
920
920
  throw invalidConfiguredRoot(trimmed, source, "the path exists but is not a directory");
921
921
  }
@@ -929,11 +929,11 @@ var init_storage_location = __esm({
929
929
  __name(describeDotMemStorage, "describeDotMemStorage");
930
930
  __name(resolveDotMemStorageRoot, "resolveDotMemStorageRoot");
931
931
  __name(probeDotMemStorageCapabilities, "probeDotMemStorageCapabilities");
932
- collectRelativeEntries = /* @__PURE__ */ __name((fs7, root, prefix = "") => {
932
+ collectRelativeEntries = /* @__PURE__ */ __name((fs9, root, prefix = "") => {
933
933
  const entries2 = [];
934
934
  let dirents;
935
935
  try {
936
- dirents = fs7.readdirSync(root, { withFileTypes: true });
936
+ dirents = fs9.readdirSync(root, { withFileTypes: true });
937
937
  } catch {
938
938
  return entries2;
939
939
  }
@@ -941,23 +941,23 @@ var init_storage_location = __esm({
941
941
  const relative = prefix ? `${prefix}/${dirent.name}` : dirent.name;
942
942
  if (relative === DOTMEM_STORAGE_LOCATOR_FILE_NAME || relative === `${DOTMEM_STORAGE_LOCATOR_FILE_NAME}.tmp`) continue;
943
943
  if (dirent.isDirectory()) {
944
- entries2.push(...collectRelativeEntries(fs7, joinStoragePath(root, dirent.name), relative));
944
+ entries2.push(...collectRelativeEntries(fs9, joinStoragePath(root, dirent.name), relative));
945
945
  } else {
946
946
  entries2.push(relative);
947
947
  }
948
948
  }
949
949
  return entries2.sort();
950
950
  }, "collectRelativeEntries");
951
- verifyMigratedData = /* @__PURE__ */ __name((fs7, from, to) => {
952
- const expected = collectRelativeEntries(fs7, from);
953
- const migrated = new Set(collectRelativeEntries(fs7, to));
951
+ verifyMigratedData = /* @__PURE__ */ __name((fs9, from, to) => {
952
+ const expected = collectRelativeEntries(fs9, from);
953
+ const migrated = new Set(collectRelativeEntries(fs9, to));
954
954
  return expected.every((relative) => migrated.has(relative));
955
955
  }, "verifyMigratedData");
956
956
  migrateStorageData = /* @__PURE__ */ __name(async (from, to) => {
957
- const fs7 = getSyncFs();
958
- if (!fs7) throw new exports.DotMemStorageLocationError("Storage migration requires filesystem access, which is unavailable in this runtime.");
957
+ const fs9 = getSyncFs();
958
+ if (!fs9) throw new exports.DotMemStorageLocationError("Storage migration requires filesystem access, which is unavailable in this runtime.");
959
959
  const fsPromises = await nodeFsPromises();
960
- for (const relative of collectRelativeEntries(fs7, from)) {
960
+ for (const relative of collectRelativeEntries(fs9, from)) {
961
961
  const source = joinStoragePath(from, ...relative.split("/"));
962
962
  const destination = joinStoragePath(to, ...relative.split("/"));
963
963
  await fsPromises.mkdir(parentStoragePath(destination), { recursive: true });
@@ -978,10 +978,10 @@ var init_storage_location = __esm({
978
978
  await fsPromises.rename(temporary, locatorFile);
979
979
  }, "writeStorageLocator");
980
980
  clearMigratedSource = /* @__PURE__ */ __name(async (root, removeRoot) => {
981
- const fs7 = getSyncFs();
982
- if (!fs7) return;
981
+ const fs9 = getSyncFs();
982
+ if (!fs9) return;
983
983
  const fsPromises = await nodeFsPromises();
984
- for (const relative of collectRelativeEntries(fs7, root)) {
984
+ for (const relative of collectRelativeEntries(fs9, root)) {
985
985
  await fsPromises.rm(joinStoragePath(root, ...relative.split("/")), { recursive: true, force: true }).catch(() => void 0);
986
986
  }
987
987
  if (removeRoot && root !== resolveUserAnchor()) {
@@ -989,11 +989,11 @@ var init_storage_location = __esm({
989
989
  }
990
990
  }, "clearMigratedSource");
991
991
  writeSettingsFile = /* @__PURE__ */ __name(async (file, transform) => {
992
- const fs7 = getSyncFs();
993
- if (!fs7) throw new exports.DotMemStorageLocationError("Writing storage settings requires filesystem access, which is unavailable in this runtime.");
992
+ const fs9 = getSyncFs();
993
+ if (!fs9) throw new exports.DotMemStorageLocationError("Writing storage settings requires filesystem access, which is unavailable in this runtime.");
994
994
  let document = {};
995
995
  try {
996
- const raw = fs7.readFileSync(file, "utf8");
996
+ const raw = fs9.readFileSync(file, "utf8");
997
997
  const parsed = JSON.parse(raw);
998
998
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("not an object");
999
999
  document = parsed;
@@ -1748,8 +1748,8 @@ __export(brain_exports, {
1748
1748
  });
1749
1749
  async function brainLoad(brainPath) {
1750
1750
  try {
1751
- const fs7 = await nodeFs();
1752
- const raw = await fs7.readFile(brainPath, "utf8");
1751
+ const fs9 = await nodeFs();
1752
+ const raw = await fs9.readFile(brainPath, "utf8");
1753
1753
  const doc = JSON.parse(raw);
1754
1754
  if (doc.format !== "dotmem.brain" || doc.version !== 1) return emptyBrain();
1755
1755
  if (!Array.isArray(doc.relationships)) return emptyBrain();
@@ -1759,26 +1759,26 @@ async function brainLoad(brainPath) {
1759
1759
  }
1760
1760
  }
1761
1761
  async function brainSave(brainPath, document) {
1762
- const fs7 = await nodeFs();
1762
+ const fs9 = await nodeFs();
1763
1763
  const dir = brainPath.includes("/") ? brainPath.slice(0, brainPath.lastIndexOf("/")) : brainPath.includes("\\") ? brainPath.slice(0, brainPath.lastIndexOf("\\")) : ".";
1764
- await fs7.mkdir(dir, { recursive: true });
1764
+ await fs9.mkdir(dir, { recursive: true });
1765
1765
  const tmp = `${brainPath}.${process.pid}.${Date.now().toString(36)}.tmp`;
1766
1766
  try {
1767
- await fs7.writeFile(tmp, JSON.stringify(document, null, 2));
1768
- await fs7.rename(tmp, brainPath);
1767
+ await fs9.writeFile(tmp, JSON.stringify(document, null, 2));
1768
+ await fs9.rename(tmp, brainPath);
1769
1769
  } catch (error) {
1770
- await fs7.rm(tmp, { force: true }).catch(() => void 0);
1770
+ await fs9.rm(tmp, { force: true }).catch(() => void 0);
1771
1771
  throw error;
1772
1772
  }
1773
1773
  }
1774
1774
  async function getBrainDocument() {
1775
- const path5 = getBrainPath();
1776
- cachedBrainPath = path5;
1777
- return brainLoad(path5);
1775
+ const path8 = getBrainPath();
1776
+ cachedBrainPath = path8;
1777
+ return brainLoad(path8);
1778
1778
  }
1779
1779
  async function saveBrainDocument(document) {
1780
- const path5 = cachedBrainPath || getBrainPath();
1781
- await brainSave(path5, document);
1780
+ const path8 = cachedBrainPath || getBrainPath();
1781
+ await brainSave(path8, document);
1782
1782
  }
1783
1783
  function resetBrainPathCache() {
1784
1784
  cachedBrainPath = null;
@@ -1934,11 +1934,11 @@ var init_state = __esm({
1934
1934
  }
1935
1935
  for (let index = 0; index < evidence.length; index++) {
1936
1936
  const entry = evidence[index];
1937
- const path5 = `evidence[${index}]`;
1937
+ const path8 = `evidence[${index}]`;
1938
1938
  if (Array.isArray(entry)) {
1939
1939
  throw canonicalEvidenceError({
1940
1940
  claimId: claim.id,
1941
- path: path5,
1941
+ path: path8,
1942
1942
  problem: CANONICAL_EVIDENCE_PROBLEMS.tupleEntry,
1943
1943
  received: entry,
1944
1944
  fix: CANONICAL_EVIDENCE_FIX.tupleEntry
@@ -1947,7 +1947,7 @@ var init_state = __esm({
1947
1947
  if (!entry || typeof entry !== "object") {
1948
1948
  throw canonicalEvidenceError({
1949
1949
  claimId: claim.id,
1950
- path: path5,
1950
+ path: path8,
1951
1951
  problem: CANONICAL_EVIDENCE_PROBLEMS.nonObjectEntry,
1952
1952
  received: entry,
1953
1953
  fix: CANONICAL_EVIDENCE_FIX.nonObjectEntry
@@ -1956,7 +1956,7 @@ var init_state = __esm({
1956
1956
  if (!requiredText(entry.id)) {
1957
1957
  throw canonicalEvidenceError({
1958
1958
  claimId: claim.id,
1959
- path: `${path5}.id`,
1959
+ path: `${path8}.id`,
1960
1960
  problem: CANONICAL_EVIDENCE_PROBLEMS.missingId,
1961
1961
  received: entry,
1962
1962
  fix: CANONICAL_EVIDENCE_FIX.missingId
@@ -1967,7 +1967,7 @@ var init_state = __esm({
1967
1967
  if (fieldValue !== void 0 && !requiredText(fieldValue)) {
1968
1968
  throw canonicalEvidenceError({
1969
1969
  claimId: claim.id,
1970
- path: `${path5}.${field}`,
1970
+ path: `${path8}.${field}`,
1971
1971
  problem: CANONICAL_EVIDENCE_PROBLEMS.invalidOptionalField(field),
1972
1972
  received: fieldValue,
1973
1973
  fix: CANONICAL_EVIDENCE_FIX.invalidOptionalField(field)
@@ -2012,12 +2012,6 @@ var init_state = __esm({
2012
2012
  if (claim.sourceProject !== void 0 && !requiredText(claim.sourceProject)) {
2013
2013
  throw new Error(`Claim ${claim.id} has an invalid sourceProject`);
2014
2014
  }
2015
- if (claim.check !== void 0) {
2016
- const check = claim.check;
2017
- 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)) {
2018
- throw new Error(`Claim ${claim.id} has an invalid check`);
2019
- }
2020
- }
2021
2015
  return claim;
2022
2016
  }, "validateClaim");
2023
2017
  validateKnowledgeState = /* @__PURE__ */ __name((value) => {
@@ -2549,6 +2543,10 @@ var init_discover = __esm({
2549
2543
  freshEligible.map((claim) => [claim.id, isEligibleByApplicability(claim, situationApplicability)])
2550
2544
  );
2551
2545
  const eligible = freshEligible.map((claim) => ({ claim, match: applicabilityMatches.get(claim.id) })).filter((candidate) => candidate.match.eligible);
2546
+ const eligibleForContext = options.includeRules === true ? eligible : eligible.filter((candidate) => {
2547
+ const knowledge = candidate.claim.knowledge;
2548
+ return !(knowledge && typeof knowledge === "object" && !Array.isArray(knowledge) && knowledge.kind === "rule");
2549
+ });
2552
2550
  const applicabilityOmissions = freshEligible.filter((claim) => !applicabilityMatches.get(claim.id).eligible).map((claim) => {
2553
2551
  const match = applicabilityMatches.get(claim.id);
2554
2552
  const mismatched = Object.entries(match.dimensions).filter(([, state3]) => state3 === "MISMATCH").map(([dimension]) => dimension);
@@ -2572,7 +2570,7 @@ var init_discover = __esm({
2572
2570
  }
2573
2571
  const currentnessOf = /* @__PURE__ */ __name((claim) => deriveCurrentness(claim, { retractedIds, supersededIds, contestedIds }), "currentnessOf");
2574
2572
  if (queryTerms.length === 0) {
2575
- const baselineAll = eligible.filter((candidate) => candidate.claim.applicability?.baseline === true).map((candidate) => candidate.claim).sort((left, right) => {
2573
+ const baselineAll = eligibleForContext.filter((candidate) => candidate.claim.applicability?.baseline === true).map((candidate) => candidate.claim).sort((left, right) => {
2576
2574
  const leftTime = acquiredTime(left);
2577
2575
  const rightTime = acquiredTime(right);
2578
2576
  return rightTime - leftTime || Number(right.scope === "project") - Number(left.scope === "project") || left.id.localeCompare(right.id);
@@ -2616,7 +2614,7 @@ var init_discover = __esm({
2616
2614
  ]
2617
2615
  };
2618
2616
  }
2619
- const ranked = eligible.map(
2617
+ const ranked = eligibleForContext.map(
2620
2618
  (candidate) => rankCandidate(
2621
2619
  candidate.claim,
2622
2620
  situation,
@@ -2631,7 +2629,7 @@ var init_discover = __esm({
2631
2629
  );
2632
2630
  const rankedIds = new Set(ranked.map((candidate) => candidate.claim.id));
2633
2631
  const rankingOmissions = [
2634
- ...eligible.filter((candidate) => !rankedIds.has(candidate.claim.id)).map((candidate) => ({
2632
+ ...eligibleForContext.filter((candidate) => !rankedIds.has(candidate.claim.id)).map((candidate) => ({
2635
2633
  id: candidate.claim.id,
2636
2634
  reason: "no-term-match",
2637
2635
  gate: "ranking",
@@ -2930,9 +2928,9 @@ var init_policy_namespace_lock = __esm({
2930
2928
  acquiredAt: (/* @__PURE__ */ new Date()).toISOString(),
2931
2929
  token: `lock-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`
2932
2930
  }), "createOwner");
2933
- readLockOwner = /* @__PURE__ */ __name(async (fs7, lockPath) => {
2931
+ readLockOwner = /* @__PURE__ */ __name(async (fs9, lockPath) => {
2934
2932
  try {
2935
- const raw = await fs7.readFile(lockPath, "utf8");
2933
+ const raw = await fs9.readFile(lockPath, "utf8");
2936
2934
  const parsed = JSON.parse(raw);
2937
2935
  if (!parsed || typeof parsed !== "object") return null;
2938
2936
  return {
@@ -2945,11 +2943,11 @@ var init_policy_namespace_lock = __esm({
2945
2943
  return null;
2946
2944
  }
2947
2945
  }, "readLockOwner");
2948
- acquireLock = /* @__PURE__ */ __name(async (fs7, lockPath, owner) => {
2946
+ acquireLock = /* @__PURE__ */ __name(async (fs9, lockPath, owner) => {
2949
2947
  let brokenOwner = null;
2950
2948
  for (let attempt = 0; attempt <= POLICY_LOCK_RETRY_ATTEMPTS; attempt++) {
2951
2949
  try {
2952
- await fs7.writeFile(lockPath, JSON.stringify(owner), { encoding: "utf8", flag: "wx" });
2950
+ await fs9.writeFile(lockPath, JSON.stringify(owner), { encoding: "utf8", flag: "wx" });
2953
2951
  return brokenOwner;
2954
2952
  } catch (error) {
2955
2953
  const code = error?.code;
@@ -2958,12 +2956,12 @@ var init_policy_namespace_lock = __esm({
2958
2956
  `Policy namespace exclusive creation is not verifiable on this substrate (${String(code)}); policy mutation fails closed`
2959
2957
  );
2960
2958
  }
2961
- const held = await readLockOwner(fs7, lockPath);
2959
+ const held = await readLockOwner(fs9, lockPath);
2962
2960
  const acquiredAt = held ? Date.parse(held.acquiredAt) : Number.NaN;
2963
2961
  const age = Number.isFinite(acquiredAt) ? Date.now() - acquiredAt : Number.POSITIVE_INFINITY;
2964
2962
  if (age > POLICY_LOCK_TTL_MS) {
2965
2963
  const stale = held ?? { pid: 0, host: "unknown", acquiredAt: "", token: "" };
2966
- const outcome = await breakStalePolicyLock(fs7, lockPath, stale);
2964
+ const outcome = await breakStalePolicyLock(fs9, lockPath, stale);
2967
2965
  if (outcome === "broken") {
2968
2966
  brokenOwner = stale;
2969
2967
  }
@@ -2982,21 +2980,21 @@ var init_policy_namespace_lock = __esm({
2982
2980
  `Policy namespace lock could not be acquired after ${POLICY_LOCK_RETRY_ATTEMPTS} bounded retries; policy mutation fails closed`
2983
2981
  );
2984
2982
  }, "acquireLock");
2985
- breakStalePolicyLock = /* @__PURE__ */ __name(async (fs7, lockPath, staleOwner) => {
2983
+ breakStalePolicyLock = /* @__PURE__ */ __name(async (fs9, lockPath, staleOwner) => {
2986
2984
  const candidate = `${lockPath}.breaking-${staleOwner.token || "unknown"}`;
2987
2985
  try {
2988
- await fs7.rename(lockPath, candidate);
2986
+ await fs9.rename(lockPath, candidate);
2989
2987
  } catch (error) {
2990
2988
  if (error.code === "ENOENT") return "lost";
2991
2989
  throw error;
2992
2990
  }
2993
- const moved = await readLockOwner(fs7, candidate);
2991
+ const moved = await readLockOwner(fs9, candidate);
2994
2992
  if (moved && moved.token === staleOwner.token) {
2995
- await fs7.rm(candidate, { force: true }).catch(() => void 0);
2993
+ await fs9.rm(candidate, { force: true }).catch(() => void 0);
2996
2994
  return "broken";
2997
2995
  }
2998
2996
  try {
2999
- await fs7.link(candidate, lockPath);
2997
+ await fs9.link(candidate, lockPath);
3000
2998
  } catch (error) {
3001
2999
  const code = error?.code;
3002
3000
  if (code !== "EEXIST") {
@@ -3005,22 +3003,22 @@ var init_policy_namespace_lock = __esm({
3005
3003
  );
3006
3004
  }
3007
3005
  }
3008
- await fs7.rm(candidate, { force: true }).catch(() => void 0);
3006
+ await fs9.rm(candidate, { force: true }).catch(() => void 0);
3009
3007
  return "lost";
3010
3008
  }, "breakStalePolicyLock");
3011
- releaseLock = /* @__PURE__ */ __name(async (fs7, lockPath, owner) => {
3012
- const held = await readLockOwner(fs7, lockPath);
3009
+ releaseLock = /* @__PURE__ */ __name(async (fs9, lockPath, owner) => {
3010
+ const held = await readLockOwner(fs9, lockPath);
3013
3011
  if (!held || held.token !== owner.token) return;
3014
- await fs7.rm(lockPath, { force: true }).catch(() => void 0);
3012
+ await fs9.rm(lockPath, { force: true }).catch(() => void 0);
3015
3013
  }, "releaseLock");
3016
3014
  withPolicyNamespaceLock = /* @__PURE__ */ __name(async (operation, options = {}) => {
3017
3015
  const directory = options.directory ?? resolveUserPolicyDir();
3018
3016
  const lockPath = resolvePolicyNamespaceLockPath(directory);
3019
3017
  return enqueue(directory, async () => {
3020
- const fs7 = await nodeFs2();
3018
+ const fs9 = await nodeFs2();
3021
3019
  const owner = await createOwner();
3022
- await fs7.mkdir(parentDirectoryOf(lockPath), { recursive: true }).catch(() => void 0);
3023
- const brokenOwner = await acquireLock(fs7, lockPath, owner);
3020
+ await fs9.mkdir(parentDirectoryOf(lockPath), { recursive: true }).catch(() => void 0);
3021
+ const brokenOwner = await acquireLock(fs9, lockPath, owner);
3024
3022
  if (brokenOwner && options.onLockBreak) {
3025
3023
  options.onLockBreak({
3026
3024
  at: (/* @__PURE__ */ new Date()).toISOString(),
@@ -3031,7 +3029,7 @@ var init_policy_namespace_lock = __esm({
3031
3029
  try {
3032
3030
  return await operation({
3033
3031
  assertOwnership: /* @__PURE__ */ __name(async () => {
3034
- const held = await readLockOwner(fs7, lockPath);
3032
+ const held = await readLockOwner(fs9, lockPath);
3035
3033
  if (!held || held.token !== owner.token) {
3036
3034
  throw new PolicyNamespaceLockError(
3037
3035
  "Policy namespace lock ownership was lost before commit; policy mutation fails closed"
@@ -3040,7 +3038,7 @@ var init_policy_namespace_lock = __esm({
3040
3038
  }, "assertOwnership")
3041
3039
  });
3042
3040
  } finally {
3043
- await releaseLock(fs7, lockPath, owner);
3041
+ await releaseLock(fs9, lockPath, owner);
3044
3042
  }
3045
3043
  });
3046
3044
  }, "withPolicyNamespaceLock");
@@ -3368,35 +3366,35 @@ var init_policy_store = __esm({
3368
3366
  }
3369
3367
  /** Read one namespace document: always fresh, always validated. */
3370
3368
  async load(namespace2) {
3371
- const fs7 = await nodeFs3();
3372
- return this.readDocument(fs7, namespace2);
3369
+ const fs9 = await nodeFs3();
3370
+ return this.readDocument(fs9, namespace2);
3373
3371
  }
3374
- async readDocument(fs7, namespace2) {
3372
+ async readDocument(fs9, namespace2) {
3375
3373
  let raw;
3376
3374
  try {
3377
- raw = await fs7.readFile(this.filePath(namespace2), "utf8");
3375
+ raw = await fs9.readFile(this.filePath(namespace2), "utf8");
3378
3376
  } catch (error) {
3379
3377
  if (error.code === "ENOENT") return emptyPolicyDocument();
3380
3378
  throw error;
3381
3379
  }
3382
3380
  return validatePolicyDocument(JSON.parse(raw));
3383
3381
  }
3384
- async writeDocument(fs7, namespace2, document) {
3385
- await fs7.mkdir(this.dir(), { recursive: true });
3382
+ async writeDocument(fs9, namespace2, document) {
3383
+ await fs9.mkdir(this.dir(), { recursive: true });
3386
3384
  const filePath = this.filePath(namespace2);
3387
3385
  const temporary = `${filePath}.${process.pid}.${Date.now().toString(36)}.tmp`;
3388
3386
  try {
3389
- await fs7.writeFile(temporary, `${JSON.stringify(document, null, 2)}
3387
+ await fs9.writeFile(temporary, `${JSON.stringify(document, null, 2)}
3390
3388
  `, "utf8");
3391
- const handle = await fs7.open(temporary, "r+");
3389
+ const handle = await fs9.open(temporary, "r+");
3392
3390
  try {
3393
3391
  await handle.sync();
3394
3392
  } finally {
3395
3393
  await handle.close();
3396
3394
  }
3397
- await fs7.rename(temporary, filePath);
3395
+ await fs9.rename(temporary, filePath);
3398
3396
  } catch (error) {
3399
- await fs7.rm(temporary, { force: true }).catch(() => void 0);
3397
+ await fs9.rm(temporary, { force: true }).catch(() => void 0);
3400
3398
  throw error;
3401
3399
  }
3402
3400
  }
@@ -3415,8 +3413,8 @@ var init_policy_store = __esm({
3415
3413
  const lockBreaks = [];
3416
3414
  try {
3417
3415
  return await withPolicyNamespaceLock(async (session2) => {
3418
- const fs7 = await nodeFs3();
3419
- const document = await this.readDocument(fs7, namespace2);
3416
+ const fs9 = await nodeFs3();
3417
+ const document = await this.readDocument(fs9, namespace2);
3420
3418
  if (options.basedOnRevision !== void 0 && options.basedOnRevision !== document.revision) {
3421
3419
  throw new PolicyStoreError(
3422
3420
  `Stale policy revision: caller expected ${options.basedOnRevision}, current document revision is ${document.revision}`
@@ -3437,7 +3435,7 @@ var init_policy_store = __esm({
3437
3435
  }
3438
3436
  validatePolicyDocument(next);
3439
3437
  await session2.assertOwnership();
3440
- await this.writeDocument(fs7, namespace2, next);
3438
+ await this.writeDocument(fs9, namespace2, next);
3441
3439
  return outcome.result;
3442
3440
  }, { directory, onLockBreak: /* @__PURE__ */ __name((lockBreak) => {
3443
3441
  lockBreaks.push(lockBreak);
@@ -3811,6 +3809,74 @@ var init_acquisition_limits = __esm({
3811
3809
  }
3812
3810
  });
3813
3811
 
3812
+ // core/knowledge/verification.ts
3813
+ var deriveTrustBasis, buildVerificationRecord, callerInjectedVerificationMetadata, isCallerDeclaredVerified;
3814
+ var init_verification = __esm({
3815
+ "core/knowledge/verification.ts"() {
3816
+ deriveTrustBasis = /* @__PURE__ */ __name((claim, options = {}) => {
3817
+ const { packageAuth, externalAttestation, verificationRecord, resolvedEvidence } = options;
3818
+ const evidenceCount = Array.isArray(claim.evidence) ? claim.evidence.length : 0;
3819
+ const resolvedIds = resolvedEvidence ?? /* @__PURE__ */ new Set();
3820
+ const evidenceResolved = evidenceCount > 0 && resolvedIds.size === evidenceCount;
3821
+ const mechanicallyChecked = verificationRecord !== null && verificationRecord !== void 0 && verificationRecord.verifyStatus === "valid";
3822
+ const externallyAttested = packageAuth !== void 0 && packageAuth.status === "valid" && externalAttestation !== void 0 && externalAttestation.validated === true;
3823
+ if (externallyAttested) {
3824
+ return {
3825
+ basis: "externally-attested",
3826
+ reason: "Package signature is cryptographically valid and an external attestation was validated by a trusted mechanism",
3827
+ evidenceResolved,
3828
+ mechanicallyChecked,
3829
+ externallyAttested: true
3830
+ };
3831
+ }
3832
+ if (mechanicallyChecked) {
3833
+ return {
3834
+ basis: "mechanically-checked",
3835
+ reason: `A ${verificationRecord.check.kind} check executed by ${verificationRecord.verifiedBy} at ${verificationRecord.verifiedAt} succeeded; status bounded to ${verificationRecord.verifyStatus}`,
3836
+ evidenceResolved,
3837
+ mechanicallyChecked: true,
3838
+ externallyAttested: false
3839
+ };
3840
+ }
3841
+ if (evidenceCount > 0) {
3842
+ return {
3843
+ basis: "evidenced",
3844
+ reason: `${evidenceCount} evidence reference(s) present but not independently resolved and validated`,
3845
+ evidenceResolved: false,
3846
+ mechanicallyChecked: false,
3847
+ externallyAttested: false
3848
+ };
3849
+ }
3850
+ const declaredLabel = claim.epistemicType === "verified" ? ` (stored label ${claim.epistemicType})` : "";
3851
+ return {
3852
+ basis: "declared",
3853
+ reason: `Caller/author assertion without independent validation${declaredLabel}. Trust follows provenance, not the label.`,
3854
+ evidenceResolved: false,
3855
+ mechanicallyChecked: false,
3856
+ externallyAttested: false
3857
+ };
3858
+ }, "deriveTrustBasis");
3859
+ buildVerificationRecord = /* @__PURE__ */ __name((claimId, probe) => {
3860
+ if (probe.status !== "valid") return null;
3861
+ return {
3862
+ verifiedAt: (/* @__PURE__ */ new Date()).toISOString(),
3863
+ verifiedBy: "dotmem-verify",
3864
+ verifyStatus: probe.status,
3865
+ check: { kind: probe.kind, target: probe.target }
3866
+ };
3867
+ }, "buildVerificationRecord");
3868
+ callerInjectedVerificationMetadata = /* @__PURE__ */ __name((knowledge) => {
3869
+ if (!knowledge || typeof knowledge !== "object" || Array.isArray(knowledge)) return [];
3870
+ const keys = [];
3871
+ for (const key of ["verifiedAt", "verifiedBy", "verifyStatus"]) {
3872
+ if (key in knowledge) keys.push(key);
3873
+ }
3874
+ return keys;
3875
+ }, "callerInjectedVerificationMetadata");
3876
+ isCallerDeclaredVerified = /* @__PURE__ */ __name((value) => value === "verified", "isCallerDeclaredVerified");
3877
+ }
3878
+ });
3879
+
3814
3880
  // core/knowledge/acquisition-boundary.ts
3815
3881
  exports.MEMORY_ACQUIRE_EVENT = void 0; exports.crossAcquisitionBoundary = void 0;
3816
3882
  var init_acquisition_boundary = __esm({
@@ -3820,6 +3886,7 @@ var init_acquisition_boundary = __esm({
3820
3886
  init_policy_store();
3821
3887
  init_applicability();
3822
3888
  init_acquisition_limits();
3889
+ init_verification();
3823
3890
  exports.MEMORY_ACQUIRE_EVENT = "memory.acquire";
3824
3891
  if (!(exports.MEMORY_ACQUIRE_EVENT in CANONICAL_EVENTS)) {
3825
3892
  throw new Error(
@@ -3829,6 +3896,12 @@ var init_acquisition_boundary = __esm({
3829
3896
  exports.crossAcquisitionBoundary = /* @__PURE__ */ __name(async (opts, dependencies = {}) => {
3830
3897
  const limits = dependencies.limits ?? MEMORY_ACQUIRE_LIMITS;
3831
3898
  checkAcquireLimits(opts.knowledge, limits);
3899
+ const injected = callerInjectedVerificationMetadata(opts.knowledge);
3900
+ if (injected.length > 0) {
3901
+ throw new Error(
3902
+ `Claim ${opts.id} rejected at write time: caller-supplied verification metadata is not accepted: ${injected.join(", ")}`
3903
+ );
3904
+ }
3832
3905
  const sanitized = sanitizeKnowledge(opts.knowledge);
3833
3906
  if (sanitized.disposition === "reject") {
3834
3907
  throw new Error(
@@ -3879,6 +3952,7 @@ var FORMAT, STATUS, NOTICE, DEFAULT_MAX_CANDIDATES, DEFAULT_MAX_CHARACTERS, MIN_
3879
3952
  var init_project = __esm({
3880
3953
  "core/knowledge/project.ts"() {
3881
3954
  init_state();
3955
+ init_verification();
3882
3956
  init_user_paths();
3883
3957
  init_discover();
3884
3958
  init_context_constants();
@@ -3890,18 +3964,36 @@ var init_project = __esm({
3890
3964
  MIN_MAX_CHARACTERS = DOTMEM_CONTEXT_DEFAULT_MIN_MAX__CHARACTERS;
3891
3965
  projectCandidate = /* @__PURE__ */ __name((candidate) => {
3892
3966
  const claim = validateClaim(candidate.claim);
3967
+ const verificationRecord = claim.knowledge && typeof claim.knowledge === "object" && !Array.isArray(claim.knowledge) && claim.knowledge.verifiedBy === "dotmem-verify" && claim.knowledge.verifyStatus === "valid" && typeof claim.knowledge.verifiedAt === "string" ? {
3968
+ verifiedAt: String(claim.knowledge.verifiedAt),
3969
+ verifiedBy: "dotmem-verify",
3970
+ verifyStatus: String(claim.knowledge.verifyStatus),
3971
+ check: { kind: "probe", target: claim.id }
3972
+ } : null;
3973
+ const derivation = deriveTrustBasis(claim, {
3974
+ verificationRecord,
3975
+ resolvedEvidence: new Set(claim.evidence.map((evidence) => evidence.id).filter((id) => id.length > 0))
3976
+ });
3977
+ const trustBasis = {
3978
+ trustBasis: derivation.basis,
3979
+ evidenceResolved: derivation.evidenceResolved,
3980
+ mechanicallyChecked: derivation.mechanicallyChecked,
3981
+ externallyAttested: derivation.externallyAttested,
3982
+ evidenceResolution: claim.evidence.map((evidence) => ({ id: evidence.id, resolved: false }))
3983
+ };
3893
3984
  return structuredClone({
3894
3985
  id: claim.id,
3895
3986
  status: "prior-acquired-experience-candidate",
3896
3987
  experience: claim.knowledge,
3897
3988
  applicability: claim.applicability,
3898
- evidence: claim.evidence,
3989
+ evidence: claim.evidence.map((evidence) => ({ ...evidence, resolved: false })),
3899
3990
  ...claim.epistemicType ? { epistemicType: claim.epistemicType } : {},
3900
3991
  ...claim.provenance ? { provenance: claim.provenance } : {},
3901
3992
  ...claim.acquiredAt ? { acquiredAt: claim.acquiredAt } : {},
3902
3993
  ...claim.revision ? { revision: claim.revision } : {},
3903
3994
  ...candidate.explanation.sourceId ? { sourceId: candidate.explanation.sourceId } : {},
3904
- ...candidate.currentness ? { currentness: candidate.currentness } : {}
3995
+ ...candidate.currentness ? { currentness: candidate.currentness } : {},
3996
+ trustBasis
3905
3997
  });
3906
3998
  }, "projectCandidate");
3907
3999
  GIST_MAX_LENGTH = 80;
@@ -3960,7 +4052,8 @@ var init_project = __esm({
3960
4052
  ...experience.provenance ? { provenance: [experience.provenance.source, experience.provenance.detail ?? null] } : {},
3961
4053
  ...experience.acquiredAt ? { acquiredAt: experience.acquiredAt } : {},
3962
4054
  ...experience.revision ? { revision: experience.revision } : {},
3963
- ...experience.sourceId ? { source: experience.sourceId } : {}
4055
+ ...experience.sourceId ? { source: experience.sourceId } : {},
4056
+ ...experience.trustBasis ? { trustBasis: experience.trustBasis } : {}
3964
4057
  }), "renderExperience");
3965
4058
  renderText = /* @__PURE__ */ __name((header, experiences, omittedCandidates, manifest, render = renderExperience, currentnessSummary) => {
3966
4059
  const lines = [header];
@@ -3998,6 +4091,7 @@ var init_project = __esm({
3998
4091
  gist: deriveGist(experience.experience),
3999
4092
  epistemic: experience.epistemicType ?? null,
4000
4093
  currentness: experience.currentness ?? null,
4094
+ trustBasis: experience.trustBasis?.trustBasis ?? null,
4001
4095
  ...experience.revision ? { revision: experience.revision.kind } : {}
4002
4096
  }), "renderCompactExperience");
4003
4097
  projectDiscoveredExperience = /* @__PURE__ */ __name((discovery, options = {}) => {
@@ -6028,8 +6122,8 @@ async function signMemPackage(input, privateKey, publicKey) {
6028
6122
  const artifact = await decodePackage(input);
6029
6123
  const rawPublicKey = new Uint8Array(await crypto.subtle.exportKey("raw", publicKey));
6030
6124
  const keyId = await keyIdentity(rawPublicKey);
6031
- const path5 = signaturePath(keyId);
6032
- const existingSignatures = { ...artifact.package?.signatures, [path5]: jsonBytes({}) };
6125
+ const path8 = signaturePath(keyId);
6126
+ const existingSignatures = { ...artifact.package?.signatures, [path8]: jsonBytes({}) };
6033
6127
  const declaredPackage = await encodePackage(artifact.state, artifact.preserved, artifact.package, existingSignatures);
6034
6128
  const declaredArtifact = await decodePackage(declaredPackage);
6035
6129
  const signature = new Uint8Array(await crypto.subtle.sign(
@@ -6048,7 +6142,7 @@ async function signMemPackage(input, privateKey, publicKey) {
6048
6142
  };
6049
6143
  return encodePackage(artifact.state, artifact.preserved, artifact.package, {
6050
6144
  ...artifact.package?.signatures,
6051
- [path5]: jsonBytes(document)
6145
+ [path8]: jsonBytes(document)
6052
6146
  });
6053
6147
  }
6054
6148
  async function decodeMemArtifact(input) {
@@ -6080,7 +6174,7 @@ async function inspectMem(input) {
6080
6174
  const knownMapKeys = /* @__PURE__ */ new Set(["state", "claim", "evidence", "provenance", "revision", "epistemicType", "revisionKind"]);
6081
6175
  const unknownMapEntries = Object.keys(artifact2.preserved?.map ?? {}).filter((key) => !knownMapKeys.has(key)).length;
6082
6176
  const vocabularyEntries = Math.max(0, (artifact2.preserved?.map.epistemicType.length ?? 4) - 4) + Math.max(0, (artifact2.preserved?.map.revisionKind.length ?? 3) - 3);
6083
- const signatures = await Promise.all(Object.entries(artifact2.package?.signatures ?? {}).sort(([left], [right]) => left.localeCompare(right)).map(([path5, part]) => verifySignature(path5, part, artifact2.integrity.contentId)));
6177
+ const signatures = await Promise.all(Object.entries(artifact2.package?.signatures ?? {}).sort(([left], [right]) => left.localeCompare(right)).map(([path8, part]) => verifySignature(path8, part, artifact2.integrity.contentId)));
6084
6178
  const authenticityStatus = signatures.length === 0 ? "unsigned" : signatures.some((signature) => signature.status === "invalid") ? "invalid" : signatures.some((signature) => signature.status === "unsupported") ? "unsupported" : "valid";
6085
6179
  return {
6086
6180
  status: "valid",
@@ -6089,10 +6183,10 @@ async function inspectMem(input) {
6089
6183
  packageVersion: MEM_PACKAGE_VERSION,
6090
6184
  memoryVersion: MEM_FORMAT_VERSION,
6091
6185
  contentId: artifact2.integrity.contentId,
6092
- parts: Object.entries(artifact2.parts).sort(([a], [b]) => a.localeCompare(b)).map(([path5, part]) => ({
6093
- path: path5,
6186
+ parts: Object.entries(artifact2.parts).sort(([a], [b]) => a.localeCompare(b)).map(([path8, part]) => ({
6187
+ path: path8,
6094
6188
  bytes: part.length,
6095
- protected: path5 !== INTEGRITY_PATH && !path5.startsWith("security/signatures/")
6189
+ protected: path8 !== INTEGRITY_PATH && !path8.startsWith("security/signatures/")
6096
6190
  })),
6097
6191
  knowledge: artifact2.state,
6098
6192
  unknownSemantics: { mapEntries: unknownMapEntries, vocabularyEntries, extensionParts: Object.keys(artifact2.package?.extensions ?? {}).sort() },
@@ -6170,14 +6264,14 @@ var init_mem_package = __esm({
6170
6264
  const digest = await globalThis.crypto.subtle.digest("SHA-256", data);
6171
6265
  return `sha256:${[...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
6172
6266
  }, "sha256");
6173
- parseJson = /* @__PURE__ */ __name((bytes, path5) => {
6267
+ parseJson = /* @__PURE__ */ __name((bytes, path8) => {
6174
6268
  try {
6175
6269
  return JSON.parse(decodeText(bytes));
6176
6270
  } catch (error) {
6177
- throw new MemArtifactError("invalid", `Invalid UTF-8 JSON in ${path5}: ${error.message}`);
6271
+ throw new MemArtifactError("invalid", `Invalid UTF-8 JSON in ${path8}: ${error.message}`);
6178
6272
  }
6179
6273
  }, "parseJson");
6180
- validEntryPath = /* @__PURE__ */ __name((path5) => path5.length > 0 && path5.length <= 240 && !path5.includes("\\") && !path5.startsWith("/") && !/^[A-Za-z]:/.test(path5) && path5.split("/").every((segment) => segment.length > 0 && segment !== "." && segment !== ".."), "validEntryPath");
6274
+ validEntryPath = /* @__PURE__ */ __name((path8) => path8.length > 0 && path8.length <= 240 && !path8.includes("\\") && !path8.startsWith("/") && !/^[A-Za-z]:/.test(path8) && path8.split("/").every((segment) => segment.length > 0 && segment !== "." && segment !== ".."), "validEntryPath");
6181
6275
  concatenate = /* @__PURE__ */ __name((chunks, size) => {
6182
6276
  const result = new Uint8Array(size);
6183
6277
  let offset = 0;
@@ -6269,31 +6363,31 @@ ${contentId}
6269
6363
  [DATA_PATH]: jsonBytes(memory2.data),
6270
6364
  ...structuredClone(preservedPackage?.extensions ?? {})
6271
6365
  };
6272
- for (const path5 of Object.keys(protectedParts)) {
6273
- if (!requiredParts.includes(path5) && !path5.startsWith("extensions/")) {
6274
- throw new MemArtifactError("invalid", `Unsupported preserved package part: ${path5}`);
6366
+ for (const path8 of Object.keys(protectedParts)) {
6367
+ if (!requiredParts.includes(path8) && !path8.startsWith("extensions/")) {
6368
+ throw new MemArtifactError("invalid", `Unsupported preserved package part: ${path8}`);
6275
6369
  }
6276
- if (!validEntryPath(path5)) throw new MemArtifactError("invalid", `Unsafe MEM package path: ${path5}`);
6370
+ if (!validEntryPath(path8)) throw new MemArtifactError("invalid", `Unsafe MEM package path: ${path8}`);
6277
6371
  }
6278
- for (const path5 of Object.keys(signatures)) {
6279
- if (!/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path5)) {
6280
- throw new MemArtifactError("invalid", `Invalid MEM signature path: ${path5}`);
6372
+ for (const path8 of Object.keys(signatures)) {
6373
+ if (!/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path8)) {
6374
+ throw new MemArtifactError("invalid", `Invalid MEM signature path: ${path8}`);
6281
6375
  }
6282
6376
  }
6283
6377
  const files = {};
6284
- for (const path5 of Object.keys(protectedParts).sort()) files[path5] = await sha256(protectedParts[path5]);
6378
+ for (const path8 of Object.keys(protectedParts).sort()) files[path8] = await sha256(protectedParts[path8]);
6285
6379
  const integrity = { algorithm: "sha256", files, contentId: await digestTableIdentity(files) };
6286
6380
  const parts = { ...protectedParts, [INTEGRITY_PATH]: jsonBytes(integrity), ...signatures };
6287
- for (const [path5, bytes] of Object.entries(parts)) {
6381
+ for (const [path8, bytes] of Object.entries(parts)) {
6288
6382
  if (bytes.length > MEM_PACKAGE_WRITE_LIMITS.maximumEntryBytes) {
6289
- throw new MemArtifactError("invalid", `MEM package entry exceeds the write limit: ${path5}`);
6383
+ throw new MemArtifactError("invalid", `MEM package entry exceeds the write limit: ${path8}`);
6290
6384
  }
6291
6385
  }
6292
6386
  const uncompressedBytes = Object.values(parts).reduce((total, bytes) => total + bytes.length, 0);
6293
6387
  if (uncompressedBytes > MEM_PACKAGE_WRITE_LIMITS.maximumUncompressedBytes) {
6294
6388
  throw new MemArtifactError("invalid", "MEM package exceeds the write limit for uncompressed content");
6295
6389
  }
6296
- const zippable = Object.fromEntries(Object.keys(parts).sort().map((path5) => [path5, [parts[path5], {
6390
+ const zippable = Object.fromEntries(Object.keys(parts).sort().map((path8) => [path8, [parts[path8], {
6297
6391
  level: 6,
6298
6392
  mtime: /* @__PURE__ */ new Date("1980-01-02T00:00:00.000Z")
6299
6393
  }]]));
@@ -6308,8 +6402,8 @@ ${contentId}
6308
6402
  isZip = /* @__PURE__ */ __name((bytes) => bytes.length >= 4 && bytes[0] === 80 && bytes[1] === 75 && (bytes[2] === 3 && bytes[3] === 4 || bytes[2] === 5 && bytes[3] === 6), "isZip");
6309
6403
  decodePackage = /* @__PURE__ */ __name(async (bytes) => {
6310
6404
  const parts = readZipParts(bytes);
6311
- for (const path5 of [...requiredParts, INTEGRITY_PATH]) {
6312
- if (!parts[path5]) throw new MemArtifactError("invalid", `Missing MEM package part: ${path5}`);
6405
+ for (const path8 of [...requiredParts, INTEGRITY_PATH]) {
6406
+ if (!parts[path8]) throw new MemArtifactError("invalid", `Missing MEM package part: ${path8}`);
6313
6407
  }
6314
6408
  const manifest = parseJson(parts[MANIFEST_PATH], MANIFEST_PATH);
6315
6409
  if (manifest.format !== MEM_PACKAGE_FORMAT && manifest.format !== MEM_PACKAGE_FORMAT_LEGACY || manifest.version !== MEM_PACKAGE_VERSION) {
@@ -6320,8 +6414,8 @@ ${contentId}
6320
6414
  }
6321
6415
  const integrity = parseJson(parts[INTEGRITY_PATH], INTEGRITY_PATH);
6322
6416
  if (integrity.algorithm !== "sha256") throw new MemArtifactError("unsupported", "Unsupported MEM package integrity algorithm");
6323
- const signaturePaths = Object.keys(parts).filter((path5) => path5.startsWith("security/signatures/")).sort();
6324
- if (signaturePaths.some((path5) => !/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path5))) {
6417
+ const signaturePaths = Object.keys(parts).filter((path8) => path8.startsWith("security/signatures/")).sort();
6418
+ if (signaturePaths.some((path8) => !/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path8))) {
6325
6419
  throw new MemArtifactError("invalid", "Invalid MEM signature entry path");
6326
6420
  }
6327
6421
  if (manifest.authenticity !== void 0 && manifest.authenticity.signed !== true) {
@@ -6330,14 +6424,14 @@ ${contentId}
6330
6424
  if (manifest.authenticity?.signed === true !== signaturePaths.length > 0) {
6331
6425
  throw new MemArtifactError("invalid", "Declared MEM signatures do not match package entries");
6332
6426
  }
6333
- const archivePaths = Object.keys(parts).filter((path5) => path5 !== INTEGRITY_PATH && !path5.startsWith("security/signatures/")).sort();
6427
+ const archivePaths = Object.keys(parts).filter((path8) => path8 !== INTEGRITY_PATH && !path8.startsWith("security/signatures/")).sort();
6334
6428
  const protectedPaths = Object.keys(integrity.files ?? {}).sort();
6335
6429
  if (JSON.stringify(archivePaths) !== JSON.stringify(protectedPaths)) {
6336
6430
  throw new MemArtifactError("invalid", "MEM package protected-parts table does not match archive contents");
6337
6431
  }
6338
- for (const path5 of protectedPaths) {
6339
- const actual = await sha256(parts[path5]);
6340
- if (integrity.files[path5] !== actual) throw new MemArtifactError("checksum_mismatch", `Checksum mismatch for ${path5}`);
6432
+ for (const path8 of protectedPaths) {
6433
+ const actual = await sha256(parts[path8]);
6434
+ if (integrity.files[path8] !== actual) throw new MemArtifactError("checksum_mismatch", `Checksum mismatch for ${path8}`);
6341
6435
  }
6342
6436
  if (integrity.contentId !== await digestTableIdentity(integrity.files)) {
6343
6437
  throw new MemArtifactError("checksum_mismatch", "MEM package content identity mismatch");
@@ -6350,14 +6444,14 @@ ${contentId}
6350
6444
  } catch (error) {
6351
6445
  throw new MemArtifactError("invalid", `Invalid packaged MEM semantics: ${error.message}`);
6352
6446
  }
6353
- const extensions = Object.fromEntries(Object.entries(parts).filter(([path5]) => path5.startsWith("extensions/")));
6354
- const signatures = Object.fromEntries(signaturePaths.map((path5) => [path5, parts[path5]]));
6447
+ const extensions = Object.fromEntries(Object.entries(parts).filter(([path8]) => path8.startsWith("extensions/")));
6448
+ const signatures = Object.fromEntries(signaturePaths.map((path8) => [path8, parts[path8]]));
6355
6449
  return { ...decoded, representation: "package-v1", package: { manifest, extensions, signatures }, parts, integrity };
6356
6450
  }, "decodePackage");
6357
- verifySignature = /* @__PURE__ */ __name(async (path5, bytes, contentId) => {
6451
+ verifySignature = /* @__PURE__ */ __name(async (path8, bytes, contentId) => {
6358
6452
  let document;
6359
6453
  try {
6360
- document = parseJson(bytes, path5);
6454
+ document = parseJson(bytes, path8);
6361
6455
  } catch (error) {
6362
6456
  return { status: "invalid", message: error.message };
6363
6457
  }
@@ -6389,7 +6483,7 @@ ${contentId}
6389
6483
  const publicKeyBytes = base64UrlDecode(document.publicKey.value);
6390
6484
  const signatureBytes = base64UrlDecode(document.signature.value);
6391
6485
  const derivedKeyId = await keyIdentity(publicKeyBytes);
6392
- if (derivedKeyId !== document.keyId || signaturePath(derivedKeyId) !== path5) {
6486
+ if (derivedKeyId !== document.keyId || signaturePath(derivedKeyId) !== path8) {
6393
6487
  return {
6394
6488
  status: "invalid",
6395
6489
  algorithm: document.algorithm,
@@ -6441,7 +6535,7 @@ var init_storage_coordinator = __esm({
6441
6535
  const staleMs = opts.staleMs ?? 6e4;
6442
6536
  const lockName = opts.lockName ?? ".storage.lock";
6443
6537
  const lockPath = `${directoryPath}/${lockName}`;
6444
- const fs7 = await nodeFs4();
6538
+ const fs9 = await nodeFs4();
6445
6539
  const started = Date.now();
6446
6540
  const heldDepth = heldLocks.get(lockPath) ?? 0;
6447
6541
  if (heldDepth > 0) {
@@ -6452,12 +6546,12 @@ var init_storage_coordinator = __esm({
6452
6546
  heldLocks.set(lockPath, heldDepth);
6453
6547
  }
6454
6548
  }
6455
- await fs7.mkdir(directoryPath, { recursive: true });
6549
+ await fs9.mkdir(directoryPath, { recursive: true });
6456
6550
  while (true) {
6457
6551
  try {
6458
- await fs7.mkdir(lockPath);
6552
+ await fs9.mkdir(lockPath);
6459
6553
  const token2 = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
6460
- await fs7.writeFile(`${lockPath}/owner.json`, JSON.stringify({ token: token2, pid: process.pid, createdAt: Date.now() }), { flag: "wx" });
6554
+ await fs9.writeFile(`${lockPath}/owner.json`, JSON.stringify({ token: token2, pid: process.pid, createdAt: Date.now() }), { flag: "wx" });
6461
6555
  break;
6462
6556
  } catch (error) {
6463
6557
  const code = error.code;
@@ -6465,7 +6559,7 @@ var init_storage_coordinator = __esm({
6465
6559
  let stale = false;
6466
6560
  let processDead = false;
6467
6561
  try {
6468
- const raw = await fs7.readFile(`${lockPath}/owner.json`);
6562
+ const raw = await fs9.readFile(`${lockPath}/owner.json`);
6469
6563
  const parsed = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` }));
6470
6564
  const ageStale = typeof parsed.createdAt === "number" && Date.now() - parsed.createdAt > staleMs;
6471
6565
  if (typeof parsed.pid === "number") {
@@ -6484,13 +6578,13 @@ var init_storage_coordinator = __esm({
6484
6578
  if (stale) {
6485
6579
  if (processDead) {
6486
6580
  try {
6487
- await fs7.rm(lockPath, { recursive: true, force: true });
6581
+ await fs9.rm(lockPath, { recursive: true, force: true });
6488
6582
  continue;
6489
6583
  } catch {
6490
6584
  }
6491
6585
  }
6492
6586
  try {
6493
- await fs7.rmdir(lockPath);
6587
+ await fs9.rmdir(lockPath);
6494
6588
  continue;
6495
6589
  } catch {
6496
6590
  }
@@ -6503,7 +6597,7 @@ var init_storage_coordinator = __esm({
6503
6597
  }
6504
6598
  let token = "";
6505
6599
  try {
6506
- const raw = await fs7.readFile(`${lockPath}/owner.json`);
6600
+ const raw = await fs9.readFile(`${lockPath}/owner.json`);
6507
6601
  token = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` })).token ?? "";
6508
6602
  } catch {
6509
6603
  token = "";
@@ -6514,19 +6608,19 @@ var init_storage_coordinator = __esm({
6514
6608
  } finally {
6515
6609
  heldLocks.delete(lockPath);
6516
6610
  try {
6517
- const raw = await fs7.readFile(`${lockPath}/owner.json`);
6611
+ const raw = await fs9.readFile(`${lockPath}/owner.json`);
6518
6612
  const parsed = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` }));
6519
6613
  if (parsed.token === token && token) {
6520
- await fs7.rm(lockPath, { recursive: true, force: true });
6614
+ await fs9.rm(lockPath, { recursive: true, force: true });
6521
6615
  }
6522
6616
  } catch {
6523
6617
  }
6524
6618
  }
6525
6619
  }, "withStorageLock");
6526
6620
  readStorageGeneration = /* @__PURE__ */ __name(async (directoryPath) => {
6527
- const fs7 = await nodeFs4();
6621
+ const fs9 = await nodeFs4();
6528
6622
  try {
6529
- const raw = await fs7.readFile(`${directoryPath}/.storage.generation`);
6623
+ const raw = await fs9.readFile(`${directoryPath}/.storage.generation`);
6530
6624
  const value = Number(decodeText(raw, { source: `${directoryPath}/.storage.generation` }).trim());
6531
6625
  return Number.isFinite(value) && value >= 0 ? value : 0;
6532
6626
  } catch {
@@ -6534,11 +6628,11 @@ var init_storage_coordinator = __esm({
6534
6628
  }
6535
6629
  }, "readStorageGeneration");
6536
6630
  writeStorageGeneration = /* @__PURE__ */ __name(async (directoryPath, value) => {
6537
- const fs7 = await nodeFs4();
6538
- await fs7.mkdir(directoryPath, { recursive: true });
6631
+ const fs9 = await nodeFs4();
6632
+ await fs9.mkdir(directoryPath, { recursive: true });
6539
6633
  const temp = `${directoryPath}/.storage.generation.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
6540
- await fs7.writeFile(temp, String(value));
6541
- await fs7.rename(temp, `${directoryPath}/.storage.generation`);
6634
+ await fs9.writeFile(temp, String(value));
6635
+ await fs9.rename(temp, `${directoryPath}/.storage.generation`);
6542
6636
  }, "writeStorageGeneration");
6543
6637
  }
6544
6638
  });
@@ -7051,12 +7145,12 @@ function resolveLanguagePath() {
7051
7145
  function resolveLanguagePreferencePath() {
7052
7146
  return resolveUserLanguagePath();
7053
7147
  }
7054
- function readJsonFile(path5) {
7055
- const fs7 = getSyncFs();
7056
- if (!fs7) return null;
7148
+ function readJsonFile(path8) {
7149
+ const fs9 = getSyncFs();
7150
+ if (!fs9) return null;
7057
7151
  let raw;
7058
7152
  try {
7059
- raw = decodeText(fs7.readFileSync(path5), { source: path5 });
7153
+ raw = decodeText(fs9.readFileSync(path8), { source: path8 });
7060
7154
  } catch {
7061
7155
  return null;
7062
7156
  }
@@ -7089,9 +7183,9 @@ function extractLanguage(value) {
7089
7183
  return null;
7090
7184
  }
7091
7185
  function loadUserLanguage() {
7092
- const fs7 = getSyncFs();
7186
+ const fs9 = getSyncFs();
7093
7187
  const anchor = resolveUserDotMemPath();
7094
- if (fs7) {
7188
+ if (fs9) {
7095
7189
  for (const name of LANGUAGE_FILE_NAMES) {
7096
7190
  const candidatePath = joinPath3(anchor, name);
7097
7191
  const parsed = readJsonFile(candidatePath);
@@ -7153,14 +7247,14 @@ function getResponseLanguage() {
7153
7247
  }
7154
7248
  async function setUserLanguage(language2) {
7155
7249
  const fsMod = await import('fs/promises');
7156
- const path5 = resolveUserLanguagePath();
7157
- const dir = parentStoragePath(path5);
7250
+ const path8 = resolveUserLanguagePath();
7251
+ const dir = parentStoragePath(path8);
7158
7252
  await fsMod.mkdir(dir, { recursive: true });
7159
7253
  const payload = { format: "dotmem.language", version: 1, language: String(language2).trim() };
7160
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
7254
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
7161
7255
  await fsMod.writeFile(temporary, `${JSON.stringify(payload, null, 2)}
7162
7256
  `, "utf8");
7163
- await fsMod.rename(temporary, path5);
7257
+ await fsMod.rename(temporary, path8);
7164
7258
  return payload.language;
7165
7259
  }
7166
7260
  async function saveUserLanguage(language2) {
@@ -10735,11 +10829,11 @@ var init_identity_governance = __esm({
10735
10829
  updatedAt: (/* @__PURE__ */ new Date(0)).toISOString()
10736
10830
  }), "defaultIdentityGovernance");
10737
10831
  loadIdentityGovernance = /* @__PURE__ */ __name((canonicalAgentName) => {
10738
- const fs7 = getSyncFs();
10739
- if (!fs7) return defaultIdentityGovernance(canonicalAgentName);
10832
+ const fs9 = getSyncFs();
10833
+ if (!fs9) return defaultIdentityGovernance(canonicalAgentName);
10740
10834
  let raw;
10741
10835
  try {
10742
- raw = fs7.readFileSync(resolveUserIdentityGovernancePath(), "utf8");
10836
+ raw = fs9.readFileSync(resolveUserIdentityGovernancePath(), "utf8");
10743
10837
  } catch {
10744
10838
  return defaultIdentityGovernance(canonicalAgentName);
10745
10839
  }
@@ -10759,19 +10853,19 @@ var init_identity_governance = __esm({
10759
10853
  authority,
10760
10854
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
10761
10855
  });
10762
- const fs7 = getSyncFs();
10763
- if (!fs7) {
10856
+ const fs9 = getSyncFs();
10857
+ if (!fs9) {
10764
10858
  throw new IdentityGovernanceError("Identity governance write requires filesystem access, unavailable in this runtime");
10765
10859
  }
10766
10860
  const filePath = resolveUserIdentityGovernancePath();
10767
- await fs7.promises.mkdir(parentStoragePath(filePath), { recursive: true });
10861
+ await fs9.promises.mkdir(parentStoragePath(filePath), { recursive: true });
10768
10862
  const temporary = `${filePath}.${process.pid}.${Date.now().toString(36)}.tmp`;
10769
10863
  try {
10770
- await fs7.promises.writeFile(temporary, `${JSON.stringify(document, null, 2)}
10864
+ await fs9.promises.writeFile(temporary, `${JSON.stringify(document, null, 2)}
10771
10865
  `, "utf8");
10772
- await fs7.promises.rename(temporary, filePath);
10866
+ await fs9.promises.rename(temporary, filePath);
10773
10867
  } catch (error) {
10774
- await fs7.promises.rm(temporary, { force: true }).catch(() => void 0);
10868
+ await fs9.promises.rm(temporary, { force: true }).catch(() => void 0);
10775
10869
  throw error;
10776
10870
  }
10777
10871
  return document;
@@ -10968,20 +11062,20 @@ var init_detection_journal = __esm({
10968
11062
  }, "validateDetectionJournalDocument");
10969
11063
  appendDetectionJournal = /* @__PURE__ */ __name(async (events) => {
10970
11064
  if (events.length === 0) return;
10971
- const fs7 = getSyncFs();
10972
- if (!fs7) return;
11065
+ const fs9 = getSyncFs();
11066
+ if (!fs9) return;
10973
11067
  await withPolicyNamespaceLock(async () => {
10974
11068
  await appendDetectionJournalUnlocked(events);
10975
11069
  }, { directory: resolveUserPolicyDir() });
10976
11070
  }, "appendDetectionJournal");
10977
11071
  appendDetectionJournalUnlocked = /* @__PURE__ */ __name(async (events) => {
10978
11072
  if (events.length === 0) return;
10979
- const fs7 = getSyncFs();
10980
- if (!fs7) return;
11073
+ const fs9 = getSyncFs();
11074
+ if (!fs9) return;
10981
11075
  const filePath = resolveUserDetectionJournalPath();
10982
11076
  let document = emptyDetectionJournal();
10983
11077
  try {
10984
- const raw = await fs7.promises.readFile(filePath, "utf8");
11078
+ const raw = await fs9.promises.readFile(filePath, "utf8");
10985
11079
  document = validateDetectionJournalDocument(JSON.parse(raw));
10986
11080
  } catch (error) {
10987
11081
  const code = error?.code;
@@ -10995,22 +11089,22 @@ var init_detection_journal = __esm({
10995
11089
  }
10996
11090
  const merged = [...document.events, ...events].slice(-DETECTION_JOURNAL_RETENTION);
10997
11091
  const dir = filePath.slice(0, Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\")));
10998
- await fs7.promises.mkdir(dir, { recursive: true });
11092
+ await fs9.promises.mkdir(dir, { recursive: true });
10999
11093
  const temporary = `${filePath}.${process.pid}.${Date.now().toString(36)}.tmp`;
11000
11094
  try {
11001
- await fs7.promises.writeFile(temporary, `${JSON.stringify({ ...document, events: merged }, null, 2)}
11095
+ await fs9.promises.writeFile(temporary, `${JSON.stringify({ ...document, events: merged }, null, 2)}
11002
11096
  `, "utf8");
11003
- await fs7.promises.rename(temporary, filePath);
11097
+ await fs9.promises.rename(temporary, filePath);
11004
11098
  } catch (error) {
11005
- await fs7.promises.rm(temporary, { force: true }).catch(() => void 0);
11099
+ await fs9.promises.rm(temporary, { force: true }).catch(() => void 0);
11006
11100
  throw error;
11007
11101
  }
11008
11102
  }, "appendDetectionJournalUnlocked");
11009
11103
  loadDetectionJournal = /* @__PURE__ */ __name(async () => {
11010
- const fs7 = getSyncFs();
11011
- if (!fs7) return emptyDetectionJournal();
11104
+ const fs9 = getSyncFs();
11105
+ if (!fs9) return emptyDetectionJournal();
11012
11106
  try {
11013
- const raw = await fs7.promises.readFile(resolveUserDetectionJournalPath(), "utf8");
11107
+ const raw = await fs9.promises.readFile(resolveUserDetectionJournalPath(), "utf8");
11014
11108
  return validateDetectionJournalDocument(JSON.parse(raw));
11015
11109
  } catch {
11016
11110
  return emptyDetectionJournal();
@@ -11086,11 +11180,11 @@ var init_store_queue = __esm({
11086
11180
  async function resolveProjectIdentity(cwd, hints) {
11087
11181
  const explicit = sanitizeIdentity(process.env.DOTMEM_PROJECT_ID);
11088
11182
  if (explicit) return explicit;
11089
- const fs7 = await import('fs/promises');
11183
+ const fs9 = await import('fs/promises');
11090
11184
  const pkgPath = cwd.endsWith("/") || cwd.endsWith("\\") ? `${cwd}package.json` : `${cwd}/package.json`;
11091
11185
  let pkgJson;
11092
11186
  try {
11093
- const content = await fs7.readFile(pkgPath, "utf8");
11187
+ const content = await fs9.readFile(pkgPath, "utf8");
11094
11188
  pkgJson = JSON.parse(content);
11095
11189
  } catch {
11096
11190
  }
@@ -11235,8 +11329,8 @@ var init_staging = __esm({
11235
11329
  };
11236
11330
  const requestId = generateRequestId();
11237
11331
  const stagePath = stagePathFor(requestId);
11238
- const fs7 = await nodeFs6();
11239
- await fs7.mkdir(resolveStagingDirectory(), { recursive: true });
11332
+ const fs9 = await nodeFs6();
11333
+ await fs9.mkdir(resolveStagingDirectory(), { recursive: true });
11240
11334
  const stageFile = {
11241
11335
  format: DOTMEM_STAGE_FORMAT,
11242
11336
  version: DOTMEM_STAGE_VERSION,
@@ -11245,9 +11339,9 @@ var init_staging = __esm({
11245
11339
  ...sourceProject ? { sourceProject } : {},
11246
11340
  claim: sanitizedClaim
11247
11341
  };
11248
- await fs7.writeFile(stagePath, JSON.stringify(stageFile), { mode: 384 });
11342
+ await fs9.writeFile(stagePath, JSON.stringify(stageFile), { mode: 384 });
11249
11343
  try {
11250
- await fs7.access(stagePath);
11344
+ await fs9.access(stagePath);
11251
11345
  } catch {
11252
11346
  throw new StageFileError(`Stage file write verification failed: ${requestId} does not exist on disk`, requestId);
11253
11347
  }
@@ -11255,9 +11349,9 @@ var init_staging = __esm({
11255
11349
  }, "writeStageFile");
11256
11350
  readStageFile = /* @__PURE__ */ __name(async (requestId) => {
11257
11351
  const stagePath = stagePathFor(requestId);
11258
- const fs7 = await nodeFs6();
11352
+ const fs9 = await nodeFs6();
11259
11353
  try {
11260
- const content = await fs7.readFile(stagePath, "utf8");
11354
+ const content = await fs9.readFile(stagePath, "utf8");
11261
11355
  return JSON.parse(content);
11262
11356
  } catch (error) {
11263
11357
  if (error.code === "ENOENT") {
@@ -11370,9 +11464,9 @@ var init_staging = __esm({
11370
11464
  }, "commitStageFile");
11371
11465
  cleanupStageFile = /* @__PURE__ */ __name(async (requestId) => {
11372
11466
  const stagePath = stagePathFor(requestId);
11373
- const fs7 = await nodeFs6();
11467
+ const fs9 = await nodeFs6();
11374
11468
  try {
11375
- await fs7.unlink(stagePath);
11469
+ await fs9.unlink(stagePath);
11376
11470
  } catch (error) {
11377
11471
  if (error.code !== "ENOENT") {
11378
11472
  throw error;
@@ -11381,19 +11475,19 @@ var init_staging = __esm({
11381
11475
  }, "cleanupStageFile");
11382
11476
  cleanupStaleStages = /* @__PURE__ */ __name(async (maxAgeMs = 24 * 60 * 60 * 1e3) => {
11383
11477
  const stagingDir = resolveStagingDirectory();
11384
- const fs7 = await nodeFs6();
11478
+ const fs9 = await nodeFs6();
11385
11479
  let count = 0;
11386
11480
  try {
11387
- const entries2 = await fs7.readdir(stagingDir, { withFileTypes: true });
11481
+ const entries2 = await fs9.readdir(stagingDir, { withFileTypes: true });
11388
11482
  const now2 = Date.now();
11389
11483
  for (const entry of entries2) {
11390
11484
  if (!entry.isFile() || !entry.name.endsWith(".stage")) continue;
11391
11485
  const filePath = `${stagingDir}/${entry.name}`;
11392
11486
  try {
11393
- const stat = await fs7.stat(filePath);
11487
+ const stat = await fs9.stat(filePath);
11394
11488
  const age = now2 - stat.mtimeMs;
11395
11489
  if (age > maxAgeMs) {
11396
- await fs7.unlink(filePath);
11490
+ await fs9.unlink(filePath);
11397
11491
  count++;
11398
11492
  }
11399
11493
  } catch {
@@ -11417,25 +11511,25 @@ function joinPath4(base, child) {
11417
11511
  function resolveLoopsFilePath() {
11418
11512
  return joinPath4(resolveUserDotMemPath(), LOOPS_FILE_NAME);
11419
11513
  }
11420
- async function readFile(path5) {
11514
+ async function readFile(path8) {
11421
11515
  try {
11422
- const fs7 = await import('fs/promises');
11423
- return await fs7.readFile(path5, "utf8");
11516
+ const fs9 = await import('fs/promises');
11517
+ return await fs9.readFile(path8, "utf8");
11424
11518
  } catch {
11425
11519
  return null;
11426
11520
  }
11427
11521
  }
11428
- async function writeFile(path5, content) {
11429
- const fs7 = await import('fs/promises');
11430
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
11431
- await fs7.mkdir(dir, { recursive: true });
11432
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
11522
+ async function writeFile(path8, content) {
11523
+ const fs9 = await import('fs/promises');
11524
+ const dir = path8.replace(/[\\/][^\\/]+$/, "");
11525
+ await fs9.mkdir(dir, { recursive: true });
11526
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
11433
11527
  try {
11434
- await fs7.writeFile(temporary, content, "utf8");
11435
- await fs7.rename(temporary, path5);
11528
+ await fs9.writeFile(temporary, content, "utf8");
11529
+ await fs9.rename(temporary, path8);
11436
11530
  } catch {
11437
- await fs7.rm(temporary, { force: true }).catch(() => void 0);
11438
- throw new Error(`Failed to write loops file at ${path5}`);
11531
+ await fs9.rm(temporary, { force: true }).catch(() => void 0);
11532
+ throw new Error(`Failed to write loops file at ${path8}`);
11439
11533
  }
11440
11534
  }
11441
11535
  function emptyDocument() {
@@ -11856,9 +11950,9 @@ async function getCommittedFiles() {
11856
11950
  return result.stdout.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
11857
11951
  }
11858
11952
  async function getFileContent(filePath) {
11859
- const fs7 = await import('fs/promises');
11953
+ const fs9 = await import('fs/promises');
11860
11954
  try {
11861
- return await fs7.readFile(filePath, "utf8");
11955
+ return await fs9.readFile(filePath, "utf8");
11862
11956
  } catch {
11863
11957
  return null;
11864
11958
  }
@@ -11974,25 +12068,25 @@ function joinPath5(base, child) {
11974
12068
  function resolveVaultFilePath() {
11975
12069
  return joinPath5(resolveUserDotMemPath(), VAULT_FILE_NAME);
11976
12070
  }
11977
- async function readFile2(path5) {
12071
+ async function readFile2(path8) {
11978
12072
  try {
11979
- const fs7 = await import('fs/promises');
11980
- return await fs7.readFile(path5, "utf8");
12073
+ const fs9 = await import('fs/promises');
12074
+ return await fs9.readFile(path8, "utf8");
11981
12075
  } catch {
11982
12076
  return null;
11983
12077
  }
11984
12078
  }
11985
- async function writeFile2(path5, content) {
11986
- const fs7 = await import('fs/promises');
11987
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
11988
- await fs7.mkdir(dir, { recursive: true });
11989
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
12079
+ async function writeFile2(path8, content) {
12080
+ const fs9 = await import('fs/promises');
12081
+ const dir = path8.replace(/[\\/][^\\/]+$/, "");
12082
+ await fs9.mkdir(dir, { recursive: true });
12083
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
11990
12084
  try {
11991
- await fs7.writeFile(temporary, content, "utf8");
11992
- await fs7.rename(temporary, path5);
12085
+ await fs9.writeFile(temporary, content, "utf8");
12086
+ await fs9.rename(temporary, path8);
11993
12087
  } catch {
11994
- await fs7.rm(temporary, { force: true }).catch(() => void 0);
11995
- throw new Error(`Failed to write vault file at ${path5}`);
12088
+ await fs9.rm(temporary, { force: true }).catch(() => void 0);
12089
+ throw new Error(`Failed to write vault file at ${path8}`);
11996
12090
  }
11997
12091
  }
11998
12092
  function emptyDocument2() {
@@ -12110,9 +12204,9 @@ function joinPath6(base, child) {
12110
12204
  return `${base.replace(/[\\/]+/g, separator3)}${separator3}${child}`;
12111
12205
  }
12112
12206
  async function readJsonFile2(filePath, pointer) {
12113
- const fs7 = await import('fs/promises');
12207
+ const fs9 = await import('fs/promises');
12114
12208
  try {
12115
- const content = await fs7.readFile(filePath, "utf8");
12209
+ const content = await fs9.readFile(filePath, "utf8");
12116
12210
  const data = JSON.parse(content);
12117
12211
  const pathParts = pointer.replace(/^\//, "").split("/").filter((p) => p.length > 0);
12118
12212
  let current = data;
@@ -12175,6 +12269,39 @@ async function evaluateClaim(claim) {
12175
12269
  detail: `Value is ${result.valueStr}, expected ${expected}`
12176
12270
  };
12177
12271
  }
12272
+ if (kind === "regex") {
12273
+ const pattern = check.pattern;
12274
+ const target = String(check.expect ?? "");
12275
+ let regex;
12276
+ try {
12277
+ regex = new RegExp(pattern);
12278
+ } catch {
12279
+ return {
12280
+ claimId: claim.id,
12281
+ probe,
12282
+ status: "error",
12283
+ detail: `Invalid regex pattern: ${pattern}`
12284
+ };
12285
+ }
12286
+ if (regex.test(target)) {
12287
+ return {
12288
+ claimId: claim.id,
12289
+ probe,
12290
+ status: "valid",
12291
+ currentValue: target,
12292
+ expectedValue: pattern,
12293
+ detail: `Value matches regex: ${pattern}`
12294
+ };
12295
+ }
12296
+ return {
12297
+ claimId: claim.id,
12298
+ probe,
12299
+ status: "stale",
12300
+ currentValue: target,
12301
+ expectedValue: pattern,
12302
+ detail: `Value does not match regex: ${pattern}`
12303
+ };
12304
+ }
12178
12305
  return {
12179
12306
  claimId: claim.id,
12180
12307
  probe,
@@ -12260,214 +12387,748 @@ function formatVerifyResult(result) {
12260
12387
  }
12261
12388
  return lines.join("\n");
12262
12389
  }
12390
+ function applyVerification(state2, claimId, record) {
12391
+ const validated = validateKnowledgeState(state2);
12392
+ const claimIndex = validated.claims.findIndex((candidate) => candidate.id === claimId);
12393
+ if (claimIndex === -1) {
12394
+ throw new Error(`Cannot verify unknown claim: ${claimId}`);
12395
+ }
12396
+ const claim = validated.claims[claimIndex];
12397
+ const knowledge = claim.knowledge;
12398
+ const existing = knowledge?.verifiedAt;
12399
+ if (typeof existing === "string") {
12400
+ const existingTime = Date.parse(existing);
12401
+ const newTime = Date.parse(record.verifiedAt);
12402
+ if (Number.isFinite(existingTime) && Number.isFinite(newTime) && existingTime >= newTime) {
12403
+ return structuredClone(validated);
12404
+ }
12405
+ }
12406
+ const nextKnowledge = knowledge ? { ...knowledge } : {};
12407
+ nextKnowledge.verifiedAt = record.verifiedAt;
12408
+ nextKnowledge.verifiedBy = record.verifiedBy;
12409
+ nextKnowledge.verifyStatus = record.verifyStatus;
12410
+ const nextClaims = validated.claims.map(
12411
+ (candidate, index) => index === claimIndex ? { ...candidate, knowledge: nextKnowledge } : candidate
12412
+ );
12413
+ return structuredClone({ ...validated, version: validated.version + 1, claims: nextClaims });
12414
+ }
12415
+ async function verifyAndPersistClaims(state2, save) {
12416
+ const validated = validateKnowledgeState(state2);
12417
+ const result = await verifyDueClaims(validated);
12418
+ const persisted = [];
12419
+ let current = validated;
12420
+ for (const probe of result.results) {
12421
+ if (probe.status !== "valid") continue;
12422
+ const record = buildVerificationRecord(probe.claimId, {
12423
+ kind: probe.probe.split(":")[0],
12424
+ target: probe.probe.split(":").slice(1).join(":"),
12425
+ status: probe.status
12426
+ });
12427
+ if (!record) continue;
12428
+ current = applyVerification(current, probe.claimId, record);
12429
+ await save(current, current.version);
12430
+ persisted.push(probe.claimId);
12431
+ }
12432
+ return { result, persisted };
12433
+ }
12263
12434
  var init_verify = __esm({
12264
12435
  "core/knowledge/verify.ts"() {
12265
12436
  init_state();
12437
+ init_verification();
12266
12438
  __name(joinPath6, "joinPath");
12267
12439
  __name(readJsonFile2, "readJsonFile");
12268
12440
  __name(evaluateClaim, "evaluateClaim");
12269
12441
  __name(isDue, "isDue");
12270
12442
  __name(verifyDueClaims, "verifyDueClaims");
12271
12443
  __name(formatVerifyResult, "formatVerifyResult");
12444
+ __name(applyVerification, "applyVerification");
12445
+ __name(verifyAndPersistClaims, "verifyAndPersistClaims");
12272
12446
  }
12273
12447
  });
12274
12448
 
12275
- // core/knowledge/context-budget.ts
12276
- function estimateTokens(text) {
12277
- return Math.ceil(text.length / 4);
12278
- }
12279
- function estimateClaimSize(claim) {
12280
- const serialized = JSON.stringify(claim.knowledge ?? {});
12281
- const characters = serialized.length;
12282
- return { tokens: estimateTokens(serialized), characters };
12283
- }
12284
- function calculateBudgetUsage(claims, budget) {
12285
- let totalChars = 0;
12286
- for (const claim of claims) {
12287
- totalChars += estimateClaimSize(claim).characters;
12288
- }
12289
- const tokens = estimateTokens(String(totalChars));
12290
- const utilization = budget === "unlimited" || budget === 0 ? 1 : Math.min(totalChars / (budget * 4), 1);
12291
- return {
12292
- tokens,
12293
- characters: totalChars,
12294
- claimCount: claims.length,
12295
- budget,
12296
- utilization
12297
- };
12298
- }
12299
- function explainBudgetAllocation(included, excluded, budget) {
12300
- const result = {
12301
- included: included.map((claim) => {
12302
- const size = estimateClaimSize(claim);
12303
- return {
12304
- claimId: claim.id,
12305
- reason: "matched discovery",
12306
- estimatedTokens: size.tokens,
12307
- estimatedCharacters: size.characters
12308
- };
12309
- }),
12310
- excluded: excluded.map((item) => ({
12311
- claimId: item.id,
12312
- reason: item.reason
12313
- })),
12314
- total: calculateBudgetUsage(included, budget)
12315
- };
12316
- if (result.total.utilization >= 0.9 && budget !== "unlimited") {
12317
- result.excluded.push({
12318
- claimId: "__budget__",
12319
- reason: `Budget at ${Math.round(result.total.utilization * 100)}% utilization (${result.total.tokens} tokens of ${budget})`
12320
- });
12321
- }
12322
- return result;
12323
- }
12324
- function formatBudgetExplanation(explanation) {
12325
- const lines = [
12326
- "Context Budget Report",
12327
- "",
12328
- `Total claims included: ${explanation.total.claimCount}`,
12329
- `Estimated tokens: ${explanation.total.tokens}`,
12330
- `Budget: ${explanation.total.budget === "unlimited" ? "unlimited" : explanation.total.budget}`,
12331
- `Utilization: ${Math.round(explanation.total.utilization * 100)}%`,
12332
- ""
12333
- ];
12334
- if (explanation.included.length > 0) {
12335
- lines.push("Included claims:");
12336
- for (const item of explanation.included) {
12337
- lines.push(` [${item.claimId}] ${item.estimatedTokens} tokens \u2014 ${item.reason}`);
12338
- }
12339
- lines.push("");
12340
- }
12341
- if (explanation.excluded.length > 0) {
12342
- lines.push("Excluded claims:");
12343
- for (const item of explanation.excluded) {
12344
- lines.push(` [${item.claimId}] ${item.reason}`);
12345
- }
12346
- lines.push("");
12347
- }
12348
- return lines.join("\n");
12349
- }
12350
- var init_context_budget = __esm({
12351
- "core/knowledge/context-budget.ts"() {
12352
- __name(estimateTokens, "estimateTokens");
12353
- __name(estimateClaimSize, "estimateClaimSize");
12354
- __name(calculateBudgetUsage, "calculateBudgetUsage");
12355
- __name(explainBudgetAllocation, "explainBudgetAllocation");
12356
- __name(formatBudgetExplanation, "formatBudgetExplanation");
12357
- }
12358
- });
12359
-
12360
- // core/knowledge/feedback.ts
12449
+ // core/knowledge/violations.ts
12361
12450
  function joinPath7(base, child) {
12362
12451
  const separator3 = process.platform === "win32" ? "\\" : "/";
12363
12452
  return `${base.replace(/[\\/]+/g, separator3)}${separator3}${child}`;
12364
12453
  }
12365
- function resolveFeedbackFilePath() {
12366
- return joinPath7(resolveUserDotMemPath(), FEEDBACK_FILE_NAME);
12454
+ function resolveViolationFilePath() {
12455
+ return joinPath7(resolveUserDotMemPath(), VIOLATION_FILE_NAME);
12367
12456
  }
12368
- async function readFile3(path5) {
12457
+ async function readFile3(path8) {
12369
12458
  try {
12370
- const fs7 = await import('fs/promises');
12371
- return await fs7.readFile(path5, "utf8");
12459
+ const fs9 = await import('fs/promises');
12460
+ return await fs9.readFile(path8, "utf8");
12372
12461
  } catch {
12373
12462
  return null;
12374
12463
  }
12375
12464
  }
12376
- async function writeFile3(path5, content) {
12377
- const fs7 = await import('fs/promises');
12378
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
12379
- await fs7.mkdir(dir, { recursive: true });
12380
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
12381
- await fs7.writeFile(temporary, content, "utf8");
12382
- await fs7.rename(temporary, path5);
12465
+ async function writeFile3(path8, content) {
12466
+ const fs9 = await import('fs/promises');
12467
+ const dir = path8.replace(/[\\/][^\\/]+$/, "");
12468
+ await fs9.mkdir(dir, { recursive: true });
12469
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
12470
+ await fs9.writeFile(temporary, content, "utf8");
12471
+ await fs9.rename(temporary, path8);
12383
12472
  }
12384
- async function loadFeedback() {
12385
- const raw = await readFile3(resolveFeedbackFilePath());
12386
- if (!raw) return { version: FEEDBACK_FORMAT_VERSION, entries: [] };
12473
+ async function loadViolations() {
12474
+ const raw = await readFile3(resolveViolationFilePath());
12475
+ if (!raw) return { version: VIOLATION_FORMAT_VERSION, entries: [] };
12387
12476
  try {
12388
12477
  const parsed = JSON.parse(raw);
12389
- if (parsed.version === FEEDBACK_FORMAT_VERSION && Array.isArray(parsed.entries)) {
12390
- return { version: FEEDBACK_FORMAT_VERSION, entries: parsed.entries };
12478
+ if (parsed.version === VIOLATION_FORMAT_VERSION && Array.isArray(parsed.entries)) {
12479
+ return { version: VIOLATION_FORMAT_VERSION, entries: parsed.entries };
12391
12480
  }
12392
12481
  } catch {
12393
12482
  }
12394
- return { version: FEEDBACK_FORMAT_VERSION, entries: [] };
12483
+ return { version: VIOLATION_FORMAT_VERSION, entries: [] };
12395
12484
  }
12396
- async function saveFeedback(document) {
12397
- await writeFile3(resolveFeedbackFilePath(), JSON.stringify(document, null, 2) + "\n");
12485
+ async function saveViolations(document) {
12486
+ await writeFile3(resolveViolationFilePath(), JSON.stringify(document, null, 2) + "\n");
12398
12487
  }
12399
- function validateFeedbackEntry(entry) {
12400
- if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
12401
- throw new Error("Feedback entry must be an object");
12402
- }
12403
- const feedback = entry;
12404
- if (typeof feedback.claimId !== "string" || !feedback.claimId) {
12405
- throw new Error("Feedback entry requires a claimId");
12406
- }
12407
- if (typeof feedback.kind !== "string" || !VALID_KINDS.has(feedback.kind)) {
12408
- throw new Error(`Feedback entry has invalid kind: ${String(feedback.kind)}`);
12409
- }
12410
- if (typeof feedback.recordedAt !== "string") {
12411
- throw new Error("Feedback entry requires a recordedAt timestamp");
12412
- }
12413
- return {
12414
- claimId: feedback.claimId,
12415
- kind: feedback.kind,
12416
- note: typeof feedback.note === "string" ? feedback.note : void 0,
12417
- recordedAt: feedback.recordedAt
12488
+ async function logViolation(ruleId, situation, description = "") {
12489
+ const document = await loadViolations();
12490
+ const record = {
12491
+ ruleId,
12492
+ violatedAt: (/* @__PURE__ */ new Date()).toISOString(),
12493
+ description,
12494
+ situation
12418
12495
  };
12496
+ document.entries.push(record);
12497
+ await saveViolations(document);
12498
+ return record;
12419
12499
  }
12420
- async function recordFeedback(claimId, kind, note) {
12421
- if (!VALID_KINDS.has(kind)) {
12422
- throw new Error(`Invalid feedback kind: ${kind}`);
12423
- }
12424
- const document = await loadFeedback();
12425
- const entry = {
12426
- claimId,
12427
- kind,
12428
- note,
12429
- recordedAt: (/* @__PURE__ */ new Date()).toISOString()
12430
- };
12431
- document.entries.push(entry);
12432
- await saveFeedback(document);
12433
- return entry;
12500
+ async function countViolations(ruleId) {
12501
+ const document = await loadViolations();
12502
+ return document.entries.filter((e) => e.ruleId === ruleId).length;
12434
12503
  }
12435
- async function getFeedbackForClaim(claimId) {
12436
- const document = await loadFeedback();
12437
- return document.entries.filter((e) => e.claimId === claimId);
12504
+ async function lastViolation(ruleId) {
12505
+ const document = await loadViolations();
12506
+ const entries2 = document.entries.filter((e) => e.ruleId === ruleId).sort((a, b) => b.violatedAt.localeCompare(a.violatedAt));
12507
+ return entries2[0]?.violatedAt;
12438
12508
  }
12439
- async function getFeedbackSummary() {
12440
- const document = await loadFeedback();
12441
- const summary = { helped: 0, misled: 0, ignored: 0 };
12442
- for (const entry of document.entries) {
12443
- summary[entry.kind]++;
12444
- }
12445
- return summary;
12509
+ async function listViolations(ruleId) {
12510
+ const document = await loadViolations();
12511
+ if (!ruleId) return document.entries;
12512
+ return document.entries.filter((e) => e.ruleId === ruleId);
12446
12513
  }
12447
- function summarizeFeedbackWeights(feedback) {
12448
- return {
12449
- helpedWeight: feedback.filter((e) => e.kind === "helped").length,
12450
- misledWeight: feedback.filter((e) => e.kind === "misled").length,
12451
- ignoredWeight: feedback.filter((e) => e.kind === "ignored").length
12452
- };
12514
+ async function clearViolations(ruleId) {
12515
+ const document = await loadViolations();
12516
+ const beforeCount = document.entries.length;
12517
+ if (ruleId) {
12518
+ document.entries = document.entries.filter((e) => e.ruleId !== ruleId);
12519
+ } else {
12520
+ document.entries = [];
12521
+ }
12522
+ await saveViolations(document);
12523
+ return beforeCount - document.entries.length;
12453
12524
  }
12454
- var FEEDBACK_FILE_NAME, FEEDBACK_FORMAT_VERSION, VALID_KINDS;
12455
- var init_feedback = __esm({
12456
- "core/knowledge/feedback.ts"() {
12525
+ var VIOLATION_FILE_NAME, VIOLATION_FORMAT_VERSION;
12526
+ var init_violations = __esm({
12527
+ "core/knowledge/violations.ts"() {
12457
12528
  init_user_paths();
12458
- FEEDBACK_FILE_NAME = "feedback.json";
12459
- FEEDBACK_FORMAT_VERSION = 1;
12529
+ VIOLATION_FILE_NAME = "violations.json";
12530
+ VIOLATION_FORMAT_VERSION = 1;
12460
12531
  __name(joinPath7, "joinPath");
12461
- __name(resolveFeedbackFilePath, "resolveFeedbackFilePath");
12532
+ __name(resolveViolationFilePath, "resolveViolationFilePath");
12462
12533
  __name(readFile3, "readFile");
12463
12534
  __name(writeFile3, "writeFile");
12464
- VALID_KINDS = /* @__PURE__ */ new Set(["helped", "misled", "ignored"]);
12465
- __name(loadFeedback, "loadFeedback");
12466
- __name(saveFeedback, "saveFeedback");
12467
- __name(validateFeedbackEntry, "validateFeedbackEntry");
12468
- __name(recordFeedback, "recordFeedback");
12469
- __name(getFeedbackForClaim, "getFeedbackForClaim");
12470
- __name(getFeedbackSummary, "getFeedbackSummary");
12535
+ __name(loadViolations, "loadViolations");
12536
+ __name(saveViolations, "saveViolations");
12537
+ __name(logViolation, "logViolation");
12538
+ __name(countViolations, "countViolations");
12539
+ __name(lastViolation, "lastViolation");
12540
+ __name(listViolations, "listViolations");
12541
+ __name(clearViolations, "clearViolations");
12542
+ }
12543
+ });
12544
+ function isRuleClaim(claim) {
12545
+ const knowledge = claim.knowledge;
12546
+ return knowledge?.kind === "rule";
12547
+ }
12548
+ function isIronRule(claim) {
12549
+ return claim.epistemicType === "human-stated" && isRuleClaim(claim);
12550
+ }
12551
+ function extractIronRules(state2, violations = {}) {
12552
+ const validated = validateKnowledgeState(state2);
12553
+ const claims = activeClaims(validated);
12554
+ const rules = [];
12555
+ for (const claim of claims) {
12556
+ if (!isIronRule(claim)) continue;
12557
+ const knowledge = claim.knowledge;
12558
+ const applicability = claim.applicability;
12559
+ const iron = applicability.iron === true || applicability.priority === "iron";
12560
+ if (!iron) continue;
12561
+ rules.push({
12562
+ id: claim.id,
12563
+ text: String(knowledge.text ?? knowledge.rule ?? claim.id),
12564
+ why: String(knowledge.why ?? knowledge.reason ?? ""),
12565
+ appliesWhen: String(knowledge.appliesWhen ?? knowledge.when ?? ""),
12566
+ violatedOn: Array.isArray(knowledge.violatedOn) ? knowledge.violatedOn : void 0,
12567
+ lastViolation: typeof knowledge.lastViolation === "string" ? knowledge.lastViolation : void 0,
12568
+ frequency: typeof knowledge.frequency === "number" ? knowledge.frequency : violations[claim.id] ?? 0
12569
+ });
12570
+ }
12571
+ return rules;
12572
+ }
12573
+ function sortRulesByViolationFrequency(rules) {
12574
+ return [...rules].sort((a, b) => {
12575
+ if (b.frequency !== a.frequency) return b.frequency - a.frequency;
12576
+ if (a.lastViolation && b.lastViolation) {
12577
+ return b.lastViolation.localeCompare(a.lastViolation);
12578
+ }
12579
+ return 0;
12580
+ });
12581
+ }
12582
+ function loadIronRules(state2) {
12583
+ const rules = sortRulesByViolationFrequency(
12584
+ extractIronRules(state2, readViolationCounts(`${resolveUserDotMemPath()}/${VIOLATION_FILE_NAME}`))
12585
+ );
12586
+ return {
12587
+ rules,
12588
+ count: rules.length,
12589
+ sortedBy: "violation-frequency"
12590
+ };
12591
+ }
12592
+ function formatRulesForSessionStart(rules) {
12593
+ if (rules.length === 0) {
12594
+ return "";
12595
+ }
12596
+ const lines = ["---", "IRON RULES (must always arrive)", "---"];
12597
+ for (const rule of rules) {
12598
+ lines.push(`${rule.id}: ${rule.text}`);
12599
+ }
12600
+ return lines.join("\n");
12601
+ }
12602
+ function formatRuleWithExplanation(rule) {
12603
+ const parts = [];
12604
+ parts.push(`[${rule.id}] ${rule.text}`);
12605
+ if (rule.why) parts.push(` WHY: ${rule.why}`);
12606
+ if (rule.appliesWhen) parts.push(` APPLIES WHEN: ${rule.appliesWhen}`);
12607
+ if (rule.violatedOn && rule.violatedOn.length > 0) {
12608
+ parts.push(` VIOLATED ${rule.violatedOn.length} TIME(S)`);
12609
+ if (rule.lastViolation) parts.push(` Last: ${rule.lastViolation}`);
12610
+ }
12611
+ return parts.join("\n");
12612
+ }
12613
+ var readViolationCounts, ruleSetSignature, formatRulesReference;
12614
+ var init_rules_loader = __esm({
12615
+ "core/knowledge/rules-loader.ts"() {
12616
+ init_state();
12617
+ init_user_paths();
12618
+ init_violations();
12619
+ __name(isRuleClaim, "isRuleClaim");
12620
+ __name(isIronRule, "isIronRule");
12621
+ __name(extractIronRules, "extractIronRules");
12622
+ readViolationCounts = /* @__PURE__ */ __name((file) => {
12623
+ try {
12624
+ const parsed = JSON.parse(fs3.readFileSync(file, "utf8"));
12625
+ const counts = {};
12626
+ for (const violation of Array.isArray(parsed.violations) ? parsed.violations : []) {
12627
+ const ruleId = typeof violation?.ruleId === "string" ? violation.ruleId : "";
12628
+ if (!ruleId) continue;
12629
+ counts[ruleId] = (counts[ruleId] ?? 0) + 1;
12630
+ }
12631
+ return counts;
12632
+ } catch {
12633
+ return {};
12634
+ }
12635
+ }, "readViolationCounts");
12636
+ __name(sortRulesByViolationFrequency, "sortRulesByViolationFrequency");
12637
+ __name(loadIronRules, "loadIronRules");
12638
+ ruleSetSignature = /* @__PURE__ */ __name((rules) => {
12639
+ const material = rules.map((rule) => `${rule.id}\0${rule.text}`).join("");
12640
+ let hash = 2166136261;
12641
+ for (let index = 0; index < material.length; index += 1) {
12642
+ hash ^= material.charCodeAt(index);
12643
+ hash = Math.imul(hash, 16777619) >>> 0;
12644
+ }
12645
+ return hash.toString(16).padStart(8, "0");
12646
+ }, "ruleSetSignature");
12647
+ formatRulesReference = /* @__PURE__ */ __name((rules) => {
12648
+ if (rules.length === 0) return "DOTMEM_IRON_RULES_V1\ncount=0";
12649
+ return [
12650
+ "DOTMEM_IRON_RULES_V1",
12651
+ `count=${rules.length}`,
12652
+ `signature=${ruleSetSignature(rules)}`,
12653
+ `ids=${rules.map((rule) => rule.id).join(",")}`
12654
+ ].join("\n");
12655
+ }, "formatRulesReference");
12656
+ __name(formatRulesForSessionStart, "formatRulesForSessionStart");
12657
+ __name(formatRuleWithExplanation, "formatRuleWithExplanation");
12658
+ }
12659
+ });
12660
+
12661
+ // core/knowledge/bootstrap.ts
12662
+ var unchangedResponse, composeBootstrap;
12663
+ var init_bootstrap = __esm({
12664
+ "core/knowledge/bootstrap.ts"() {
12665
+ init_discover();
12666
+ init_project();
12667
+ init_rules_loader();
12668
+ init_user_paths();
12669
+ init_context_constants();
12670
+ unchangedResponse = /* @__PURE__ */ __name((knowledgeVersion, sinceVersion) => {
12671
+ const text = [
12672
+ "DOTMEM_BOOTSTRAP_V1",
12673
+ `storage=${resolveUserDotMemPath()}`,
12674
+ `knowledgeVersion=${knowledgeVersion}`,
12675
+ `rules=DOTMEM_IRON_RULES_V1 count=0 signature=00000000 ids=`,
12676
+ `UNCHANGED:true`,
12677
+ `sinceVersion=${sinceVersion}`,
12678
+ `assertedVersion=${knowledgeVersion}`
12679
+ ].join("\n");
12680
+ return {
12681
+ format: "dotmem-bootstrap-v1",
12682
+ storage: resolveUserDotMemPath(),
12683
+ knowledgeVersion,
12684
+ rules: { count: 0, signature: "00000000", ids: [] },
12685
+ context: null,
12686
+ unchanged: true,
12687
+ sinceVersion,
12688
+ text
12689
+ };
12690
+ }, "unchangedResponse");
12691
+ composeBootstrap = /* @__PURE__ */ __name(async (options = {}) => {
12692
+ const { sinceVersion, situation } = options;
12693
+ const { loadCombinedKnowledgeState: loadCombinedKnowledgeState2 } = await Promise.resolve().then(() => (init_memory(), memory_exports));
12694
+ const state2 = await loadCombinedKnowledgeState2();
12695
+ const knowledgeVersion = state2.version;
12696
+ if (Number.isInteger(sinceVersion) && sinceVersion >= 0 && sinceVersion === knowledgeVersion) {
12697
+ return unchangedResponse(knowledgeVersion, sinceVersion);
12698
+ }
12699
+ const discovery = await discoverAcquiredExperience(
12700
+ state2,
12701
+ situation ?? "",
12702
+ { maxCandidates: DOTMEM_CONTEXT_DEFAULT_MAX_CANDIDATES }
12703
+ );
12704
+ const context2 = projectDiscoveredExperience(discovery, {
12705
+ maxCandidates: DOTMEM_CONTEXT_DEFAULT_MAX_CANDIDATES,
12706
+ maxCharacters: DOTMEM_CONTEXT_DEFAULT_MAX_CHARACTERS
12707
+ });
12708
+ let rules = [];
12709
+ try {
12710
+ rules = loadIronRules(state2).rules;
12711
+ } catch {
12712
+ rules = [];
12713
+ }
12714
+ const rulesReference = {
12715
+ count: rules.length,
12716
+ signature: ruleSetSignature(rules),
12717
+ ids: rules.map((rule) => rule.id)
12718
+ };
12719
+ const text = [
12720
+ "DOTMEM_BOOTSTRAP_V1",
12721
+ `storage=${resolveUserDotMemPath()}`,
12722
+ `knowledgeVersion=${knowledgeVersion}`,
12723
+ `rules=DOTMEM_IRON_RULES_V1 count=${rulesReference.count} signature=${rulesReference.signature} ids=${rulesReference.ids.join(",")}`,
12724
+ "UNCHANGED:false",
12725
+ "",
12726
+ context2.text
12727
+ ].join("\n");
12728
+ return {
12729
+ format: "dotmem-bootstrap-v1",
12730
+ storage: resolveUserDotMemPath(),
12731
+ knowledgeVersion,
12732
+ rules: rulesReference,
12733
+ context: context2,
12734
+ unchanged: false,
12735
+ text
12736
+ };
12737
+ }, "composeBootstrap");
12738
+ }
12739
+ });
12740
+
12741
+ // core/knowledge/inspect-report.ts
12742
+ var redactValue, redactKnowledge, statusProse, formatParts, redactKnowledgeInInspection, renderInspectReport;
12743
+ var init_inspect_report = __esm({
12744
+ "core/knowledge/inspect-report.ts"() {
12745
+ init_sanitizer();
12746
+ redactValue = /* @__PURE__ */ __name((value) => {
12747
+ if (typeof value === "string" && looksLikeSecretValue(value)) {
12748
+ return "[redacted]";
12749
+ }
12750
+ return value;
12751
+ }, "redactValue");
12752
+ redactKnowledge = /* @__PURE__ */ __name((knowledge, redact) => {
12753
+ if (knowledge === null || typeof knowledge !== "object") {
12754
+ return redactValue(knowledge);
12755
+ }
12756
+ if (Array.isArray(knowledge)) {
12757
+ return knowledge.map((item) => redactKnowledge(item, redact));
12758
+ }
12759
+ const obj = knowledge;
12760
+ const result = {};
12761
+ for (const [key, value] of Object.entries(obj)) {
12762
+ if (redact && (isSecretKey(key) || looksLikeSecretValue(value))) {
12763
+ result[key] = { requiresSecret: true, secretStorage: "external" };
12764
+ continue;
12765
+ }
12766
+ result[key] = redactKnowledge(value, redact);
12767
+ }
12768
+ return result;
12769
+ }, "redactKnowledge");
12770
+ statusProse = /* @__PURE__ */ __name((status) => {
12771
+ switch (status) {
12772
+ case "valid":
12773
+ return "The MEM artifact is valid and intact.";
12774
+ case "invalid":
12775
+ return "The MEM artifact is invalid: its structure or semantics do not conform to the MEM format.";
12776
+ case "checksum_mismatch":
12777
+ return "The MEM artifact failed integrity verification: one or more parts do not match their recorded checksums.";
12778
+ case "unsupported":
12779
+ return "The MEM artifact uses an unsupported format or version.";
12780
+ case "corrupt":
12781
+ return "The MEM artifact is corrupt and could not be decoded.";
12782
+ default:
12783
+ return `The MEM artifact status is ${status}.`;
12784
+ }
12785
+ }, "statusProse");
12786
+ formatParts = /* @__PURE__ */ __name((parts) => {
12787
+ const list2 = parts ?? [];
12788
+ const lines = [` total: ${list2.length}`];
12789
+ for (const part of list2) {
12790
+ lines.push(` - ${part.path} (${part.bytes} bytes, protected=${part.protected})`);
12791
+ }
12792
+ return lines;
12793
+ }, "formatParts");
12794
+ redactKnowledgeInInspection = /* @__PURE__ */ __name((inspection, redact) => {
12795
+ if (!redact || !inspection.knowledge) return inspection;
12796
+ return {
12797
+ ...inspection,
12798
+ knowledge: redactKnowledge(inspection.knowledge, redact)
12799
+ };
12800
+ }, "redactKnowledgeInInspection");
12801
+ renderInspectReport = /* @__PURE__ */ __name((inspection, options = {}) => {
12802
+ const { redact = true, includeKnowledge = false, limit = 50 } = options;
12803
+ const report = redactKnowledgeInInspection(inspection, redact);
12804
+ const lines = [];
12805
+ lines.push("# Dotmem MEM Inspection Report");
12806
+ lines.push("");
12807
+ lines.push(`- **Status:** ${report.status}`);
12808
+ lines.push(`- **Message:** ${statusProse(report.status)}`);
12809
+ lines.push(`- **Representation:** ${report.representation}`);
12810
+ if (report.packageVersion !== void 0) lines.push(`- **Package version:** ${report.packageVersion}`);
12811
+ if (report.memoryVersion !== void 0) lines.push(`- **Memory version:** ${report.memoryVersion}`);
12812
+ if (report.contentId) lines.push(`- **Content ID:** ${report.contentId}`);
12813
+ lines.push("");
12814
+ lines.push("## Integrity");
12815
+ if (report.integrity) {
12816
+ lines.push(`- **Status:** ${report.integrity.status}`);
12817
+ lines.push(`- **Algorithm:** ${report.integrity.algorithm}`);
12818
+ lines.push(`- **Content ID:** ${report.integrity.contentId}`);
12819
+ } else {
12820
+ lines.push("- **Status:** not available");
12821
+ }
12822
+ lines.push("");
12823
+ lines.push("## Authenticity");
12824
+ if (report.authenticity) {
12825
+ lines.push(`- **Status:** ${report.authenticity.status}`);
12826
+ lines.push(`- **Trust:** ${report.authenticity.trust}`);
12827
+ lines.push(`- **Signatures:** ${report.authenticity.signatures.length}`);
12828
+ if (report.authenticity.signatures.length > 0) {
12829
+ lines.push("");
12830
+ lines.push("### Signatures");
12831
+ for (const signature of report.authenticity.signatures) {
12832
+ lines.push(`- ${signature.algorithm ?? "unknown"} / ${signature.keyId ?? "unknown-key"}: **${signature.status}**`);
12833
+ if (signature.message) lines.push(` - ${signature.message}`);
12834
+ }
12835
+ }
12836
+ lines.push("");
12837
+ lines.push("> Unsigned does not mean corrupt: the package has integrity but no cryptographic signature.");
12838
+ } else {
12839
+ lines.push("- **Status:** not available");
12840
+ }
12841
+ lines.push("");
12842
+ lines.push("## Parts");
12843
+ lines.push(...formatParts(report.parts));
12844
+ lines.push("");
12845
+ lines.push("## Claims");
12846
+ const claims = report.knowledge?.claims;
12847
+ if (Array.isArray(claims)) {
12848
+ lines.push(`- **Total:** ${claims.length}`);
12849
+ lines.push(`- **Shown:** ${Math.min(claims.length, limit)}`);
12850
+ lines.push("");
12851
+ for (const claim of claims.slice(0, limit)) {
12852
+ lines.push(`- \`${claim.id}\``);
12853
+ if (claim.epistemicType) lines.push(` - epistemicType: ${claim.epistemicType}`);
12854
+ if (claim.evidence?.length) {
12855
+ lines.push(` - evidence: ${claim.evidence.map((e) => e.id).join(", ")}`);
12856
+ }
12857
+ if (claim.revision) lines.push(` - revision: ${claim.revision.kind}`);
12858
+ }
12859
+ } else {
12860
+ lines.push("- **Total:** not available (knowledge payload not present)");
12861
+ }
12862
+ lines.push("");
12863
+ lines.push("## Redaction");
12864
+ lines.push(`- **Redacted:** ${redact ? "yes" : "no"}`);
12865
+ lines.push("- Secret-shaped values are replaced with placeholders by default. Use --no-redact (CLI only) to disable.");
12866
+ const markdown = lines.join("\n");
12867
+ const json = {
12868
+ status: report.status,
12869
+ representation: report.representation,
12870
+ message: statusProse(report.status),
12871
+ ...report.packageVersion !== void 0 ? { packageVersion: report.packageVersion } : {},
12872
+ ...report.memoryVersion !== void 0 ? { memoryVersion: report.memoryVersion } : {},
12873
+ ...report.contentId ? { contentId: report.contentId } : {},
12874
+ integrity: report.integrity ?? null,
12875
+ authenticity: report.authenticity ?? null,
12876
+ parts: report.parts,
12877
+ claims: includeKnowledge && Array.isArray(report.knowledge?.claims) ? report.knowledge.claims.slice(0, limit).map((claim) => ({
12878
+ id: claim.id,
12879
+ epistemicType: claim.epistemicType,
12880
+ evidence: claim.evidence,
12881
+ revision: claim.revision
12882
+ })) : void 0,
12883
+ claimCount: Array.isArray(report.knowledge?.claims) ? report.knowledge.claims.length : null,
12884
+ redacted: redact,
12885
+ ...includeKnowledge && report.knowledge ? { knowledge: redactKnowledge(report.knowledge, redact) } : {}
12886
+ };
12887
+ return { markdown, json };
12888
+ }, "renderInspectReport");
12889
+ }
12890
+ });
12891
+ var readPackage, listStore;
12892
+ var init_read_only = __esm({
12893
+ "core/knowledge/read-only.ts"() {
12894
+ init_mem_package();
12895
+ init_user_paths();
12896
+ readPackage = /* @__PURE__ */ __name(async (file) => {
12897
+ const resolved = path3__default.default.resolve(file);
12898
+ const bytes = await fs__default.default.readFile(resolved);
12899
+ const inspection = await inspectMem(bytes);
12900
+ return { ...inspection, file: resolved };
12901
+ }, "readPackage");
12902
+ listStore = /* @__PURE__ */ __name(async (root) => {
12903
+ const storageRoot = root ?? resolveUserDotMemPath();
12904
+ const packages = [];
12905
+ let dirents;
12906
+ try {
12907
+ dirents = await fs__default.default.readdir(storageRoot, { withFileTypes: true });
12908
+ } catch {
12909
+ return { root: storageRoot, packages: [] };
12910
+ }
12911
+ for (const entry of dirents) {
12912
+ if (!entry.isFile() || !entry.name.endsWith(".mem") || entry.name === "@brain.mem") continue;
12913
+ const filePath = path3__default.default.join(storageRoot, entry.name);
12914
+ try {
12915
+ const inspection = await readPackage(filePath);
12916
+ packages.push({ file: inspection.file, path: entry.name, inspection });
12917
+ } catch (error) {
12918
+ packages.push({
12919
+ file: filePath,
12920
+ path: entry.name,
12921
+ inspection: {
12922
+ status: "corrupt",
12923
+ representation: "unknown",
12924
+ message: `Unable to inspect: ${error instanceof Error ? error.message : String(error)}`,
12925
+ parts: []
12926
+ }
12927
+ });
12928
+ }
12929
+ }
12930
+ packages.sort((left, right) => left.path.localeCompare(right.path));
12931
+ return { root: storageRoot, packages };
12932
+ }, "listStore");
12933
+ }
12934
+ });
12935
+
12936
+ // core/knowledge/context-budget.ts
12937
+ function estimateTokens(text) {
12938
+ return Math.ceil(text.length / 4);
12939
+ }
12940
+ function estimateClaimSize(claim) {
12941
+ const serialized = JSON.stringify(claim.knowledge ?? {});
12942
+ const characters = serialized.length;
12943
+ return { tokens: estimateTokens(serialized), characters };
12944
+ }
12945
+ function calculateBudgetUsage(claims, budget) {
12946
+ let totalChars = 0;
12947
+ for (const claim of claims) {
12948
+ totalChars += estimateClaimSize(claim).characters;
12949
+ }
12950
+ const tokens = estimateTokens(String(totalChars));
12951
+ const utilization = budget === "unlimited" || budget === 0 ? 1 : Math.min(totalChars / (budget * 4), 1);
12952
+ return {
12953
+ tokens,
12954
+ characters: totalChars,
12955
+ claimCount: claims.length,
12956
+ budget,
12957
+ utilization
12958
+ };
12959
+ }
12960
+ function explainBudgetAllocation(included, excluded, budget) {
12961
+ const result = {
12962
+ included: included.map((claim) => {
12963
+ const size = estimateClaimSize(claim);
12964
+ return {
12965
+ claimId: claim.id,
12966
+ reason: "matched discovery",
12967
+ estimatedTokens: size.tokens,
12968
+ estimatedCharacters: size.characters
12969
+ };
12970
+ }),
12971
+ excluded: excluded.map((item) => ({
12972
+ claimId: item.id,
12973
+ reason: item.reason
12974
+ })),
12975
+ total: calculateBudgetUsage(included, budget)
12976
+ };
12977
+ if (result.total.utilization >= 0.9 && budget !== "unlimited") {
12978
+ result.excluded.push({
12979
+ claimId: "__budget__",
12980
+ reason: `Budget at ${Math.round(result.total.utilization * 100)}% utilization (${result.total.tokens} tokens of ${budget})`
12981
+ });
12982
+ }
12983
+ return result;
12984
+ }
12985
+ function formatBudgetExplanation(explanation) {
12986
+ const lines = [
12987
+ "Context Budget Report",
12988
+ "",
12989
+ `Total claims included: ${explanation.total.claimCount}`,
12990
+ `Estimated tokens: ${explanation.total.tokens}`,
12991
+ `Budget: ${explanation.total.budget === "unlimited" ? "unlimited" : explanation.total.budget}`,
12992
+ `Utilization: ${Math.round(explanation.total.utilization * 100)}%`,
12993
+ ""
12994
+ ];
12995
+ if (explanation.included.length > 0) {
12996
+ lines.push("Included claims:");
12997
+ for (const item of explanation.included) {
12998
+ lines.push(` [${item.claimId}] ${item.estimatedTokens} tokens \u2014 ${item.reason}`);
12999
+ }
13000
+ lines.push("");
13001
+ }
13002
+ if (explanation.excluded.length > 0) {
13003
+ lines.push("Excluded claims:");
13004
+ for (const item of explanation.excluded) {
13005
+ lines.push(` [${item.claimId}] ${item.reason}`);
13006
+ }
13007
+ lines.push("");
13008
+ }
13009
+ return lines.join("\n");
13010
+ }
13011
+ var init_context_budget = __esm({
13012
+ "core/knowledge/context-budget.ts"() {
13013
+ __name(estimateTokens, "estimateTokens");
13014
+ __name(estimateClaimSize, "estimateClaimSize");
13015
+ __name(calculateBudgetUsage, "calculateBudgetUsage");
13016
+ __name(explainBudgetAllocation, "explainBudgetAllocation");
13017
+ __name(formatBudgetExplanation, "formatBudgetExplanation");
13018
+ }
13019
+ });
13020
+
13021
+ // core/knowledge/feedback.ts
13022
+ function joinPath8(base, child) {
13023
+ const separator3 = process.platform === "win32" ? "\\" : "/";
13024
+ return `${base.replace(/[\\/]+/g, separator3)}${separator3}${child}`;
13025
+ }
13026
+ function resolveFeedbackFilePath() {
13027
+ return joinPath8(resolveUserDotMemPath(), FEEDBACK_FILE_NAME);
13028
+ }
13029
+ async function readFile4(path8) {
13030
+ try {
13031
+ const fs9 = await import('fs/promises');
13032
+ return await fs9.readFile(path8, "utf8");
13033
+ } catch {
13034
+ return null;
13035
+ }
13036
+ }
13037
+ async function writeFile4(path8, content) {
13038
+ const fs9 = await import('fs/promises');
13039
+ const dir = path8.replace(/[\\/][^\\/]+$/, "");
13040
+ await fs9.mkdir(dir, { recursive: true });
13041
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
13042
+ await fs9.writeFile(temporary, content, "utf8");
13043
+ await fs9.rename(temporary, path8);
13044
+ }
13045
+ async function loadFeedback() {
13046
+ const raw = await readFile4(resolveFeedbackFilePath());
13047
+ if (!raw) return { version: FEEDBACK_FORMAT_VERSION, entries: [] };
13048
+ try {
13049
+ const parsed = JSON.parse(raw);
13050
+ if (parsed.version === FEEDBACK_FORMAT_VERSION && Array.isArray(parsed.entries)) {
13051
+ return { version: FEEDBACK_FORMAT_VERSION, entries: parsed.entries };
13052
+ }
13053
+ } catch {
13054
+ }
13055
+ return { version: FEEDBACK_FORMAT_VERSION, entries: [] };
13056
+ }
13057
+ async function saveFeedback(document) {
13058
+ await writeFile4(resolveFeedbackFilePath(), JSON.stringify(document, null, 2) + "\n");
13059
+ }
13060
+ function validateFeedbackEntry(entry) {
13061
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
13062
+ throw new Error("Feedback entry must be an object");
13063
+ }
13064
+ const feedback = entry;
13065
+ if (typeof feedback.claimId !== "string" || !feedback.claimId) {
13066
+ throw new Error("Feedback entry requires a claimId");
13067
+ }
13068
+ if (typeof feedback.kind !== "string" || !VALID_KINDS.has(feedback.kind)) {
13069
+ throw new Error(`Feedback entry has invalid kind: ${String(feedback.kind)}`);
13070
+ }
13071
+ if (typeof feedback.recordedAt !== "string") {
13072
+ throw new Error("Feedback entry requires a recordedAt timestamp");
13073
+ }
13074
+ return {
13075
+ claimId: feedback.claimId,
13076
+ kind: feedback.kind,
13077
+ note: typeof feedback.note === "string" ? feedback.note : void 0,
13078
+ recordedAt: feedback.recordedAt
13079
+ };
13080
+ }
13081
+ async function recordFeedback(claimId, kind, note) {
13082
+ if (!VALID_KINDS.has(kind)) {
13083
+ throw new Error(`Invalid feedback kind: ${kind}`);
13084
+ }
13085
+ const document = await loadFeedback();
13086
+ const entry = {
13087
+ claimId,
13088
+ kind,
13089
+ note,
13090
+ recordedAt: (/* @__PURE__ */ new Date()).toISOString()
13091
+ };
13092
+ document.entries.push(entry);
13093
+ await saveFeedback(document);
13094
+ return entry;
13095
+ }
13096
+ async function getFeedbackForClaim(claimId) {
13097
+ const document = await loadFeedback();
13098
+ return document.entries.filter((e) => e.claimId === claimId);
13099
+ }
13100
+ async function getFeedbackSummary() {
13101
+ const document = await loadFeedback();
13102
+ const summary = { helped: 0, misled: 0, ignored: 0 };
13103
+ for (const entry of document.entries) {
13104
+ summary[entry.kind]++;
13105
+ }
13106
+ return summary;
13107
+ }
13108
+ function summarizeFeedbackWeights(feedback) {
13109
+ return {
13110
+ helpedWeight: feedback.filter((e) => e.kind === "helped").length,
13111
+ misledWeight: feedback.filter((e) => e.kind === "misled").length,
13112
+ ignoredWeight: feedback.filter((e) => e.kind === "ignored").length
13113
+ };
13114
+ }
13115
+ var FEEDBACK_FILE_NAME, FEEDBACK_FORMAT_VERSION, VALID_KINDS;
13116
+ var init_feedback = __esm({
13117
+ "core/knowledge/feedback.ts"() {
13118
+ init_user_paths();
13119
+ FEEDBACK_FILE_NAME = "feedback.json";
13120
+ FEEDBACK_FORMAT_VERSION = 1;
13121
+ __name(joinPath8, "joinPath");
13122
+ __name(resolveFeedbackFilePath, "resolveFeedbackFilePath");
13123
+ __name(readFile4, "readFile");
13124
+ __name(writeFile4, "writeFile");
13125
+ VALID_KINDS = /* @__PURE__ */ new Set(["helped", "misled", "ignored"]);
13126
+ __name(loadFeedback, "loadFeedback");
13127
+ __name(saveFeedback, "saveFeedback");
13128
+ __name(validateFeedbackEntry, "validateFeedbackEntry");
13129
+ __name(recordFeedback, "recordFeedback");
13130
+ __name(getFeedbackForClaim, "getFeedbackForClaim");
13131
+ __name(getFeedbackSummary, "getFeedbackSummary");
12471
13132
  __name(summarizeFeedbackWeights, "summarizeFeedbackWeights");
12472
13133
  }
12473
13134
  });
@@ -12522,333 +13183,121 @@ var init_correction = __esm({
12522
13183
  // core/knowledge/incidents.ts
12523
13184
  function findIncidentById(id) {
12524
13185
  return INCIDENT_EVAL_TEST_SET.find((incident) => incident.id === id);
12525
- }
12526
- function listIncidents() {
12527
- return [...INCIDENT_EVAL_TEST_SET];
12528
- }
12529
- function buildIncidentState(overrides = {}) {
12530
- const baseClaims = [
12531
- {
12532
- id: "behavior:watch-files",
12533
- epistemicType: "observed",
12534
- applicability: { verified: true },
12535
- evidence: [{ id: "ev-watch-1", observedAt: "2026-01-01T00:00:00Z" }],
12536
- knowledge: { trigger: "file watching", rule: "watch files with watch tool" },
12537
- acquiredAt: "2026-01-01T00:00:00Z"
12538
- },
12539
- {
12540
- id: "behavior:state-engine",
12541
- epistemicType: "observed",
12542
- applicability: { verified: true },
12543
- evidence: [{ id: "ev-state-1", observedAt: "2026-01-01T00:00:00Z" }],
12544
- knowledge: { trigger: "state engine", rule: "state is foundation" },
12545
- acquiredAt: "2026-01-01T00:00:00Z"
12546
- },
12547
- {
12548
- id: "behavior:git-push-guard",
12549
- epistemicType: "observed",
12550
- applicability: { verified: true },
12551
- evidence: [{ id: "ev-push-1", observedAt: "2026-01-01T00:00:00Z" }],
12552
- knowledge: { trigger: "git push", rule: "guard git operations" },
12553
- acquiredAt: "2026-01-01T00:00:00Z"
12554
- },
12555
- {
12556
- id: "behavior:memory-layer",
12557
- epistemicType: "observed",
12558
- applicability: { verified: true },
12559
- evidence: [{ id: "ev-mem-1", observedAt: "2026-01-01T00:00:00Z" }],
12560
- knowledge: { trigger: "memory", rule: "memory is state plus store" },
12561
- acquiredAt: "2026-01-01T00:00:00Z"
12562
- },
12563
- {
12564
- id: "project:current-project",
12565
- epistemicType: "observed",
12566
- applicability: { scope: "project", verified: true },
12567
- evidence: [{ id: "ev-proj-1", observedAt: "2026-01-01T00:00:00Z" }],
12568
- knowledge: { trigger: "current project", anchor: "project root" },
12569
- acquiredAt: "2026-01-01T00:00:00Z"
12570
- }
12571
- ];
12572
- return {
12573
- version: 1,
12574
- claims: [...baseClaims, ...overrides.claims ?? []]
12575
- };
12576
- }
12577
- function evaluateIncident(incident, matchedClaims) {
12578
- const got = matchedClaims;
12579
- const missing = incident.expectedClaimIds.filter((id) => !got.includes(id));
12580
- const unexpected = got.filter((id) => !incident.expectedClaimIds.includes(id));
12581
- return {
12582
- incidentId: incident.id,
12583
- passed: missing.length === 0 && unexpected.length === 0,
12584
- expected: incident.expectedClaimIds,
12585
- got,
12586
- missing,
12587
- unexpected
12588
- };
12589
- }
12590
- function formatIncidentReport(report) {
12591
- const lines = [
12592
- `Incident Eval Report: ${report.passed}/${report.total} passed`,
12593
- ""
12594
- ];
12595
- for (const result of report.results) {
12596
- const status = result.passed ? "PASS" : "FAIL";
12597
- lines.push(`[${status}] ${result.incidentId}`);
12598
- if (!result.passed) {
12599
- if (result.missing.length > 0) {
12600
- lines.push(` Missing: ${result.missing.join(", ")}`);
12601
- }
12602
- if (result.unexpected.length > 0) {
12603
- lines.push(` Unexpected: ${result.unexpected.join(", ")}`);
12604
- }
12605
- }
12606
- }
12607
- return lines.join("\n");
12608
- }
12609
- var INCIDENT_EVAL_TEST_SET;
12610
- var init_incidents = __esm({
12611
- "core/knowledge/incidents.ts"() {
12612
- INCIDENT_EVAL_TEST_SET = [
12613
- {
12614
- id: "incident-001",
12615
- situation: "user asks about file watching",
12616
- expectedClaimIds: ["behavior:watch-files"],
12617
- excludedIds: ["behavior:state-engine"],
12618
- description: "File watching should pull the watch-files rule, not the state engine rule"
12619
- },
12620
- {
12621
- id: "incident-002",
12622
- situation: "user asks about git push",
12623
- expectedClaimIds: ["behavior:git-push-guard"],
12624
- excludedIds: ["behavior:memory-layer"],
12625
- description: "Git push should trigger the push guard, not the memory layer"
12626
- },
12627
- {
12628
- id: "incident-003",
12629
- situation: "current project context",
12630
- expectedClaimIds: ["project:current-project"],
12631
- excludedIds: ["behavior:state-engine"],
12632
- description: "Current project situation should surface the project anchor claim"
12633
- }
12634
- ];
12635
- __name(findIncidentById, "findIncidentById");
12636
- __name(listIncidents, "listIncidents");
12637
- __name(buildIncidentState, "buildIncidentState");
12638
- __name(evaluateIncident, "evaluateIncident");
12639
- __name(formatIncidentReport, "formatIncidentReport");
12640
- }
12641
- });
12642
-
12643
- // core/knowledge/violations.ts
12644
- function joinPath8(base, child) {
12645
- const separator3 = process.platform === "win32" ? "\\" : "/";
12646
- return `${base.replace(/[\\/]+/g, separator3)}${separator3}${child}`;
12647
- }
12648
- function resolveViolationFilePath() {
12649
- return joinPath8(resolveUserDotMemPath(), VIOLATION_FILE_NAME);
12650
- }
12651
- async function readFile4(path5) {
12652
- try {
12653
- const fs7 = await import('fs/promises');
12654
- return await fs7.readFile(path5, "utf8");
12655
- } catch {
12656
- return null;
12657
- }
12658
- }
12659
- async function writeFile4(path5, content) {
12660
- const fs7 = await import('fs/promises');
12661
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
12662
- await fs7.mkdir(dir, { recursive: true });
12663
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
12664
- await fs7.writeFile(temporary, content, "utf8");
12665
- await fs7.rename(temporary, path5);
12666
- }
12667
- async function loadViolations() {
12668
- const raw = await readFile4(resolveViolationFilePath());
12669
- if (!raw) return { version: VIOLATION_FORMAT_VERSION, entries: [] };
12670
- try {
12671
- const parsed = JSON.parse(raw);
12672
- if (parsed.version === VIOLATION_FORMAT_VERSION && Array.isArray(parsed.entries)) {
12673
- return { version: VIOLATION_FORMAT_VERSION, entries: parsed.entries };
12674
- }
12675
- } catch {
12676
- }
12677
- return { version: VIOLATION_FORMAT_VERSION, entries: [] };
12678
- }
12679
- async function saveViolations(document) {
12680
- await writeFile4(resolveViolationFilePath(), JSON.stringify(document, null, 2) + "\n");
12681
- }
12682
- async function logViolation(ruleId, situation, description = "") {
12683
- const document = await loadViolations();
12684
- const record = {
12685
- ruleId,
12686
- violatedAt: (/* @__PURE__ */ new Date()).toISOString(),
12687
- description,
12688
- situation
12689
- };
12690
- document.entries.push(record);
12691
- await saveViolations(document);
12692
- return record;
12693
- }
12694
- async function countViolations(ruleId) {
12695
- const document = await loadViolations();
12696
- return document.entries.filter((e) => e.ruleId === ruleId).length;
12697
- }
12698
- async function lastViolation(ruleId) {
12699
- const document = await loadViolations();
12700
- const entries2 = document.entries.filter((e) => e.ruleId === ruleId).sort((a, b) => b.violatedAt.localeCompare(a.violatedAt));
12701
- return entries2[0]?.violatedAt;
12702
- }
12703
- async function listViolations(ruleId) {
12704
- const document = await loadViolations();
12705
- if (!ruleId) return document.entries;
12706
- return document.entries.filter((e) => e.ruleId === ruleId);
12707
- }
12708
- async function clearViolations(ruleId) {
12709
- const document = await loadViolations();
12710
- const beforeCount = document.entries.length;
12711
- if (ruleId) {
12712
- document.entries = document.entries.filter((e) => e.ruleId !== ruleId);
12713
- } else {
12714
- document.entries = [];
12715
- }
12716
- await saveViolations(document);
12717
- return beforeCount - document.entries.length;
12718
- }
12719
- var VIOLATION_FILE_NAME, VIOLATION_FORMAT_VERSION;
12720
- var init_violations = __esm({
12721
- "core/knowledge/violations.ts"() {
12722
- init_user_paths();
12723
- VIOLATION_FILE_NAME = "violations.json";
12724
- VIOLATION_FORMAT_VERSION = 1;
12725
- __name(joinPath8, "joinPath");
12726
- __name(resolveViolationFilePath, "resolveViolationFilePath");
12727
- __name(readFile4, "readFile");
12728
- __name(writeFile4, "writeFile");
12729
- __name(loadViolations, "loadViolations");
12730
- __name(saveViolations, "saveViolations");
12731
- __name(logViolation, "logViolation");
12732
- __name(countViolations, "countViolations");
12733
- __name(lastViolation, "lastViolation");
12734
- __name(listViolations, "listViolations");
12735
- __name(clearViolations, "clearViolations");
12736
- }
12737
- });
12738
- function isRuleClaim(claim) {
12739
- const knowledge = claim.knowledge;
12740
- return knowledge?.kind === "rule";
12741
- }
12742
- function isIronRule(claim) {
12743
- return claim.epistemicType === "human-stated" && isRuleClaim(claim);
12744
- }
12745
- function extractIronRules(state2, violations = {}) {
12746
- const validated = validateKnowledgeState(state2);
12747
- const claims = activeClaims(validated);
12748
- const rules = [];
12749
- for (const claim of claims) {
12750
- if (!isIronRule(claim)) continue;
12751
- const knowledge = claim.knowledge;
12752
- const applicability = claim.applicability;
12753
- const iron = applicability.iron === true || applicability.priority === "iron";
12754
- if (!iron) continue;
12755
- rules.push({
12756
- id: claim.id,
12757
- text: String(knowledge.text ?? knowledge.rule ?? claim.id),
12758
- why: String(knowledge.why ?? knowledge.reason ?? ""),
12759
- appliesWhen: String(knowledge.appliesWhen ?? knowledge.when ?? ""),
12760
- violatedOn: Array.isArray(knowledge.violatedOn) ? knowledge.violatedOn : void 0,
12761
- lastViolation: typeof knowledge.lastViolation === "string" ? knowledge.lastViolation : void 0,
12762
- frequency: typeof knowledge.frequency === "number" ? knowledge.frequency : violations[claim.id] ?? 0
12763
- });
12764
- }
12765
- return rules;
12766
- }
12767
- function sortRulesByViolationFrequency(rules) {
12768
- return [...rules].sort((a, b) => {
12769
- if (b.frequency !== a.frequency) return b.frequency - a.frequency;
12770
- if (a.lastViolation && b.lastViolation) {
12771
- return b.lastViolation.localeCompare(a.lastViolation);
13186
+ }
13187
+ function listIncidents() {
13188
+ return [...INCIDENT_EVAL_TEST_SET];
13189
+ }
13190
+ function buildIncidentState(overrides = {}) {
13191
+ const baseClaims = [
13192
+ {
13193
+ id: "behavior:watch-files",
13194
+ epistemicType: "observed",
13195
+ applicability: { verified: true },
13196
+ evidence: [{ id: "ev-watch-1", observedAt: "2026-01-01T00:00:00Z" }],
13197
+ knowledge: { trigger: "file watching", rule: "watch files with watch tool" },
13198
+ acquiredAt: "2026-01-01T00:00:00Z"
13199
+ },
13200
+ {
13201
+ id: "behavior:state-engine",
13202
+ epistemicType: "observed",
13203
+ applicability: { verified: true },
13204
+ evidence: [{ id: "ev-state-1", observedAt: "2026-01-01T00:00:00Z" }],
13205
+ knowledge: { trigger: "state engine", rule: "state is foundation" },
13206
+ acquiredAt: "2026-01-01T00:00:00Z"
13207
+ },
13208
+ {
13209
+ id: "behavior:git-push-guard",
13210
+ epistemicType: "observed",
13211
+ applicability: { verified: true },
13212
+ evidence: [{ id: "ev-push-1", observedAt: "2026-01-01T00:00:00Z" }],
13213
+ knowledge: { trigger: "git push", rule: "guard git operations" },
13214
+ acquiredAt: "2026-01-01T00:00:00Z"
13215
+ },
13216
+ {
13217
+ id: "behavior:memory-layer",
13218
+ epistemicType: "observed",
13219
+ applicability: { verified: true },
13220
+ evidence: [{ id: "ev-mem-1", observedAt: "2026-01-01T00:00:00Z" }],
13221
+ knowledge: { trigger: "memory", rule: "memory is state plus store" },
13222
+ acquiredAt: "2026-01-01T00:00:00Z"
13223
+ },
13224
+ {
13225
+ id: "project:current-project",
13226
+ epistemicType: "observed",
13227
+ applicability: { scope: "project", verified: true },
13228
+ evidence: [{ id: "ev-proj-1", observedAt: "2026-01-01T00:00:00Z" }],
13229
+ knowledge: { trigger: "current project", anchor: "project root" },
13230
+ acquiredAt: "2026-01-01T00:00:00Z"
12772
13231
  }
12773
- return 0;
12774
- });
13232
+ ];
13233
+ return {
13234
+ version: 1,
13235
+ claims: [...baseClaims, ...overrides.claims ?? []]
13236
+ };
12775
13237
  }
12776
- function loadIronRules(state2) {
12777
- const rules = sortRulesByViolationFrequency(
12778
- extractIronRules(state2, readViolationCounts(`${resolveUserDotMemPath()}/${VIOLATION_FILE_NAME}`))
12779
- );
13238
+ function evaluateIncident(incident, matchedClaims) {
13239
+ const got = matchedClaims;
13240
+ const missing = incident.expectedClaimIds.filter((id) => !got.includes(id));
13241
+ const unexpected = got.filter((id) => !incident.expectedClaimIds.includes(id));
12780
13242
  return {
12781
- rules,
12782
- count: rules.length,
12783
- sortedBy: "violation-frequency"
13243
+ incidentId: incident.id,
13244
+ passed: missing.length === 0 && unexpected.length === 0,
13245
+ expected: incident.expectedClaimIds,
13246
+ got,
13247
+ missing,
13248
+ unexpected
12784
13249
  };
12785
13250
  }
12786
- function formatRulesForSessionStart(rules) {
12787
- if (rules.length === 0) {
12788
- return "";
12789
- }
12790
- const lines = ["---", "IRON RULES (must always arrive)", "---"];
12791
- for (const rule of rules) {
12792
- lines.push(`${rule.id}: ${rule.text}`);
13251
+ function formatIncidentReport(report) {
13252
+ const lines = [
13253
+ `Incident Eval Report: ${report.passed}/${report.total} passed`,
13254
+ ""
13255
+ ];
13256
+ for (const result of report.results) {
13257
+ const status = result.passed ? "PASS" : "FAIL";
13258
+ lines.push(`[${status}] ${result.incidentId}`);
13259
+ if (!result.passed) {
13260
+ if (result.missing.length > 0) {
13261
+ lines.push(` Missing: ${result.missing.join(", ")}`);
13262
+ }
13263
+ if (result.unexpected.length > 0) {
13264
+ lines.push(` Unexpected: ${result.unexpected.join(", ")}`);
13265
+ }
13266
+ }
12793
13267
  }
12794
13268
  return lines.join("\n");
12795
13269
  }
12796
- function formatRuleWithExplanation(rule) {
12797
- const parts = [];
12798
- parts.push(`[${rule.id}] ${rule.text}`);
12799
- if (rule.why) parts.push(` WHY: ${rule.why}`);
12800
- if (rule.appliesWhen) parts.push(` APPLIES WHEN: ${rule.appliesWhen}`);
12801
- if (rule.violatedOn && rule.violatedOn.length > 0) {
12802
- parts.push(` VIOLATED ${rule.violatedOn.length} TIME(S)`);
12803
- if (rule.lastViolation) parts.push(` Last: ${rule.lastViolation}`);
12804
- }
12805
- return parts.join("\n");
12806
- }
12807
- var readViolationCounts, ruleSetSignature, formatRulesReference;
12808
- var init_rules_loader = __esm({
12809
- "core/knowledge/rules-loader.ts"() {
12810
- init_state();
12811
- init_user_paths();
12812
- init_violations();
12813
- __name(isRuleClaim, "isRuleClaim");
12814
- __name(isIronRule, "isIronRule");
12815
- __name(extractIronRules, "extractIronRules");
12816
- readViolationCounts = /* @__PURE__ */ __name((file) => {
12817
- try {
12818
- const parsed = JSON.parse(fs2.readFileSync(file, "utf8"));
12819
- const counts = {};
12820
- for (const violation of Array.isArray(parsed.violations) ? parsed.violations : []) {
12821
- const ruleId = typeof violation?.ruleId === "string" ? violation.ruleId : "";
12822
- if (!ruleId) continue;
12823
- counts[ruleId] = (counts[ruleId] ?? 0) + 1;
12824
- }
12825
- return counts;
12826
- } catch {
12827
- return {};
12828
- }
12829
- }, "readViolationCounts");
12830
- __name(sortRulesByViolationFrequency, "sortRulesByViolationFrequency");
12831
- __name(loadIronRules, "loadIronRules");
12832
- ruleSetSignature = /* @__PURE__ */ __name((rules) => {
12833
- const material = rules.map((rule) => `${rule.id}\0${rule.text}`).join("");
12834
- let hash = 2166136261;
12835
- for (let index = 0; index < material.length; index += 1) {
12836
- hash ^= material.charCodeAt(index);
12837
- hash = Math.imul(hash, 16777619) >>> 0;
13270
+ var INCIDENT_EVAL_TEST_SET;
13271
+ var init_incidents = __esm({
13272
+ "core/knowledge/incidents.ts"() {
13273
+ INCIDENT_EVAL_TEST_SET = [
13274
+ {
13275
+ id: "incident-001",
13276
+ situation: "user asks about file watching",
13277
+ expectedClaimIds: ["behavior:watch-files"],
13278
+ excludedIds: ["behavior:state-engine"],
13279
+ description: "File watching should pull the watch-files rule, not the state engine rule"
13280
+ },
13281
+ {
13282
+ id: "incident-002",
13283
+ situation: "user asks about git push",
13284
+ expectedClaimIds: ["behavior:git-push-guard"],
13285
+ excludedIds: ["behavior:memory-layer"],
13286
+ description: "Git push should trigger the push guard, not the memory layer"
13287
+ },
13288
+ {
13289
+ id: "incident-003",
13290
+ situation: "current project context",
13291
+ expectedClaimIds: ["project:current-project"],
13292
+ excludedIds: ["behavior:state-engine"],
13293
+ description: "Current project situation should surface the project anchor claim"
12838
13294
  }
12839
- return hash.toString(16).padStart(8, "0");
12840
- }, "ruleSetSignature");
12841
- formatRulesReference = /* @__PURE__ */ __name((rules) => {
12842
- if (rules.length === 0) return "DOTMEM_IRON_RULES_V1\ncount=0";
12843
- return [
12844
- "DOTMEM_IRON_RULES_V1",
12845
- `count=${rules.length}`,
12846
- `signature=${ruleSetSignature(rules)}`,
12847
- `ids=${rules.map((rule) => rule.id).join(",")}`
12848
- ].join("\n");
12849
- }, "formatRulesReference");
12850
- __name(formatRulesForSessionStart, "formatRulesForSessionStart");
12851
- __name(formatRuleWithExplanation, "formatRuleWithExplanation");
13295
+ ];
13296
+ __name(findIncidentById, "findIncidentById");
13297
+ __name(listIncidents, "listIncidents");
13298
+ __name(buildIncidentState, "buildIncidentState");
13299
+ __name(evaluateIncident, "evaluateIncident");
13300
+ __name(formatIncidentReport, "formatIncidentReport");
12852
13301
  }
12853
13302
  });
12854
13303
 
@@ -12860,21 +13309,21 @@ function joinPath9(base, child) {
12860
13309
  function resolveSessionFilePath() {
12861
13310
  return joinPath9(resolveUserDotMemPath(), SESSION_FILE_NAME);
12862
13311
  }
12863
- async function readFile5(path5) {
13312
+ async function readFile5(path8) {
12864
13313
  try {
12865
- const fs7 = await import('fs/promises');
12866
- return await fs7.readFile(path5, "utf8");
13314
+ const fs9 = await import('fs/promises');
13315
+ return await fs9.readFile(path8, "utf8");
12867
13316
  } catch {
12868
13317
  return null;
12869
13318
  }
12870
13319
  }
12871
- async function writeFile5(path5, content) {
12872
- const fs7 = await import('fs/promises');
12873
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
12874
- await fs7.mkdir(dir, { recursive: true });
12875
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
12876
- await fs7.writeFile(temporary, content, "utf8");
12877
- await fs7.rename(temporary, path5);
13320
+ async function writeFile5(path8, content) {
13321
+ const fs9 = await import('fs/promises');
13322
+ const dir = path8.replace(/[\\/][^\\/]+$/, "");
13323
+ await fs9.mkdir(dir, { recursive: true });
13324
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
13325
+ await fs9.writeFile(temporary, content, "utf8");
13326
+ await fs9.rename(temporary, path8);
12878
13327
  }
12879
13328
  async function loadSession() {
12880
13329
  const raw = await readFile5(resolveSessionFilePath());
@@ -12976,25 +13425,25 @@ function joinPath10(base, child) {
12976
13425
  function resolveExemplarsPath() {
12977
13426
  return joinPath10(resolveUserDotMemPath(), EXEMPLARS_FILE_NAME);
12978
13427
  }
12979
- async function readFile6(path5) {
13428
+ async function readFile6(path8) {
12980
13429
  try {
12981
- const fs7 = await import('fs/promises');
12982
- return await fs7.readFile(path5, "utf8");
13430
+ const fs9 = await import('fs/promises');
13431
+ return await fs9.readFile(path8, "utf8");
12983
13432
  } catch {
12984
13433
  return null;
12985
13434
  }
12986
13435
  }
12987
- async function writeFile6(path5, content) {
12988
- const fs7 = await import('fs/promises');
12989
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
12990
- await fs7.mkdir(dir, { recursive: true });
12991
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
13436
+ async function writeFile6(path8, content) {
13437
+ const fs9 = await import('fs/promises');
13438
+ const dir = path8.replace(/[\\/][^\\/]+$/, "");
13439
+ await fs9.mkdir(dir, { recursive: true });
13440
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
12992
13441
  try {
12993
- await fs7.writeFile(temporary, content, "utf8");
12994
- await fs7.rename(temporary, path5);
13442
+ await fs9.writeFile(temporary, content, "utf8");
13443
+ await fs9.rename(temporary, path8);
12995
13444
  } catch {
12996
- await fs7.rm(temporary, { force: true }).catch(() => void 0);
12997
- throw new Error(`Failed to write exemplars file at ${path5}`);
13445
+ await fs9.rm(temporary, { force: true }).catch(() => void 0);
13446
+ throw new Error(`Failed to write exemplars file at ${path8}`);
12998
13447
  }
12999
13448
  }
13000
13449
  function emptyStore() {
@@ -13208,25 +13657,25 @@ function joinPath11(base, child) {
13208
13657
  function resolvePersonalityAnchorPath() {
13209
13658
  return joinPath11(resolveUserDotMemPath(), PERSONALITY_ANCHOR_FILE_NAME);
13210
13659
  }
13211
- async function readFile7(path5) {
13660
+ async function readFile7(path8) {
13212
13661
  try {
13213
- const fs7 = await import('fs/promises');
13214
- return await fs7.readFile(path5, "utf8");
13662
+ const fs9 = await import('fs/promises');
13663
+ return await fs9.readFile(path8, "utf8");
13215
13664
  } catch {
13216
13665
  return null;
13217
13666
  }
13218
13667
  }
13219
- async function writeFile7(path5, content) {
13220
- const fs7 = await import('fs/promises');
13221
- const dir = path5.replace(/[\\/][^\\/]+$/, "");
13222
- await fs7.mkdir(dir, { recursive: true });
13223
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
13668
+ async function writeFile7(path8, content) {
13669
+ const fs9 = await import('fs/promises');
13670
+ const dir = path8.replace(/[\\/][^\\/]+$/, "");
13671
+ await fs9.mkdir(dir, { recursive: true });
13672
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
13224
13673
  try {
13225
- await fs7.writeFile(temporary, content, "utf8");
13226
- await fs7.rename(temporary, path5);
13674
+ await fs9.writeFile(temporary, content, "utf8");
13675
+ await fs9.rename(temporary, path8);
13227
13676
  } catch {
13228
- await fs7.rm(temporary, { force: true }).catch(() => void 0);
13229
- throw new Error(`Failed to write personality anchor at ${path5}`);
13677
+ await fs9.rm(temporary, { force: true }).catch(() => void 0);
13678
+ throw new Error(`Failed to write personality anchor at ${path8}`);
13230
13679
  }
13231
13680
  }
13232
13681
  function emptyAnchor() {
@@ -13364,8 +13813,8 @@ async function loadPersonalityAnchor() {
13364
13813
  async function savePersonalityAnchor(anchor) {
13365
13814
  const validated = validateAnchor(anchor);
13366
13815
  const dirPath = resolveUserDotMemPath();
13367
- const fs7 = await import('fs/promises');
13368
- await fs7.mkdir(dirPath, { recursive: true });
13816
+ const fs9 = await import('fs/promises');
13817
+ await fs9.mkdir(dirPath, { recursive: true });
13369
13818
  await writeFile7(resolvePersonalityAnchorPath(), JSON.stringify(validated, null, 2));
13370
13819
  }
13371
13820
  async function updatePersonalityAnchor(updates) {
@@ -13467,7 +13916,7 @@ function pkgDirname() {
13467
13916
  return __dirname;
13468
13917
  }
13469
13918
  try {
13470
- return path2__default.default.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli.cjs', document.baseURI).href))));
13919
+ return path3__default.default.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli.cjs', document.baseURI).href))));
13471
13920
  } catch {
13472
13921
  return process.cwd();
13473
13922
  }
@@ -13475,7 +13924,7 @@ function pkgDirname() {
13475
13924
  function candidatePaths() {
13476
13925
  const paths = [];
13477
13926
  try {
13478
- paths.push(path2__default.default.join(pkgDirname(), "built-in-context.json"));
13927
+ paths.push(path3__default.default.join(pkgDirname(), "built-in-context.json"));
13479
13928
  } catch {
13480
13929
  }
13481
13930
  return paths;
@@ -13544,9 +13993,9 @@ function loadBuiltInContext() {
13544
13993
  let lastError = "Built-in context artifact not found";
13545
13994
  const candidates = _artifactPathOverride ? [_artifactPathOverride] : candidatePaths();
13546
13995
  for (const candidate of candidates) {
13547
- if (!fs2__default.default.existsSync(candidate)) continue;
13996
+ if (!fs3__default.default.existsSync(candidate)) continue;
13548
13997
  try {
13549
- const raw = fs2__default.default.readFileSync(candidate);
13998
+ const raw = fs3__default.default.readFileSync(candidate);
13550
13999
  const parsed = JSON.parse(decodeText(raw, { source: candidate }));
13551
14000
  const artifact = validateArtifact(parsed);
13552
14001
  cached = artifact;
@@ -13577,14 +14026,14 @@ function loadBuiltInContext() {
13577
14026
  }
13578
14027
  let attemptedPath = "";
13579
14028
  try {
13580
- attemptedPath = path2__default.default.join(pkgDirname(), "built-in-context.json");
14029
+ attemptedPath = path3__default.default.join(pkgDirname(), "built-in-context.json");
13581
14030
  } catch {
13582
14031
  }
13583
14032
  let packageVersion = "unknown";
13584
14033
  try {
13585
- const pkgPath = path2__default.default.join(pkgDirname(), "package.json");
13586
- if (fs2__default.default.existsSync(pkgPath)) {
13587
- const pkg = JSON.parse(fs2__default.default.readFileSync(pkgPath, "utf8"));
14034
+ const pkgPath = path3__default.default.join(pkgDirname(), "package.json");
14035
+ if (fs3__default.default.existsSync(pkgPath)) {
14036
+ const pkg = JSON.parse(fs3__default.default.readFileSync(pkgPath, "utf8"));
13588
14037
  packageVersion = typeof pkg.version === "string" ? pkg.version : "unknown";
13589
14038
  }
13590
14039
  } catch {
@@ -13797,14 +14246,17 @@ __export(knowledge_exports, {
13797
14246
  addLoop: () => addLoop,
13798
14247
  addWaitingForUser: () => addWaitingForUser,
13799
14248
  appendDetectionJournal: () => appendDetectionJournal,
14249
+ applyVerification: () => applyVerification,
13800
14250
  assertBuiltInContextAvailable: () => assertBuiltInContextAvailable,
13801
14251
  assertNoConversationalOverride: () => assertNoConversationalOverride,
13802
14252
  authorityRelaxationPermitted: () => authorityRelaxationPermitted,
13803
14253
  authorityRevocationPermitted: () => authorityRevocationPermitted,
13804
14254
  buildIncidentState: () => buildIncidentState,
14255
+ buildVerificationRecord: () => buildVerificationRecord,
13805
14256
  builtInContextRulesMapped: () => builtInContextRulesMapped,
13806
14257
  calculateAnchorBudget: () => calculateAnchorBudget,
13807
14258
  calculateBudgetUsage: () => calculateBudgetUsage,
14259
+ callerInjectedVerificationMetadata: () => callerInjectedVerificationMetadata,
13808
14260
  canonicalApplicabilityValue: () => canonicalApplicabilityValue,
13809
14261
  canonicalEvent: () => canonicalEvent,
13810
14262
  canonicalEvidenceError: () => canonicalEvidenceError,
@@ -13823,6 +14275,7 @@ __export(knowledge_exports, {
13823
14275
  clearViolations: () => clearViolations,
13824
14276
  closeLoop: () => closeLoop,
13825
14277
  commitStageFile: () => commitStageFile,
14278
+ composeBootstrap: () => composeBootstrap,
13826
14279
  constructEffectiveAgentContract: () => constructEffectiveAgentContract,
13827
14280
  countViolations: () => countViolations,
13828
14281
  crossAcquisitionBoundary: () => exports.crossAcquisitionBoundary,
@@ -13832,6 +14285,7 @@ __export(knowledge_exports, {
13832
14285
  defaultPolicyId: () => defaultPolicyId,
13833
14286
  deriveCurrentness: () => deriveCurrentness,
13834
14287
  deriveSituationApplicability: () => deriveSituationApplicability,
14288
+ deriveTrustBasis: () => deriveTrustBasis,
13835
14289
  describeDotMemStorage: () => describeDotMemStorage,
13836
14290
  detectAuthorityEscalationAttempt: () => detectAuthorityEscalationAttempt,
13837
14291
  detectBehaviorCoreMutationAttempt: () => detectBehaviorCoreMutationAttempt,
@@ -13884,6 +14338,7 @@ __export(knowledge_exports, {
13884
14338
  inspectMem: () => inspectMem,
13885
14339
  isBaselineClaim: () => isBaselineClaim,
13886
14340
  isBuiltInContextAvailable: () => isBuiltInContextAvailable,
14341
+ isCallerDeclaredVerified: () => isCallerDeclaredVerified,
13887
14342
  isEligibleByApplicability: () => isEligibleByApplicability,
13888
14343
  isIronRule: () => isIronRule,
13889
14344
  isItalian: () => isItalian,
@@ -13895,6 +14350,7 @@ __export(knowledge_exports, {
13895
14350
  listExemplars: () => listExemplars,
13896
14351
  listIncidents: () => listIncidents,
13897
14352
  listLoops: () => listLoops,
14353
+ listStore: () => listStore,
13898
14354
  listViews: () => listViews,
13899
14355
  listViolations: () => listViolations,
13900
14356
  loadBuiltInContext: () => loadBuiltInContext,
@@ -13924,6 +14380,7 @@ __export(knowledge_exports, {
13924
14380
  projectExemplarContext: () => projectExemplarContext,
13925
14381
  projectPersonalityAnchor: () => projectPersonalityAnchor,
13926
14382
  readDotMemStorageLocator: () => readDotMemStorageLocator,
14383
+ readPackage: () => readPackage,
13927
14384
  readStageFile: () => readStageFile,
13928
14385
  readStorageSettings: () => exports.readStorageSettings,
13929
14386
  readUserLanguage: () => readUserLanguage,
@@ -13935,6 +14392,7 @@ __export(knowledge_exports, {
13935
14392
  renderAgentRules: () => renderAgentRules,
13936
14393
  renderExpandedClaim: () => renderExpandedClaim,
13937
14394
  renderExplanation: () => renderExplanation,
14395
+ renderInspectReport: () => renderInspectReport,
13938
14396
  renderMarkdownIndex: () => renderMarkdownIndex,
13939
14397
  renderOperatorContract: () => renderOperatorContract,
13940
14398
  renderView: () => renderView,
@@ -14022,6 +14480,7 @@ __export(knowledge_exports, {
14022
14480
  vaultList: () => vaultList,
14023
14481
  vaultPut: () => vaultPut,
14024
14482
  vaultResolve: () => vaultResolve,
14483
+ verifyAndPersistClaims: () => verifyAndPersistClaims,
14025
14484
  verifyDueClaims: () => verifyDueClaims,
14026
14485
  withPolicyNamespaceLock: () => withPolicyNamespaceLock,
14027
14486
  withoutOverlays: () => withoutOverlays,
@@ -14071,6 +14530,10 @@ var init_knowledge = __esm({
14071
14530
  init_rule_checker();
14072
14531
  init_vault();
14073
14532
  init_verify();
14533
+ init_verification();
14534
+ init_bootstrap();
14535
+ init_inspect_report();
14536
+ init_read_only();
14074
14537
  init_context_budget();
14075
14538
  init_feedback();
14076
14539
  init_correction();
@@ -14299,16 +14762,16 @@ function detectLineEnding(content) {
14299
14762
  return content.includes("\r\n") ? "\r\n" : "\n";
14300
14763
  }
14301
14764
  async function ensureDotMemReadme(_projectRoot, readmeSource) {
14302
- const fs7 = await import('fs/promises');
14765
+ const fs9 = await import('fs/promises');
14303
14766
  const dotmemDir = resolveUserDotMemPath();
14304
14767
  try {
14305
- await fs7.mkdir(dotmemDir, { recursive: true });
14768
+ await fs9.mkdir(dotmemDir, { recursive: true });
14306
14769
  } catch {
14307
14770
  }
14308
14771
  const contractDestination = resolveUserContractPath();
14309
14772
  const readmeDestination = resolveUserReadmePath();
14310
14773
  try {
14311
- await fs7.access(contractDestination);
14774
+ await fs9.access(contractDestination);
14312
14775
  } catch {
14313
14776
  let source = readmeSource;
14314
14777
  if (!source) {
@@ -14326,7 +14789,7 @@ async function ensureDotMemReadme(_projectRoot, readmeSource) {
14326
14789
  return pathname.startsWith("/") && pathname.length > 3 && pathname[2] === ":" ? pathname.slice(1) : pathname;
14327
14790
  });
14328
14791
  for (const candidate of sourceCandidates) {
14329
- if (await fs7.access(candidate).then(() => true).catch(() => false)) {
14792
+ if (await fs9.access(candidate).then(() => true).catch(() => false)) {
14330
14793
  source = candidate;
14331
14794
  break;
14332
14795
  }
@@ -14334,22 +14797,22 @@ async function ensureDotMemReadme(_projectRoot, readmeSource) {
14334
14797
  source ??= sourceCandidates.at(-1);
14335
14798
  }
14336
14799
  try {
14337
- const contractContent = await fs7.readFile(source, "utf8");
14800
+ const contractContent = await fs9.readFile(source, "utf8");
14338
14801
  if (!contractContent.trim()) {
14339
14802
  throw new Error(`Refusing to install ${source} as the dotmem contract: the file is empty`);
14340
14803
  }
14341
- await fs7.writeFile(contractDestination, contractContent, "utf8");
14804
+ await fs9.writeFile(contractDestination, contractContent, "utf8");
14342
14805
  } catch (error) {
14343
14806
  throw new Error(`Failed to install dotmem contract from ${source} to ${contractDestination}: ${error instanceof Error ? error.message : String(error)}`);
14344
14807
  }
14345
14808
  }
14346
14809
  try {
14347
- await fs7.access(readmeDestination);
14810
+ await fs9.access(readmeDestination);
14348
14811
  return { action: "already-present", path: readmeDestination };
14349
14812
  } catch {
14350
14813
  }
14351
14814
  try {
14352
- await fs7.writeFile(readmeDestination, DEFAULT_README_CONTENT, "utf8");
14815
+ await fs9.writeFile(readmeDestination, DEFAULT_README_CONTENT, "utf8");
14353
14816
  return { action: "created", path: readmeDestination };
14354
14817
  } catch (error) {
14355
14818
  throw new Error(`Failed to write dotmem README at ${readmeDestination}: ${error instanceof Error ? error.message : String(error)}`);
@@ -14885,11 +15348,11 @@ function denoFs() {
14885
15348
  writeFile: writeFile8,
14886
15349
  rename,
14887
15350
  copyFile,
14888
- rm: /* @__PURE__ */ __name((path5, opts) => rm(path5, opts), "rm"),
15351
+ rm: /* @__PURE__ */ __name((path8, opts) => rm(path8, opts), "rm"),
14889
15352
  mkdir,
14890
- open: /* @__PURE__ */ __name(async (path5, flags) => {
15353
+ open: /* @__PURE__ */ __name(async (path8, flags) => {
14891
15354
  if (!Deno.open) throw new Error("Deno.open is unavailable");
14892
- const file = await Deno.open(path5, flags);
15355
+ const file = await Deno.open(path8, flags);
14893
15356
  return {
14894
15357
  writeFile: /* @__PURE__ */ __name(async (data) => {
14895
15358
  const written = await file.write(data);
@@ -14941,8 +15404,8 @@ var init_durable_store = __esm({
14941
15404
  }
14942
15405
  /** Load all entries from disk. Throws on unreadable/corrupt store. */
14943
15406
  async load() {
14944
- const fs7 = await resolveFs();
14945
- if (!fs7) {
15407
+ const fs9 = await resolveFs();
15408
+ if (!fs9) {
14946
15409
  throw new DurableStorageUnavailableError(
14947
15410
  "Durable memory storage is unavailable in this runtime: no filesystem backend could be resolved."
14948
15411
  );
@@ -14952,7 +15415,7 @@ var init_durable_store = __esm({
14952
15415
  async () => {
14953
15416
  let raw;
14954
15417
  try {
14955
- raw = await fs7.readFile(this.filePath);
15418
+ raw = await fs9.readFile(this.filePath);
14956
15419
  } catch (error) {
14957
15420
  const code = error?.code;
14958
15421
  if (code === "ENOENT") {
@@ -14970,7 +15433,7 @@ var init_durable_store = __esm({
14970
15433
  parsed = JSON.parse(decodeText(raw, { source: this.filePath }));
14971
15434
  } catch {
14972
15435
  try {
14973
- const bakRaw = await fs7.readFile(`${this.filePath}.bak`);
15436
+ const bakRaw = await fs9.readFile(`${this.filePath}.bak`);
14974
15437
  parsed = JSON.parse(decodeText(bakRaw, { source: `${this.filePath}.bak` }));
14975
15438
  } catch {
14976
15439
  throw new DurableStorageUnavailableError(
@@ -15044,8 +15507,8 @@ var init_durable_store = __esm({
15044
15507
  await this.load();
15045
15508
  }
15046
15509
  async persist(entries2, nextVersion) {
15047
- const fs7 = await resolveFs();
15048
- if (!fs7) {
15510
+ const fs9 = await resolveFs();
15511
+ if (!fs9) {
15049
15512
  throw new DurableStorageUnavailableError(
15050
15513
  "Durable memory storage is unavailable: no filesystem backend could be resolved."
15051
15514
  );
@@ -15054,10 +15517,10 @@ var init_durable_store = __esm({
15054
15517
  version: nextVersion,
15055
15518
  entries: [...entries2.values()]
15056
15519
  };
15057
- await fs7.mkdir(parentDir(this.filePath), { recursive: true });
15520
+ await fs9.mkdir(parentDir(this.filePath), { recursive: true });
15058
15521
  const temporary = `${this.filePath}.${pidSuffix()}.${uniqueSuffix2()}.tmp`;
15059
15522
  try {
15060
- const handle = await fs7.open(temporary, "wx");
15523
+ const handle = await fs9.open(temporary, "wx");
15061
15524
  try {
15062
15525
  const bytes = new TextEncoder().encode(JSON.stringify(state2, null, 2) + "\n");
15063
15526
  await handle.writeFile(bytes);
@@ -15065,26 +15528,26 @@ var init_durable_store = __esm({
15065
15528
  } finally {
15066
15529
  await handle.close();
15067
15530
  }
15068
- await fs7.readFile(temporary);
15069
- await this.keepLastValidVersion(fs7);
15070
- await fs7.rename(temporary, this.filePath);
15531
+ await fs9.readFile(temporary);
15532
+ await this.keepLastValidVersion(fs9);
15533
+ await fs9.rename(temporary, this.filePath);
15071
15534
  await this.syncDirectory(parentDir(this.filePath));
15072
15535
  } catch (error) {
15073
- await fs7.rm(temporary, { force: true }).catch(() => void 0);
15536
+ await fs9.rm(temporary, { force: true }).catch(() => void 0);
15074
15537
  throw error;
15075
15538
  }
15076
15539
  }
15077
- async keepLastValidVersion(fs7) {
15540
+ async keepLastValidVersion(fs9) {
15078
15541
  try {
15079
- await fs7.copyFile(this.filePath, `${this.filePath}.bak`);
15542
+ await fs9.copyFile(this.filePath, `${this.filePath}.bak`);
15080
15543
  } catch {
15081
15544
  }
15082
15545
  }
15083
15546
  async syncDirectory(directoryPath) {
15084
- const fs7 = await resolveFs();
15085
- if (!fs7) return;
15547
+ const fs9 = await resolveFs();
15548
+ if (!fs9) return;
15086
15549
  try {
15087
- const handle = await fs7.open(directoryPath, "r");
15550
+ const handle = await fs9.open(directoryPath, "r");
15088
15551
  try {
15089
15552
  await handle.sync();
15090
15553
  } finally {
@@ -15195,9 +15658,9 @@ function computeRelevance(entry) {
15195
15658
  };
15196
15659
  return recencyScore * confidenceScore * accessScore * typeBoost[entry.type] * scopeBoost[entry.scope];
15197
15660
  }
15198
- function getNestedPath(obj, path5) {
15199
- if (!path5 || typeof path5 !== "string") return void 0;
15200
- const parts = path5.replace(/^state\./, "").split(".");
15661
+ function getNestedPath(obj, path8) {
15662
+ if (!path8 || typeof path8 !== "string") return void 0;
15663
+ const parts = path8.replace(/^state\./, "").split(".");
15201
15664
  let current = obj;
15202
15665
  for (const part of parts) {
15203
15666
  if (current === null || current === void 0) return void 0;
@@ -15205,9 +15668,9 @@ function getNestedPath(obj, path5) {
15205
15668
  }
15206
15669
  return current;
15207
15670
  }
15208
- function setNestedPath(obj, path5, value) {
15209
- if (!path5 || typeof path5 !== "string") return;
15210
- const parts = path5.replace(/^state\./, "").split(".");
15671
+ function setNestedPath(obj, path8, value) {
15672
+ if (!path8 || typeof path8 !== "string") return;
15673
+ const parts = path8.replace(/^state\./, "").split(".");
15211
15674
  let current = obj;
15212
15675
  for (let i2 = 0; i2 < parts.length - 1; i2++) {
15213
15676
  const part = parts[i2];
@@ -15218,9 +15681,9 @@ function setNestedPath(obj, path5, value) {
15218
15681
  }
15219
15682
  current[parts[parts.length - 1]] = value;
15220
15683
  }
15221
- function deleteNestedPath(obj, path5) {
15222
- if (!path5 || typeof path5 !== "string") return;
15223
- const parts = path5.replace(/^state\./, "").split(".");
15684
+ function deleteNestedPath(obj, path8) {
15685
+ if (!path8 || typeof path8 !== "string") return;
15686
+ const parts = path8.replace(/^state\./, "").split(".");
15224
15687
  let current = obj;
15225
15688
  for (let i2 = 0; i2 < parts.length - 1; i2++) {
15226
15689
  const part = parts[i2];
@@ -15722,13 +16185,13 @@ async function findClaimAcrossAllSources(claimId, scope, sourceProject) {
15722
16185
  const matches2 = [];
15723
16186
  const scanDirectory = /* @__PURE__ */ __name(async (dir) => {
15724
16187
  try {
15725
- const fs7 = await import('fs/promises');
15726
- const entries2 = await fs7.readdir(dir, { withFileTypes: true });
16188
+ const fs9 = await import('fs/promises');
16189
+ const entries2 = await fs9.readdir(dir, { withFileTypes: true });
15727
16190
  for (const e of entries2) {
15728
16191
  if (e.isFile() && e.name.endsWith(".mem") && e.name !== "@brain.mem") {
15729
16192
  const filePath = `${dir}/${e.name}`;
15730
16193
  try {
15731
- const bytes = await fs7.readFile(filePath);
16194
+ const bytes = await fs9.readFile(filePath);
15732
16195
  const artifact = await decodeMemArtifact(bytes);
15733
16196
  const state2 = artifact.state;
15734
16197
  if (!state2) continue;
@@ -16435,11 +16898,11 @@ var init_handshake_session = __esm({
16435
16898
  SESSION_FILE_NAME2 = "handshake-session.json";
16436
16899
  resolveHandshakeSessionPath = /* @__PURE__ */ __name(() => joinStoragePath(joinStoragePath(resolveUserDotMemPath(), RUNTIME_NAMESPACE_DIR), SESSION_FILE_NAME2), "resolveHandshakeSessionPath");
16437
16900
  loadHandshakeSessionRecord = /* @__PURE__ */ __name(() => {
16438
- const fs7 = getSyncFs();
16439
- if (!fs7) return null;
16901
+ const fs9 = getSyncFs();
16902
+ if (!fs9) return null;
16440
16903
  let raw;
16441
16904
  try {
16442
- raw = fs7.readFileSync(resolveHandshakeSessionPath(), "utf8");
16905
+ raw = fs9.readFileSync(resolveHandshakeSessionPath(), "utf8");
16443
16906
  } catch {
16444
16907
  return null;
16445
16908
  }
@@ -16451,26 +16914,26 @@ var init_handshake_session = __esm({
16451
16914
  }
16452
16915
  }, "loadHandshakeSessionRecord");
16453
16916
  saveHandshakeSessionRecord = /* @__PURE__ */ __name(async (record) => {
16454
- const fs7 = getSyncFs();
16455
- if (!fs7) {
16917
+ const fs9 = getSyncFs();
16918
+ if (!fs9) {
16456
16919
  throw new Error("Persisting the handshake session record requires filesystem access, unavailable in this runtime");
16457
16920
  }
16458
16921
  const filePath = resolveHandshakeSessionPath();
16459
- await fs7.promises.mkdir(parentStoragePath(filePath), { recursive: true });
16922
+ await fs9.promises.mkdir(parentStoragePath(filePath), { recursive: true });
16460
16923
  const temporary = `${filePath}.${process.pid}.${Date.now().toString(36)}.tmp`;
16461
16924
  try {
16462
- await fs7.promises.writeFile(temporary, `${JSON.stringify(record, null, 2)}
16925
+ await fs9.promises.writeFile(temporary, `${JSON.stringify(record, null, 2)}
16463
16926
  `, "utf8");
16464
- await fs7.promises.rename(temporary, filePath);
16927
+ await fs9.promises.rename(temporary, filePath);
16465
16928
  } catch (error) {
16466
- await fs7.promises.rm(temporary, { force: true }).catch(() => void 0);
16929
+ await fs9.promises.rm(temporary, { force: true }).catch(() => void 0);
16467
16930
  throw error;
16468
16931
  }
16469
16932
  }, "saveHandshakeSessionRecord");
16470
16933
  clearHandshakeSessionRecord = /* @__PURE__ */ __name(async () => {
16471
- const fs7 = getSyncFs();
16472
- if (!fs7) return;
16473
- await fs7.promises.rm(resolveHandshakeSessionPath(), { force: true }).catch(() => void 0);
16934
+ const fs9 = getSyncFs();
16935
+ if (!fs9) return;
16936
+ await fs9.promises.rm(resolveHandshakeSessionPath(), { force: true }).catch(() => void 0);
16474
16937
  }, "clearHandshakeSessionRecord");
16475
16938
  computeCurrentRuntimeId = /* @__PURE__ */ __name(() => computeRuntimeId({
16476
16939
  platform: process.platform,
@@ -18510,33 +18973,33 @@ var validateContinuityDocument = /* @__PURE__ */ __name((value) => {
18510
18973
  snapshots: document.snapshots
18511
18974
  };
18512
18975
  }, "validateContinuityDocument");
18513
- var deleteContinuityArtifact = /* @__PURE__ */ __name(async (path5) => {
18514
- const fs7 = getSyncFs();
18515
- if (!fs7) return;
18516
- await fs7.promises.rm(path5, { force: true });
18976
+ var deleteContinuityArtifact = /* @__PURE__ */ __name(async (path8) => {
18977
+ const fs9 = getSyncFs();
18978
+ if (!fs9) return;
18979
+ await fs9.promises.rm(path8, { force: true });
18517
18980
  }, "deleteContinuityArtifact");
18518
- var loadContinuityDocument = /* @__PURE__ */ __name(async (path5) => {
18519
- const fs7 = getSyncFs();
18520
- if (!fs7) return emptyContinuityDocument();
18981
+ var loadContinuityDocument = /* @__PURE__ */ __name(async (path8) => {
18982
+ const fs9 = getSyncFs();
18983
+ if (!fs9) return emptyContinuityDocument();
18521
18984
  try {
18522
- const raw = await fs7.promises.readFile(path5, "utf8");
18985
+ const raw = await fs9.promises.readFile(path8, "utf8");
18523
18986
  return validateContinuityDocument(JSON.parse(raw));
18524
18987
  } catch {
18525
18988
  return emptyContinuityDocument();
18526
18989
  }
18527
18990
  }, "loadContinuityDocument");
18528
- var saveContinuityDocument = /* @__PURE__ */ __name(async (path5, document) => {
18529
- const fs7 = getSyncFs();
18530
- if (!fs7) return;
18991
+ var saveContinuityDocument = /* @__PURE__ */ __name(async (path8, document) => {
18992
+ const fs9 = getSyncFs();
18993
+ if (!fs9) return;
18531
18994
  const validated = validateContinuityDocument(document);
18532
- await fs7.promises.mkdir(resolveUserContinuityDir(), { recursive: true });
18533
- const temporary = `${path5}.${process.pid}.${Date.now().toString(36)}.tmp`;
18995
+ await fs9.promises.mkdir(resolveUserContinuityDir(), { recursive: true });
18996
+ const temporary = `${path8}.${process.pid}.${Date.now().toString(36)}.tmp`;
18534
18997
  try {
18535
- await fs7.promises.writeFile(temporary, `${JSON.stringify(validated, null, 2)}
18998
+ await fs9.promises.writeFile(temporary, `${JSON.stringify(validated, null, 2)}
18536
18999
  `, "utf8");
18537
- await fs7.promises.rename(temporary, path5);
19000
+ await fs9.promises.rename(temporary, path8);
18538
19001
  } catch (error) {
18539
- await fs7.promises.rm(temporary, { force: true }).catch(() => void 0);
19002
+ await fs9.promises.rm(temporary, { force: true }).catch(() => void 0);
18540
19003
  throw error;
18541
19004
  }
18542
19005
  }, "saveContinuityDocument");
@@ -19170,48 +19633,48 @@ var HardRulesRegistry = class {
19170
19633
  return resolveRegistryFilePath(this.directory);
19171
19634
  }
19172
19635
  async load() {
19173
- const fs7 = await import('fs/promises');
19636
+ const fs9 = await import('fs/promises');
19174
19637
  try {
19175
- const raw = await fs7.readFile(this.filePath(), "utf8");
19638
+ const raw = await fs9.readFile(this.filePath(), "utf8");
19176
19639
  return validateDocument4(JSON.parse(raw));
19177
19640
  } catch (err2) {
19178
19641
  if (err2.code === "ENOENT") return emptyDocument3();
19179
19642
  throw err2;
19180
19643
  }
19181
19644
  }
19182
- async readDoc(fs7) {
19645
+ async readDoc(fs9) {
19183
19646
  try {
19184
- const raw = await fs7.readFile(this.filePath(), "utf8");
19647
+ const raw = await fs9.readFile(this.filePath(), "utf8");
19185
19648
  return validateDocument4(JSON.parse(raw));
19186
19649
  } catch (err2) {
19187
19650
  if (err2.code === "ENOENT") return emptyDocument3();
19188
19651
  throw err2;
19189
19652
  }
19190
19653
  }
19191
- async writeDoc(fs7, doc) {
19192
- await fs7.mkdir(this.dir(), { recursive: true });
19654
+ async writeDoc(fs9, doc) {
19655
+ await fs9.mkdir(this.dir(), { recursive: true });
19193
19656
  const fp = this.filePath();
19194
19657
  const tmp = `${fp}.${process.pid}.${Date.now().toString(36)}.tmp`;
19195
19658
  try {
19196
- await fs7.writeFile(tmp, `${JSON.stringify(doc, null, 2)}
19659
+ await fs9.writeFile(tmp, `${JSON.stringify(doc, null, 2)}
19197
19660
  `, "utf8");
19198
- const handle = await fs7.open(tmp, "r+");
19661
+ const handle = await fs9.open(tmp, "r+");
19199
19662
  try {
19200
19663
  await handle.sync();
19201
19664
  } finally {
19202
19665
  await handle.close();
19203
19666
  }
19204
- await fs7.rename(tmp, fp);
19667
+ await fs9.rename(tmp, fp);
19205
19668
  } catch (err2) {
19206
- await fs7.rm(tmp, { force: true }).catch(() => void 0);
19669
+ await fs9.rm(tmp, { force: true }).catch(() => void 0);
19207
19670
  throw err2;
19208
19671
  }
19209
19672
  }
19210
19673
  async mutate(operation, options = {}) {
19211
19674
  const directory = this.dir();
19212
19675
  return withPolicyNamespaceLock(async (session2) => {
19213
- const fs7 = await import('fs/promises');
19214
- const doc = await this.readDoc(fs7);
19676
+ const fs9 = await import('fs/promises');
19677
+ const doc = await this.readDoc(fs9);
19215
19678
  if (options.basedOnRevision !== void 0 && options.basedOnRevision !== doc.revision) {
19216
19679
  throw new HardRulesRegistryError(`Stale hard-rules revision: expected ${options.basedOnRevision}, current ${doc.revision}`);
19217
19680
  }
@@ -19219,7 +19682,7 @@ var HardRulesRegistry = class {
19219
19682
  let next = outcome.document;
19220
19683
  validateDocument4(next);
19221
19684
  await session2.assertOwnership();
19222
- await this.writeDoc(fs7, next);
19685
+ await this.writeDoc(fs9, next);
19223
19686
  return outcome.result;
19224
19687
  }, { directory });
19225
19688
  }
@@ -19379,15 +19842,15 @@ var HardRulesRegistry = class {
19379
19842
  // core/functions/bootstrap.ts
19380
19843
  async function checkProjectState(_cwd) {
19381
19844
  const userDotMemDir = resolveUserDotMemPath();
19382
- const userLogicMemPath = path2__default.default.join(userDotMemDir, "logic.mem");
19845
+ const userLogicMemPath = path3__default.default.join(userDotMemDir, "logic.mem");
19383
19846
  let logicMemValid = false;
19384
- if (fs2__default.default.existsSync(userLogicMemPath)) {
19847
+ if (fs3__default.default.existsSync(userLogicMemPath)) {
19385
19848
  logicMemValid = true;
19386
19849
  }
19387
19850
  const projectId = await resolveProjectIdentity(process.cwd());
19388
19851
  const projectAnchorPath = resolveUserProjectMemoryPath(projectId);
19389
- const projectAnchorPresent = fs2__default.default.existsSync(projectAnchorPath);
19390
- const initialized = fs2__default.default.existsSync(userDotMemDir) && logicMemValid && projectAnchorPresent;
19852
+ const projectAnchorPresent = fs3__default.default.existsSync(projectAnchorPath);
19853
+ const initialized = fs3__default.default.existsSync(userDotMemDir) && logicMemValid && projectAnchorPresent;
19391
19854
  return {
19392
19855
  initialized,
19393
19856
  dotmemDir: userDotMemDir,
@@ -19401,8 +19864,8 @@ async function checkProjectState(_cwd) {
19401
19864
  __name(checkProjectState, "checkProjectState");
19402
19865
  async function getMemoryReadiness(_cwd) {
19403
19866
  const userDotMemDir = resolveUserDotMemPath();
19404
- const userProjectsDir = path2__default.default.join(userDotMemDir, "projects");
19405
- if (!fs2__default.default.existsSync(userProjectsDir)) {
19867
+ const userProjectsDir = path3__default.default.join(userDotMemDir, "projects");
19868
+ if (!fs3__default.default.existsSync(userProjectsDir)) {
19406
19869
  return { ready: false, totalSources: 0, totalClaims: 0, sources: [] };
19407
19870
  }
19408
19871
  try {
@@ -19450,12 +19913,12 @@ async function detectAiEnvironment() {
19450
19913
  }
19451
19914
  if (process.platform !== "win32") {
19452
19915
  try {
19453
- const status = fs2__default.default.readFileSync("/proc/self/status", "utf8");
19916
+ const status = fs3__default.default.readFileSync("/proc/self/status", "utf8");
19454
19917
  const ppidMatch = status.match(/^PPid:\s*(\d+)$/m);
19455
19918
  if (ppidMatch) {
19456
19919
  const ppid = parseInt(ppidMatch[1], 10);
19457
19920
  try {
19458
- const comm = fs2__default.default.readFileSync(`/proc/${ppid}/comm`, "utf8").trim();
19921
+ const comm = fs3__default.default.readFileSync(`/proc/${ppid}/comm`, "utf8").trim();
19459
19922
  const knownAiParents = ["codex", "kilo", "claude", "aider", "continue", "cursor"];
19460
19923
  const matchedParent = knownAiParents.find((ai) => comm.toLowerCase().includes(ai));
19461
19924
  if (matchedParent) {
@@ -19484,33 +19947,33 @@ async function detectAiEnvironment() {
19484
19947
  __name(detectAiEnvironment, "detectAiEnvironment");
19485
19948
  async function ensureUserDotMemInitialized() {
19486
19949
  const userDotMemDir = resolveUserDotMemPath();
19487
- const userProjectsDir = path2__default.default.join(userDotMemDir, "projects");
19488
- const userLogicMemPath = path2__default.default.join(userDotMemDir, "logic.mem");
19950
+ const userProjectsDir = path3__default.default.join(userDotMemDir, "projects");
19951
+ const userLogicMemPath = path3__default.default.join(userDotMemDir, "logic.mem");
19489
19952
  const userContractPath = resolveUserContractPath();
19490
19953
  const userBrainPath = resolveUserBrainPath();
19491
19954
  try {
19492
- fs2__default.default.mkdirSync(userDotMemDir, { recursive: true });
19493
- fs2__default.default.mkdirSync(userProjectsDir, { recursive: true });
19955
+ fs3__default.default.mkdirSync(userDotMemDir, { recursive: true });
19956
+ fs3__default.default.mkdirSync(userProjectsDir, { recursive: true });
19494
19957
  } catch {
19495
19958
  }
19496
- if (!fs2__default.default.existsSync(userLogicMemPath)) {
19959
+ if (!fs3__default.default.existsSync(userLogicMemPath)) {
19497
19960
  const seedBytes = await encodeLogicSeed();
19498
- fs2__default.default.writeFileSync(userLogicMemPath, seedBytes);
19961
+ fs3__default.default.writeFileSync(userLogicMemPath, seedBytes);
19499
19962
  }
19500
- if (!fs2__default.default.existsSync(userContractPath)) {
19963
+ if (!fs3__default.default.existsSync(userContractPath)) {
19501
19964
  await ensureDotMemReadme();
19502
19965
  }
19503
- if (!fs2__default.default.existsSync(userBrainPath)) {
19966
+ if (!fs3__default.default.existsSync(userBrainPath)) {
19504
19967
  const emptyBrainDoc = {
19505
19968
  format: "dotmem.brain",
19506
19969
  version: 1,
19507
19970
  relationships: []
19508
19971
  };
19509
- fs2__default.default.writeFileSync(userBrainPath, JSON.stringify(emptyBrainDoc, null, 2));
19972
+ fs3__default.default.writeFileSync(userBrainPath, JSON.stringify(emptyBrainDoc, null, 2));
19510
19973
  }
19511
- const userLanguagePath = path2__default.default.join(userDotMemDir, "language.json");
19512
- if (!fs2__default.default.existsSync(userLanguagePath)) {
19513
- fs2__default.default.writeFileSync(userLanguagePath, JSON.stringify({ format: "dotmem.language", version: 1, language: "it-IT" }, null, 2));
19974
+ const userLanguagePath = path3__default.default.join(userDotMemDir, "language.json");
19975
+ if (!fs3__default.default.existsSync(userLanguagePath)) {
19976
+ fs3__default.default.writeFileSync(userLanguagePath, JSON.stringify({ format: "dotmem.language", version: 1, language: "it-IT" }, null, 2));
19514
19977
  }
19515
19978
  }
19516
19979
  __name(ensureUserDotMemInitialized, "ensureUserDotMemInitialized");
@@ -20506,17 +20969,38 @@ __name(runStorageCli, "runStorageCli");
20506
20969
 
20507
20970
  // core/cli/commands/inspect.ts
20508
20971
  init_mem_package();
20509
- function runInspectCli(file) {
20972
+ init_inspect_report();
20973
+ var redactDefault = true;
20974
+ function runInspectCli(file, args) {
20510
20975
  if (!file) {
20511
- console.error("Usage: npx dotmem inspect FILE.mem");
20976
+ console.error("Usage: npx dotmem inspect FILE.mem [--format md|json] [--redact|--no-redact] [--limit N] [--offset N] [--claims]");
20512
20977
  process.exitCode = 1;
20513
20978
  return;
20514
20979
  }
20980
+ const format = args.includes("--format=json") || args.includes("--format json") ? "json" : "md";
20981
+ const redactArg = args.find((a) => a === "--no-redact" || a === "--redact");
20982
+ const redact = redactArg === "--no-redact" ? false : redactDefault;
20983
+ const limitIndex = args.findIndex((a) => a === "--limit");
20984
+ const limit = limitIndex >= 0 ? Number(args[limitIndex + 1]) : 50;
20985
+ const includeClaims = args.includes("--claims");
20515
20986
  void (async () => {
20516
20987
  try {
20517
- const bytes = await fs2__default.default.promises.readFile(path2__default.default.resolve(file));
20988
+ const bytes = await fs3__default.default.promises.readFile(path3__default.default.resolve(file));
20518
20989
  const result = await inspectMem(bytes);
20519
- console.info(JSON.stringify(result, null, 2));
20990
+ const report = renderInspectReport(result, {
20991
+ redact,
20992
+ includeKnowledge: includeClaims,
20993
+ limit: Number.isFinite(limit) && limit > 0 ? limit : 50
20994
+ });
20995
+ if (format === "json") {
20996
+ console.info(JSON.stringify(report.json, null, 2));
20997
+ } else {
20998
+ console.info(report.markdown);
20999
+ if (redact) {
21000
+ console.info("");
21001
+ console.info("Note: secret-shaped values are redacted. Use --no-redact for full local inspection.");
21002
+ }
21003
+ }
20520
21004
  if (result.status !== "valid") process.exitCode = 2;
20521
21005
  } catch (error) {
20522
21006
  console.error(`Unable to inspect ${file}: ${error instanceof Error ? error.message : String(error)}`);
@@ -20582,6 +21066,148 @@ async function runContinuityCli(args) {
20582
21066
  }
20583
21067
  }
20584
21068
  __name(runContinuityCli, "runContinuityCli");
21069
+
21070
+ // core/cli/commands/dump.ts
21071
+ init_read_only();
21072
+ init_inspect_report();
21073
+ async function runDumpCli(args) {
21074
+ const target = args[0];
21075
+ const format = args.includes("--format=json") || args.includes("--format json") ? "json" : "ndjson";
21076
+ const redactArg = args.find((a) => a === "--no-redact" || a === "--redact");
21077
+ const redact = redactArg === "--no-redact" ? false : true;
21078
+ const sinceIndex = args.findIndex((a) => a === "--since");
21079
+ const since = sinceIndex >= 0 ? Number(args[sinceIndex + 1]) : void 0;
21080
+ const root = target ? path3__default.default.resolve(target) : void 0;
21081
+ const listing = await listStore(root);
21082
+ const entries2 = listing.packages.filter((pkg) => since === void 0 || (pkg.inspection.memoryVersion ?? 0) >= since).map((pkg) => renderInspectReport(pkg.inspection, { redact, includeKnowledge: false, limit: 20 }));
21083
+ if (format === "json") {
21084
+ console.info(JSON.stringify({
21085
+ root: listing.root,
21086
+ redacted: redact,
21087
+ count: entries2.length,
21088
+ packages: entries2.map((e) => e.json)
21089
+ }, null, 2));
21090
+ return;
21091
+ }
21092
+ for (const entry of entries2) {
21093
+ const report = entry.json;
21094
+ console.info(`=== ${report.status === "valid" ? "" : "[corrupt] "}${report.packageVersion ? "package-v1" : report.representation}`);
21095
+ console.info(entry.markdown);
21096
+ }
21097
+ }
21098
+ __name(runDumpCli, "runDumpCli");
21099
+
21100
+ // core/cli/commands/diff.ts
21101
+ init_mem_package();
21102
+ var extractClaims = /* @__PURE__ */ __name((inspection) => {
21103
+ if (inspection.status !== "valid" || !inspection.knowledge) return [];
21104
+ const state2 = inspection.knowledge;
21105
+ if (!Array.isArray(state2.claims)) return [];
21106
+ return state2.claims.map((claim) => {
21107
+ const c = claim;
21108
+ return { id: String(c.id ?? ""), knowledge: c.knowledge, epistemicType: c.epistemicType };
21109
+ }).filter((c) => c.id.length > 0);
21110
+ }, "extractClaims");
21111
+ var knowledgeEqual = /* @__PURE__ */ __name((left, right) => JSON.stringify(stableValue2(left)) === JSON.stringify(stableValue2(right)), "knowledgeEqual");
21112
+ var stableValue2 = /* @__PURE__ */ __name((value) => {
21113
+ if (Array.isArray(value)) return value.map(stableValue2);
21114
+ if (value && typeof value === "object") {
21115
+ return Object.fromEntries(
21116
+ Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => [k, stableValue2(v)])
21117
+ );
21118
+ }
21119
+ return value;
21120
+ }, "stableValue");
21121
+ async function runDiffCli(args) {
21122
+ const [fileA, fileB] = args;
21123
+ if (!fileA || !fileB) {
21124
+ console.error("Usage: npx dotmem diff FILE_A.mem FILE_B.mem");
21125
+ process.exitCode = 1;
21126
+ return;
21127
+ }
21128
+ let inspectionA;
21129
+ let inspectionB;
21130
+ try {
21131
+ inspectionA = await inspectMem(await fs__default.default.readFile(path3__default.default.resolve(fileA)));
21132
+ } catch (error) {
21133
+ console.error(`Unable to read ${fileA}: ${error instanceof Error ? error.message : String(error)}`);
21134
+ process.exitCode = 1;
21135
+ return;
21136
+ }
21137
+ try {
21138
+ inspectionB = await inspectMem(await fs__default.default.readFile(path3__default.default.resolve(fileB)));
21139
+ } catch (error) {
21140
+ console.error(`Unable to read ${fileB}: ${error instanceof Error ? error.message : String(error)}`);
21141
+ process.exitCode = 1;
21142
+ return;
21143
+ }
21144
+ if (inspectionA.status !== "valid") {
21145
+ console.error(`Invalid input ${fileA}: ${inspectionA.status}`);
21146
+ process.exitCode = 1;
21147
+ return;
21148
+ }
21149
+ if (inspectionB.status !== "valid") {
21150
+ console.error(`Invalid input ${fileB}: ${inspectionB.status}`);
21151
+ process.exitCode = 1;
21152
+ return;
21153
+ }
21154
+ const claimsA = extractClaims(inspectionA);
21155
+ const claimsB = extractClaims(inspectionB);
21156
+ const mapA = new Map(claimsA.map((c) => [c.id, c]));
21157
+ const mapB = new Map(claimsB.map((c) => [c.id, c]));
21158
+ const added = [];
21159
+ const removed = [];
21160
+ const changed = [];
21161
+ for (const id of [...mapA.keys()].sort()) {
21162
+ if (!mapB.has(id)) removed.push(mapA.get(id));
21163
+ }
21164
+ for (const id of [...mapB.keys()].sort()) {
21165
+ if (!mapA.has(id)) added.push(mapB.get(id));
21166
+ else {
21167
+ const before = mapA.get(id);
21168
+ const after = mapB.get(id);
21169
+ if (!knowledgeEqual(before.knowledge, after.knowledge) || before.epistemicType !== after.epistemicType) {
21170
+ changed.push({ id, before, after });
21171
+ }
21172
+ }
21173
+ }
21174
+ const report = {
21175
+ fileA: path3__default.default.resolve(fileA),
21176
+ fileB: path3__default.default.resolve(fileB),
21177
+ countA: claimsA.length,
21178
+ countB: claimsB.length,
21179
+ added: added.map((c) => c.id),
21180
+ removed: removed.map((c) => c.id),
21181
+ changed: changed.map((c) => c.id),
21182
+ addedClaims: added,
21183
+ removedClaims: removed,
21184
+ changedClaims: changed,
21185
+ identical: added.length === 0 && removed.length === 0 && changed.length === 0
21186
+ };
21187
+ console.info(JSON.stringify(report, null, 2));
21188
+ }
21189
+ __name(runDiffCli, "runDiffCli");
21190
+
21191
+ // core/cli/commands/bootstrap.ts
21192
+ init_bootstrap();
21193
+ async function runBootstrapCli(args) {
21194
+ const sinceIndex = args.findIndex((a) => a === "--since");
21195
+ const since = sinceIndex >= 0 ? Number(args[sinceIndex + 1]) : void 0;
21196
+ const situationIndex = args.findIndex((a) => a === "--situation");
21197
+ const situation = situationIndex >= 0 ? args[situationIndex + 1] : void 0;
21198
+ try {
21199
+ const response = await composeBootstrap({
21200
+ sinceVersion: since,
21201
+ situation
21202
+ });
21203
+ console.info(response.text);
21204
+ if (response.unchanged) process.exitCode = 0;
21205
+ } catch (error) {
21206
+ console.error(`Bootstrap failed: ${error instanceof Error ? error.message : String(error)}`);
21207
+ process.exitCode = 1;
21208
+ }
21209
+ }
21210
+ __name(runBootstrapCli, "runBootstrapCli");
20585
21211
  async function runHandshakeCli(args) {
20586
21212
  const reset = args.includes("--reset");
20587
21213
  const status = args.includes("--status");
@@ -20828,8 +21454,8 @@ async function runRenderCli(args) {
20828
21454
  return;
20829
21455
  }
20830
21456
  if (outFile) {
20831
- const fs7 = await import('fs/promises');
20832
- await fs7.writeFile(outFile, result.markdown, "utf8");
21457
+ const fs9 = await import('fs/promises');
21458
+ await fs9.writeFile(outFile, result.markdown, "utf8");
20833
21459
  console.info(`Rendered ${view} view to ${outFile}: ${result.claimsWritten} claims`);
20834
21460
  } else {
20835
21461
  console.info(result.markdown);
@@ -20867,8 +21493,8 @@ async function runNoteCli(args) {
20867
21493
  content = await readStdin();
20868
21494
  origin = "stdin";
20869
21495
  } else {
20870
- const fs7 = await import('fs/promises');
20871
- content = await fs7.readFile(fileArg, "utf8");
21496
+ const fs9 = await import('fs/promises');
21497
+ content = await fs9.readFile(fileArg, "utf8");
20872
21498
  origin = fileArg.split(/[\\/]/).pop() ?? fileArg;
20873
21499
  }
20874
21500
  const titleIndex = args.indexOf("--title");
@@ -20952,8 +21578,8 @@ async function runNoteCli(args) {
20952
21578
  process14__default.default.exitCode = 1;
20953
21579
  return;
20954
21580
  }
20955
- const fs7 = await import('fs/promises');
20956
- await fs7.writeFile(outFile, content, "utf8");
21581
+ const fs9 = await import('fs/promises');
21582
+ await fs9.writeFile(outFile, content, "utf8");
20957
21583
  console.info(`Exported note ${id} to ${outFile}`);
20958
21584
  break;
20959
21585
  }
@@ -21050,9 +21676,9 @@ async function runSeedCli(args) {
21050
21676
  content = await readStdin();
21051
21677
  origin = "stdin";
21052
21678
  } else {
21053
- const fs7 = await import('fs/promises');
21679
+ const fs9 = await import('fs/promises');
21054
21680
  try {
21055
- content = await fs7.readFile(input, "utf8");
21681
+ content = await fs9.readFile(input, "utf8");
21056
21682
  } catch (error) {
21057
21683
  console.error(`Unable to read seed file: ${error instanceof Error ? error.message : String(error)}`);
21058
21684
  process14__default.default.exitCode = 1;
@@ -21181,12 +21807,34 @@ __name(runVaultCli, "runVaultCli");
21181
21807
 
21182
21808
  // core/cli/commands/verify.ts
21183
21809
  init_memory();
21810
+ init_memory();
21184
21811
  init_verify();
21185
21812
  async function runVerifyCli(args) {
21186
21813
  const json = args.includes("--json");
21814
+ const persist = args.includes("--persist");
21187
21815
  try {
21188
21816
  const state2 = await loadCombinedKnowledgeState();
21189
21817
  const result = await verifyDueClaims(state2);
21818
+ if (persist) {
21819
+ const { repository } = await getUserKnowledgeRuntime();
21820
+ const current = await repository.load();
21821
+ const { result: persistedResult, persisted } = await verifyAndPersistClaims(
21822
+ current,
21823
+ (next, expectedVersion) => repository.save(next, expectedVersion)
21824
+ );
21825
+ if (json) {
21826
+ console.info(JSON.stringify({ ...persistedResult, persisted }, null, 2));
21827
+ } else {
21828
+ console.info(formatVerifyResult(persistedResult));
21829
+ if (persisted.length > 0) {
21830
+ console.info(`Persisted verification metadata for: ${persisted.join(", ")}`);
21831
+ }
21832
+ }
21833
+ if (persistedResult.stale > 0) {
21834
+ process.exitCode = 2;
21835
+ }
21836
+ return;
21837
+ }
21190
21838
  if (json) {
21191
21839
  console.info(JSON.stringify(result, null, 2));
21192
21840
  return;
@@ -21391,7 +22039,7 @@ var collectStores = /* @__PURE__ */ __name(async () => {
21391
22039
  const files = [];
21392
22040
  for (const dir of sourceDirs) {
21393
22041
  try {
21394
- const entries2 = await fs4__default.default.readdir(dir, { withFileTypes: true });
22042
+ const entries2 = await fs__default.default.readdir(dir, { withFileTypes: true });
21395
22043
  for (const e of entries2) {
21396
22044
  if (e.isFile() && e.name.endsWith(".mem") && e.name !== "@brain.mem") {
21397
22045
  files.push({ sourceId: e.name, filePath: `${dir}/${e.name}` });
@@ -21403,7 +22051,7 @@ var collectStores = /* @__PURE__ */ __name(async () => {
21403
22051
  const stores = [];
21404
22052
  for (const { sourceId, filePath } of files) {
21405
22053
  try {
21406
- const bytes = await fs4__default.default.readFile(filePath);
22054
+ const bytes = await fs__default.default.readFile(filePath);
21407
22055
  const artifact = await decodeMemArtifact(bytes);
21408
22056
  stores.push({ sourceId, filePath, state: artifact.state, artifact });
21409
22057
  } catch (error) {
@@ -21626,7 +22274,7 @@ async function runDoctorCli(args) {
21626
22274
  }
21627
22275
  const filePath = store5.filePath;
21628
22276
  const expectedVersion = store5.state.version;
21629
- await withStorageLock(path2__default.default.dirname(filePath), async () => {
22277
+ await withStorageLock(path3__default.default.dirname(filePath), async () => {
21630
22278
  const fsMod = await import('fs/promises');
21631
22279
  let currentBytes;
21632
22280
  try {
@@ -21647,7 +22295,7 @@ async function runDoctorCli(args) {
21647
22295
  }
21648
22296
  const tmp = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
21649
22297
  try {
21650
- await fsMod.mkdir(path2__default.default.dirname(filePath), { recursive: true });
22298
+ await fsMod.mkdir(path3__default.default.dirname(filePath), { recursive: true });
21651
22299
  const encoded = await encodeMemPackage(newState, currentArtifact.preserved, currentArtifact.package);
21652
22300
  await fsMod.writeFile(tmp, encoded);
21653
22301
  await decodeMemArtifact(await fsMod.readFile(tmp));
@@ -21761,7 +22409,7 @@ Verify the AGENTS.md scintilla block matches SCINTILLA_SIGNAL_HASH.
21761
22409
  const agentsMd = fileIdx !== -1 && args[fileIdx + 1] !== void 0 ? args[fileIdx + 1] : "AGENTS.md";
21762
22410
  let content;
21763
22411
  try {
21764
- content = fs2__default.default.readFileSync(agentsMd, "utf8");
22412
+ content = fs3__default.default.readFileSync(agentsMd, "utf8");
21765
22413
  } catch {
21766
22414
  console.info(`scintilla block not found: ${agentsMd} does not exist (nothing to verify)`);
21767
22415
  return;
@@ -21848,7 +22496,7 @@ function dispatch4(command, args) {
21848
22496
  return;
21849
22497
  }
21850
22498
  if (command === "--version" || command === "-v") {
21851
- const pkg = JSON.parse(fs2__default.default.readFileSync(new URL("package.json", (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli.cjs', document.baseURI).href))), "utf8"));
22499
+ const pkg = JSON.parse(fs3__default.default.readFileSync(new URL("package.json", (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli.cjs', document.baseURI).href))), "utf8"));
21852
22500
  console.info(pkg.version);
21853
22501
  process14__default.default.exit(0);
21854
22502
  return;
@@ -21963,11 +22611,66 @@ Report or relocate the canonical dotmem storage location.
21963
22611
  }
21964
22612
  if (command === "inspect") {
21965
22613
  if (args[0] === "--help" || args[0] === "-h") {
21966
- console.info("Usage: npx dotmem inspect FILE.mem");
22614
+ console.info(`Usage: npx dotmem inspect FILE.mem [--format md|json] [--redact|--no-redact] [--limit N] [--offset N] [--claims]
22615
+
22616
+ Read-only inspection of a .mem package. Secret-shaped values are redacted by default.
22617
+
22618
+ FILE.mem the package to inspect
22619
+ --format md human-readable Markdown report (default)
22620
+ --format json structured JSON report
22621
+ --redact redact secret-shaped values (default)
22622
+ --no-redact disable redaction (local CLI inspection only)
22623
+ --limit N max claims to list (default 50)
22624
+ --offset N claims offset
22625
+ --claims include claim summaries in the report`);
22626
+ process14__default.default.exit(0);
22627
+ return;
22628
+ }
22629
+ void runInspectCli(args[0], args.slice(1));
22630
+ return;
22631
+ }
22632
+ if (command === "dump") {
22633
+ if (args[0] === "--help" || args[0] === "-h") {
22634
+ console.info(`Usage: npx dotmem dump [root|file] [--format json|ndjson] [--redact|--no-redact] [--since <version>]
22635
+
22636
+ Bounded, deterministic, read-only store-wide dump. Redacted by default.
22637
+
22638
+ (no target) dump the default storage root
22639
+ root|file dump a specific directory or package
22640
+ --format ndjson newline-delimited JSON (default)
22641
+ --format json single JSON document
22642
+ --redact redact secret-shaped values (default)
22643
+ --no-redact disable redaction (local CLI inspection only)
22644
+ --since <v> only packages at or above memory version`);
22645
+ process14__default.default.exit(0);
22646
+ return;
22647
+ }
22648
+ void runDumpCli(args);
22649
+ return;
22650
+ }
22651
+ if (command === "diff") {
22652
+ if (args[0] === "--help" || args[0] === "-h") {
22653
+ console.info(`Usage: npx dotmem diff FILE_A.mem FILE_B.mem
22654
+
22655
+ Deterministic, read-only diff between two MEM packages. Reports added,
22656
+ removed, and changed claims. Never mutates anything.`);
22657
+ process14__default.default.exit(0);
22658
+ return;
22659
+ }
22660
+ void runDiffCli(args);
22661
+ return;
22662
+ }
22663
+ if (command === "bootstrap") {
22664
+ if (args[0] === "--help" || args[0] === "-h") {
22665
+ console.info(`Usage: npx dotmem bootstrap [--since <version>] [--situation "<text>"]
22666
+
22667
+ Unified bootstrap: one call returns the initial context plus the rules
22668
+ reference. Pass --since to receive a small deterministic UNCHANGED response
22669
+ when the store has not changed since that version. Read-only; never mutates anything.`);
21967
22670
  process14__default.default.exit(0);
21968
22671
  return;
21969
22672
  }
21970
- void runInspectCli(args[0]);
22673
+ void runBootstrapCli(args);
21971
22674
  return;
21972
22675
  }
21973
22676
  if (command === "continuity") {