dotmem 0.3.2 → 0.3.3

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/global.cjs CHANGED
@@ -4,21 +4,24 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var memorio = require('memorio');
6
6
  var crypto5 = require('crypto');
7
- var fs = require('fs');
8
- var path8 = require('path');
7
+ var fs6 = require('fs');
8
+ var path5 = require('path');
9
9
  var url = require('url');
10
10
  var fs14 = require('fs/promises');
11
11
  var child_process = require('child_process');
12
+ var os = require('os');
12
13
  require('@noble/post-quantum/ml-dsa.js');
13
14
  var hybrid_js = require('@noble/post-quantum/hybrid.js');
14
15
  var module$1 = require('module');
16
+ require('reflect-metadata');
17
+ var typeorm = require('typeorm');
15
18
 
16
19
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
17
20
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
18
21
 
19
22
  var crypto5__default = /*#__PURE__*/_interopDefault(crypto5);
20
- var fs__default = /*#__PURE__*/_interopDefault(fs);
21
- var path8__default = /*#__PURE__*/_interopDefault(path8);
23
+ var fs6__default = /*#__PURE__*/_interopDefault(fs6);
24
+ var path5__default = /*#__PURE__*/_interopDefault(path5);
22
25
  var fs14__default = /*#__PURE__*/_interopDefault(fs14);
23
26
 
24
27
  var __defProp = Object.defineProperty;
@@ -26,12 +29,6 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
26
29
  var __getOwnPropNames = Object.getOwnPropertyNames;
27
30
  var __hasOwnProp = Object.prototype.hasOwnProperty;
28
31
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
29
- var __require = /* @__PURE__ */ ((x3) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x3, {
30
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
31
- }) : x3)(function(x3) {
32
- if (typeof require !== "undefined") return require.apply(this, arguments);
33
- throw Error('Dynamic require of "' + x3 + '" is not supported');
34
- });
35
32
  var __esm = (fn, res, err3) => function __init() {
36
33
  if (err3) throw err3[0];
37
34
  try {
@@ -53,6 +50,14 @@ var __copyProps = (to, from, except, desc) => {
53
50
  return to;
54
51
  };
55
52
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
53
+ var __decorateClass = (decorators, target, key, kind) => {
54
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
55
+ for (var i3 = decorators.length - 1, decorator; i3 >= 0; i3--)
56
+ if (decorator = decorators[i3])
57
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
58
+ if (kind && result) __defProp(target, key, result);
59
+ return result;
60
+ };
56
61
 
57
62
  // core/security/privacy-gate.ts
58
63
  var REDACTED, SENSITIVE_CATEGORY_PATTERNS, PII_TOKEN_PATTERNS, isHighEntropyToken, findHighEntropyTokens, containsSensitiveCategory, detectPrivacyIssues, redactTokens, privacyGate, applyPrivacyGate, sanitizeContent, containsSensitiveData, isSafeToPersist, redact, privacy_gate, PrivacyGate, gate, checkPrivacy, scan, redactPII, scanSecrets, classifyPrivacy;
@@ -854,18 +859,18 @@ var init_storage_settings = __esm({
854
859
  throw invalidSettings(file2, "must contain a JSON object");
855
860
  }
856
861
  const document = parsed;
857
- const unknownFields = Object.keys(document).filter((key) => key !== "storage");
858
- if (unknownFields.length > 0) {
859
- throw invalidSettings(file2, `contains unsupported top-level fields (${unknownFields.join(", ")})`);
862
+ const anyFields = Object.keys(document).filter((key) => key !== "storage");
863
+ if (anyFields.length > 0) {
864
+ throw invalidSettings(file2, `contains unsupported top-level fields (${anyFields.join(", ")})`);
860
865
  }
861
866
  const storage = document.storage;
862
867
  if (storage === void 0) return {};
863
868
  if (!storage || typeof storage !== "object" || Array.isArray(storage)) {
864
869
  throw invalidSettings(file2, "has a storage field that is not an object");
865
870
  }
866
- const unknownStorageFields = Object.keys(storage).filter((key) => key !== "root" && key !== "mode");
867
- if (unknownStorageFields.length > 0) {
868
- throw invalidSettings(file2, `storage contains unsupported fields (${unknownStorageFields.join(", ")})`);
871
+ const anyStorageFields = Object.keys(storage).filter((key) => key !== "root" && key !== "mode");
872
+ if (anyStorageFields.length > 0) {
873
+ throw invalidSettings(file2, `storage contains unsupported fields (${anyStorageFields.join(", ")})`);
869
874
  }
870
875
  if (storage.mode !== void 0 && (typeof storage.mode !== "string" || !SETTINGS_MODES.includes(storage.mode))) {
871
876
  throw invalidSettings(file2, `storage.mode must be one of ${SETTINGS_MODES.join(", ")} (received ${JSON.stringify(storage.mode)})`);
@@ -913,7 +918,7 @@ var init_storage_settings = __esm({
913
918
  if (code === "EACCES" || code === "EPERM") {
914
919
  throw invalidSettings(file2, `cannot be read (${code})`);
915
920
  }
916
- throw invalidSettings(file2, `cannot be read (${code ?? "unknown error"})`);
921
+ throw invalidSettings(file2, `cannot be read (${code ?? "any error"})`);
917
922
  }
918
923
  return raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw;
919
924
  }, "readTextFile");
@@ -962,7 +967,7 @@ var init_text_encoding = __esm({
962
967
  decodeText = /* @__PURE__ */ __name((bytes, options = {}) => {
963
968
  const bom = detectBom(bytes);
964
969
  if (bom === "utf-16le" || bom === "utf-16be") {
965
- throw new UnsupportedEncodingError(`UTF-16 encoded content detected in ${options.source ?? "unknown"}; dotmem persists UTF-8 only. Re-save the file as UTF-8 without BOM.`);
970
+ throw new UnsupportedEncodingError(`UTF-16 encoded content detected in ${options.source ?? "any"}; dotmem persists UTF-8 only. Re-save the file as UTF-8 without BOM.`);
966
971
  }
967
972
  let content = bytes;
968
973
  if (bom === "utf-8") {
@@ -1045,7 +1050,7 @@ var init_storage_location = __esm({
1045
1050
  if (code === "ENOENT") return "the directory does not exist";
1046
1051
  if (code === "EACCES" || code === "EPERM") return `the directory is not accessible (${code})`;
1047
1052
  if (code === "ENOTDIR") return "the path is not a directory";
1048
- return `the directory cannot be accessed (${code ?? "unknown error"})`;
1053
+ return `the directory cannot be accessed (${code ?? "any error"})`;
1049
1054
  }, "describeAccessFailure");
1050
1055
  validateConfiguredStorageRoot = /* @__PURE__ */ __name((value, source) => {
1051
1056
  if (typeof value !== "string" || !value.trim()) {
@@ -1096,9 +1101,9 @@ var init_storage_location = __esm({
1096
1101
  throw new DotMemStorageLocationError(`dotmem storage location cannot be resolved: the user locator file at ${locatorFile} must contain a JSON object.`);
1097
1102
  }
1098
1103
  const locator = parsed;
1099
- const unknownFields = Object.keys(locator).filter((key) => key !== "version" && key !== "storageRoot");
1100
- if (unknownFields.length > 0) {
1101
- throw new DotMemStorageLocationError(`dotmem storage location cannot be resolved: the user locator file at ${locatorFile} contains unsupported fields (${unknownFields.join(", ")}). The locator holds location metadata only.`);
1104
+ const anyFields = Object.keys(locator).filter((key) => key !== "version" && key !== "storageRoot");
1105
+ if (anyFields.length > 0) {
1106
+ throw new DotMemStorageLocationError(`dotmem storage location cannot be resolved: the user locator file at ${locatorFile} contains unsupported fields (${anyFields.join(", ")}). The locator holds location metadata only.`);
1102
1107
  }
1103
1108
  if (locator.version !== DOTMEM_STORAGE_LOCATOR_VERSION) {
1104
1109
  throw new DotMemStorageLocationError(`dotmem storage location cannot be resolved: the user locator file at ${locatorFile} has unsupported version ${JSON.stringify(locator.version)}; expected ${DOTMEM_STORAGE_LOCATOR_VERSION}.`);
@@ -1446,22 +1451,22 @@ var init_conversation_events = __esm({
1446
1451
  const fs16 = fsSync();
1447
1452
  if (fs16) {
1448
1453
  try {
1449
- const path10 = EVENTS_FILE();
1450
- const parent = path10.substring(0, Math.max(path10.lastIndexOf("/"), path10.lastIndexOf("\\")));
1454
+ const path11 = EVENTS_FILE();
1455
+ const parent = path11.substring(0, Math.max(path11.lastIndexOf("/"), path11.lastIndexOf("\\")));
1451
1456
  try {
1452
1457
  fs16.mkdirSync(parent, { recursive: true });
1453
1458
  } catch {
1454
1459
  }
1455
- const tmp = `${path10}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
1460
+ const tmp = `${path11}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
1456
1461
  fs16.writeFileSync(tmp, JSON.stringify(events));
1457
1462
  try {
1458
- if (fs16.existsSync(path10)) fs16.copyFileSync(path10, `${path10}.bak`);
1463
+ if (fs16.existsSync(path11)) fs16.copyFileSync(path11, `${path11}.bak`);
1459
1464
  } catch {
1460
1465
  }
1461
1466
  try {
1462
- fs16.renameSync(tmp, path10);
1467
+ fs16.renameSync(tmp, path11);
1463
1468
  } catch {
1464
- fs16.copyFileSync(tmp, path10);
1469
+ fs16.copyFileSync(tmp, path11);
1465
1470
  try {
1466
1471
  fs16.unlinkSync(tmp);
1467
1472
  } catch {
@@ -1602,8 +1607,8 @@ var init_conversation_events = __esm({
1602
1607
  try {
1603
1608
  const fs16 = fsSync();
1604
1609
  if (fs16) {
1605
- const path10 = EVENTS_FILE();
1606
- const parent = path10.substring(0, Math.max(path10.lastIndexOf("/"), path10.lastIndexOf("\\")));
1610
+ const path11 = EVENTS_FILE();
1611
+ const parent = path11.substring(0, Math.max(path11.lastIndexOf("/"), path11.lastIndexOf("\\")));
1607
1612
  return await withStorageLock(parent, run);
1608
1613
  }
1609
1614
  } catch {
@@ -1799,9 +1804,9 @@ var init_policy_namespace_lock = __esm({
1799
1804
  currentHost = /* @__PURE__ */ __name(async () => {
1800
1805
  try {
1801
1806
  const os = await import('os');
1802
- return typeof os.hostname === "function" && os.hostname() ? os.hostname() : "unknown";
1807
+ return typeof os.hostname === "function" && os.hostname() ? os.hostname() : "any";
1803
1808
  } catch {
1804
- return "unknown";
1809
+ return "any";
1805
1810
  }
1806
1811
  }, "currentHost");
1807
1812
  delay = /* @__PURE__ */ __name(async (milliseconds) => {
@@ -1820,7 +1825,7 @@ var init_policy_namespace_lock = __esm({
1820
1825
  if (!parsed || typeof parsed !== "object") return null;
1821
1826
  return {
1822
1827
  pid: typeof parsed.pid === "number" ? parsed.pid : 0,
1823
- host: typeof parsed.host === "string" ? parsed.host : "unknown",
1828
+ host: typeof parsed.host === "string" ? parsed.host : "any",
1824
1829
  acquiredAt: typeof parsed.acquiredAt === "string" ? parsed.acquiredAt : "",
1825
1830
  token: typeof parsed.token === "string" ? parsed.token : ""
1826
1831
  };
@@ -1843,7 +1848,7 @@ var init_policy_namespace_lock = __esm({
1843
1848
  const acquiredAt = held ? Date.parse(held.acquiredAt) : Number.NaN;
1844
1849
  const age = Number.isFinite(acquiredAt) ? Date.now() - acquiredAt : Number.POSITIVE_INFINITY;
1845
1850
  if (age > POLICY_LOCK_TTL_MS) {
1846
- const stale = held ?? { pid: 0, host: "unknown", acquiredAt: "", token: "" };
1851
+ const stale = held ?? { pid: 0, host: "any", acquiredAt: "", token: "" };
1847
1852
  const outcome = await breakStalePolicyLock(fs16, lockPath, stale);
1848
1853
  if (outcome === "broken") {
1849
1854
  brokenOwner = stale;
@@ -1860,7 +1865,7 @@ var init_policy_namespace_lock = __esm({
1860
1865
  throw new PolicyNamespaceLockError(`Policy namespace lock could not be acquired after ${POLICY_LOCK_RETRY_ATTEMPTS} bounded retries; policy mutation fails closed`);
1861
1866
  }, "acquireLock");
1862
1867
  breakStalePolicyLock = /* @__PURE__ */ __name(async (fs16, lockPath, staleOwner) => {
1863
- const candidate = `${lockPath}.breaking-${staleOwner.token || "unknown"}`;
1868
+ const candidate = `${lockPath}.breaking-${staleOwner.token || "any"}`;
1864
1869
  try {
1865
1870
  await fs16.rename(lockPath, candidate);
1866
1871
  } catch (error) {
@@ -2082,11 +2087,11 @@ var init_state = __esm({
2082
2087
  if (evidence.length === 0) return;
2083
2088
  for (let index = 0; index < evidence.length; index++) {
2084
2089
  const entry = evidence[index];
2085
- const path10 = `evidence[${index}]`;
2090
+ const path11 = `evidence[${index}]`;
2086
2091
  if (Array.isArray(entry)) {
2087
2092
  throw canonicalEvidenceError({
2088
2093
  claimId: claim.id,
2089
- path: path10,
2094
+ path: path11,
2090
2095
  problem: CANONICAL_EVIDENCE_PROBLEMS.tupleEntry,
2091
2096
  received: entry,
2092
2097
  fix: CANONICAL_EVIDENCE_FIX.tupleEntry
@@ -2095,7 +2100,7 @@ var init_state = __esm({
2095
2100
  if (!entry || typeof entry !== "object") {
2096
2101
  throw canonicalEvidenceError({
2097
2102
  claimId: claim.id,
2098
- path: path10,
2103
+ path: path11,
2099
2104
  problem: CANONICAL_EVIDENCE_PROBLEMS.nonObjectEntry,
2100
2105
  received: entry,
2101
2106
  fix: CANONICAL_EVIDENCE_FIX.nonObjectEntry
@@ -2104,7 +2109,7 @@ var init_state = __esm({
2104
2109
  if (!requiredText(entry.id)) {
2105
2110
  throw canonicalEvidenceError({
2106
2111
  claimId: claim.id,
2107
- path: `${path10}.id`,
2112
+ path: `${path11}.id`,
2108
2113
  problem: CANONICAL_EVIDENCE_PROBLEMS.missingId,
2109
2114
  received: entry,
2110
2115
  fix: CANONICAL_EVIDENCE_FIX.missingId
@@ -2115,7 +2120,7 @@ var init_state = __esm({
2115
2120
  if (fieldValue !== void 0 && !requiredText(fieldValue)) {
2116
2121
  throw canonicalEvidenceError({
2117
2122
  claimId: claim.id,
2118
- path: `${path10}.${field}`,
2123
+ path: `${path11}.${field}`,
2119
2124
  problem: CANONICAL_EVIDENCE_PROBLEMS.invalidOptionalField(field),
2120
2125
  received: fieldValue,
2121
2126
  fix: CANONICAL_EVIDENCE_FIX.invalidOptionalField(field)
@@ -2178,7 +2183,7 @@ var init_state = __esm({
2178
2183
  if (options?.allowUnresolvedRevisions !== true) {
2179
2184
  for (const claim of state3.claims) {
2180
2185
  for (const relatedId of claim.revision?.claimIds || []) {
2181
- if (!ids.has(relatedId)) throw new Error(`Claim ${claim.id} references unknown claim ${relatedId}`);
2186
+ if (!ids.has(relatedId)) throw new Error(`Claim ${claim.id} references any claim ${relatedId}`);
2182
2187
  }
2183
2188
  }
2184
2189
  }
@@ -2202,7 +2207,7 @@ var init_state = __esm({
2202
2207
  }
2203
2208
  for (const claim of update.claims) {
2204
2209
  for (const relatedId of claim.revision?.claimIds || []) {
2205
- if (!known.has(relatedId)) throw new Error(`Claim ${claim.id} references unknown prior claim ${relatedId}`);
2210
+ if (!known.has(relatedId)) throw new Error(`Claim ${claim.id} references any prior claim ${relatedId}`);
2206
2211
  }
2207
2212
  }
2208
2213
  return structuredClone({ version: state3.version + 1, claims: [...state3.claims, ...update.claims] });
@@ -2935,7 +2940,7 @@ var init_policy_store = __esm({
2935
2940
  authority: { kind: "system", source: "policy-namespace-lock" },
2936
2941
  target: resolvePolicyNamespaceLockPath(directory),
2937
2942
  outcome: "applied",
2938
- detail: `stale policy namespace lock broken; previous owner pid ${lockBreak.brokenOwner.pid} host ${lockBreak.brokenOwner.host} acquiredAt ${lockBreak.brokenOwner.acquiredAt || "unknown"}`
2943
+ detail: `stale policy namespace lock broken; previous owner pid ${lockBreak.brokenOwner.pid} host ${lockBreak.brokenOwner.host} acquiredAt ${lockBreak.brokenOwner.acquiredAt || "any"}`
2939
2944
  })
2940
2945
  );
2941
2946
  next = { ...next, audit: boundedAudit([...next.audit, ...breakEntries], next.overrides) };
@@ -3255,7 +3260,7 @@ var init_policy_store = __esm({
3255
3260
  });
3256
3261
 
3257
3262
  // core/knowledge/sanitizer.ts
3258
- var SECRET_KEY_INDICATORS, isSecretKey, looksLikeSecretValue, looksLikeMojibake, collectMojibake, semanticizeSecret, sanitizeObject, sanitizeArray, sanitizeKnowledge;
3263
+ var SECRET_KEY_INDICATORS, isSecretKey, looksLikeSecretValue, looksLikeMojibake, collectMojibake, semanticizeSecret, sanitizeObject, sanitizeArray, sanitizeKnowledge, createSanitizedEnv;
3259
3264
  var init_sanitizer = __esm({
3260
3265
  "core/knowledge/sanitizer.ts"() {
3261
3266
  SECRET_KEY_INDICATORS = ["password", "passwd", "pwd", "secret", "apikey", "api_key", "token", "accesstoken", "refreshtoken", "privatekey", "private_key", "clientsecret", "authorization", "bearer", "credential", "credentials", "recoverycode", "sessionsecret", "jwtsecret"];
@@ -3380,6 +3385,15 @@ var init_sanitizer = __esm({
3380
3385
  disposition: "persist"
3381
3386
  };
3382
3387
  }, "sanitizeKnowledge");
3388
+ createSanitizedEnv = /* @__PURE__ */ __name(() => {
3389
+ const env = {};
3390
+ for (const [key, value] of Object.entries(process.env)) {
3391
+ if (isSecretKey(key)) continue;
3392
+ if (value === void 0 || value === null) continue;
3393
+ env[key] = value;
3394
+ }
3395
+ return env;
3396
+ }, "createSanitizedEnv");
3383
3397
  }
3384
3398
  });
3385
3399
 
@@ -3531,7 +3545,7 @@ var init_built_in_context = __esm({
3531
3545
  return __dirname;
3532
3546
  }
3533
3547
  try {
3534
- return path8__default.default.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('global.cjs', document.baseURI).href))));
3548
+ return path5__default.default.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('global.cjs', document.baseURI).href))));
3535
3549
  } catch {
3536
3550
  return process.cwd();
3537
3551
  }
@@ -3539,7 +3553,7 @@ var init_built_in_context = __esm({
3539
3553
  candidatePaths = /* @__PURE__ */ __name(() => {
3540
3554
  const paths = [];
3541
3555
  try {
3542
- paths.push(path8__default.default.join(pkgDirname(), "built-in-context.json"));
3556
+ paths.push(path5__default.default.join(pkgDirname(), "built-in-context.json"));
3543
3557
  } catch {
3544
3558
  }
3545
3559
  return paths;
@@ -3608,11 +3622,11 @@ var init_built_in_context = __esm({
3608
3622
  let lastError = "Built-in context artifact not found";
3609
3623
  const candidates = _artifactPathOverride ? [_artifactPathOverride] : candidatePaths();
3610
3624
  for (const candidate of candidates) {
3611
- if (!fs__default.default.existsSync(candidate)) continue;
3625
+ if (!fs6__default.default.existsSync(candidate)) continue;
3612
3626
  let readAttempts = 0;
3613
3627
  while (readAttempts < 60) {
3614
3628
  try {
3615
- const raw = fs__default.default.readFileSync(candidate);
3629
+ const raw = fs6__default.default.readFileSync(candidate);
3616
3630
  const parsed = JSON.parse(decodeText(raw, { source: candidate }));
3617
3631
  const artifact = validateArtifact(parsed);
3618
3632
  cached = artifact;
@@ -3649,15 +3663,15 @@ var init_built_in_context = __esm({
3649
3663
  }
3650
3664
  let attemptedPath = "";
3651
3665
  try {
3652
- attemptedPath = path8__default.default.join(pkgDirname(), "built-in-context.json");
3666
+ attemptedPath = path5__default.default.join(pkgDirname(), "built-in-context.json");
3653
3667
  } catch {
3654
3668
  }
3655
- let packageVersion = "unknown";
3669
+ let packageVersion = "any";
3656
3670
  try {
3657
- const pkgPath = path8__default.default.join(pkgDirname(), "package.json");
3658
- if (fs__default.default.existsSync(pkgPath)) {
3659
- const pkg = JSON.parse(fs__default.default.readFileSync(pkgPath, "utf8"));
3660
- packageVersion = typeof pkg.version === "string" ? pkg.version : "unknown";
3671
+ const pkgPath = path5__default.default.join(pkgDirname(), "package.json");
3672
+ if (fs6__default.default.existsSync(pkgPath)) {
3673
+ const pkg = JSON.parse(fs6__default.default.readFileSync(pkgPath, "utf8"));
3674
+ packageVersion = typeof pkg.version === "string" ? pkg.version : "any";
3661
3675
  }
3662
3676
  } catch {
3663
3677
  }
@@ -5258,14 +5272,14 @@ var init_mem_package = __esm({
5258
5272
  const digest = await globalThis.crypto.subtle.digest("SHA-256", data);
5259
5273
  return `sha256:${[...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
5260
5274
  }, "sha256");
5261
- parseJson = /* @__PURE__ */ __name((bytes, path10) => {
5275
+ parseJson = /* @__PURE__ */ __name((bytes, path11) => {
5262
5276
  try {
5263
5277
  return JSON.parse(decodeText(bytes));
5264
5278
  } catch (error) {
5265
- throw new MemArtifactError("invalid", `Invalid UTF-8 JSON in ${path10}: ${error.message}`);
5279
+ throw new MemArtifactError("invalid", `Invalid UTF-8 JSON in ${path11}: ${error.message}`);
5266
5280
  }
5267
5281
  }, "parseJson");
5268
- validEntryPath = /* @__PURE__ */ __name((path10) => path10.length > 0 && path10.length <= 240 && !path10.includes("\\") && !path10.startsWith("/") && !/^[A-Za-z]:/.test(path10) && path10.split("/").every((segment) => segment.length > 0 && segment !== "." && segment !== ".."), "validEntryPath");
5282
+ validEntryPath = /* @__PURE__ */ __name((path11) => path11.length > 0 && path11.length <= 240 && !path11.includes("\\") && !path11.startsWith("/") && !/^[A-Za-z]:/.test(path11) && path11.split("/").every((segment) => segment.length > 0 && segment !== "." && segment !== ".."), "validEntryPath");
5269
5283
  concatenate = /* @__PURE__ */ __name((chunks, size) => {
5270
5284
  const result = new Uint8Array(size);
5271
5285
  let offset = 0;
@@ -5341,24 +5355,24 @@ var init_mem_package = __esm({
5341
5355
  [DATA_PATH]: jsonBytes(memory2.data),
5342
5356
  ...structuredClone(preservedPackage?.extensions ?? {})
5343
5357
  };
5344
- for (const path10 of Object.keys(protectedParts)) {
5345
- if (!requiredParts.includes(path10) && !path10.startsWith("extensions/")) {
5346
- throw new MemArtifactError("invalid", `Unsupported preserved package part: ${path10}`);
5358
+ for (const path11 of Object.keys(protectedParts)) {
5359
+ if (!requiredParts.includes(path11) && !path11.startsWith("extensions/")) {
5360
+ throw new MemArtifactError("invalid", `Unsupported preserved package part: ${path11}`);
5347
5361
  }
5348
- if (!validEntryPath(path10)) throw new MemArtifactError("invalid", `Unsafe MEM package path: ${path10}`);
5362
+ if (!validEntryPath(path11)) throw new MemArtifactError("invalid", `Unsafe MEM package path: ${path11}`);
5349
5363
  }
5350
- for (const path10 of Object.keys(signatures)) {
5351
- if (!/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path10)) {
5352
- throw new MemArtifactError("invalid", `Invalid MEM signature path: ${path10}`);
5364
+ for (const path11 of Object.keys(signatures)) {
5365
+ if (!/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path11)) {
5366
+ throw new MemArtifactError("invalid", `Invalid MEM signature path: ${path11}`);
5353
5367
  }
5354
5368
  }
5355
5369
  const files = {};
5356
- for (const path10 of Object.keys(protectedParts).sort()) files[path10] = await sha2562(protectedParts[path10]);
5370
+ for (const path11 of Object.keys(protectedParts).sort()) files[path11] = await sha2562(protectedParts[path11]);
5357
5371
  const integrity = { algorithm: "sha256", files, contentId: await digestTableIdentity(files) };
5358
5372
  const parts = { ...protectedParts, [INTEGRITY_PATH]: jsonBytes(integrity), ...signatures };
5359
- for (const [path10, bytes] of Object.entries(parts)) {
5373
+ for (const [path11, bytes] of Object.entries(parts)) {
5360
5374
  if (bytes.length > MEM_PACKAGE_WRITE_LIMITS.maximumEntryBytes) {
5361
- throw new MemArtifactError("invalid", `MEM package entry exceeds the write limit: ${path10}`);
5375
+ throw new MemArtifactError("invalid", `MEM package entry exceeds the write limit: ${path11}`);
5362
5376
  }
5363
5377
  }
5364
5378
  const uncompressedBytes = Object.values(parts).reduce((total, bytes) => total + bytes.length, 0);
@@ -5366,10 +5380,10 @@ var init_mem_package = __esm({
5366
5380
  throw new MemArtifactError("invalid", "MEM package exceeds the write limit for uncompressed content");
5367
5381
  }
5368
5382
  const zippable = Object.fromEntries(
5369
- Object.keys(parts).sort().map((path10) => [
5370
- path10,
5383
+ Object.keys(parts).sort().map((path11) => [
5384
+ path11,
5371
5385
  [
5372
- parts[path10],
5386
+ parts[path11],
5373
5387
  {
5374
5388
  level: 6,
5375
5389
  mtime: /* @__PURE__ */ new Date("1980-01-02T00:00:00.000Z")
@@ -5389,8 +5403,8 @@ var init_mem_package = __esm({
5389
5403
  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");
5390
5404
  decodePackage = /* @__PURE__ */ __name(async (bytes) => {
5391
5405
  const parts = readZipParts(bytes);
5392
- for (const path10 of [...requiredParts, INTEGRITY_PATH]) {
5393
- if (!parts[path10]) throw new MemArtifactError("invalid", `Missing MEM package part: ${path10}`);
5406
+ for (const path11 of [...requiredParts, INTEGRITY_PATH]) {
5407
+ if (!parts[path11]) throw new MemArtifactError("invalid", `Missing MEM package part: ${path11}`);
5394
5408
  }
5395
5409
  const manifest = parseJson(parts[MANIFEST_PATH], MANIFEST_PATH);
5396
5410
  if (manifest.format !== MEM_PACKAGE_FORMAT && manifest.format !== MEM_PACKAGE_FORMAT_LEGACY || manifest.version !== MEM_PACKAGE_VERSION) {
@@ -5401,8 +5415,8 @@ var init_mem_package = __esm({
5401
5415
  }
5402
5416
  const integrity = parseJson(parts[INTEGRITY_PATH], INTEGRITY_PATH);
5403
5417
  if (integrity.algorithm !== "sha256") throw new MemArtifactError("unsupported", "Unsupported MEM package integrity algorithm");
5404
- const signaturePaths = Object.keys(parts).filter((path10) => path10.startsWith("security/signatures/")).sort();
5405
- if (signaturePaths.some((path10) => !/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path10))) {
5418
+ const signaturePaths = Object.keys(parts).filter((path11) => path11.startsWith("security/signatures/")).sort();
5419
+ if (signaturePaths.some((path11) => !/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path11))) {
5406
5420
  throw new MemArtifactError("invalid", "Invalid MEM signature entry path");
5407
5421
  }
5408
5422
  if (manifest.authenticity !== void 0 && manifest.authenticity.signed !== true) {
@@ -5411,14 +5425,14 @@ var init_mem_package = __esm({
5411
5425
  if (manifest.authenticity?.signed === true !== signaturePaths.length > 0) {
5412
5426
  throw new MemArtifactError("invalid", "Declared MEM signatures do not match package entries");
5413
5427
  }
5414
- const archivePaths = Object.keys(parts).filter((path10) => path10 !== INTEGRITY_PATH && !path10.startsWith("security/signatures/")).sort();
5428
+ const archivePaths = Object.keys(parts).filter((path11) => path11 !== INTEGRITY_PATH && !path11.startsWith("security/signatures/")).sort();
5415
5429
  const protectedPaths = Object.keys(integrity.files ?? {}).sort();
5416
5430
  if (JSON.stringify(archivePaths) !== JSON.stringify(protectedPaths)) {
5417
5431
  throw new MemArtifactError("invalid", "MEM package protected-parts table does not match archive contents");
5418
5432
  }
5419
- for (const path10 of protectedPaths) {
5420
- const actual = await sha2562(parts[path10]);
5421
- if (integrity.files[path10] !== actual) throw new MemArtifactError("checksum_mismatch", `Checksum mismatch for ${path10}`);
5433
+ for (const path11 of protectedPaths) {
5434
+ const actual = await sha2562(parts[path11]);
5435
+ if (integrity.files[path11] !== actual) throw new MemArtifactError("checksum_mismatch", `Checksum mismatch for ${path11}`);
5422
5436
  }
5423
5437
  if (integrity.contentId !== await digestTableIdentity(integrity.files)) {
5424
5438
  throw new MemArtifactError("checksum_mismatch", "MEM package content identity mismatch");
@@ -5431,8 +5445,8 @@ var init_mem_package = __esm({
5431
5445
  } catch (error) {
5432
5446
  throw new MemArtifactError("invalid", `Invalid packaged MEM semantics: ${error.message}`);
5433
5447
  }
5434
- const extensions = Object.fromEntries(Object.entries(parts).filter(([path10]) => path10.startsWith("extensions/")));
5435
- const signatures = Object.fromEntries(signaturePaths.map((path10) => [path10, parts[path10]]));
5448
+ const extensions = Object.fromEntries(Object.entries(parts).filter(([path11]) => path11.startsWith("extensions/")));
5449
+ const signatures = Object.fromEntries(signaturePaths.map((path11) => [path11, parts[path11]]));
5436
5450
  return { ...decoded, representation: "package-v1", package: { manifest, extensions, signatures }, parts, integrity };
5437
5451
  }, "decodePackage");
5438
5452
  decodeMemArtifact = /* @__PURE__ */ __name(async (input) => {
@@ -5471,13 +5485,13 @@ var init_quarantine = __esm({
5471
5485
  quarantineClaimRecord = /* @__PURE__ */ __name(async (record) => {
5472
5486
  if (!record.filePath) return null;
5473
5487
  try {
5474
- const dir = path8__default.default.dirname(record.filePath);
5475
- const quarantineDir = path8__default.default.join(dir, "quarantine");
5488
+ const dir = path5__default.default.dirname(record.filePath);
5489
+ const quarantineDir = path5__default.default.join(dir, "quarantine");
5476
5490
  await fs14__default.default.mkdir(quarantineDir, { recursive: true });
5477
- const safeId = String(record.claimId ?? "unknown").replace(/[^a-zA-Z0-9._-]/g, "-");
5491
+ const safeId = String(record.claimId ?? "any").replace(/[^a-zA-Z0-9._-]/g, "-");
5478
5492
  const timestamp = record.timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
5479
5493
  const fileName = `${safeId}-${Date.now()}.json`;
5480
- const fullPath = path8__default.default.join(quarantineDir, fileName);
5494
+ const fullPath = path5__default.default.join(quarantineDir, fileName);
5481
5495
  const payload = {
5482
5496
  claimId: record.claimId,
5483
5497
  store: record.store,
@@ -5518,7 +5532,7 @@ var init_store_registry = __esm({
5518
5532
  }
5519
5533
  for (const dirent of dirents) {
5520
5534
  if (!dirent.isFile()) continue;
5521
- const filePath = path8__default.default.join(directory, dirent.name);
5535
+ const filePath = path5__default.default.join(directory, dirent.name);
5522
5536
  if (isMemFile(dirent.name)) {
5523
5537
  entries2.push({ id: dirent.name, path: filePath, kind: "active", active: true, reason: "active .mem store" });
5524
5538
  continue;
@@ -5681,7 +5695,7 @@ var init_claim_delete = __esm({
5681
5695
  }
5682
5696
  let deleted = false;
5683
5697
  for (const location of selected) {
5684
- await withStorageLock(path8__default.default.dirname(location.filePath), async () => {
5698
+ await withStorageLock(path5__default.default.dirname(location.filePath), async () => {
5685
5699
  const bytes = await fs14__default.default.readFile(location.filePath);
5686
5700
  const artifact = await decodeMemArtifact(bytes);
5687
5701
  if (!artifact.state) throw new Error(`Unable to read store ${location.filePath}`);
@@ -6162,31 +6176,6 @@ var init_mem_repository = __esm({
6162
6176
  };
6163
6177
  }
6164
6178
  });
6165
- function parseProbe(probe) {
6166
- if (!probe) return null;
6167
- if (typeof probe === "string") {
6168
- const parts = probe.trim().split(/\s+/);
6169
- return { type: parts[0], args: parts.slice(1) };
6170
- }
6171
- if (typeof probe === "object") {
6172
- const type = String(probe.type ?? probe.kind ?? probe.name ?? "");
6173
- if (type === "file-exists") return { type, args: [String(probe.path ?? probe.file ?? probe.target ?? "")] };
6174
- if (type === "file-contains") return { type, args: [String(probe.path ?? probe.file ?? ""), String(probe.literal ?? probe.contains ?? probe.value ?? "")] };
6175
- if (type === "json-path") return { type, args: [String(probe.file ?? probe.path ?? ""), String(probe.path ?? probe.jsonPath ?? ""), String(probe.expected ?? probe.value ?? "")] };
6176
- if (type === "command") return { type, args: Array.isArray(probe.args) ? probe.args.map(String) : Array.isArray(probe.command) ? probe.command.map(String) : String(probe.command ?? "").split(/\s+/).filter(Boolean) };
6177
- return { type, args: [] };
6178
- }
6179
- return null;
6180
- }
6181
- function allowlist() {
6182
- try {
6183
- const raw = fs__default.default.readFileSync(`${resolveUserDotMemPath()}/probe-allowlist.json`, "utf8");
6184
- const parsed = JSON.parse(raw);
6185
- if (Array.isArray(parsed)) return parsed.map(String);
6186
- } catch {
6187
- }
6188
- return ["node", "git", "bun"];
6189
- }
6190
6179
  function runProbe(probe) {
6191
6180
  const spec = parseProbe(probe);
6192
6181
  if (!spec) return true;
@@ -6196,23 +6185,54 @@ function runProbe(probe) {
6196
6185
  let ok = false;
6197
6186
  try {
6198
6187
  if (spec.type === "file-exists") {
6199
- ok = fs__default.default.existsSync(spec.args[0]);
6188
+ const target = spec.args[0];
6189
+ if (!isAuthorizedPath(target)) {
6190
+ cache.set(key, { at: Date.now(), ok: false });
6191
+ return false;
6192
+ }
6193
+ ok = fs6__default.default.existsSync(target);
6200
6194
  } else if (spec.type === "file-contains") {
6201
- const content = fs__default.default.readFileSync(spec.args[0], "utf8");
6195
+ const target = spec.args[0];
6196
+ if (!isAuthorizedPath(target)) {
6197
+ cache.set(key, { at: Date.now(), ok: false });
6198
+ return false;
6199
+ }
6200
+ const stat = fs6__default.default.statSync(target);
6201
+ if (stat.size > MAX_PROBE_FILE_BYTES) {
6202
+ cache.set(key, { at: Date.now(), ok: false });
6203
+ return false;
6204
+ }
6205
+ const content = fs6__default.default.readFileSync(target, "utf8");
6202
6206
  ok = content.includes(spec.args[1]);
6203
6207
  } else if (spec.type === "json-path") {
6204
- const obj = JSON.parse(fs__default.default.readFileSync(spec.args[0], "utf8"));
6208
+ const target = spec.args[0];
6209
+ if (!isAuthorizedPath(target)) {
6210
+ cache.set(key, { at: Date.now(), ok: false });
6211
+ return false;
6212
+ }
6213
+ const stat = fs6__default.default.statSync(target);
6214
+ if (stat.size > MAX_PROBE_FILE_BYTES) {
6215
+ cache.set(key, { at: Date.now(), ok: false });
6216
+ return false;
6217
+ }
6218
+ const obj = JSON.parse(fs6__default.default.readFileSync(target, "utf8"));
6205
6219
  const pathParts = spec.args[1].split(".");
6206
6220
  let cur = obj;
6207
6221
  for (const p of pathParts) cur = cur?.[p];
6208
6222
  ok = String(cur) === spec.args[2];
6209
6223
  } else if (spec.type === "command") {
6210
6224
  const cmd = spec.args[0];
6211
- if (!allowlist().includes(cmd)) {
6225
+ const args = spec.args.slice(1);
6226
+ if (args.some((a) => DANGEROUS_FLAGS.has(a))) {
6227
+ cache.set(key, { at: Date.now(), ok: false });
6228
+ return false;
6229
+ }
6230
+ const handler = isTrustedCommand(cmd, args);
6231
+ if (!handler) {
6212
6232
  cache.set(key, { at: Date.now(), ok: false });
6213
6233
  return false;
6214
6234
  }
6215
- const res = child_process.spawnSync(cmd, spec.args.slice(1), { timeout: 5e3, encoding: "utf8", shell: false, maxBuffer: 64 * 1024 });
6235
+ const res = child_process.spawnSync(handler.cmd, handler.args, { timeout: 5e3, encoding: "utf8", shell: false, maxBuffer: 64 * 1024, env: createSanitizedEnv() });
6216
6236
  ok = res.status === 0;
6217
6237
  } else {
6218
6238
  ok = false;
@@ -6223,12 +6243,91 @@ function runProbe(probe) {
6223
6243
  cache.set(key, { at: Date.now(), ok });
6224
6244
  return ok;
6225
6245
  }
6226
- var cache, CACHE_MS;
6246
+ var TRUSTED_PROBES, DANGEROUS_FLAGS, MAX_PROBE_FILE_BYTES, AUTHORIZED_ROOTS, isAuthorizedPath, isTrustedCommand, parseProbe, cache, CACHE_MS;
6227
6247
  var init_probe = __esm({
6228
6248
  "core/knowledge/probe.ts"() {
6229
- init_user_paths();
6230
- __name(parseProbe, "parseProbe");
6231
- __name(allowlist, "allowlist");
6249
+ init_sanitizer();
6250
+ TRUSTED_PROBES = [
6251
+ { id: "node-version", cmd: "node", args: ["--version"] },
6252
+ { id: "git-version", cmd: "git", args: ["--version"] }
6253
+ ];
6254
+ DANGEROUS_FLAGS = /* @__PURE__ */ new Set(["-e", "--eval", "-p", "--print", "-r", "--require", "--loader", "--input-type", "--experimental-vm-modules", "--experimental-loader"]);
6255
+ MAX_PROBE_FILE_BYTES = 10 * 1024 * 1024;
6256
+ AUTHORIZED_ROOTS = Array.from(/* @__PURE__ */ new Set([
6257
+ path5__default.default.resolve(process.cwd()),
6258
+ path5__default.default.resolve(os.tmpdir())
6259
+ ]));
6260
+ isAuthorizedPath = /* @__PURE__ */ __name((candidate) => {
6261
+ if (typeof candidate !== "string" || candidate.length === 0) return false;
6262
+ if (candidate.includes("\0")) return false;
6263
+ if (candidate.startsWith("\\\\") || candidate.startsWith("//")) return false;
6264
+ const resolved = path5__default.default.resolve(candidate);
6265
+ const lexicallyAllowed = AUTHORIZED_ROOTS.some((root) => {
6266
+ const rel = path5__default.default.relative(root, resolved);
6267
+ return rel === "" || !rel.startsWith("..") && !path5__default.default.isAbsolute(rel);
6268
+ });
6269
+ if (!lexicallyAllowed) return false;
6270
+ try {
6271
+ if (fs6__default.default.existsSync(resolved)) {
6272
+ const real = fs6__default.default.realpathSync(resolved);
6273
+ const reallyAllowed = AUTHORIZED_ROOTS.some((root) => {
6274
+ let realRoot = root;
6275
+ try {
6276
+ realRoot = fs6__default.default.realpathSync(root);
6277
+ } catch {
6278
+ }
6279
+ const rel = path5__default.default.relative(realRoot, real);
6280
+ return rel === "" || !rel.startsWith("..") && !path5__default.default.isAbsolute(rel);
6281
+ });
6282
+ if (!reallyAllowed) return false;
6283
+ }
6284
+ } catch {
6285
+ return false;
6286
+ }
6287
+ return true;
6288
+ }, "isAuthorizedPath");
6289
+ isTrustedCommand = /* @__PURE__ */ __name((cmd, args) => {
6290
+ return TRUSTED_PROBES.find((p) => p.cmd === cmd && JSON.stringify(p.args) === JSON.stringify(args)) ?? null;
6291
+ }, "isTrustedCommand");
6292
+ parseProbe = /* @__PURE__ */ __name((probe) => {
6293
+ if (!probe) return null;
6294
+ if (typeof probe === "string") {
6295
+ const parts = probe.trim().split(/\s+/);
6296
+ return { type: parts[0], args: parts.slice(1) };
6297
+ }
6298
+ if (typeof probe === "object") {
6299
+ const type = String(probe.type ?? probe.kind ?? probe.name ?? "");
6300
+ if (type === "file-exists") return { type, args: [String(probe.path ?? probe.file ?? probe.target ?? "")] };
6301
+ if (type === "file-contains") return { type, args: [String(probe.path ?? probe.file ?? ""), String(probe.literal ?? probe.contains ?? probe.value ?? "")] };
6302
+ if (type === "json-path") return { type, args: [String(probe.file ?? probe.path ?? ""), String(probe.path ?? probe.jsonPath ?? ""), String(probe.expected ?? probe.value ?? "")] };
6303
+ if (type === "command" || type === "probe") {
6304
+ if (typeof probe.id === "string") {
6305
+ const found = TRUSTED_PROBES.find((p) => p.id === probe.id);
6306
+ if (found) return { type: "command", args: [found.cmd, ...found.args] };
6307
+ return { type: "command", args: [] };
6308
+ }
6309
+ let cmd;
6310
+ let args = [];
6311
+ if (Array.isArray(probe.args) && probe.args.length > 0) {
6312
+ cmd = String(probe.args[0]);
6313
+ args = probe.args.slice(1).map(String);
6314
+ } else if (Array.isArray(probe.command)) {
6315
+ cmd = String(probe.command[0]);
6316
+ args = probe.command.slice(1).map(String);
6317
+ } else if (typeof probe.command === "string") {
6318
+ const parts = probe.command.trim().split(/\s+/);
6319
+ cmd = parts[0];
6320
+ args = parts.slice(1);
6321
+ }
6322
+ if (cmd) {
6323
+ return { type: "command", args: [cmd, ...args] };
6324
+ }
6325
+ return { type: "command", args: [] };
6326
+ }
6327
+ return { type, args: [] };
6328
+ }
6329
+ return null;
6330
+ }, "parseProbe");
6232
6331
  cache = /* @__PURE__ */ new Map();
6233
6332
  CACHE_MS = 6e4;
6234
6333
  __name(runProbe, "runProbe");
@@ -6243,19 +6342,6 @@ __export(telemetry_exports, {
6243
6342
  recordProjection: () => recordProjection,
6244
6343
  recordRetraction: () => recordRetraction
6245
6344
  });
6246
- function load() {
6247
- try {
6248
- return JSON.parse(fs__default.default.readFileSync(file(), "utf8"));
6249
- } catch {
6250
- return {};
6251
- }
6252
- }
6253
- function save(store7) {
6254
- try {
6255
- fs__default.default.writeFileSync(file(), JSON.stringify(store7, null, 2), "utf8");
6256
- } catch {
6257
- }
6258
- }
6259
6345
  function recordProjection(ids) {
6260
6346
  const store7 = load();
6261
6347
  const now3 = (/* @__PURE__ */ new Date()).toISOString();
@@ -6284,13 +6370,24 @@ function recordRetraction(id) {
6284
6370
  function readTelemetry() {
6285
6371
  return load();
6286
6372
  }
6287
- var file;
6373
+ var file, load, save;
6288
6374
  var init_telemetry = __esm({
6289
6375
  "core/knowledge/telemetry.ts"() {
6290
6376
  init_user_paths();
6291
6377
  file = /* @__PURE__ */ __name(() => `${resolveUserDotMemPath()}/telemetry.json`, "file");
6292
- __name(load, "load");
6293
- __name(save, "save");
6378
+ load = /* @__PURE__ */ __name(() => {
6379
+ try {
6380
+ return JSON.parse(fs6__default.default.readFileSync(file(), "utf8"));
6381
+ } catch {
6382
+ return {};
6383
+ }
6384
+ }, "load");
6385
+ save = /* @__PURE__ */ __name((store7) => {
6386
+ try {
6387
+ fs6__default.default.writeFileSync(file(), JSON.stringify(store7, null, 2), "utf8");
6388
+ } catch {
6389
+ }
6390
+ }, "save");
6294
6391
  __name(recordProjection, "recordProjection");
6295
6392
  __name(recordFeedback, "recordFeedback");
6296
6393
  __name(recordRetraction, "recordRetraction");
@@ -6337,7 +6434,7 @@ var init_currentness = __esm({
6337
6434
  const verifiedAt = verifiedAtOf(claim);
6338
6435
  if (verifiedAt !== void 0) return "verified";
6339
6436
  if (claim.epistemicType === "verified") return "unverified";
6340
- return "unknown-currentness";
6437
+ return "any-currentness";
6341
6438
  }, "deriveCurrentness");
6342
6439
  }
6343
6440
  });
@@ -7181,7 +7278,7 @@ var init_staging = __esm({
7181
7278
  throw new Error("Stage file must contain a claim object");
7182
7279
  }
7183
7280
  const claimValidation = buildClaimRecord({
7184
- id: s.claim.id,
7281
+ id: typeof s.claim.id === "string" ? s.claim.id : "",
7185
7282
  knowledge: s.claim.knowledge,
7186
7283
  applicability: s.claim.applicability,
7187
7284
  evidence: s.claim.evidence,
@@ -7598,7 +7695,7 @@ var init_violations = __esm({
7598
7695
  VIOLATION_FILE_NAME = "violations.json";
7599
7696
  }
7600
7697
  });
7601
- var isRuleClaim, isIronRule, extractIronRules, readViolationCounts, sortRulesByViolationFrequency, loadIronRules, ruleSetSignature;
7698
+ var isRuleClaim, isIronRule, extractIronRules, readViolationCounts, sortRulesByViolationFrequency, loadIronRules;
7602
7699
  var init_rules_loader = __esm({
7603
7700
  "core/knowledge/rules-loader.ts"() {
7604
7701
  init_state();
@@ -7635,7 +7732,7 @@ var init_rules_loader = __esm({
7635
7732
  }, "extractIronRules");
7636
7733
  readViolationCounts = /* @__PURE__ */ __name((file2) => {
7637
7734
  try {
7638
- const parsed = JSON.parse(fs.readFileSync(file2, "utf8"));
7735
+ const parsed = JSON.parse(fs6.readFileSync(file2, "utf8"));
7639
7736
  const counts = {};
7640
7737
  for (const violation of Array.isArray(parsed.violations) ? parsed.violations : []) {
7641
7738
  const ruleId = typeof violation?.ruleId === "string" ? violation.ruleId : "";
@@ -7664,15 +7761,6 @@ var init_rules_loader = __esm({
7664
7761
  sortedBy: "violation-frequency"
7665
7762
  };
7666
7763
  }, "loadIronRules");
7667
- ruleSetSignature = /* @__PURE__ */ __name((rules) => {
7668
- const material = rules.map((rule) => `${rule.id}\0${rule.text}`).join("");
7669
- let hash = 2166136261;
7670
- for (let index = 0; index < material.length; index += 1) {
7671
- hash ^= material.charCodeAt(index);
7672
- hash = Math.imul(hash, 16777619) >>> 0;
7673
- }
7674
- return hash.toString(16).padStart(8, "0");
7675
- }, "ruleSetSignature");
7676
7764
  }
7677
7765
  });
7678
7766
 
@@ -7856,25 +7944,25 @@ var init_exemplars = __esm({
7856
7944
  resolveExemplarsPath = /* @__PURE__ */ __name(() => {
7857
7945
  return joinPath3(resolveUserDotMemPath(), EXEMPLARS_FILE_NAME);
7858
7946
  }, "resolveExemplarsPath");
7859
- readFile = /* @__PURE__ */ __name(async (path10) => {
7947
+ readFile = /* @__PURE__ */ __name(async (path11) => {
7860
7948
  try {
7861
7949
  const fs16 = await import('fs/promises');
7862
- return await fs16.readFile(path10, "utf8");
7950
+ return await fs16.readFile(path11, "utf8");
7863
7951
  } catch {
7864
7952
  return null;
7865
7953
  }
7866
7954
  }, "readFile");
7867
- writeFile = /* @__PURE__ */ __name(async (path10, content) => {
7955
+ writeFile = /* @__PURE__ */ __name(async (path11, content) => {
7868
7956
  const fs16 = await import('fs/promises');
7869
- const dir = path10.replace(/[\\/][^\\/]+$/, "");
7957
+ const dir = path11.replace(/[\\/][^\\/]+$/, "");
7870
7958
  await fs16.mkdir(dir, { recursive: true });
7871
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
7959
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
7872
7960
  try {
7873
7961
  await fs16.writeFile(temporary, content, "utf8");
7874
- await fs16.rename(temporary, path10);
7962
+ await fs16.rename(temporary, path11);
7875
7963
  } catch {
7876
7964
  await fs16.rm(temporary, { force: true }).catch(() => void 0);
7877
- throw new Error(`Failed to write exemplars file at ${path10}`);
7965
+ throw new Error(`Failed to write exemplars file at ${path11}`);
7878
7966
  }
7879
7967
  }, "writeFile");
7880
7968
  emptyStore = /* @__PURE__ */ __name(() => {
@@ -11412,25 +11500,25 @@ var init_loops = __esm({
11412
11500
  release();
11413
11501
  }
11414
11502
  }, "withLoopLock");
11415
- readFile2 = /* @__PURE__ */ __name(async (path10) => {
11503
+ readFile2 = /* @__PURE__ */ __name(async (path11) => {
11416
11504
  try {
11417
11505
  const fs16 = await import('fs/promises');
11418
- return await fs16.readFile(path10, "utf8");
11506
+ return await fs16.readFile(path11, "utf8");
11419
11507
  } catch {
11420
11508
  return null;
11421
11509
  }
11422
11510
  }, "readFile");
11423
- writeFile2 = /* @__PURE__ */ __name(async (path10, content) => {
11511
+ writeFile2 = /* @__PURE__ */ __name(async (path11, content) => {
11424
11512
  const fs16 = await import('fs/promises');
11425
- const dir = path10.replace(/[\\/][^\\/]+$/, "");
11513
+ const dir = path11.replace(/[\\/][^\\/]+$/, "");
11426
11514
  await fs16.mkdir(dir, { recursive: true });
11427
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
11515
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
11428
11516
  try {
11429
11517
  await fs16.writeFile(temporary, content, "utf8");
11430
- await fs16.rename(temporary, path10);
11518
+ await fs16.rename(temporary, path11);
11431
11519
  } catch {
11432
11520
  await fs16.rm(temporary, { force: true }).catch(() => void 0);
11433
- throw new Error(`Failed to write loops file at ${path10}`);
11521
+ throw new Error(`Failed to write loops file at ${path11}`);
11434
11522
  }
11435
11523
  }, "writeFile");
11436
11524
  emptyDocument = /* @__PURE__ */ __name(() => {
@@ -11514,7 +11602,7 @@ var init_loops = __esm({
11514
11602
  text: input.text,
11515
11603
  waitor: input.waitor,
11516
11604
  openedAt: input.openedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
11517
- authorAgent: input.authorAgent ?? "unknown",
11605
+ authorAgent: input.authorAgent ?? "any",
11518
11606
  targetRole: input.targetRole ?? "any",
11519
11607
  status: input.status ?? "open",
11520
11608
  projectId: input.projectId,
@@ -11580,25 +11668,25 @@ var init_personality_anchor = __esm({
11580
11668
  resolvePersonalityAnchorPath = /* @__PURE__ */ __name(() => {
11581
11669
  return joinPath5(resolveUserDotMemPath(), PERSONALITY_ANCHOR_FILE_NAME);
11582
11670
  }, "resolvePersonalityAnchorPath");
11583
- readFile3 = /* @__PURE__ */ __name(async (path10) => {
11671
+ readFile3 = /* @__PURE__ */ __name(async (path11) => {
11584
11672
  try {
11585
11673
  const fs16 = await import('fs/promises');
11586
- return await fs16.readFile(path10, "utf8");
11674
+ return await fs16.readFile(path11, "utf8");
11587
11675
  } catch {
11588
11676
  return null;
11589
11677
  }
11590
11678
  }, "readFile");
11591
- writeFile3 = /* @__PURE__ */ __name(async (path10, content) => {
11679
+ writeFile3 = /* @__PURE__ */ __name(async (path11, content) => {
11592
11680
  const fs16 = await import('fs/promises');
11593
- const dir = path10.replace(/[\\/][^\\/]+$/, "");
11681
+ const dir = path11.replace(/[\\/][^\\/]+$/, "");
11594
11682
  await fs16.mkdir(dir, { recursive: true });
11595
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
11683
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
11596
11684
  try {
11597
11685
  await fs16.writeFile(temporary, content, "utf8");
11598
- await fs16.rename(temporary, path10);
11686
+ await fs16.rename(temporary, path11);
11599
11687
  } catch {
11600
11688
  await fs16.rm(temporary, { force: true }).catch(() => void 0);
11601
- throw new Error(`Failed to write personality anchor at ${path10}`);
11689
+ throw new Error(`Failed to write personality anchor at ${path11}`);
11602
11690
  }
11603
11691
  }, "writeFile");
11604
11692
  emptyAnchor = /* @__PURE__ */ __name(() => {
@@ -11807,6 +11895,7 @@ var init_repository = __esm({
11807
11895
  var init_rule_checker = __esm({
11808
11896
  "core/knowledge/rule-checker.ts"() {
11809
11897
  init_state();
11898
+ init_sanitizer();
11810
11899
  }
11811
11900
  });
11812
11901
 
@@ -11897,12 +11986,12 @@ var init_user_language = __esm({
11897
11986
  resolveLanguagePreferencePath = /* @__PURE__ */ __name(() => {
11898
11987
  return resolveUserLanguagePath();
11899
11988
  }, "resolveLanguagePreferencePath");
11900
- readJsonFile = /* @__PURE__ */ __name((path10) => {
11989
+ readJsonFile = /* @__PURE__ */ __name((path11) => {
11901
11990
  const fs16 = getSyncFs();
11902
11991
  if (!fs16) return null;
11903
11992
  let raw;
11904
11993
  try {
11905
- raw = decodeText(fs16.readFileSync(path10), { source: path10 });
11994
+ raw = decodeText(fs16.readFileSync(path11), { source: path11 });
11906
11995
  } catch {
11907
11996
  return null;
11908
11997
  }
@@ -11999,14 +12088,14 @@ var init_user_language = __esm({
11999
12088
  }, "getResponseLanguage");
12000
12089
  setUserLanguage = /* @__PURE__ */ __name(async (language2) => {
12001
12090
  const fsMod = await import('fs/promises');
12002
- const path10 = resolveUserLanguagePath();
12003
- const dir = parentStoragePath(path10);
12091
+ const path11 = resolveUserLanguagePath();
12092
+ const dir = parentStoragePath(path11);
12004
12093
  await fsMod.mkdir(dir, { recursive: true });
12005
12094
  const payload = { format: "dotmem.language", version: 1, language: String(language2).trim() };
12006
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
12095
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
12007
12096
  await fsMod.writeFile(temporary, `${JSON.stringify(payload, null, 2)}
12008
12097
  `, "utf8");
12009
- await fsMod.rename(temporary, path10);
12098
+ await fsMod.rename(temporary, path11);
12010
12099
  return payload.language;
12011
12100
  }, "setUserLanguage");
12012
12101
  saveUserLanguage = /* @__PURE__ */ __name(async (language2) => {
@@ -12060,115 +12149,755 @@ var init_session_metrics = __esm({
12060
12149
  }
12061
12150
  });
12062
12151
 
12063
- // core/knowledge/loading-policy.ts
12064
- var init_loading_policy = __esm({
12065
- "core/knowledge/loading-policy.ts"() {
12066
- }
12067
- });
12068
-
12069
- // core/knowledge/index.ts
12070
- var init_knowledge = __esm({
12071
- "core/knowledge/index.ts"() {
12072
- init_acquisition_boundary();
12073
- init_acquisition_limits();
12074
- init_applicability();
12075
- init_behavioral_invariants();
12076
- init_bootstrap();
12077
- init_built_in_context();
12078
- init_built_in_context_rules();
12079
- init_canonical_hash();
12080
- init_canonical_reconstruction();
12081
- init_canonical_schema();
12082
- init_context_budget();
12083
- init_contract();
12084
- init_correction();
12085
- init_currentness();
12152
+ // core/knowledge/hard-rules-registry.ts
12153
+ var HARD_RULES_REGISTRY_FORMAT, HARD_RULES_REGISTRY_VERSION, HARD_RULES_REGISTRY_AUDIT_RETENTION, HARD_RULES_REGISTRY_FILE_NAME, HardRulesRegistryError, requiredText3, nowIso, joinPath7, resolveRegistryDir, resolveRegistryFilePath, validateHardRuleAuthority, canonicalFingerprint, validateRule, validateDocument2, emptyDocument2, boundedAudit2, buildAudit, HardRulesRegistry;
12154
+ var init_hard_rules_registry = __esm({
12155
+ "core/knowledge/hard-rules-registry.ts"() {
12086
12156
  init_detection_events();
12087
- init_detection_journal();
12088
- init_discover();
12089
- init_solvers();
12090
- init_signatures();
12091
- init_probe();
12092
- init_semantic_provider();
12093
- init_effective_contract();
12094
- init_exemplars();
12095
- init_explain();
12096
- init_feedback();
12097
- init_fingerprint();
12098
- init_identity_governance();
12099
- init_identity_resolution();
12100
- init_incidents();
12101
- init_inspect_report();
12102
- init_language_detect();
12103
- init_loops();
12104
- init_mem_package();
12105
- init_personality_anchor();
12106
12157
  init_policy();
12107
12158
  init_policy_namespace_lock();
12108
- init_policy_store();
12109
- init_project();
12110
- init_project_anchor();
12111
- init_read_only();
12112
- init_renderer();
12113
- init_repository();
12114
- init_rule_checker();
12115
- init_rules_loader();
12116
- init_runtime();
12117
- init_scope_eligibility();
12118
- init_select();
12119
- init_session();
12120
- init_staging();
12121
- init_state();
12122
- init_storage_location();
12123
- init_storage_settings();
12124
- init_tool_guard();
12125
- init_user_identity();
12126
- init_user_language();
12127
12159
  init_user_paths();
12128
- init_vault();
12129
- init_verification();
12130
- init_verify();
12131
- init_violations();
12132
- init_claim_identity();
12133
- init_store_registry();
12134
- init_migration_audit();
12135
- init_session_metrics();
12136
- init_loading_policy();
12137
- init_session_metrics();
12138
- init_session_metrics();
12139
- init_session_metrics();
12140
- }
12141
- });
12142
-
12143
- // core/logic/helpers.ts
12144
- var normalizeClaimIds2, revisionFromAcquire;
12145
- var init_helpers = __esm({
12146
- "core/logic/helpers.ts"() {
12147
- normalizeClaimIds2 = /* @__PURE__ */ __name((value) => {
12148
- if (!value) return [];
12149
- return Array.isArray(value) ? value : [value];
12150
- }, "normalizeClaimIds");
12151
- revisionFromAcquire = /* @__PURE__ */ __name((opts) => {
12152
- const refines = normalizeClaimIds2(opts.refines);
12153
- const supersedes = normalizeClaimIds2(opts.supersedes);
12154
- const retracts = normalizeClaimIds2(opts.retracts);
12155
- if ([refines, supersedes, retracts].filter((ids) => ids.length > 0).length > 1) {
12156
- throw new Error("Acquired knowledge can refine, supersede, or retract prior knowledge, not more than one");
12160
+ HARD_RULES_REGISTRY_FORMAT = "dotmem.hard-rules";
12161
+ HARD_RULES_REGISTRY_VERSION = 1;
12162
+ HARD_RULES_REGISTRY_AUDIT_RETENTION = 200;
12163
+ HARD_RULES_REGISTRY_FILE_NAME = "hard-rules.registry.json";
12164
+ HardRulesRegistryError = class extends Error {
12165
+ static {
12166
+ __name(this, "HardRulesRegistryError");
12157
12167
  }
12158
- if (refines.length > 0) return { kind: "refines", claimIds: refines, ...opts.reason ? { reason: opts.reason } : {} };
12159
- if (supersedes.length > 0) return { kind: "supersedes", claimIds: supersedes, ...opts.reason ? { reason: opts.reason } : {} };
12160
- if (retracts.length > 0) return { kind: "retracts", claimIds: retracts, ...opts.reason ? { reason: opts.reason } : {} };
12161
- return void 0;
12162
- }, "revisionFromAcquire");
12168
+ constructor(message) {
12169
+ super(message);
12170
+ this.name = "HardRulesRegistryError";
12171
+ }
12172
+ };
12173
+ requiredText3 = /* @__PURE__ */ __name((v) => typeof v === "string" && v.trim().length > 0, "requiredText");
12174
+ nowIso = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
12175
+ joinPath7 = /* @__PURE__ */ __name((base, child) => {
12176
+ const sep = process.platform === "win32" ? "\\" : "/";
12177
+ return `${base.replace(/[\\/]+/g, sep)}${sep}${child}`;
12178
+ }, "joinPath");
12179
+ resolveRegistryDir = /* @__PURE__ */ __name((directory) => directory ?? joinPath7(resolveUserDotMemPath(), "policy"), "resolveRegistryDir");
12180
+ resolveRegistryFilePath = /* @__PURE__ */ __name((directory) => joinPath7(resolveRegistryDir(directory), HARD_RULES_REGISTRY_FILE_NAME), "resolveRegistryFilePath");
12181
+ validateHardRuleAuthority = /* @__PURE__ */ __name((value) => {
12182
+ try {
12183
+ return validatePolicyAuthority(value);
12184
+ } catch (err3) {
12185
+ void detectAuthorityEscalationAttempt({ claimed: "invalid hard-rule authority", channel: "hard-rules" }).catch(() => void 0);
12186
+ throw err3 instanceof HardRulesRegistryError ? err3 : new HardRulesRegistryError(err3.message);
12187
+ }
12188
+ }, "validateHardRuleAuthority");
12189
+ canonicalFingerprint = /* @__PURE__ */ __name((rule) => {
12190
+ const payload = {
12191
+ id: rule.id,
12192
+ version: rule.version,
12193
+ ruleClass: rule.ruleClass,
12194
+ status: rule.status,
12195
+ scope: rule.scope,
12196
+ statement: rule.statement,
12197
+ applicability: rule.applicability ?? null,
12198
+ authority: rule.authority
12199
+ };
12200
+ return `hr.${rule.id}@v${rule.version}.${Buffer.from(JSON.stringify(payload)).toString("base64").slice(0, 16)}`;
12201
+ }, "canonicalFingerprint");
12202
+ validateRule = /* @__PURE__ */ __name((value) => {
12203
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new HardRulesRegistryError("Hard rule must be an object");
12204
+ const r = value;
12205
+ if (!requiredText3(r.id)) throw new HardRulesRegistryError("id is required");
12206
+ if (typeof r.version !== "number" || !Number.isInteger(r.version) || r.version < 1) throw new HardRulesRegistryError("version must be a positive integer");
12207
+ if (typeof r.revision !== "number" || !Number.isInteger(r.revision) || r.revision < 0) throw new HardRulesRegistryError("revision must be a non-negative integer");
12208
+ if (typeof r.ruleClass !== "string" || !["IMMUTABLE", "OWNER_CONTROLLED", "USER_OVERRIDEABLE", "SESSION"].includes(r.ruleClass)) throw new HardRulesRegistryError("invalid ruleClass");
12209
+ if (typeof r.status !== "string" || !["proposed", "under_review", "approved", "active", "suspended", "retired", "rejected"].includes(r.status)) throw new HardRulesRegistryError("invalid status");
12210
+ if (!requiredText3(r.scope)) throw new HardRulesRegistryError("scope is required");
12211
+ if (!requiredText3(r.statement)) throw new HardRulesRegistryError("statement is required");
12212
+ if (!requiredText3(r.grantedAt)) throw new HardRulesRegistryError("grantedAt is required");
12213
+ if (!requiredText3(r.createdAt)) throw new HardRulesRegistryError("createdAt is required");
12214
+ const authority = validateHardRuleAuthority(r.authority);
12215
+ const validated = {
12216
+ id: r.id,
12217
+ version: r.version,
12218
+ revision: r.revision,
12219
+ ruleClass: r.ruleClass,
12220
+ status: r.status,
12221
+ scope: r.scope,
12222
+ statement: r.statement,
12223
+ ...r.applicability && typeof r.applicability === "object" ? { applicability: r.applicability } : {},
12224
+ authority,
12225
+ grantedAt: r.grantedAt,
12226
+ createdAt: r.createdAt,
12227
+ ...requiredText3(r.updatedAt) ? { updatedAt: r.updatedAt } : {},
12228
+ fingerprint: ""
12229
+ };
12230
+ const fp = canonicalFingerprint(validated);
12231
+ if (requiredText3(r.fingerprint) && r.fingerprint !== fp) {
12232
+ throw new HardRulesRegistryError(`Hard rule fingerprint mismatch for ${validated.id}`);
12233
+ }
12234
+ validated.fingerprint = fp;
12235
+ if (requiredText3(r.provenance) === false && r.provenance !== void 0) ;
12236
+ if (r.provenance && typeof r.provenance === "object") validated.provenance = r.provenance;
12237
+ if (requiredText3(r.auditRef)) validated.auditRef = r.auditRef;
12238
+ return validated;
12239
+ }, "validateRule");
12240
+ validateDocument2 = /* @__PURE__ */ __name((value) => {
12241
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new HardRulesRegistryError("document must be an object");
12242
+ const d = value;
12243
+ if (d.format !== HARD_RULES_REGISTRY_FORMAT) throw new HardRulesRegistryError("invalid format");
12244
+ if (d.version !== HARD_RULES_REGISTRY_VERSION) throw new HardRulesRegistryError("invalid version");
12245
+ if (typeof d.revision !== "number" || !Number.isInteger(d.revision) || d.revision < 0) throw new HardRulesRegistryError("invalid revision");
12246
+ if (!Array.isArray(d.rules)) throw new HardRulesRegistryError("rules must be an array");
12247
+ if (!Array.isArray(d.audit)) throw new HardRulesRegistryError("audit must be an array");
12248
+ const ids = /* @__PURE__ */ new Set();
12249
+ const rules = d.rules.map(validateRule);
12250
+ for (const rule of rules) {
12251
+ if (ids.has(rule.id + "@" + rule.version)) throw new HardRulesRegistryError(`Duplicate hard rule ${rule.id} v${rule.version}`);
12252
+ ids.add(rule.id + "@" + rule.version);
12253
+ }
12254
+ const audit2 = d.audit.map((e) => {
12255
+ if (!e || typeof e !== "object" || Array.isArray(e)) throw new HardRulesRegistryError("audit entry must be an object");
12256
+ const r = e;
12257
+ if (!requiredText3(r.id)) throw new HardRulesRegistryError("audit id required");
12258
+ if (!requiredText3(r.action)) throw new HardRulesRegistryError("audit action required");
12259
+ if (!requiredText3(r.at)) throw new HardRulesRegistryError("audit at required");
12260
+ if (r.outcome !== "applied" && r.outcome !== "rejected") throw new HardRulesRegistryError("audit outcome invalid");
12261
+ return r;
12262
+ });
12263
+ return { format: HARD_RULES_REGISTRY_FORMAT, version: HARD_RULES_REGISTRY_VERSION, revision: d.revision, rules, audit: audit2 };
12264
+ }, "validateDocument");
12265
+ emptyDocument2 = /* @__PURE__ */ __name(() => ({
12266
+ format: HARD_RULES_REGISTRY_FORMAT,
12267
+ version: HARD_RULES_REGISTRY_VERSION,
12268
+ revision: 0,
12269
+ rules: [],
12270
+ audit: []
12271
+ }), "emptyDocument");
12272
+ boundedAudit2 = /* @__PURE__ */ __name((entries2) => {
12273
+ if (entries2.length <= HARD_RULES_REGISTRY_AUDIT_RETENTION) return [...entries2];
12274
+ const kept = [];
12275
+ let budget = HARD_RULES_REGISTRY_AUDIT_RETENTION;
12276
+ for (let i3 = entries2.length - 1; i3 >= 0; i3--) {
12277
+ const e = entries2[i3];
12278
+ if (e.mandatory === true || budget > 0) {
12279
+ kept.unshift(e);
12280
+ if (e.mandatory !== true) budget--;
12281
+ }
12282
+ }
12283
+ return kept;
12284
+ }, "boundedAudit");
12285
+ buildAudit = /* @__PURE__ */ __name((entry) => ({
12286
+ id: entry.id ?? `hr-audit.${entry.action}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}`,
12287
+ action: entry.action,
12288
+ at: entry.at,
12289
+ ...entry.actorPrincipal !== void 0 ? { actorPrincipal: entry.actorPrincipal } : {},
12290
+ ...entry.targetRuleId !== void 0 ? { targetRuleId: entry.targetRuleId } : {},
12291
+ ...entry.targetVersion !== void 0 ? { targetVersion: entry.targetVersion } : {},
12292
+ ...entry.scope !== void 0 ? { scope: entry.scope } : {},
12293
+ outcome: entry.outcome,
12294
+ ...entry.reason !== void 0 ? { reason: entry.reason } : {},
12295
+ ...entry.detail !== void 0 ? { detail: entry.detail } : {},
12296
+ ...entry.mandatory !== void 0 ? { mandatory: entry.mandatory } : {}
12297
+ }), "buildAudit");
12298
+ HardRulesRegistry = class {
12299
+ constructor(directory) {
12300
+ this.directory = directory;
12301
+ }
12302
+ directory;
12303
+ static {
12304
+ __name(this, "HardRulesRegistry");
12305
+ }
12306
+ dir() {
12307
+ return resolveRegistryDir(this.directory);
12308
+ }
12309
+ filePath() {
12310
+ return resolveRegistryFilePath(this.directory);
12311
+ }
12312
+ async load() {
12313
+ const fs16 = await import('fs/promises');
12314
+ try {
12315
+ const raw = await fs16.readFile(this.filePath(), "utf8");
12316
+ return validateDocument2(JSON.parse(raw));
12317
+ } catch (err3) {
12318
+ if (err3.code === "ENOENT") return emptyDocument2();
12319
+ throw err3;
12320
+ }
12321
+ }
12322
+ async readDoc(fs16) {
12323
+ try {
12324
+ const raw = await fs16.readFile(this.filePath(), "utf8");
12325
+ return validateDocument2(JSON.parse(raw));
12326
+ } catch (err3) {
12327
+ if (err3.code === "ENOENT") return emptyDocument2();
12328
+ throw err3;
12329
+ }
12330
+ }
12331
+ async writeDoc(fs16, doc) {
12332
+ await fs16.mkdir(this.dir(), { recursive: true });
12333
+ const fp = this.filePath();
12334
+ const tmp = `${fp}.${process.pid}.${Date.now().toString(36)}.tmp`;
12335
+ try {
12336
+ await fs16.writeFile(tmp, `${JSON.stringify(doc, null, 2)}
12337
+ `, "utf8");
12338
+ const handle = await fs16.open(tmp, "r+");
12339
+ try {
12340
+ await handle.sync();
12341
+ } finally {
12342
+ await handle.close();
12343
+ }
12344
+ await fs16.rename(tmp, fp);
12345
+ } catch (err3) {
12346
+ await fs16.rm(tmp, { force: true }).catch(() => void 0);
12347
+ throw err3;
12348
+ }
12349
+ }
12350
+ async mutate(operation, options = {}) {
12351
+ const directory = this.dir();
12352
+ return withPolicyNamespaceLock(
12353
+ async (session3) => {
12354
+ const fs16 = await import('fs/promises');
12355
+ const doc = await this.readDoc(fs16);
12356
+ if (options.basedOnRevision !== void 0 && options.basedOnRevision !== doc.revision) {
12357
+ throw new HardRulesRegistryError(`Stale hard-rules revision: expected ${options.basedOnRevision}, current ${doc.revision}`);
12358
+ }
12359
+ const outcome = operation(doc);
12360
+ let next = outcome.document;
12361
+ validateDocument2(next);
12362
+ await session3.assertOwnership();
12363
+ await this.writeDoc(fs16, next);
12364
+ return outcome.result;
12365
+ },
12366
+ { directory }
12367
+ );
12368
+ }
12369
+ async listRules() {
12370
+ const doc = await this.load();
12371
+ return [...doc.rules].sort((a, b) => a.id.localeCompare(b.id) || a.version - b.version);
12372
+ }
12373
+ async activeRules(scope) {
12374
+ const doc = await this.load();
12375
+ return doc.rules.filter((r) => r.status === "active" && (!scope || r.scope === "*" || r.scope === scope || scope.startsWith(r.scope.endsWith("/") ? r.scope : r.scope + "/")));
12376
+ }
12377
+ async failClosedResolve(scope) {
12378
+ const actives = await this.activeRules(scope);
12379
+ if (actives.length === 0) return { outcome: "none", rule: null, reason: "no applicable hard rule" };
12380
+ if (actives.length > 1) return { outcome: "conflicting", rule: null, reason: "conflicting active hard rules" };
12381
+ const r = actives[0];
12382
+ if (r.ruleClass === "IMMUTABLE" || r.ruleClass === "OWNER_CONTROLLED") {
12383
+ if (r.authority.kind !== "HI" && r.authority.kind !== "operator") {
12384
+ return { outcome: "unresolved-authority", rule: null, reason: "unresolved authority" };
12385
+ }
12386
+ }
12387
+ return { outcome: "applicable", rule: r, reason: "applicable" };
12388
+ }
12389
+ async assign(input, basedOnRevision) {
12390
+ const authority = validateHardRuleAuthority(input.authority);
12391
+ if (!requiredText3(input.scope)) throw new HardRulesRegistryError("scope is required");
12392
+ if (!requiredText3(input.statement)) throw new HardRulesRegistryError("statement is required");
12393
+ if (!["IMMUTABLE", "OWNER_CONTROLLED", "USER_OVERRIDEABLE", "SESSION"].includes(input.ruleClass)) throw new HardRulesRegistryError("invalid ruleClass");
12394
+ const doc0 = await this.load();
12395
+ const ruleId = input.id ?? `hr.${Date.now()}.${Math.random().toString(36).slice(2, 8)}`;
12396
+ const existing = doc0.rules.filter((r) => r.id === ruleId);
12397
+ const version = input.version ?? (existing.length > 0 ? Math.max(...existing.map((r) => r.version)) + 1 : 1);
12398
+ const priorActive = existing.find((r) => r.status === "active" && r.ruleClass === "IMMUTABLE");
12399
+ if (priorActive && input.ruleClass !== "IMMUTABLE") {
12400
+ throw new HardRulesRegistryError("cannot weaken immutable rule");
12401
+ }
12402
+ if (priorActive && authority.kind !== "HI") {
12403
+ throw new HardRulesRegistryError("immutable rule requires HI authority to amend");
12404
+ }
12405
+ const createdAt = nowIso();
12406
+ const grantedAt = input.grantedAt ?? createdAt;
12407
+ const rule = {
12408
+ id: ruleId,
12409
+ version,
12410
+ revision: 0,
12411
+ ruleClass: input.ruleClass,
12412
+ status: "proposed",
12413
+ scope: input.scope,
12414
+ statement: input.statement,
12415
+ ...input.applicability ? { applicability: input.applicability } : {},
12416
+ authority,
12417
+ grantedAt,
12418
+ createdAt,
12419
+ fingerprint: ""
12420
+ };
12421
+ rule.fingerprint = canonicalFingerprint({ ...rule, fingerprint: "" });
12422
+ return this.mutate(
12423
+ (doc) => {
12424
+ const revision = doc.revision + 1;
12425
+ const stored = { ...rule, revision, fingerprint: canonicalFingerprint({ ...rule, revision, fingerprint: "" }) };
12426
+ const rules = doc.rules.map((r) => {
12427
+ if (r.id === stored.id && r.version !== stored.version && r.status === "active") {
12428
+ return { ...r, status: "retired", updatedAt: nowIso() };
12429
+ }
12430
+ return r;
12431
+ });
12432
+ rules.push(stored);
12433
+ const audit2 = boundedAudit2([
12434
+ ...doc.audit,
12435
+ buildAudit({
12436
+ action: "rule.assigned",
12437
+ at: stored.grantedAt,
12438
+ actorPrincipal: authority.kind,
12439
+ targetRuleId: stored.id,
12440
+ targetVersion: stored.version,
12441
+ scope: stored.scope,
12442
+ outcome: "applied",
12443
+ detail: `hard rule ${stored.id} v${stored.version} assigned (${stored.ruleClass})`,
12444
+ mandatory: true
12445
+ })
12446
+ ]);
12447
+ return { document: { ...doc, revision, rules, audit: audit2 }, result: stored };
12448
+ },
12449
+ { basedOnRevision }
12450
+ );
12451
+ }
12452
+ async activate(input, basedOnRevision) {
12453
+ const doc0 = await this.load();
12454
+ const rule = doc0.rules.find((r) => r.id === input.id && r.version === input.version);
12455
+ if (!rule) throw new HardRulesRegistryError("rule not found");
12456
+ if (rule.status !== "approved" && rule.status !== "proposed") ;
12457
+ const authority = input.authority ? validateHardRuleAuthority(input.authority) : rule.authority;
12458
+ if ((rule.ruleClass === "IMMUTABLE" || rule.ruleClass === "OWNER_CONTROLLED") && authority.kind !== "HI" && authority.kind !== "operator") {
12459
+ throw new HardRulesRegistryError("activation requires HI or operator authority");
12460
+ }
12461
+ const actives = doc0.rules.filter((r) => r.status === "active" && r.scope === rule.scope && r.id !== rule.id);
12462
+ if (actives.length > 0 && (rule.ruleClass === "IMMUTABLE" || rule.ruleClass === "OWNER_CONTROLLED")) {
12463
+ throw new HardRulesRegistryError("conflicting active mandatory rules");
12464
+ }
12465
+ return this.mutate(
12466
+ (doc) => {
12467
+ const idx = doc.rules.findIndex((r) => r.id === input.id && r.version === input.version);
12468
+ if (idx < 0) throw new HardRulesRegistryError("rule not found");
12469
+ const current = doc.rules[idx];
12470
+ const rules = doc.rules.map((r) => {
12471
+ if (r.id === current.id && r.version !== current.version && r.status === "active") {
12472
+ return { ...r, status: "retired", updatedAt: nowIso() };
12473
+ }
12474
+ return r;
12475
+ });
12476
+ const now3 = nowIso();
12477
+ rules[idx >= rules.length ? rules.length - 1 : idx] = { ...current, status: "active", updatedAt: now3 };
12478
+ const targetIndex = rules.findIndex((r) => r.id === current.id && r.version === current.version);
12479
+ if (targetIndex >= 0) rules[targetIndex] = { ...current, status: "active", updatedAt: now3 };
12480
+ const updated = rules.find((r) => r.id === current.id && r.version === current.version);
12481
+ const revision = doc.revision + 1;
12482
+ const audit2 = boundedAudit2([
12483
+ ...doc.audit,
12484
+ buildAudit({
12485
+ action: "rule.activated",
12486
+ at: now3,
12487
+ actorPrincipal: input.actorPrincipal ?? authority.kind,
12488
+ targetRuleId: updated.id,
12489
+ targetVersion: updated.version,
12490
+ scope: updated.scope,
12491
+ outcome: "applied",
12492
+ mandatory: true
12493
+ })
12494
+ ]);
12495
+ return { document: { ...doc, revision, rules, audit: audit2 }, result: updated };
12496
+ },
12497
+ { basedOnRevision }
12498
+ );
12499
+ }
12500
+ async remove(id, authority, basedOnRevision) {
12501
+ const auth = validateHardRuleAuthority(authority);
12502
+ const doc0 = await this.load();
12503
+ const rule = doc0.rules.find((r) => r.id === id && r.status === "active");
12504
+ if (rule) {
12505
+ if (rule.ruleClass === "IMMUTABLE") throw new HardRulesRegistryError("cannot remove immutable rule");
12506
+ if (rule.ruleClass === "OWNER_CONTROLLED" && auth.kind !== "HI" && auth.kind !== "operator") throw new HardRulesRegistryError("unauthenticated cannot remove owner-controlled rule");
12507
+ }
12508
+ await this.mutate(
12509
+ (doc) => {
12510
+ const rules = doc.rules.filter((r) => r.id !== id);
12511
+ if (rules.length === doc.rules.length) return { document: doc, result: void 0 };
12512
+ const revision = doc.revision + 1;
12513
+ const audit2 = boundedAudit2([
12514
+ ...doc.audit,
12515
+ buildAudit({
12516
+ action: "rule.removed",
12517
+ at: nowIso(),
12518
+ actorPrincipal: auth.kind,
12519
+ targetRuleId: id,
12520
+ scope: rule?.scope,
12521
+ outcome: "applied",
12522
+ mandatory: true
12523
+ })
12524
+ ]);
12525
+ return { document: { ...doc, revision, rules, audit: audit2 }, result: void 0 };
12526
+ },
12527
+ { basedOnRevision }
12528
+ );
12529
+ }
12530
+ async auditTrail() {
12531
+ const doc = await this.load();
12532
+ return [...doc.audit];
12533
+ }
12534
+ async revision() {
12535
+ const doc = await this.load();
12536
+ return doc.revision;
12537
+ }
12538
+ };
12163
12539
  }
12164
12540
  });
12165
12541
 
12166
- // core/logic/index.ts
12167
- var logic_exports = {};
12168
- __export(logic_exports, {
12169
- LogicEngine: () => LogicEngine,
12170
- default: () => logic_default,
12171
- getLogicRuntime: () => getLogicRuntime,
12542
+ // core/context-compiler/index.ts
12543
+ var CHARS_PER_TOKEN, estimateTokens, DEFAULT_BUDGETS, dedupe, ContextCompiler, compileContext;
12544
+ var init_context_compiler = __esm({
12545
+ "core/context-compiler/index.ts"() {
12546
+ CHARS_PER_TOKEN = 4;
12547
+ estimateTokens = /* @__PURE__ */ __name((text) => Math.ceil((text || "").length / CHARS_PER_TOKEN), "estimateTokens");
12548
+ DEFAULT_BUDGETS = {
12549
+ identity: 0.1,
12550
+ rules: 0.15,
12551
+ conversationalState: 0.3,
12552
+ retrievedKnowledge: 0.45
12553
+ };
12554
+ dedupe = /* @__PURE__ */ __name((items) => {
12555
+ const seen = /* @__PURE__ */ new Set();
12556
+ const result = [];
12557
+ for (const item of items) {
12558
+ const key = item.trim().toLowerCase();
12559
+ if (seen.has(key)) continue;
12560
+ seen.add(key);
12561
+ result.push(item);
12562
+ }
12563
+ return result;
12564
+ }, "dedupe");
12565
+ ContextCompiler = class {
12566
+ static {
12567
+ __name(this, "ContextCompiler");
12568
+ }
12569
+ compile(input) {
12570
+ const totalBudget = input.tokenBudget ?? 4096;
12571
+ const totalChars = totalBudget * CHARS_PER_TOKEN;
12572
+ const budgets = {
12573
+ identity: Math.floor(totalChars * (input.categoryBudgets?.identity ?? DEFAULT_BUDGETS.identity)),
12574
+ rules: Math.floor(totalChars * (input.categoryBudgets?.rules ?? DEFAULT_BUDGETS.rules)),
12575
+ conversationalState: Math.floor(totalChars * (input.categoryBudgets?.conversationalState ?? DEFAULT_BUDGETS.conversationalState)),
12576
+ retrievedKnowledge: Math.floor(totalChars * (input.categoryBudgets?.retrievedKnowledge ?? DEFAULT_BUDGETS.retrievedKnowledge))
12577
+ };
12578
+ const omissions = [];
12579
+ const identityText = (input.identity ?? "").trim();
12580
+ let identityUsed = 0;
12581
+ const mandatoryParts = [];
12582
+ if (identityText) {
12583
+ if (identityText.length <= budgets.identity) {
12584
+ mandatoryParts.push(identityText);
12585
+ identityUsed = identityText.length;
12586
+ } else {
12587
+ omissions.push({
12588
+ category: "identity",
12589
+ whatWasOmitted: identityText,
12590
+ whyOmitted: "token budget exceeded",
12591
+ wouldBreakContinuity: true
12592
+ });
12593
+ }
12594
+ }
12595
+ const rules = input.rules ?? [];
12596
+ const activeRules = [];
12597
+ let rulesUsed = 0;
12598
+ for (const rule of rules) {
12599
+ if (rulesUsed + rule.length <= budgets.rules) {
12600
+ activeRules.push(rule);
12601
+ rulesUsed += rule.length;
12602
+ } else {
12603
+ omissions.push({
12604
+ category: "rules",
12605
+ whatWasOmitted: rule,
12606
+ whyOmitted: "token budget exceeded",
12607
+ wouldBreakContinuity: false
12608
+ });
12609
+ }
12610
+ }
12611
+ const state3 = input.conversationalState ?? null;
12612
+ const mandatoryStateParts = [];
12613
+ if (state3) {
12614
+ if (state3.objective) mandatoryStateParts.push(`Objective: ${state3.objective}`);
12615
+ if (state3.currentWorkingPosition) mandatoryStateParts.push(`Working position: ${state3.currentWorkingPosition}`);
12616
+ if (state3.openLoops.length > 0) {
12617
+ mandatoryStateParts.push(`Open loops: ${state3.openLoops.map((l) => l.description).join("; ")}`);
12618
+ }
12619
+ if (state3.rejectedApproaches.length > 0) {
12620
+ mandatoryStateParts.push(`Rejected approaches: ${state3.rejectedApproaches.map((r) => `${r.approach} (${r.reason})`).join("; ")}`);
12621
+ }
12622
+ }
12623
+ const activeParts = [];
12624
+ if (state3) {
12625
+ if (state3.currentProblem) activeParts.push(`Current problem: ${state3.currentProblem}`);
12626
+ if (state3.establishedUnderstanding) activeParts.push(`Established understanding: ${state3.establishedUnderstanding}`);
12627
+ if (state3.decisionsMade.length > 0) {
12628
+ activeParts.push(`Decisions: ${state3.decisionsMade.map((d) => `${d.decision} (rationale: ${d.rationale})`).join("; ")}`);
12629
+ }
12630
+ if (state3.pendingDecisions.length > 0) {
12631
+ activeParts.push(`Pending decisions: ${state3.pendingDecisions.map((d) => `${d.decision} [${d.options.join(", ")}]`).join("; ")}`);
12632
+ }
12633
+ if (state3.unresolvedQuestions.length > 0) {
12634
+ activeParts.push(`Unresolved questions: ${state3.unresolvedQuestions.map((q) => q.question).join("; ")}`);
12635
+ }
12636
+ if (state3.reasoningTrajectory.length > 0) {
12637
+ activeParts.push(`Reasoning trajectory: ${state3.reasoningTrajectory.map((r) => r.conclusion).join(" -> ")}`);
12638
+ }
12639
+ if (state3.nextConversationalStep) {
12640
+ activeParts.push(`Next step: ${state3.nextConversationalStep}`);
12641
+ }
12642
+ if (state3.lastCompletedAction) {
12643
+ activeParts.push(`Last completed action: ${state3.lastCompletedAction}`);
12644
+ }
12645
+ }
12646
+ const dedupedActive = dedupe(activeParts.filter((part) => !mandatoryStateParts.includes(part)));
12647
+ let stateUsed = 0;
12648
+ const admittedMandatoryState = [];
12649
+ const admittedActive = [];
12650
+ for (const part of mandatoryStateParts) {
12651
+ if (stateUsed + part.length <= budgets.conversationalState) {
12652
+ admittedMandatoryState.push(part);
12653
+ stateUsed += part.length;
12654
+ } else {
12655
+ omissions.push({
12656
+ category: "conversationalState",
12657
+ whatWasOmitted: part,
12658
+ whyOmitted: "token budget exceeded",
12659
+ wouldBreakContinuity: true
12660
+ });
12661
+ }
12662
+ }
12663
+ for (const part of dedupedActive) {
12664
+ if (stateUsed + part.length <= budgets.conversationalState) {
12665
+ admittedActive.push(part);
12666
+ stateUsed += part.length;
12667
+ } else {
12668
+ omissions.push({
12669
+ category: "conversationalState",
12670
+ whatWasOmitted: part,
12671
+ whyOmitted: "token budget exceeded",
12672
+ wouldBreakContinuity: false
12673
+ });
12674
+ }
12675
+ }
12676
+ const refs = [...input.knowledgeReferences ?? []].sort((a, b) => b.relevance - a.relevance);
12677
+ const retrievedParts = [];
12678
+ let retrievedUsed = 0;
12679
+ for (const ref of refs) {
12680
+ const text2 = ref.summary ? `${ref.kind}:${ref.identifier} - ${ref.summary}` : `${ref.kind}:${ref.identifier}`;
12681
+ if (retrievedUsed + text2.length <= budgets.retrievedKnowledge) {
12682
+ retrievedParts.push(text2);
12683
+ retrievedUsed += text2.length;
12684
+ } else {
12685
+ omissions.push({
12686
+ category: "retrievedKnowledge",
12687
+ whatWasOmitted: text2,
12688
+ whyOmitted: "token budget exceeded",
12689
+ wouldBreakContinuity: false
12690
+ });
12691
+ }
12692
+ }
12693
+ const optionalParts = [];
12694
+ let optionalUsed = 0;
12695
+ const remainingBudget = totalChars - (identityUsed + rulesUsed + stateUsed + retrievedUsed);
12696
+ for (const item of input.historicalContext ?? []) {
12697
+ if (optionalUsed + item.length <= remainingBudget) {
12698
+ optionalParts.push(item);
12699
+ optionalUsed += item.length;
12700
+ } else {
12701
+ omissions.push({
12702
+ category: "historical",
12703
+ whatWasOmitted: item,
12704
+ whyOmitted: "token budget exceeded",
12705
+ wouldBreakContinuity: false
12706
+ });
12707
+ }
12708
+ }
12709
+ const admittedSet = new Set([...mandatoryParts, ...admittedMandatoryState, ...admittedActive].map((s) => s.trim().toLowerCase()));
12710
+ const isDuplicate = /* @__PURE__ */ __name((item) => {
12711
+ const normalized = item.trim().toLowerCase();
12712
+ for (const existing of admittedSet) {
12713
+ if (existing.includes(normalized) || normalized.includes(existing)) return true;
12714
+ }
12715
+ return false;
12716
+ }, "isDuplicate");
12717
+ const finalRetrieved = dedupe(retrievedParts.filter((p) => !isDuplicate(p)));
12718
+ const finalOptional = dedupe(optionalParts.filter((p) => !isDuplicate(p) && !finalRetrieved.includes(p)));
12719
+ const mandatory = [...mandatoryParts, ...admittedMandatoryState].join("\n");
12720
+ const active = [...admittedActive];
12721
+ const retrieved = finalRetrieved;
12722
+ const optional = finalOptional;
12723
+ const text = [mandatory ? `## MANDATORY
12724
+ ${mandatory}` : "", active.length ? `## ACTIVE
12725
+ ${active.join("\n")}` : "", retrieved.length ? `## RETRIEVED
12726
+ ${retrieved.join("\n")}` : "", optional.length ? `## OPTIONAL
12727
+ ${optional.join("\n")}` : "", rules.length ? `## RULES
12728
+ ${activeRules.join("\n")}` : ""].filter(Boolean).join("\n\n");
12729
+ const budgetUsed = estimateTokens(text);
12730
+ return {
12731
+ mandatory,
12732
+ active,
12733
+ retrieved,
12734
+ optional,
12735
+ omissions,
12736
+ budgetUsed,
12737
+ budgetAvailable: totalBudget,
12738
+ text
12739
+ };
12740
+ }
12741
+ };
12742
+ compileContext = /* @__PURE__ */ __name((input) => {
12743
+ const compiler = new ContextCompiler();
12744
+ return compiler.compile(input);
12745
+ }, "compileContext");
12746
+ }
12747
+ });
12748
+
12749
+ // core/knowledge/rule-enforcement.ts
12750
+ var resolveApplicableRules;
12751
+ var init_rule_enforcement = __esm({
12752
+ "core/knowledge/rule-enforcement.ts"() {
12753
+ init_rules_loader();
12754
+ init_violations();
12755
+ init_hard_rules_registry();
12756
+ init_memory();
12757
+ init_context_compiler();
12758
+ resolveApplicableRules = /* @__PURE__ */ __name(async (situation, scope) => {
12759
+ const state3 = await loadCombinedKnowledgeState();
12760
+ const rules = [];
12761
+ const seen = /* @__PURE__ */ new Set();
12762
+ const ironReport = loadIronRules(state3);
12763
+ for (const rule of ironReport.rules) {
12764
+ if (seen.has(rule.id)) continue;
12765
+ seen.add(rule.id);
12766
+ const claim = state3.claims.find((c) => c.id === rule.id);
12767
+ rules.push({
12768
+ id: rule.id,
12769
+ text: rule.text,
12770
+ tier: "context",
12771
+ source: "iron",
12772
+ appliesWhen: rule.appliesWhen || void 0,
12773
+ hasCheck: !!claim?.check
12774
+ });
12775
+ }
12776
+ try {
12777
+ const registry = new HardRulesRegistry();
12778
+ const active = scope ? await registry.activeRules(scope) : await registry.activeRules();
12779
+ for (const rule of active) {
12780
+ if (seen.has(rule.id)) continue;
12781
+ seen.add(rule.id);
12782
+ rules.push({
12783
+ id: rule.id,
12784
+ text: rule.statement,
12785
+ tier: rule.ruleClass === "IMMUTABLE" || rule.ruleClass === "OWNER_CONTROLLED" ? "hard-precondition" : "precondition",
12786
+ source: "hard",
12787
+ appliesWhen: rule.scope,
12788
+ hasCheck: false
12789
+ });
12790
+ }
12791
+ } catch {
12792
+ }
12793
+ return rules;
12794
+ }, "resolveApplicableRules");
12795
+ }
12796
+ });
12797
+
12798
+ // core/knowledge/index.ts
12799
+ var init_knowledge = __esm({
12800
+ "core/knowledge/index.ts"() {
12801
+ init_acquisition_boundary();
12802
+ init_acquisition_limits();
12803
+ init_applicability();
12804
+ init_behavioral_invariants();
12805
+ init_bootstrap();
12806
+ init_built_in_context();
12807
+ init_built_in_context_rules();
12808
+ init_canonical_hash();
12809
+ init_canonical_reconstruction();
12810
+ init_canonical_schema();
12811
+ init_context_budget();
12812
+ init_contract();
12813
+ init_correction();
12814
+ init_currentness();
12815
+ init_detection_events();
12816
+ init_detection_journal();
12817
+ init_discover();
12818
+ init_solvers();
12819
+ init_signatures();
12820
+ init_probe();
12821
+ init_semantic_provider();
12822
+ init_effective_contract();
12823
+ init_exemplars();
12824
+ init_explain();
12825
+ init_feedback();
12826
+ init_fingerprint();
12827
+ init_identity_governance();
12828
+ init_identity_resolution();
12829
+ init_incidents();
12830
+ init_inspect_report();
12831
+ init_language_detect();
12832
+ init_loops();
12833
+ init_mem_package();
12834
+ init_personality_anchor();
12835
+ init_policy();
12836
+ init_policy_namespace_lock();
12837
+ init_policy_store();
12838
+ init_project();
12839
+ init_project_anchor();
12840
+ init_read_only();
12841
+ init_renderer();
12842
+ init_repository();
12843
+ init_rule_checker();
12844
+ init_rules_loader();
12845
+ init_runtime();
12846
+ init_scope_eligibility();
12847
+ init_select();
12848
+ init_session();
12849
+ init_staging();
12850
+ init_state();
12851
+ init_storage_location();
12852
+ init_storage_settings();
12853
+ init_tool_guard();
12854
+ init_user_identity();
12855
+ init_user_language();
12856
+ init_user_paths();
12857
+ init_vault();
12858
+ init_verification();
12859
+ init_verify();
12860
+ init_violations();
12861
+ init_claim_identity();
12862
+ init_store_registry();
12863
+ init_migration_audit();
12864
+ init_session_metrics();
12865
+ init_session_metrics();
12866
+ init_session_metrics();
12867
+ init_session_metrics();
12868
+ init_rule_enforcement();
12869
+ }
12870
+ });
12871
+
12872
+ // core/logic/helpers.ts
12873
+ var normalizeClaimIds2, revisionFromAcquire;
12874
+ var init_helpers = __esm({
12875
+ "core/logic/helpers.ts"() {
12876
+ normalizeClaimIds2 = /* @__PURE__ */ __name((value) => {
12877
+ if (!value) return [];
12878
+ return Array.isArray(value) ? value : [value];
12879
+ }, "normalizeClaimIds");
12880
+ revisionFromAcquire = /* @__PURE__ */ __name((opts) => {
12881
+ const refines = normalizeClaimIds2(opts.refines);
12882
+ const supersedes = normalizeClaimIds2(opts.supersedes);
12883
+ const retracts = normalizeClaimIds2(opts.retracts);
12884
+ if ([refines, supersedes, retracts].filter((ids) => ids.length > 0).length > 1) {
12885
+ throw new Error("Acquired knowledge can refine, supersede, or retract prior knowledge, not more than one");
12886
+ }
12887
+ if (refines.length > 0) return { kind: "refines", claimIds: refines, ...opts.reason ? { reason: opts.reason } : {} };
12888
+ if (supersedes.length > 0) return { kind: "supersedes", claimIds: supersedes, ...opts.reason ? { reason: opts.reason } : {} };
12889
+ if (retracts.length > 0) return { kind: "retracts", claimIds: retracts, ...opts.reason ? { reason: opts.reason } : {} };
12890
+ return void 0;
12891
+ }, "revisionFromAcquire");
12892
+ }
12893
+ });
12894
+
12895
+ // core/logic/index.ts
12896
+ var logic_exports = {};
12897
+ __export(logic_exports, {
12898
+ LogicEngine: () => LogicEngine,
12899
+ default: () => logic_default,
12900
+ getLogicRuntime: () => getLogicRuntime,
12172
12901
  logic: () => logic
12173
12902
  });
12174
12903
  var LOGIC_MEM_FILE, nodeCwd2, cachedRuntime, resetLogicRuntime, getLogicRuntime, LogicEngine, _inferConfidence, logic, logic_default;
@@ -12469,21 +13198,6 @@ __export(encryption_exports, {
12469
13198
  decryptPayload: () => decryptPayload,
12470
13199
  encryptPayload: () => encryptPayload
12471
13200
  });
12472
- function getHybridKeys() {
12473
- const dir = `${resolveUserDotMemPath()}/keys`;
12474
- try {
12475
- fs__default.default.mkdirSync(dir, { recursive: true });
12476
- } catch {
12477
- }
12478
- try {
12479
- const raw = JSON.parse(fs__default.default.readFileSync(hybridKeyFile(), "utf8"));
12480
- return { publicKey: Buffer.from(raw.publicKey, "hex"), secretKey: Buffer.from(raw.secretKey, "hex") };
12481
- } catch {
12482
- }
12483
- const keys = hybrid_js.ml_kem768_x25519.keygen();
12484
- fs__default.default.writeFileSync(hybridKeyFile(), JSON.stringify({ publicKey: Buffer.from(keys.publicKey).toString("hex"), secretKey: Buffer.from(keys.secretKey).toString("hex") }), { mode: 384 });
12485
- return { publicKey: keys.publicKey, secretKey: keys.secretKey };
12486
- }
12487
13201
  function encryptPayload(plaintext) {
12488
13202
  const keys = getHybridKeys();
12489
13203
  const { sharedSecret, cipherText: kemCt } = hybrid_js.ml_kem768_x25519.encapsulate(keys.publicKey);
@@ -12499,7 +13213,7 @@ function decryptPayload(envelope) {
12499
13213
  try {
12500
13214
  if (!envelope.startsWith("{")) {
12501
13215
  const keyFile = `${resolveUserDotMemPath()}/keys/local.key`;
12502
- const hex = fs__default.default.readFileSync(keyFile, "utf8").trim();
13216
+ const hex = fs6__default.default.readFileSync(keyFile, "utf8").trim();
12503
13217
  const key2 = Buffer.from(hex, "hex");
12504
13218
  const [ivB64, tagB64, ctB64] = envelope.split(":");
12505
13219
  const iv2 = Buffer.from(ivB64, "base64");
@@ -12526,12 +13240,26 @@ function decryptPayload(envelope) {
12526
13240
  return null;
12527
13241
  }
12528
13242
  }
12529
- var hybridKeyFile;
13243
+ var hybridKeyFile, getHybridKeys;
12530
13244
  var init_encryption = __esm({
12531
13245
  "core/knowledge/encryption.ts"() {
12532
13246
  init_user_paths();
12533
13247
  hybridKeyFile = /* @__PURE__ */ __name(() => `${resolveUserDotMemPath()}/keys/hybrid.key`, "hybridKeyFile");
12534
- __name(getHybridKeys, "getHybridKeys");
13248
+ getHybridKeys = /* @__PURE__ */ __name(() => {
13249
+ const dir = `${resolveUserDotMemPath()}/keys`;
13250
+ try {
13251
+ fs6__default.default.mkdirSync(dir, { recursive: true });
13252
+ } catch {
13253
+ }
13254
+ try {
13255
+ const raw = JSON.parse(fs6__default.default.readFileSync(hybridKeyFile(), "utf8"));
13256
+ return { publicKey: Buffer.from(raw.publicKey, "hex"), secretKey: Buffer.from(raw.secretKey, "hex") };
13257
+ } catch {
13258
+ }
13259
+ const keys = hybrid_js.ml_kem768_x25519.keygen();
13260
+ fs6__default.default.writeFileSync(hybridKeyFile(), JSON.stringify({ publicKey: Buffer.from(keys.publicKey).toString("hex"), secretKey: Buffer.from(keys.secretKey).toString("hex") }), { mode: 384 });
13261
+ return { publicKey: keys.publicKey, secretKey: keys.secretKey };
13262
+ }, "getHybridKeys");
12535
13263
  __name(encryptPayload, "encryptPayload");
12536
13264
  __name(decryptPayload, "decryptPayload");
12537
13265
  }
@@ -12582,13 +13310,13 @@ var init_brain = __esm({
12582
13310
  }, "brainSave");
12583
13311
  cachedBrainPath = null;
12584
13312
  getBrainDocument = /* @__PURE__ */ __name(async () => {
12585
- const path10 = getBrainPath();
12586
- cachedBrainPath = path10;
12587
- return brainLoad(path10);
13313
+ const path11 = getBrainPath();
13314
+ cachedBrainPath = path11;
13315
+ return brainLoad(path11);
12588
13316
  }, "getBrainDocument");
12589
13317
  saveBrainDocument = /* @__PURE__ */ __name(async (document) => {
12590
- const path10 = cachedBrainPath || getBrainPath();
12591
- await brainSave(path10, document);
13318
+ const path11 = cachedBrainPath || getBrainPath();
13319
+ await brainSave(path11, document);
12592
13320
  }, "saveBrainDocument");
12593
13321
  resetBrainPathCache = /* @__PURE__ */ __name(() => {
12594
13322
  cachedBrainPath = null;
@@ -14133,7 +14861,7 @@ ${content}`);
14133
14861
  for (const file2 of files) {
14134
14862
  if (!file2.endsWith(".arch.mem")) continue;
14135
14863
  try {
14136
- const bytes = await fs14__default.default.readFile(path8__default.default.join(dir, file2));
14864
+ const bytes = await fs14__default.default.readFile(path5__default.default.join(dir, file2));
14137
14865
  const { metadata } = readZip(bytes);
14138
14866
  entries2.push(metadata);
14139
14867
  } catch {
@@ -14395,7 +15123,7 @@ var init_acquire = __esm({
14395
15123
  const { findClaimLocations: findClaimLocations2 } = await Promise.resolve().then(() => (init_claim_identity(), claim_identity_exports));
14396
15124
  const locations = await findClaimLocations2(targetId);
14397
15125
  if (locations.length === 0) {
14398
- throw new Error(`Claim ${claimId} references unknown prior claim ${targetId}. Searched all stores.`);
15126
+ throw new Error(`Claim ${claimId} references any prior claim ${targetId}. Searched all stores.`);
14399
15127
  }
14400
15128
  if (locations.length > 1) {
14401
15129
  throw new Error(`Claim ${claimId} references ambiguous prior claim ${targetId} in ${locations.length} stores: ` + locations.map((location) => `${location.storeId} [scope=${location.scope ?? "unspecified"}${location.sourceProject ? `, project ${location.sourceProject}` : ""}]`).join(", "));
@@ -14790,11 +15518,11 @@ var init_durable_store = __esm({
14790
15518
  writeFile: writeFile4,
14791
15519
  rename,
14792
15520
  copyFile,
14793
- rm: /* @__PURE__ */ __name((path10, opts) => rm(path10, opts), "rm"),
15521
+ rm: /* @__PURE__ */ __name((path11, opts) => rm(path11, opts), "rm"),
14794
15522
  mkdir,
14795
- open: /* @__PURE__ */ __name(async (path10, flags) => {
15523
+ open: /* @__PURE__ */ __name(async (path11, flags) => {
14796
15524
  if (!Deno.open) throw new Error("Deno.open is unavailable");
14797
- const file2 = await Deno.open(path10, flags);
15525
+ const file2 = await Deno.open(path11, flags);
14798
15526
  return {
14799
15527
  writeFile: /* @__PURE__ */ __name(async (data) => {
14800
15528
  const written = await file2.write(data);
@@ -15109,9 +15837,9 @@ var init_entries = __esm({
15109
15837
  };
15110
15838
  return recencyScore * confidenceScore * accessScore * typeBoost[entry.type] * scopeBoost[entry.scope];
15111
15839
  }, "computeRelevance");
15112
- getNestedPath = /* @__PURE__ */ __name((obj, path10) => {
15113
- if (!path10 || typeof path10 !== "string") return void 0;
15114
- const parts = path10.replace(/^state\./, "").split(".");
15840
+ getNestedPath = /* @__PURE__ */ __name((obj, path11) => {
15841
+ if (!path11 || typeof path11 !== "string") return void 0;
15842
+ const parts = path11.replace(/^state\./, "").split(".");
15115
15843
  let current = obj;
15116
15844
  for (const part of parts) {
15117
15845
  if (current === null || current === void 0) return void 0;
@@ -15119,9 +15847,9 @@ var init_entries = __esm({
15119
15847
  }
15120
15848
  return current;
15121
15849
  }, "getNestedPath");
15122
- setNestedPath = /* @__PURE__ */ __name((obj, path10, value) => {
15123
- if (!path10 || typeof path10 !== "string") return;
15124
- const parts = path10.replace(/^state\./, "").split(".");
15850
+ setNestedPath = /* @__PURE__ */ __name((obj, path11, value) => {
15851
+ if (!path11 || typeof path11 !== "string") return;
15852
+ const parts = path11.replace(/^state\./, "").split(".");
15125
15853
  let current = obj;
15126
15854
  for (let i3 = 0; i3 < parts.length - 1; i3++) {
15127
15855
  const part = parts[i3];
@@ -15132,9 +15860,9 @@ var init_entries = __esm({
15132
15860
  }
15133
15861
  current[parts[parts.length - 1]] = value;
15134
15862
  }, "setNestedPath");
15135
- deleteNestedPath = /* @__PURE__ */ __name((obj, path10) => {
15136
- if (!path10 || typeof path10 !== "string") return;
15137
- const parts = path10.replace(/^state\./, "").split(".");
15863
+ deleteNestedPath = /* @__PURE__ */ __name((obj, path11) => {
15864
+ if (!path11 || typeof path11 !== "string") return;
15865
+ const parts = path11.replace(/^state\./, "").split(".");
15138
15866
  let current = obj;
15139
15867
  for (let i3 = 0; i3 < parts.length - 1; i3++) {
15140
15868
  const part = parts[i3];
@@ -15608,14 +16336,14 @@ var init_store = __esm({
15608
16336
  const fs16 = getSyncFs();
15609
16337
  if (!fs16) return;
15610
16338
  const validated = validateConversationalState(state3);
15611
- const path10 = resolveConversationalStatePath(validated.scope, validated.subject, validated.conversationId, tenantId);
16339
+ const path11 = resolveConversationalStatePath(validated.scope, validated.subject, validated.conversationId, tenantId);
15612
16340
  const fsPromises = await import('fs/promises');
15613
16341
  await fsPromises.mkdir(resolveConversationalStateDir(tenantId), { recursive: true });
15614
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
16342
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
15615
16343
  try {
15616
16344
  await fsPromises.writeFile(temporary, `${JSON.stringify(validated, null, 2)}
15617
16345
  `, "utf8");
15618
- await fsPromises.rename(temporary, path10);
16346
+ await fsPromises.rename(temporary, path11);
15619
16347
  } catch (error) {
15620
16348
  await fsPromises.rm(temporary, { force: true }).catch(() => void 0);
15621
16349
  throw error;
@@ -15763,7 +16491,7 @@ var init_conversational_state = __esm({
15763
16491
  });
15764
16492
 
15765
16493
  // core/memory/capture-persistence.ts
15766
- var CAPTURE_STORE_KEY, CAPTURE_KEY_PREFIX, sessionRecordKey, nowIso, CapturePersistence, defaultPersistence, getCapturePersistence;
16494
+ var CAPTURE_STORE_KEY, CAPTURE_KEY_PREFIX, sessionRecordKey, nowIso2, CapturePersistence, defaultPersistence, getCapturePersistence;
15767
16495
  var init_capture_persistence = __esm({
15768
16496
  "core/memory/capture-persistence.ts"() {
15769
16497
  init_durable_store();
@@ -15771,7 +16499,7 @@ var init_capture_persistence = __esm({
15771
16499
  CAPTURE_STORE_KEY = "capture-items";
15772
16500
  CAPTURE_KEY_PREFIX = "capture:";
15773
16501
  sessionRecordKey = /* @__PURE__ */ __name((conversationId) => `${CAPTURE_KEY_PREFIX}${conversationId}`, "sessionRecordKey");
15774
- nowIso = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
16502
+ nowIso2 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
15775
16503
  CapturePersistence = class {
15776
16504
  static {
15777
16505
  __name(this, "CapturePersistence");
@@ -15786,7 +16514,7 @@ var init_capture_persistence = __esm({
15786
16514
  conversationId,
15787
16515
  items,
15788
16516
  explicitInstructions,
15789
- updatedAt: nowIso()
16517
+ updatedAt: nowIso2()
15790
16518
  };
15791
16519
  await this.store.set({
15792
16520
  id: sessionRecordKey(conversationId),
@@ -15846,7 +16574,7 @@ var init_capture_persistence = __esm({
15846
16574
  }, "getCapturePersistence");
15847
16575
  }
15848
16576
  });
15849
- var DEFAULT_CONFIG, CATEGORY_KEYWORDS, REMEMBER_PATTERNS, DO_NOT_REMEMBER_PATTERNS, generateId, nowIso2, normalizeText, tokenize2, jaccardSimilarity, containsPhrase2, detectExplicitInstructions, classifyCategory, determineEpistemicType, determineConfidence, extractEntities, extractRelationships, findExistingSimilarItems, findExistingMemoryEntries, shouldStoreInCoreMemory, routeToStorage, CaptureEngine, captureEngine, captureConversation, captureTurn;
16577
+ var DEFAULT_CONFIG, CATEGORY_KEYWORDS, REMEMBER_PATTERNS, DO_NOT_REMEMBER_PATTERNS, generateId, nowIso3, normalizeText, tokenize2, jaccardSimilarity, containsPhrase2, detectExplicitInstructions, classifyCategory, determineEpistemicType, determineConfidence, extractEntities, extractRelationships, findExistingSimilarItems, findExistingMemoryEntries, shouldStoreInCoreMemory, routeToStorage, CaptureEngine, captureEngine, captureConversation, captureTurn;
15850
16578
  var init_capture_engine = __esm({
15851
16579
  "core/memory/capture-engine.ts"() {
15852
16580
  init_exemplars();
@@ -15882,7 +16610,7 @@ var init_capture_engine = __esm({
15882
16610
  generateId = /* @__PURE__ */ __name(() => {
15883
16611
  return `capture-${memorio.hlc.serialize(memorio.hlc.tick())}-${Math.random().toString(36).slice(2, 10)}`;
15884
16612
  }, "generateId");
15885
- nowIso2 = /* @__PURE__ */ __name(() => {
16613
+ nowIso3 = /* @__PURE__ */ __name(() => {
15886
16614
  return (/* @__PURE__ */ new Date()).toISOString();
15887
16615
  }, "nowIso");
15888
16616
  normalizeText = /* @__PURE__ */ __name((text) => {
@@ -15915,7 +16643,7 @@ var init_capture_engine = __esm({
15915
16643
  type: "remember",
15916
16644
  content: text,
15917
16645
  source,
15918
- timestamp: nowIso2()
16646
+ timestamp: nowIso3()
15919
16647
  });
15920
16648
  break;
15921
16649
  }
@@ -15926,7 +16654,7 @@ var init_capture_engine = __esm({
15926
16654
  type: "do-not-remember",
15927
16655
  content: text,
15928
16656
  source,
15929
- timestamp: nowIso2()
16657
+ timestamp: nowIso3()
15930
16658
  });
15931
16659
  break;
15932
16660
  }
@@ -16279,7 +17007,7 @@ var init_capture_engine = __esm({
16279
17007
  const source = {
16280
17008
  conversationId: options.conversationId,
16281
17009
  messageIds: options.messageIds ?? [],
16282
- timestamp: nowIso2(),
17010
+ timestamp: nowIso3(),
16283
17011
  turnIndex: 0
16284
17012
  };
16285
17013
  const instructions = detectExplicitInstructions(text, source);
@@ -16299,7 +17027,7 @@ var init_capture_engine = __esm({
16299
17027
  classification: "temporary_context",
16300
17028
  confidence: "low",
16301
17029
  epistemicType: "observed",
16302
- capturedAt: nowIso2(),
17030
+ capturedAt: nowIso3(),
16303
17031
  method: "automatic"
16304
17032
  },
16305
17033
  confidence: "low",
@@ -16319,7 +17047,7 @@ var init_capture_engine = __esm({
16319
17047
  classification: category,
16320
17048
  confidence,
16321
17049
  epistemicType,
16322
- capturedAt: nowIso2(),
17050
+ capturedAt: nowIso3(),
16323
17051
  method: hasExplicitRemember ? "explicit" : "automatic"
16324
17052
  };
16325
17053
  const item = {
@@ -16381,7 +17109,7 @@ var init_capture_engine = __esm({
16381
17109
  const source = {
16382
17110
  conversationId: options.conversationId,
16383
17111
  messageIds: [msg.id ?? `msg-${index}`],
16384
- timestamp: msg.timestamp ?? nowIso2(),
17112
+ timestamp: msg.timestamp ?? nowIso3(),
16385
17113
  turnIndex: index
16386
17114
  };
16387
17115
  const instructions = detectExplicitInstructions(msg.content, source);
@@ -16401,7 +17129,7 @@ var init_capture_engine = __esm({
16401
17129
  classification: "temporary_context",
16402
17130
  confidence: "low",
16403
17131
  epistemicType: "observed",
16404
- capturedAt: nowIso2(),
17132
+ capturedAt: nowIso3(),
16405
17133
  method: "automatic"
16406
17134
  },
16407
17135
  confidence: "low",
@@ -16421,7 +17149,7 @@ var init_capture_engine = __esm({
16421
17149
  classification: category,
16422
17150
  confidence,
16423
17151
  epistemicType,
16424
- capturedAt: nowIso2(),
17152
+ capturedAt: nowIso3(),
16425
17153
  method: hasExplicitRemember ? "explicit" : "automatic"
16426
17154
  };
16427
17155
  const item = {
@@ -16578,7 +17306,7 @@ var init_capture_engine = __esm({
16578
17306
  if (this.clearedConversations.has(conversationId)) {
16579
17307
  ctx = {
16580
17308
  conversationId,
16581
- startedAt: nowIso2(),
17309
+ startedAt: nowIso3(),
16582
17310
  items: [],
16583
17311
  explicitInstructions: []
16584
17312
  };
@@ -16598,7 +17326,7 @@ var init_capture_engine = __esm({
16598
17326
  }
16599
17327
  ctx = {
16600
17328
  conversationId,
16601
- startedAt: nowIso2(),
17329
+ startedAt: nowIso3(),
16602
17330
  items: [],
16603
17331
  explicitInstructions: []
16604
17332
  };
@@ -16770,7 +17498,7 @@ var init_note = __esm({
16770
17498
  init_storage_coordinator();
16771
17499
  init_claim_identity();
16772
17500
  TOMBSTONE_FILE = "deleted-notes.tombstones.json";
16773
- tombstonePath = /* @__PURE__ */ __name(() => path8__default.default.join(resolveUserDotMemPath(), TOMBSTONE_FILE), "tombstonePath");
17501
+ tombstonePath = /* @__PURE__ */ __name(() => path5__default.default.join(resolveUserDotMemPath(), TOMBSTONE_FILE), "tombstonePath");
16774
17502
  loadNoteTombstones = /* @__PURE__ */ __name(async () => {
16775
17503
  try {
16776
17504
  const raw = await fs14__default.default.readFile(tombstonePath(), "utf8");
@@ -16786,7 +17514,7 @@ var init_note = __esm({
16786
17514
  if (!existing.some((t) => t.id === id)) {
16787
17515
  existing.push({ id, deletedAt: (/* @__PURE__ */ new Date()).toISOString() });
16788
17516
  }
16789
- await fs14__default.default.mkdir(path8__default.default.dirname(tombstonePath()), { recursive: true });
17517
+ await fs14__default.default.mkdir(path5__default.default.dirname(tombstonePath()), { recursive: true });
16790
17518
  await fs14__default.default.writeFile(tombstonePath(), JSON.stringify({ deletedNotes: existing }, null, 2), "utf8");
16791
17519
  const g2 = globalThis.__dotmemDeletedNotes || /* @__PURE__ */ new Set();
16792
17520
  g2.add(id);
@@ -16813,7 +17541,7 @@ var init_note = __esm({
16813
17541
  if (referencing.length === 0) continue;
16814
17542
  const newClaims = artifact.state.claims.filter((claim) => !(claim.revision?.claimIds ?? []).includes(noteId));
16815
17543
  const newState = { version: artifact.state.version + 1, claims: newClaims };
16816
- await withStorageLock(path8__default.default.dirname(filePath), async () => {
17544
+ await withStorageLock(path5__default.default.dirname(filePath), async () => {
16817
17545
  const currentBytes = await fs14__default.default.readFile(filePath);
16818
17546
  const currentArtifact = await decodeMemArtifact(currentBytes);
16819
17547
  if (!currentArtifact.state || currentArtifact.state.version !== artifact.state.version) {
@@ -16821,7 +17549,7 @@ var init_note = __esm({
16821
17549
  }
16822
17550
  const tmp = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
16823
17551
  try {
16824
- await fs14__default.default.mkdir(path8__default.default.dirname(filePath), { recursive: true });
17552
+ await fs14__default.default.mkdir(path5__default.default.dirname(filePath), { recursive: true });
16825
17553
  const { quarantineClaimRecord: quarantineClaimRecord2 } = await Promise.resolve().then(() => (init_quarantine(), quarantine_exports));
16826
17554
  for (const claim of referencing) {
16827
17555
  await quarantineClaimRecord2({
@@ -16954,7 +17682,7 @@ var init_note = __esm({
16954
17682
  return { deleted: 0, byStore: {}, allDeleted: finalOccurrences2.length === 0, remaining: finalOccurrences2 };
16955
17683
  }
16956
17684
  for (const [filePath, occs] of byFile) {
16957
- const storeId = occs[0]?.store ?? "unknown";
17685
+ const storeId = occs[0]?.store ?? "any";
16958
17686
  try {
16959
17687
  const bytes = await fs14__default.default.readFile(filePath);
16960
17688
  const artifact = await decodeMemArtifact(bytes);
@@ -16970,7 +17698,7 @@ var init_note = __esm({
16970
17698
  }
16971
17699
  const newClaims = artifact.state.claims.filter((c) => !(c.id === id && c.kind === "note"));
16972
17700
  const newState = { version: artifact.state.version + 1, claims: newClaims };
16973
- await withStorageLock(path8__default.default.dirname(filePath), async () => {
17701
+ await withStorageLock(path5__default.default.dirname(filePath), async () => {
16974
17702
  const currentBytes = await fs14__default.default.readFile(filePath);
16975
17703
  const currentArtifact = await decodeMemArtifact(currentBytes);
16976
17704
  if (!currentArtifact.state || currentArtifact.state.version !== artifact.state.version) {
@@ -16978,7 +17706,7 @@ var init_note = __esm({
16978
17706
  }
16979
17707
  const tmp = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
16980
17708
  try {
16981
- await fs14__default.default.mkdir(path8__default.default.dirname(filePath), { recursive: true });
17709
+ await fs14__default.default.mkdir(path5__default.default.dirname(filePath), { recursive: true });
16982
17710
  const encoded = await encodeMemPackage(newState, currentArtifact.preserved, currentArtifact.package);
16983
17711
  await fs14__default.default.writeFile(tmp, encoded);
16984
17712
  await decodeMemArtifact(await fs14__default.default.readFile(tmp));
@@ -17072,9 +17800,9 @@ var init_note = __esm({
17072
17800
  };
17073
17801
  }, "noteDeleteAll");
17074
17802
  try {
17075
- const tp = path8__default.default.join(resolveUserDotMemPath(), TOMBSTONE_FILE);
17076
- if (fs__default.default.existsSync(tp)) {
17077
- const raw = fs__default.default.readFileSync(tp, "utf8");
17803
+ const tp = path5__default.default.join(resolveUserDotMemPath(), TOMBSTONE_FILE);
17804
+ if (fs6__default.default.existsSync(tp)) {
17805
+ const raw = fs6__default.default.readFileSync(tp, "utf8");
17078
17806
  const parsed = JSON.parse(raw);
17079
17807
  const arr = Array.isArray(parsed) ? parsed : parsed.deletedNotes ?? [];
17080
17808
  const g2 = globalThis.__dotmemDeletedNotes || /* @__PURE__ */ new Set();
@@ -17407,8 +18135,8 @@ var init_ontology = __esm({
17407
18135
  errors.push("relation must be object");
17408
18136
  continue;
17409
18137
  }
17410
- if (!ids.has(r.from)) errors.push(`relation.from unknown: ${r.from}`);
17411
- if (!ids.has(r.to)) errors.push(`relation.to unknown: ${r.to}`);
18138
+ if (!ids.has(r.from)) errors.push(`relation.from any: ${r.from}`);
18139
+ if (!ids.has(r.to)) errors.push(`relation.to any: ${r.to}`);
17412
18140
  if (!RELATION_TYPES.includes(r.type)) errors.push(`relation.type invalid: ${r.type}`);
17413
18141
  }
17414
18142
  return { valid: errors.length === 0, errors };
@@ -17425,7 +18153,7 @@ var init_ontology = __esm({
17425
18153
  ),
17426
18154
  byPos: graph.concepts.reduce(
17427
18155
  (acc, c) => {
17428
- const k = c.pos || "unknown";
18156
+ const k = c.pos || "any";
17429
18157
  acc[k] = (acc[k] || 0) + 1;
17430
18158
  return acc;
17431
18159
  },
@@ -17485,7 +18213,7 @@ var init_anthology = __esm({
17485
18213
  errors.push("provenance must be an object");
17486
18214
  return { valid: false, errors };
17487
18215
  }
17488
- const kinds = ["user-statement", "system-observation", "imported-document", "external-source", "agent-inference", "model-summary", "human-correction", "system-event", "unknown"];
18216
+ const kinds = ["user-statement", "system-observation", "imported-document", "external-source", "agent-inference", "model-summary", "human-correction", "system-event", "any"];
17489
18217
  if (!kinds.includes(p.kind)) errors.push("invalid provenance kind");
17490
18218
  if (p.observedAt !== void 0 && (typeof p.observedAt !== "string" || isNaN(Date.parse(p.observedAt)))) {
17491
18219
  errors.push("observedAt must be valid ISO timestamp if provided");
@@ -17539,681 +18267,908 @@ var init_anthology = __esm({
17539
18267
  schemaVersion: 0,
17540
18268
  category: "legacy",
17541
18269
  payload: item,
17542
- scope: item?.scope ?? "unknown",
17543
- provenance: { kind: "unknown" },
18270
+ scope: item?.scope ?? "any",
18271
+ provenance: { kind: "any" },
17544
18272
  epistemicStatus: "unassessed",
17545
- sensitivity: "unknown",
18273
+ sensitivity: "any",
17546
18274
  temporal: { recordedAt: item?.createdAt ? new Date(item.createdAt).toISOString() : (/* @__PURE__ */ new Date(0)).toISOString() },
17547
18275
  revision: { revision: 0 }
17548
18276
  };
17549
18277
  }, "normalizeLegacyRecord");
17550
- MEMORY_CATEGORIES = ["observation", "claim", "fact-candidate", "hypothesis", "decision", "preference", "instruction", "experience", "goal", "relationship", "derived-summary", "unknown-disputed", "legacy"];
18278
+ MEMORY_CATEGORIES = ["observation", "claim", "fact-candidate", "hypothesis", "decision", "preference", "instruction", "experience", "goal", "relationship", "derived-summary", "any-disputed", "legacy"];
17551
18279
  EPISTEMIC_STATUSES = ["unassessed", "asserted", "corroborated", "reviewed", "disputed", "refuted", "superseded"];
17552
18280
  }
17553
- });
17554
- function stripCode(content) {
17555
- let out = "";
17556
- let i3 = 0;
17557
- const n = content.length;
17558
- while (i3 < n) {
17559
- const c = content[i3];
17560
- const next = content[i3 + 1];
17561
- if (c === "/" && next === "/") {
17562
- const nl = content.indexOf("\n", i3);
17563
- if (nl === -1) break;
17564
- out += "\n";
17565
- i3 = nl + 1;
17566
- continue;
17567
- }
17568
- if (c === "/" && next === "*") {
17569
- const end = content.indexOf("*/", i3 + 2);
17570
- if (end === -1) break;
17571
- const seg = content.slice(i3, end + 2);
17572
- out += seg.replace(/[^\n]/g, " ");
17573
- i3 = end + 2;
17574
- continue;
18281
+ });
18282
+ function audit(options = {}) {
18283
+ const projectPath = options.projectPath ?? process.cwd();
18284
+ const allFindings = scanDir(projectPath, projectPath);
18285
+ allFindings.push(...runNpmAudit(projectPath));
18286
+ const quality = allFindings.filter((f) => f.category === "quality");
18287
+ const security2 = allFindings.filter((f) => f.category === "security");
18288
+ const performance = allFindings.filter((f) => f.category === "performance");
18289
+ const errorCount = allFindings.filter((f) => f.severity === "critical" || f.severity === "high").length;
18290
+ const totalFindings = allFindings.length;
18291
+ const score = Math.max(0, 100 - errorCount * 10 - (totalFindings - errorCount) * 2);
18292
+ const grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : score >= 60 ? "D" : "F";
18293
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
18294
+ const result = {
18295
+ projectPath,
18296
+ timestamp,
18297
+ quality,
18298
+ security: security2,
18299
+ performance,
18300
+ score,
18301
+ grade,
18302
+ summary: `Audit complete: ${totalFindings} findings (${errorCount} critical/high). Score: ${score}/100 (Grade: ${grade}).`,
18303
+ report: ""
18304
+ };
18305
+ result.report = generateReport({ quality, security: security2, performance, score, grade, projectPath, timestamp });
18306
+ if (options.onFinding) {
18307
+ for (const f of allFindings) {
18308
+ options.onFinding(f);
17575
18309
  }
17576
- if (c === '"' || c === "'" || c === "`") {
17577
- const quote = c;
17578
- let j = i3 + 1;
17579
- while (j < n) {
17580
- if (content[j] === "\\") {
17581
- j += 2;
18310
+ }
18311
+ return {
18312
+ name: "audit",
18313
+ version: "0.3.0",
18314
+ description: "Professional IT audit: quality, security, performance, npm vulnerabilities.",
18315
+ hooks: {
18316
+ onAudit(_result) {
18317
+ }
18318
+ },
18319
+ run: /* @__PURE__ */ __name(() => result, "run"),
18320
+ report: /* @__PURE__ */ __name(() => result.report, "report")
18321
+ };
18322
+ }
18323
+ var stripCode, hasEval, isInNonCode, collectDangerousNames, hasProcessExec, scanFile, scanDir, runNpmAudit, generateReport;
18324
+ var init_audit = __esm({
18325
+ "plugins/audit/index.ts"() {
18326
+ stripCode = /* @__PURE__ */ __name((content) => {
18327
+ let out = "";
18328
+ let i3 = 0;
18329
+ const n = content.length;
18330
+ while (i3 < n) {
18331
+ const c = content[i3];
18332
+ const next = content[i3 + 1];
18333
+ if (c === "/" && next === "/") {
18334
+ const nl = content.indexOf("\n", i3);
18335
+ if (nl === -1) break;
18336
+ out += "\n";
18337
+ i3 = nl + 1;
17582
18338
  continue;
17583
18339
  }
17584
- if (content[j] === quote) {
17585
- j++;
17586
- break;
18340
+ if (c === "/" && next === "*") {
18341
+ const end = content.indexOf("*/", i3 + 2);
18342
+ if (end === -1) break;
18343
+ const seg = content.slice(i3, end + 2);
18344
+ out += seg.replace(/[^\n]/g, " ");
18345
+ i3 = end + 2;
18346
+ continue;
17587
18347
  }
17588
- if (content[j] === "\n") break;
17589
- j++;
17590
- }
17591
- const seg = content.slice(i3, j);
17592
- out += seg.replace(/[^\n]/g, " ");
17593
- i3 = j;
17594
- continue;
17595
- }
17596
- if (c === "/") {
17597
- let k = out.length - 1;
17598
- while (k >= 0 && /\s/.test(out[k])) k--;
17599
- const prev = k >= 0 ? out[k] : "";
17600
- const regexStartChars = "(,=:[!&|?{;+-*/%^~";
17601
- if (regexStartChars.includes(prev) || prev === "") {
17602
- let j = i3 + 1;
17603
- let inClass = false;
17604
- while (j < n) {
17605
- if (content[j] === "\\") {
17606
- j += 2;
18348
+ if (c === '"' || c === "'" || c === "`") {
18349
+ const quote = c;
18350
+ let j = i3 + 1;
18351
+ while (j < n) {
18352
+ if (content[j] === "\\") {
18353
+ j += 2;
18354
+ continue;
18355
+ }
18356
+ if (content[j] === quote) {
18357
+ j++;
18358
+ break;
18359
+ }
18360
+ if (content[j] === "\n") break;
18361
+ j++;
18362
+ }
18363
+ const seg = content.slice(i3, j);
18364
+ out += seg.replace(/[^\n]/g, " ");
18365
+ i3 = j;
18366
+ continue;
18367
+ }
18368
+ if (c === "/") {
18369
+ let k = out.length - 1;
18370
+ while (k >= 0 && /\s/.test(out[k])) k--;
18371
+ const prev = k >= 0 ? out[k] : "";
18372
+ const regexStartChars = "(,=:[!&|?{;+-*/%^~";
18373
+ if (regexStartChars.includes(prev) || prev === "") {
18374
+ let j = i3 + 1;
18375
+ let inClass = false;
18376
+ while (j < n) {
18377
+ if (content[j] === "\\") {
18378
+ j += 2;
18379
+ continue;
18380
+ }
18381
+ if (content[j] === "[") {
18382
+ inClass = true;
18383
+ j++;
18384
+ continue;
18385
+ }
18386
+ if (content[j] === "]") {
18387
+ inClass = false;
18388
+ j++;
18389
+ continue;
18390
+ }
18391
+ if (content[j] === "/" && !inClass) {
18392
+ j++;
18393
+ break;
18394
+ }
18395
+ if (content[j] === "\n") break;
18396
+ j++;
18397
+ }
18398
+ const seg = content.slice(i3, j);
18399
+ out += seg.replace(/[^\n]/g, " ");
18400
+ i3 = j;
17607
18401
  continue;
17608
18402
  }
17609
- if (content[j] === "[") {
17610
- inClass = true;
17611
- j++;
18403
+ }
18404
+ out += c;
18405
+ i3++;
18406
+ }
18407
+ return out;
18408
+ }, "stripCode");
18409
+ hasEval = /* @__PURE__ */ __name((content) => {
18410
+ const code = stripCode(content);
18411
+ if (/\b(?:globalThis|global|window|self)\s*\.\s*eval\s*\(/.test(code)) return true;
18412
+ if (/\beval\s*\(/.test(code)) return true;
18413
+ return false;
18414
+ }, "hasEval");
18415
+ isInNonCode = /* @__PURE__ */ __name((content, index) => {
18416
+ let i3 = 0;
18417
+ let inLineComment = false;
18418
+ let inBlockComment = false;
18419
+ let inString = null;
18420
+ while (i3 < index) {
18421
+ const c = content[i3];
18422
+ const next = content[i3 + 1];
18423
+ if (inLineComment) {
18424
+ if (c === "\n") inLineComment = false;
18425
+ i3++;
18426
+ continue;
18427
+ }
18428
+ if (inBlockComment) {
18429
+ if (c === "*" && next === "/") {
18430
+ inBlockComment = false;
18431
+ i3 += 2;
17612
18432
  continue;
17613
18433
  }
17614
- if (content[j] === "]") {
17615
- inClass = false;
17616
- j++;
18434
+ i3++;
18435
+ continue;
18436
+ }
18437
+ if (inString) {
18438
+ if (c === "\\") {
18439
+ i3 += 2;
17617
18440
  continue;
17618
18441
  }
17619
- if (content[j] === "/" && !inClass) {
17620
- j++;
17621
- break;
18442
+ if (c === inString) inString = null;
18443
+ i3++;
18444
+ continue;
18445
+ }
18446
+ if (c === "/" && next === "/") {
18447
+ inLineComment = true;
18448
+ i3 += 2;
18449
+ continue;
18450
+ }
18451
+ if (c === "/" && next === "*") {
18452
+ inBlockComment = true;
18453
+ i3 += 2;
18454
+ continue;
18455
+ }
18456
+ if (c === '"' || c === "'" || c === "`") {
18457
+ inString = c;
18458
+ i3++;
18459
+ continue;
18460
+ }
18461
+ i3++;
18462
+ }
18463
+ return inLineComment || inBlockComment || inString !== null;
18464
+ }, "isInNonCode");
18465
+ collectDangerousNames = /* @__PURE__ */ __name((content) => {
18466
+ const names = /* @__PURE__ */ new Set();
18467
+ const namespaces = /* @__PURE__ */ new Set();
18468
+ const addName = /* @__PURE__ */ __name((name, local) => {
18469
+ if (["exec", "execSync", "spawn", "spawnSync"].includes(name)) {
18470
+ names.add(local);
18471
+ }
18472
+ }, "addName");
18473
+ let m;
18474
+ const esImport = /import\s*\{([^}]+)\}\s*from\s*['"](?:node:)?child_process['"]/g;
18475
+ while ((m = esImport.exec(content)) !== null) {
18476
+ if (isInNonCode(content, m.index)) continue;
18477
+ for (const part of m[1].split(",")) {
18478
+ const p = part.trim();
18479
+ if (!p) continue;
18480
+ const alias = p.match(/^(\w+)\s+as\s+(\w+)$/);
18481
+ if (alias) addName(alias[1], alias[2]);
18482
+ else addName(p, p);
18483
+ }
18484
+ }
18485
+ const esNs = /import\s*\*\s*as\s+(\w+)\s*from\s*['"](?:node:)?child_process['"]/g;
18486
+ while ((m = esNs.exec(content)) !== null) {
18487
+ if (isInNonCode(content, m.index)) continue;
18488
+ namespaces.add(m[1]);
18489
+ }
18490
+ const cjsDestruct = /(?:const|let|var)\s*\{([^}]+)\}\s*=\s*require\(\s*['"](?:node:)?child_process['"]\s*\)/g;
18491
+ while ((m = cjsDestruct.exec(content)) !== null) {
18492
+ if (isInNonCode(content, m.index)) continue;
18493
+ for (const part of m[1].split(",")) {
18494
+ const p = part.trim();
18495
+ if (!p) continue;
18496
+ const colon = p.match(/^(\w+)\s*:\s*(\w+)$/);
18497
+ if (colon) {
18498
+ addName(colon[1], colon[2]);
18499
+ continue;
17622
18500
  }
17623
- if (content[j] === "\n") break;
17624
- j++;
18501
+ const alias = p.match(/^(\w+)\s+as\s+(\w+)$/);
18502
+ if (alias) addName(alias[1], alias[2]);
18503
+ else addName(p, p);
18504
+ }
18505
+ }
18506
+ const cjsNs = /(?:const|let|var)\s+(\w+)\s*=\s*require\(\s*['"](?:node:)?child_process['"]\s*\)/g;
18507
+ while ((m = cjsNs.exec(content)) !== null) {
18508
+ if (isInNonCode(content, m.index)) continue;
18509
+ namespaces.add(m[1]);
18510
+ }
18511
+ const cjsProp = /(?:const|let|var)\s+(\w+)\s*=\s*require\(\s*['"](?:node:)?child_process['"]\s*\)\s*\.\s*(exec|execSync|spawn|spawnSync)\b/g;
18512
+ while ((m = cjsProp.exec(content)) !== null) {
18513
+ if (isInNonCode(content, m.index)) continue;
18514
+ names.add(m[1]);
18515
+ }
18516
+ return { names, namespaces };
18517
+ }, "collectDangerousNames");
18518
+ hasProcessExec = /* @__PURE__ */ __name((content) => {
18519
+ const code = stripCode(content);
18520
+ const { names, namespaces } = collectDangerousNames(content);
18521
+ for (const ns of namespaces) {
18522
+ const re = new RegExp("\\b" + ns + "\\s*\\.\\s*(exec|execSync|spawn|spawnSync)\\s*\\(");
18523
+ if (re.test(code)) return true;
18524
+ }
18525
+ for (const name of names) {
18526
+ const re = new RegExp("\\b" + name + "\\s*\\(");
18527
+ if (re.test(code)) return true;
18528
+ }
18529
+ if (/\b(?:child_process|childProcess)\s*\.\s*(exec|execSync|spawn|spawnSync)\s*\(/.test(code)) return true;
18530
+ if (/require\(\s*['"](?:node:)?child_process['"]\s*\)\s*\.\s*(exec|execSync|spawn|spawnSync)\s*\(/.test(code)) return true;
18531
+ return false;
18532
+ }, "hasProcessExec");
18533
+ scanFile = /* @__PURE__ */ __name((filePath, content, projectPath) => {
18534
+ const findings = [];
18535
+ const lines = content.split("\n");
18536
+ const relPath = path5.relative(projectPath, filePath);
18537
+ const ext = path5.extname(filePath);
18538
+ if (/password\s*=\s*['"]/i.test(content)) {
18539
+ findings.push({ id: "SEC-001", category: "security", severity: "critical", framework: "OWASP", control: "A02", message: "Hardcoded password detected", file: relPath, remediation: "Use environment variables or a secrets manager (NIST IA-5)" });
18540
+ }
18541
+ if (/api[_-]?key\s*=\s*['"]/i.test(content)) {
18542
+ findings.push({ id: "SEC-002", category: "security", severity: "critical", framework: "OWASP", control: "A02", message: "Hardcoded API key detected", file: relPath, remediation: "Use environment variables or a secrets manager (NIST IA-5)" });
18543
+ }
18544
+ if (/secret\s*=\s*['"]/i.test(content)) {
18545
+ findings.push({ id: "SEC-003", category: "security", severity: "critical", framework: "OWASP", control: "A02", message: "Hardcoded secret detected", file: relPath, remediation: "Use environment variables or a secrets manager (NIST SC-13)" });
18546
+ }
18547
+ if (hasEval(content)) {
18548
+ findings.push({ id: "SEC-004", category: "security", severity: "high", framework: "OWASP", control: "A03", message: "Use of eval() detected (code injection risk)", file: relPath, remediation: "Avoid eval(); use safer alternatives (NSA-2 Input Validation)" });
18549
+ }
18550
+ if (/innerHTML\s*=/.test(content)) {
18551
+ findings.push({ id: "SEC-005", category: "security", severity: "high", framework: "OWASP", control: "A03", message: "innerHTML assignment (XSS risk)", file: relPath, remediation: "Use textContent or DOM sanitization (OWASP A03)" });
18552
+ }
18553
+ if (/document\.write\s*\(/.test(content)) {
18554
+ findings.push({ id: "SEC-006", category: "security", severity: "medium", framework: "OWASP", control: "A03", message: "document.write() usage (XSS risk)", file: relPath, remediation: "Use DOM manipulation methods instead" });
18555
+ }
18556
+ if (hasProcessExec(content)) {
18557
+ findings.push({ id: "SEC-007", category: "security", severity: "high", framework: "OWASP", control: "A03", message: "Shell command execution detected (command injection risk)", file: relPath, remediation: "Validate and sanitize all inputs (NSA-2, NIST SI-10)" });
18558
+ }
18559
+ if (/cors\s*\(\s*\{\s*origin:\s*['"]\*['"]/.test(content)) {
18560
+ findings.push({ id: "SEC-008", category: "security", severity: "medium", framework: "OWASP", control: "A01", message: "CORS wildcard origin (overly permissive)", file: relPath, remediation: "Restrict CORS to trusted origins (NIST AC-3)" });
18561
+ }
18562
+ if (/debug\s*:\s*true/.test(content)) {
18563
+ findings.push({ id: "SEC-009", category: "security", severity: "low", framework: "OWASP", control: "A05", message: "Debug mode enabled", file: relPath, remediation: "Disable debug in production (NIST CM-6)" });
18564
+ }
18565
+ const consoleCount = (content.match(/console\.log/g) || []).length;
18566
+ if (consoleCount > 5 && !filePath.includes("test")) {
18567
+ findings.push({ id: "SEC-010", category: "security", severity: "low", framework: "OWASP", control: "A09", message: `${consoleCount} console.debug statements (potential info leak)`, file: relPath, remediation: "Use structured logging (NIST AU-2, AU-3)" });
18568
+ }
18569
+ if (ext === ".c" || ext === ".cpp" || ext === ".rs") {
18570
+ if (/strcpy|strcat|sprintf|gets\s*\(/.test(content)) {
18571
+ findings.push({ id: "SEC-011", category: "security", severity: "critical", framework: "NSA", control: "NSA-3", message: "Unsafe C/C++ string function (buffer overflow risk)", file: relPath, remediation: "Use bounded alternatives (strncpy, snprintf) (NSA-3 Memory Safety)" });
17625
18572
  }
17626
- const seg = content.slice(i3, j);
17627
- out += seg.replace(/[^\n]/g, " ");
17628
- i3 = j;
17629
- continue;
17630
18573
  }
17631
- }
17632
- out += c;
17633
- i3++;
17634
- }
17635
- return out;
17636
- }
17637
- function hasEval(content) {
17638
- const code = stripCode(content);
17639
- if (/\b(?:globalThis|global|window|self)\s*\.\s*eval\s*\(/.test(code)) return true;
17640
- if (/\beval\s*\(/.test(code)) return true;
17641
- return false;
17642
- }
17643
- function isInNonCode(content, index) {
17644
- let i3 = 0;
17645
- let inLineComment = false;
17646
- let inBlockComment = false;
17647
- let inString = null;
17648
- while (i3 < index) {
17649
- const c = content[i3];
17650
- const next = content[i3 + 1];
17651
- if (inLineComment) {
17652
- if (c === "\n") inLineComment = false;
17653
- i3++;
17654
- continue;
17655
- }
17656
- if (inBlockComment) {
17657
- if (c === "*" && next === "/") {
17658
- inBlockComment = false;
17659
- i3 += 2;
17660
- continue;
18574
+ if (lines.length > 500) {
18575
+ findings.push({ id: "QLT-001", category: "quality", severity: "medium", framework: "ISO 25010", control: "Maintainability", message: `File too long (${lines.length} lines)`, file: relPath, remediation: "Split into smaller modules (max 300 lines recommended)" });
17661
18576
  }
17662
- i3++;
17663
- continue;
17664
- }
17665
- if (inString) {
17666
- if (c === "\\") {
17667
- i3 += 2;
17668
- continue;
18577
+ const todoCount = (content.match(/TODO|FIXME|HACK|XXX/gi) || []).length;
18578
+ if (todoCount > 3) {
18579
+ findings.push({ id: "QLT-002", category: "quality", severity: "low", framework: "ISO 25010", control: "Maintainability", message: `${todoCount} TODO/FIXME/HACK markers`, file: relPath, remediation: "Resolve technical debt items" });
17669
18580
  }
17670
- if (c === inString) inString = null;
17671
- i3++;
17672
- continue;
17673
- }
17674
- if (c === "/" && next === "/") {
17675
- inLineComment = true;
17676
- i3 += 2;
17677
- continue;
17678
- }
17679
- if (c === "/" && next === "*") {
17680
- inBlockComment = true;
17681
- i3 += 2;
17682
- continue;
17683
- }
17684
- if (c === '"' || c === "'" || c === "`") {
17685
- inString = c;
17686
- i3++;
17687
- continue;
17688
- }
17689
- i3++;
17690
- }
17691
- return inLineComment || inBlockComment || inString !== null;
17692
- }
17693
- function collectDangerousNames(content) {
17694
- const names = /* @__PURE__ */ new Set();
17695
- const namespaces = /* @__PURE__ */ new Set();
17696
- const addName = /* @__PURE__ */ __name((name, local) => {
17697
- if (["exec", "execSync", "spawn", "spawnSync"].includes(name)) {
17698
- names.add(local);
17699
- }
17700
- }, "addName");
17701
- let m;
17702
- const esImport = /import\s*\{([^}]+)\}\s*from\s*['"](?:node:)?child_process['"]/g;
17703
- while ((m = esImport.exec(content)) !== null) {
17704
- if (isInNonCode(content, m.index)) continue;
17705
- for (const part of m[1].split(",")) {
17706
- const p = part.trim();
17707
- if (!p) continue;
17708
- const alias = p.match(/^(\w+)\s+as\s+(\w+)$/);
17709
- if (alias) addName(alias[1], alias[2]);
17710
- else addName(p, p);
17711
- }
17712
- }
17713
- const esNs = /import\s*\*\s*as\s+(\w+)\s*from\s*['"](?:node:)?child_process['"]/g;
17714
- while ((m = esNs.exec(content)) !== null) {
17715
- if (isInNonCode(content, m.index)) continue;
17716
- namespaces.add(m[1]);
17717
- }
17718
- const cjsDestruct = /(?:const|let|var)\s*\{([^}]+)\}\s*=\s*require\(\s*['"](?:node:)?child_process['"]\s*\)/g;
17719
- while ((m = cjsDestruct.exec(content)) !== null) {
17720
- if (isInNonCode(content, m.index)) continue;
17721
- for (const part of m[1].split(",")) {
17722
- const p = part.trim();
17723
- if (!p) continue;
17724
- const colon = p.match(/^(\w+)\s*:\s*(\w+)$/);
17725
- if (colon) {
17726
- addName(colon[1], colon[2]);
17727
- continue;
17728
- }
17729
- const alias = p.match(/^(\w+)\s+as\s+(\w+)$/);
17730
- if (alias) addName(alias[1], alias[2]);
17731
- else addName(p, p);
17732
- }
17733
- }
17734
- const cjsNs = /(?:const|let|var)\s+(\w+)\s*=\s*require\(\s*['"](?:node:)?child_process['"]\s*\)/g;
17735
- while ((m = cjsNs.exec(content)) !== null) {
17736
- if (isInNonCode(content, m.index)) continue;
17737
- namespaces.add(m[1]);
17738
- }
17739
- const cjsProp = /(?:const|let|var)\s+(\w+)\s*=\s*require\(\s*['"](?:node:)?child_process['"]\s*\)\s*\.\s*(exec|execSync|spawn|spawnSync)\b/g;
17740
- while ((m = cjsProp.exec(content)) !== null) {
17741
- if (isInNonCode(content, m.index)) continue;
17742
- names.add(m[1]);
17743
- }
17744
- return { names, namespaces };
17745
- }
17746
- function hasProcessExec(content) {
17747
- const code = stripCode(content);
17748
- const { names, namespaces } = collectDangerousNames(content);
17749
- for (const ns of namespaces) {
17750
- const re = new RegExp("\\b" + ns + "\\s*\\.\\s*(exec|execSync|spawn|spawnSync)\\s*\\(");
17751
- if (re.test(code)) return true;
17752
- }
17753
- for (const name of names) {
17754
- const re = new RegExp("\\b" + name + "\\s*\\(");
17755
- if (re.test(code)) return true;
17756
- }
17757
- if (/\b(?:child_process|childProcess)\s*\.\s*(exec|execSync|spawn|spawnSync)\s*\(/.test(code)) return true;
17758
- if (/require\(\s*['"](?:node:)?child_process['"]\s*\)\s*\.\s*(exec|execSync|spawn|spawnSync)\s*\(/.test(code)) return true;
17759
- return false;
17760
- }
17761
- function scanFile(filePath, content, projectPath) {
17762
- const findings = [];
17763
- const lines = content.split("\n");
17764
- const relPath = path8.relative(projectPath, filePath);
17765
- const ext = path8.extname(filePath);
17766
- if (/password\s*=\s*['"]/i.test(content)) {
17767
- findings.push({ id: "SEC-001", category: "security", severity: "critical", framework: "OWASP", control: "A02", message: "Hardcoded password detected", file: relPath, remediation: "Use environment variables or a secrets manager (NIST IA-5)" });
17768
- }
17769
- if (/api[_-]?key\s*=\s*['"]/i.test(content)) {
17770
- findings.push({ id: "SEC-002", category: "security", severity: "critical", framework: "OWASP", control: "A02", message: "Hardcoded API key detected", file: relPath, remediation: "Use environment variables or a secrets manager (NIST IA-5)" });
17771
- }
17772
- if (/secret\s*=\s*['"]/i.test(content)) {
17773
- findings.push({ id: "SEC-003", category: "security", severity: "critical", framework: "OWASP", control: "A02", message: "Hardcoded secret detected", file: relPath, remediation: "Use environment variables or a secrets manager (NIST SC-13)" });
17774
- }
17775
- if (hasEval(content)) {
17776
- findings.push({ id: "SEC-004", category: "security", severity: "high", framework: "OWASP", control: "A03", message: "Use of eval() detected (code injection risk)", file: relPath, remediation: "Avoid eval(); use safer alternatives (NSA-2 Input Validation)" });
17777
- }
17778
- if (/innerHTML\s*=/.test(content)) {
17779
- findings.push({ id: "SEC-005", category: "security", severity: "high", framework: "OWASP", control: "A03", message: "innerHTML assignment (XSS risk)", file: relPath, remediation: "Use textContent or DOM sanitization (OWASP A03)" });
17780
- }
17781
- if (/document\.write\s*\(/.test(content)) {
17782
- findings.push({ id: "SEC-006", category: "security", severity: "medium", framework: "OWASP", control: "A03", message: "document.write() usage (XSS risk)", file: relPath, remediation: "Use DOM manipulation methods instead" });
17783
- }
17784
- if (hasProcessExec(content)) {
17785
- findings.push({ id: "SEC-007", category: "security", severity: "high", framework: "OWASP", control: "A03", message: "Shell command execution detected (command injection risk)", file: relPath, remediation: "Validate and sanitize all inputs (NSA-2, NIST SI-10)" });
17786
- }
17787
- if (/cors\s*\(\s*\{\s*origin:\s*['"]\*['"]/.test(content)) {
17788
- findings.push({ id: "SEC-008", category: "security", severity: "medium", framework: "OWASP", control: "A01", message: "CORS wildcard origin (overly permissive)", file: relPath, remediation: "Restrict CORS to trusted origins (NIST AC-3)" });
17789
- }
17790
- if (/debug\s*:\s*true/.test(content)) {
17791
- findings.push({ id: "SEC-009", category: "security", severity: "low", framework: "OWASP", control: "A05", message: "Debug mode enabled", file: relPath, remediation: "Disable debug in production (NIST CM-6)" });
17792
- }
17793
- const consoleCount = (content.match(/console\.log/g) || []).length;
17794
- if (consoleCount > 5 && !filePath.includes("test")) {
17795
- findings.push({ id: "SEC-010", category: "security", severity: "low", framework: "OWASP", control: "A09", message: `${consoleCount} console.debug statements (potential info leak)`, file: relPath, remediation: "Use structured logging (NIST AU-2, AU-3)" });
17796
- }
17797
- if (ext === ".c" || ext === ".cpp" || ext === ".rs") {
17798
- if (/strcpy|strcat|sprintf|gets\s*\(/.test(content)) {
17799
- findings.push({ id: "SEC-011", category: "security", severity: "critical", framework: "NSA", control: "NSA-3", message: "Unsafe C/C++ string function (buffer overflow risk)", file: relPath, remediation: "Use bounded alternatives (strncpy, snprintf) (NSA-3 Memory Safety)" });
17800
- }
17801
- }
17802
- if (lines.length > 500) {
17803
- findings.push({ id: "QLT-001", category: "quality", severity: "medium", framework: "ISO 25010", control: "Maintainability", message: `File too long (${lines.length} lines)`, file: relPath, remediation: "Split into smaller modules (max 300 lines recommended)" });
17804
- }
17805
- const todoCount = (content.match(/TODO|FIXME|HACK|XXX/gi) || []).length;
17806
- if (todoCount > 3) {
17807
- findings.push({ id: "QLT-002", category: "quality", severity: "low", framework: "ISO 25010", control: "Maintainability", message: `${todoCount} TODO/FIXME/HACK markers`, file: relPath, remediation: "Resolve technical debt items" });
17808
- }
17809
- if (!content.includes("test") && (ext === ".ts" || ext === ".js") && !filePath.includes("test") && !filePath.includes("spec")) {
17810
- findings.push({ id: "QLT-003", category: "quality", severity: "info", framework: "ISO 25010", control: "Testability", message: "No test references found", file: relPath, remediation: "Add unit tests for this module" });
17811
- }
17812
- if (/await\s+\w+\(/.test(content) && !content.includes("try") && !content.includes("catch")) {
17813
- findings.push({ id: "QLT-004", category: "quality", severity: "medium", framework: "ISO 25010", control: "Reliability", message: "Async operations without try/catch", file: relPath, remediation: "Add error handling for async operations" });
17814
- }
17815
- const nestedLoops = content.match(/for\s*\(.*\)\s*\{[^}]*for\s*\(/g);
17816
- if (nestedLoops && nestedLoops.length > 0) {
17817
- findings.push({ id: "PRF-001", category: "performance", severity: "medium", framework: "OSI L7", control: "Application Layer", message: `Nested loops detected (${nestedLoops.length} instances, O(n^2) risk)`, file: relPath, remediation: "Optimize nested iterations; consider indexing or caching" });
17818
- }
17819
- if (/JSON\.parse\(.*JSON\.stringify/.test(content)) {
17820
- findings.push({ id: "PRF-002", category: "performance", severity: "medium", framework: "OSI L7", control: "Application Layer", message: "Deep clone via JSON parse/stringify", file: relPath, remediation: "Use structuredClone() or targeted cloning" });
17821
- }
17822
- const syncReads = (content.match(/readFileSync/g) || []).length;
17823
- if (syncReads > 3) {
17824
- findings.push({ id: "PRF-003", category: "performance", severity: "low", framework: "OSI L7", control: "Application Layer", message: `${syncReads} synchronous file reads`, file: relPath, remediation: "Use async file reads in request paths" });
17825
- }
17826
- return findings;
17827
- }
17828
- function scanDir(dir, projectPath) {
17829
- const allFindings = [];
17830
- try {
17831
- const entries2 = fs.readdirSync(dir, { withFileTypes: true });
17832
- for (const entry of entries2) {
17833
- if (["node_modules", ".git", "dist", ".cache", "coverage", ".private", ".project", ".dev"].includes(entry.name)) continue;
17834
- const fullPath = path8.join(dir, entry.name);
17835
- if (entry.isDirectory()) {
17836
- allFindings.push(...scanDir(fullPath, projectPath));
17837
- } else if (entry.isFile() && /\.(ts|js|tsx|jsx|py|go|rs|c|cpp|java)$/.test(entry.name)) {
18581
+ if (!content.includes("test") && (ext === ".ts" || ext === ".js") && !filePath.includes("test") && !filePath.includes("spec")) {
18582
+ findings.push({ id: "QLT-003", category: "quality", severity: "info", framework: "ISO 25010", control: "Testability", message: "No test references found", file: relPath, remediation: "Add unit tests for this module" });
18583
+ }
18584
+ if (/await\s+\w+\(/.test(content) && !content.includes("try") && !content.includes("catch")) {
18585
+ findings.push({ id: "QLT-004", category: "quality", severity: "medium", framework: "ISO 25010", control: "Reliability", message: "Async operations without try/catch", file: relPath, remediation: "Add error handling for async operations" });
18586
+ }
18587
+ const nestedLoops = content.match(/for\s*\(.*\)\s*\{[^}]*for\s*\(/g);
18588
+ if (nestedLoops && nestedLoops.length > 0) {
18589
+ findings.push({ id: "PRF-001", category: "performance", severity: "medium", framework: "OSI L7", control: "Application Layer", message: `Nested loops detected (${nestedLoops.length} instances, O(n^2) risk)`, file: relPath, remediation: "Optimize nested iterations; consider indexing or caching" });
18590
+ }
18591
+ if (/JSON\.parse\(.*JSON\.stringify/.test(content)) {
18592
+ findings.push({ id: "PRF-002", category: "performance", severity: "medium", framework: "OSI L7", control: "Application Layer", message: "Deep clone via JSON parse/stringify", file: relPath, remediation: "Use structuredClone() or targeted cloning" });
18593
+ }
18594
+ const syncReads = (content.match(/readFileSync/g) || []).length;
18595
+ if (syncReads > 3) {
18596
+ findings.push({ id: "PRF-003", category: "performance", severity: "low", framework: "OSI L7", control: "Application Layer", message: `${syncReads} synchronous file reads`, file: relPath, remediation: "Use async file reads in request paths" });
18597
+ }
18598
+ return findings;
18599
+ }, "scanFile");
18600
+ scanDir = /* @__PURE__ */ __name((dir, projectPath) => {
18601
+ const allFindings = [];
18602
+ try {
18603
+ const entries2 = fs6.readdirSync(dir, { withFileTypes: true });
18604
+ for (const entry of entries2) {
18605
+ if (["node_modules", ".git", "dist", ".cache", "coverage", ".private", ".project", ".dev"].includes(entry.name)) continue;
18606
+ const fullPath = path5.join(dir, entry.name);
18607
+ if (entry.isDirectory()) {
18608
+ allFindings.push(...scanDir(fullPath, projectPath));
18609
+ } else if (entry.isFile() && /\.(ts|js|tsx|jsx|py|go|rs|c|cpp|java)$/.test(entry.name)) {
18610
+ try {
18611
+ const content = fs6.readFileSync(fullPath, "utf-8");
18612
+ allFindings.push(...scanFile(fullPath, content, projectPath));
18613
+ } catch {
18614
+ }
18615
+ }
18616
+ }
18617
+ } catch {
18618
+ }
18619
+ return allFindings;
18620
+ }, "scanDir");
18621
+ runNpmAudit = /* @__PURE__ */ __name((projectPath) => {
18622
+ const findings = [];
18623
+ try {
18624
+ let output = "";
17838
18625
  try {
17839
- const content = fs.readFileSync(fullPath, "utf-8");
17840
- allFindings.push(...scanFile(fullPath, content, projectPath));
17841
- } catch {
18626
+ output = child_process.execFileSync("npm", ["audit", "--json"], { cwd: projectPath, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
18627
+ } catch (e) {
18628
+ output = e.stdout || "";
18629
+ }
18630
+ if (!output) return findings;
18631
+ const data = JSON.parse(output);
18632
+ const vulns = data.vulnerabilities ?? {};
18633
+ let idCounter = 1;
18634
+ for (const [name, info] of Object.entries(vulns)) {
18635
+ const severity = (info.severity ?? "low").toLowerCase();
18636
+ const mappedSeverity = severity === "critical" ? "critical" : severity === "high" ? "high" : severity === "moderate" ? "medium" : "low";
18637
+ const via = Array.isArray(info.via) ? info.via.filter((v) => typeof v === "object").map((v) => v.title || v.name).join(", ") : "";
18638
+ findings.push({
18639
+ id: `NPM-${String(idCounter++).padStart(3, "0")}`,
18640
+ category: "security",
18641
+ severity: mappedSeverity,
18642
+ framework: "npm audit",
18643
+ control: "OWASP A06",
18644
+ message: `${name}: ${via || info.name || "vulnerability"} (${severity})`,
18645
+ file: "package.json",
18646
+ remediation: `Run "npm audit fix" or update ${name} to a patched version`
18647
+ });
17842
18648
  }
18649
+ const meta = data.metadata?.vulnerabilities;
18650
+ if (meta && meta.total > 0) {
18651
+ findings.push({
18652
+ id: "NPM-SUM",
18653
+ category: "security",
18654
+ severity: meta.critical > 0 ? "critical" : meta.high > 0 ? "high" : meta.moderate > 0 ? "medium" : "low",
18655
+ framework: "npm audit",
18656
+ control: "OWASP A06",
18657
+ message: `npm audit: ${meta.total} vulnerabilities (${meta.critical} critical, ${meta.high} high, ${meta.moderate} moderate, ${meta.low} low)`,
18658
+ file: "package.json",
18659
+ remediation: 'Run "npm audit fix" to resolve. Review breaking changes before applying.'
18660
+ });
18661
+ }
18662
+ } catch {
17843
18663
  }
17844
- }
17845
- } catch {
17846
- }
17847
- return allFindings;
17848
- }
17849
- function runNpmAudit(projectPath) {
17850
- const findings = [];
17851
- try {
17852
- let output = "";
17853
- try {
17854
- output = child_process.execFileSync("npm", ["audit", "--json"], { cwd: projectPath, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
17855
- } catch (e) {
17856
- output = e.stdout || "";
17857
- }
17858
- if (!output) return findings;
17859
- const data = JSON.parse(output);
17860
- const vulns = data.vulnerabilities ?? {};
17861
- let idCounter = 1;
17862
- for (const [name, info] of Object.entries(vulns)) {
17863
- const severity = (info.severity ?? "low").toLowerCase();
17864
- const mappedSeverity = severity === "critical" ? "critical" : severity === "high" ? "high" : severity === "moderate" ? "medium" : "low";
17865
- const via = Array.isArray(info.via) ? info.via.filter((v) => typeof v === "object").map((v) => v.title || v.name).join(", ") : "";
17866
- findings.push({
17867
- id: `NPM-${String(idCounter++).padStart(3, "0")}`,
17868
- category: "security",
17869
- severity: mappedSeverity,
17870
- framework: "npm audit",
17871
- control: "OWASP A06",
17872
- message: `${name}: ${via || info.name || "vulnerability"} (${severity})`,
17873
- file: "package.json",
17874
- remediation: `Run "npm audit fix" or update ${name} to a patched version`
17875
- });
17876
- }
17877
- const meta = data.metadata?.vulnerabilities;
17878
- if (meta && meta.total > 0) {
17879
- findings.push({
17880
- id: "NPM-SUM",
17881
- category: "security",
17882
- severity: meta.critical > 0 ? "critical" : meta.high > 0 ? "high" : meta.moderate > 0 ? "medium" : "low",
17883
- framework: "npm audit",
17884
- control: "OWASP A06",
17885
- message: `npm audit: ${meta.total} vulnerabilities (${meta.critical} critical, ${meta.high} high, ${meta.moderate} moderate, ${meta.low} low)`,
17886
- file: "package.json",
17887
- remediation: 'Run "npm audit fix" to resolve. Review breaking changes before applying.'
17888
- });
17889
- }
17890
- } catch {
17891
- }
17892
- return findings;
17893
- }
17894
- function generateReport(result) {
17895
- const { quality, security: security2, performance, score, grade, projectPath, timestamp } = result;
17896
- const all = [...quality, ...security2, ...performance];
17897
- const critical = all.filter((f) => f.severity === "critical").length;
17898
- const high = all.filter((f) => f.severity === "high").length;
17899
- const medium = all.filter((f) => f.severity === "medium").length;
17900
- const low = all.filter((f) => f.severity === "low" || f.severity === "info").length;
17901
- let report = "";
17902
- report += "\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n";
17903
- report += " PROFESSIONAL IT AUDIT REPORT\n";
17904
- report += "\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\n";
17905
- report += `Project: ${projectPath}
18664
+ return findings;
18665
+ }, "runNpmAudit");
18666
+ generateReport = /* @__PURE__ */ __name((result) => {
18667
+ const { quality, security: security2, performance, score, grade, projectPath, timestamp } = result;
18668
+ const all = [...quality, ...security2, ...performance];
18669
+ const critical = all.filter((f) => f.severity === "critical").length;
18670
+ const high = all.filter((f) => f.severity === "high").length;
18671
+ const medium = all.filter((f) => f.severity === "medium").length;
18672
+ const low = all.filter((f) => f.severity === "low" || f.severity === "info").length;
18673
+ let report = "";
18674
+ report += "\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n";
18675
+ report += " PROFESSIONAL IT AUDIT REPORT\n";
18676
+ report += "\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n\n";
18677
+ report += `Project: ${projectPath}
17906
18678
  `;
17907
- report += `Date: ${timestamp}
18679
+ report += `Date: ${timestamp}
17908
18680
  `;
17909
- report += `Auditor: dotmem audit plugin
18681
+ report += `Auditor: dotmem audit plugin
17910
18682
  `;
17911
- report += `Frameworks: OWASP Top 10, NIST SP 800-53, NSA/CISA Guidelines, ISO 25010, npm audit
18683
+ report += `Frameworks: OWASP Top 10, NIST SP 800-53, NSA/CISA Guidelines, ISO 25010, npm audit
17912
18684
  `;
17913
- report += `OSI Layers: L7 (Application) analyzed
18685
+ report += `OSI Layers: L7 (Application) analyzed
17914
18686
 
17915
18687
  `;
17916
- report += "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n";
17917
- report += " EXECUTIVE SUMMARY\n";
17918
- report += "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n";
17919
- report += `Overall Score: ${score}/100 (Grade: ${grade})
18688
+ report += "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n";
18689
+ report += " EXECUTIVE SUMMARY\n";
18690
+ report += "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n";
18691
+ report += `Overall Score: ${score}/100 (Grade: ${grade})
17920
18692
  `;
17921
- report += `Total Findings: ${all.length}
18693
+ report += `Total Findings: ${all.length}
17922
18694
  `;
17923
- report += ` Critical: ${critical} High: ${high} Medium: ${medium} Low/Info: ${low}
18695
+ report += ` Critical: ${critical} High: ${high} Medium: ${medium} Low/Info: ${low}
17924
18696
 
17925
18697
  `;
17926
- report += ` Quality: ${quality.length} findings
18698
+ report += ` Quality: ${quality.length} findings
17927
18699
  `;
17928
- report += ` Security: ${security2.length} findings (incl. npm vulnerabilities)
18700
+ report += ` Security: ${security2.length} findings (incl. npm vulnerabilities)
17929
18701
  `;
17930
- report += ` Performance: ${performance.length} findings
18702
+ report += ` Performance: ${performance.length} findings
17931
18703
 
17932
18704
  `;
17933
- report += "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n";
17934
- report += " 1. SECURITY ASSESSMENT\n";
17935
- report += "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n";
17936
- report += "Frameworks: OWASP Top 10 (2021), NIST SP 800-53 Rev.5, NSA Secure Coding, npm audit\n\n";
17937
- if (security2.length === 0) {
17938
- report += "No security findings. All checks passed.\n\n";
17939
- } else {
17940
- for (const f of security2) {
17941
- report += `[${f.severity.toUpperCase()}] ${f.id}: ${f.message}
18705
+ report += "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n";
18706
+ report += " 1. SECURITY ASSESSMENT\n";
18707
+ report += "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n";
18708
+ report += "Frameworks: OWASP Top 10 (2021), NIST SP 800-53 Rev.5, NSA Secure Coding, npm audit\n\n";
18709
+ if (security2.length === 0) {
18710
+ report += "No security findings. All checks passed.\n\n";
18711
+ } else {
18712
+ for (const f of security2) {
18713
+ report += `[${f.severity.toUpperCase()}] ${f.id}: ${f.message}
17942
18714
  `;
17943
- report += ` Framework: ${f.framework} ${f.control}
18715
+ report += ` Framework: ${f.framework} ${f.control}
17944
18716
  `;
17945
- if (f.file) report += ` File: ${f.file}
18717
+ if (f.file) report += ` File: ${f.file}
17946
18718
  `;
17947
- report += ` Remediation: ${f.remediation}
18719
+ report += ` Remediation: ${f.remediation}
17948
18720
 
17949
18721
  `;
17950
- }
17951
- }
17952
- report += "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n";
17953
- report += " 2. QUALITY ASSESSMENT\n";
17954
- report += "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n";
17955
- report += "Framework: ISO/IEC 25010 Software Quality Model\n\n";
17956
- if (quality.length === 0) {
17957
- report += "No quality findings. All checks passed.\n\n";
17958
- } else {
17959
- for (const f of quality) {
17960
- report += `[${f.severity.toUpperCase()}] ${f.id}: ${f.message}
18722
+ }
18723
+ }
18724
+ report += "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n";
18725
+ report += " 2. QUALITY ASSESSMENT\n";
18726
+ report += "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n";
18727
+ report += "Framework: ISO/IEC 25010 Software Quality Model\n\n";
18728
+ if (quality.length === 0) {
18729
+ report += "No quality findings. All checks passed.\n\n";
18730
+ } else {
18731
+ for (const f of quality) {
18732
+ report += `[${f.severity.toUpperCase()}] ${f.id}: ${f.message}
17961
18733
  `;
17962
- report += ` Framework: ${f.framework} - ${f.control}
18734
+ report += ` Framework: ${f.framework} - ${f.control}
17963
18735
  `;
17964
- if (f.file) report += ` File: ${f.file}
18736
+ if (f.file) report += ` File: ${f.file}
17965
18737
  `;
17966
- report += ` Remediation: ${f.remediation}
18738
+ report += ` Remediation: ${f.remediation}
17967
18739
 
17968
18740
  `;
17969
- }
17970
- }
17971
- report += "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n";
17972
- report += " 3. PERFORMANCE ASSESSMENT\n";
17973
- report += "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n";
17974
- report += "Framework: OSI Model Layer 7 (Application) Analysis\n\n";
17975
- if (performance.length === 0) {
17976
- report += "No performance findings. All checks passed.\n\n";
17977
- } else {
17978
- for (const f of performance) {
17979
- report += `[${f.severity.toUpperCase()}] ${f.id}: ${f.message}
18741
+ }
18742
+ }
18743
+ report += "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n";
18744
+ report += " 3. PERFORMANCE ASSESSMENT\n";
18745
+ report += "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n";
18746
+ report += "Framework: OSI Model Layer 7 (Application) Analysis\n\n";
18747
+ if (performance.length === 0) {
18748
+ report += "No performance findings. All checks passed.\n\n";
18749
+ } else {
18750
+ for (const f of performance) {
18751
+ report += `[${f.severity.toUpperCase()}] ${f.id}: ${f.message}
17980
18752
  `;
17981
- report += ` Framework: ${f.framework} - ${f.control}
18753
+ report += ` Framework: ${f.framework} - ${f.control}
17982
18754
  `;
17983
- if (f.file) report += ` File: ${f.file}
18755
+ if (f.file) report += ` File: ${f.file}
17984
18756
  `;
17985
- report += ` Remediation: ${f.remediation}
18757
+ report += ` Remediation: ${f.remediation}
17986
18758
 
17987
18759
  `;
17988
- }
17989
- }
17990
- report += "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n";
17991
- report += " 4. RECOMMENDATIONS\n";
17992
- report += "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n";
17993
- const criticalFindings = all.filter((f) => f.severity === "critical" || f.severity === "high");
17994
- if (criticalFindings.length === 0) {
17995
- report += "No critical or high-severity findings. Project meets baseline security standards.\n\n";
17996
- } else {
17997
- report += "Priority actions (critical/high severity):\n";
17998
- for (const f of criticalFindings) {
17999
- report += ` - ${f.id}: ${f.message} (${f.file ?? "N/A"})
18000
- `;
18001
- }
18002
- report += "\n";
18003
- }
18004
- report += "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n";
18005
- report += " 5. FRAMEWORK COMPLIANCE MATRIX\n";
18006
- report += "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n";
18007
- report += "OWASP Top 10 (2021):\n";
18008
- const owaspIds = ["A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08", "A09", "A10"];
18009
- const owaspNames = ["Broken Access Control", "Cryptographic Failures", "Injection", "Insecure Design", "Security Misconfiguration", "Vulnerable Components", "Auth Failures", "Integrity Failures", "Logging Failures", "SSRF"];
18010
- for (let i3 = 0; i3 < owaspIds.length; i3++) {
18011
- const found = security2.some((f) => f.control === owaspIds[i3]);
18012
- report += ` ${owaspIds[i3]} ${owaspNames[i3]}: ${found ? "FINDINGS" : "PASS"}
18013
- `;
18014
- }
18015
- report += "\nnpm audit:\n";
18016
- const npmFindings = security2.filter((f) => f.framework === "npm audit");
18017
- report += ` Total vulnerabilities: ${npmFindings.filter((f) => f.id !== "NPM-SUM").length}
18018
- `;
18019
- report += ` Status: ${npmFindings.length > 0 ? "FINDINGS" : "PASS"}
18020
- `;
18021
- report += "\n\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n";
18022
- report += " END OF REPORT\n";
18023
- report += "\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n";
18024
- return report;
18025
- }
18026
- function audit(options = {}) {
18027
- const projectPath = options.projectPath ?? process.cwd();
18028
- const allFindings = scanDir(projectPath, projectPath);
18029
- allFindings.push(...runNpmAudit(projectPath));
18030
- const quality = allFindings.filter((f) => f.category === "quality");
18031
- const security2 = allFindings.filter((f) => f.category === "security");
18032
- const performance = allFindings.filter((f) => f.category === "performance");
18033
- const errorCount = allFindings.filter((f) => f.severity === "critical" || f.severity === "high").length;
18034
- const totalFindings = allFindings.length;
18035
- const score = Math.max(0, 100 - errorCount * 10 - (totalFindings - errorCount) * 2);
18036
- const grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : score >= 60 ? "D" : "F";
18037
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
18038
- const result = {
18039
- projectPath,
18040
- timestamp,
18041
- quality,
18042
- security: security2,
18043
- performance,
18044
- score,
18045
- grade,
18046
- summary: `Audit complete: ${totalFindings} findings (${errorCount} critical/high). Score: ${score}/100 (Grade: ${grade}).`,
18047
- report: ""
18048
- };
18049
- result.report = generateReport({ quality, security: security2, performance, score, grade, projectPath, timestamp });
18050
- if (options.onFinding) {
18051
- for (const f of allFindings) {
18052
- options.onFinding(f);
18053
- }
18054
- }
18055
- return {
18056
- name: "audit",
18057
- version: "0.3.0",
18058
- description: "Professional IT audit: quality, security, performance, npm vulnerabilities.",
18059
- hooks: {
18060
- onAudit(_result) {
18760
+ }
18061
18761
  }
18062
- },
18063
- run: /* @__PURE__ */ __name(() => result, "run"),
18064
- report: /* @__PURE__ */ __name(() => result.report, "report")
18065
- };
18066
- }
18067
- var init_audit = __esm({
18068
- "plugins/audit/index.ts"() {
18069
- __name(stripCode, "stripCode");
18070
- __name(hasEval, "hasEval");
18071
- __name(isInNonCode, "isInNonCode");
18072
- __name(collectDangerousNames, "collectDangerousNames");
18073
- __name(hasProcessExec, "hasProcessExec");
18074
- __name(scanFile, "scanFile");
18075
- __name(scanDir, "scanDir");
18076
- __name(runNpmAudit, "runNpmAudit");
18077
- __name(generateReport, "generateReport");
18762
+ report += "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n";
18763
+ report += " 4. RECOMMENDATIONS\n";
18764
+ report += "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n";
18765
+ const criticalFindings = all.filter((f) => f.severity === "critical" || f.severity === "high");
18766
+ if (criticalFindings.length === 0) {
18767
+ report += "No critical or high-severity findings. Project meets baseline security standards.\n\n";
18768
+ } else {
18769
+ report += "Priority actions (critical/high severity):\n";
18770
+ for (const f of criticalFindings) {
18771
+ report += ` - ${f.id}: ${f.message} (${f.file ?? "N/A"})
18772
+ `;
18773
+ }
18774
+ report += "\n";
18775
+ }
18776
+ report += "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n";
18777
+ report += " 5. FRAMEWORK COMPLIANCE MATRIX\n";
18778
+ report += "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n";
18779
+ report += "OWASP Top 10 (2021):\n";
18780
+ const owaspIds = ["A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08", "A09", "A10"];
18781
+ const owaspNames = ["Broken Access Control", "Cryptographic Failures", "Injection", "Insecure Design", "Security Misconfiguration", "Vulnerable Components", "Auth Failures", "Integrity Failures", "Logging Failures", "SSRF"];
18782
+ for (let i3 = 0; i3 < owaspIds.length; i3++) {
18783
+ const found = security2.some((f) => f.control === owaspIds[i3]);
18784
+ report += ` ${owaspIds[i3]} ${owaspNames[i3]}: ${found ? "FINDINGS" : "PASS"}
18785
+ `;
18786
+ }
18787
+ report += "\nnpm audit:\n";
18788
+ const npmFindings = security2.filter((f) => f.framework === "npm audit");
18789
+ report += ` Total vulnerabilities: ${npmFindings.filter((f) => f.id !== "NPM-SUM").length}
18790
+ `;
18791
+ report += ` Status: ${npmFindings.length > 0 ? "FINDINGS" : "PASS"}
18792
+ `;
18793
+ report += "\n\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n";
18794
+ report += " END OF REPORT\n";
18795
+ report += "\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n";
18796
+ return report;
18797
+ }, "generateReport");
18078
18798
  __name(audit, "audit");
18079
18799
  }
18080
18800
  });
18081
- function resolveDbPath(override) {
18082
- if (override) return override;
18083
- const root = resolveDotMemStorageRoot();
18084
- const dir = path8__default.default.join(root, "neurocore");
18085
- if (!fs__default.default.existsSync(dir)) fs__default.default.mkdirSync(dir, { recursive: true });
18086
- return path8__default.default.join(dir, "neurocore.db");
18087
- }
18088
- var DatabaseSync, SCHEMA_VERSION, NeuroCoreSqliteStore, createSqliteStore;
18801
+ var SCHEMA_VERSION, SchemaVersion, Episode, Assessment, Pattern, Proposal, Adaptation, Verification, resolveDbPath, ENTITIES, NeuroCoreSqliteStore, createSqliteStore;
18089
18802
  var init_sqlite = __esm({
18090
18803
  "plugins/neurocore/storage/sqlite.ts"() {
18091
18804
  init_storage_location();
18092
- ({ DatabaseSync } = globalThis.process?.getBuiltinModule?.("node:sqlite") ?? __require("sqlite"));
18093
18805
  SCHEMA_VERSION = 1;
18094
- __name(resolveDbPath, "resolveDbPath");
18806
+ SchemaVersion = class {
18807
+ version;
18808
+ };
18809
+ __name(SchemaVersion, "SchemaVersion");
18810
+ __decorateClass([
18811
+ typeorm.PrimaryColumn("integer")
18812
+ ], SchemaVersion.prototype, "version", 2);
18813
+ SchemaVersion = __decorateClass([
18814
+ typeorm.Entity("schema_version")
18815
+ ], SchemaVersion);
18816
+ Episode = class {
18817
+ id;
18818
+ scope;
18819
+ context;
18820
+ objective;
18821
+ observation;
18822
+ outcome;
18823
+ provenance;
18824
+ createdAt;
18825
+ memoryRefs;
18826
+ evidence;
18827
+ };
18828
+ __name(Episode, "Episode");
18829
+ __decorateClass([
18830
+ typeorm.PrimaryColumn("text")
18831
+ ], Episode.prototype, "id", 2);
18832
+ __decorateClass([
18833
+ typeorm.Column("text")
18834
+ ], Episode.prototype, "scope", 2);
18835
+ __decorateClass([
18836
+ typeorm.Column("text")
18837
+ ], Episode.prototype, "context", 2);
18838
+ __decorateClass([
18839
+ typeorm.Column("text")
18840
+ ], Episode.prototype, "objective", 2);
18841
+ __decorateClass([
18842
+ typeorm.Column("text")
18843
+ ], Episode.prototype, "observation", 2);
18844
+ __decorateClass([
18845
+ typeorm.Column("text")
18846
+ ], Episode.prototype, "outcome", 2);
18847
+ __decorateClass([
18848
+ typeorm.Column("text")
18849
+ ], Episode.prototype, "provenance", 2);
18850
+ __decorateClass([
18851
+ typeorm.Column({ name: "created_at", type: "text" })
18852
+ ], Episode.prototype, "createdAt", 2);
18853
+ __decorateClass([
18854
+ typeorm.Column({ name: "memory_refs", type: "text", nullable: true })
18855
+ ], Episode.prototype, "memoryRefs", 2);
18856
+ __decorateClass([
18857
+ typeorm.Column({ name: "evidence", type: "text", nullable: true })
18858
+ ], Episode.prototype, "evidence", 2);
18859
+ Episode = __decorateClass([
18860
+ typeorm.Entity("episodes")
18861
+ ], Episode);
18862
+ Assessment = class {
18863
+ id;
18864
+ episodeId;
18865
+ assessmentType;
18866
+ findings;
18867
+ evidence;
18868
+ structuredEvidence;
18869
+ confidence;
18870
+ limitations;
18871
+ assessedAt;
18872
+ assessor;
18873
+ };
18874
+ __name(Assessment, "Assessment");
18875
+ __decorateClass([
18876
+ typeorm.PrimaryColumn("text")
18877
+ ], Assessment.prototype, "id", 2);
18878
+ __decorateClass([
18879
+ typeorm.Column({ name: "episode_id", type: "text" })
18880
+ ], Assessment.prototype, "episodeId", 2);
18881
+ __decorateClass([
18882
+ typeorm.Column({ name: "assessment_type", type: "text" })
18883
+ ], Assessment.prototype, "assessmentType", 2);
18884
+ __decorateClass([
18885
+ typeorm.Column("text")
18886
+ ], Assessment.prototype, "findings", 2);
18887
+ __decorateClass([
18888
+ typeorm.Column("text")
18889
+ ], Assessment.prototype, "evidence", 2);
18890
+ __decorateClass([
18891
+ typeorm.Column({ name: "structured_evidence", type: "text", nullable: true })
18892
+ ], Assessment.prototype, "structuredEvidence", 2);
18893
+ __decorateClass([
18894
+ typeorm.Column("real")
18895
+ ], Assessment.prototype, "confidence", 2);
18896
+ __decorateClass([
18897
+ typeorm.Column("text")
18898
+ ], Assessment.prototype, "limitations", 2);
18899
+ __decorateClass([
18900
+ typeorm.Column({ name: "assessed_at", type: "text" })
18901
+ ], Assessment.prototype, "assessedAt", 2);
18902
+ __decorateClass([
18903
+ typeorm.Column("text")
18904
+ ], Assessment.prototype, "assessor", 2);
18905
+ Assessment = __decorateClass([
18906
+ typeorm.Entity("assessments")
18907
+ ], Assessment);
18908
+ Pattern = class {
18909
+ id;
18910
+ scope;
18911
+ description;
18912
+ episodeIds;
18913
+ supportingEvidence;
18914
+ contradictingEvidence;
18915
+ confidence;
18916
+ status;
18917
+ revision;
18918
+ firstObserved;
18919
+ lastObserved;
18920
+ };
18921
+ __name(Pattern, "Pattern");
18922
+ __decorateClass([
18923
+ typeorm.PrimaryColumn("text")
18924
+ ], Pattern.prototype, "id", 2);
18925
+ __decorateClass([
18926
+ typeorm.Column("text")
18927
+ ], Pattern.prototype, "scope", 2);
18928
+ __decorateClass([
18929
+ typeorm.Column("text")
18930
+ ], Pattern.prototype, "description", 2);
18931
+ __decorateClass([
18932
+ typeorm.Column({ name: "episode_ids", type: "text" })
18933
+ ], Pattern.prototype, "episodeIds", 2);
18934
+ __decorateClass([
18935
+ typeorm.Column({ name: "supporting_evidence", type: "text" })
18936
+ ], Pattern.prototype, "supportingEvidence", 2);
18937
+ __decorateClass([
18938
+ typeorm.Column({ name: "contradicting_evidence", type: "text" })
18939
+ ], Pattern.prototype, "contradictingEvidence", 2);
18940
+ __decorateClass([
18941
+ typeorm.Column("real")
18942
+ ], Pattern.prototype, "confidence", 2);
18943
+ __decorateClass([
18944
+ typeorm.Column("text")
18945
+ ], Pattern.prototype, "status", 2);
18946
+ __decorateClass([
18947
+ typeorm.Column("integer")
18948
+ ], Pattern.prototype, "revision", 2);
18949
+ __decorateClass([
18950
+ typeorm.Column({ name: "first_observed", type: "text", nullable: true })
18951
+ ], Pattern.prototype, "firstObserved", 2);
18952
+ __decorateClass([
18953
+ typeorm.Column({ name: "last_observed", type: "text", nullable: true })
18954
+ ], Pattern.prototype, "lastObserved", 2);
18955
+ Pattern = __decorateClass([
18956
+ typeorm.Entity("patterns")
18957
+ ], Pattern);
18958
+ Proposal = class {
18959
+ id;
18960
+ patternId;
18961
+ problem;
18962
+ proposedStrategy;
18963
+ applicableContext;
18964
+ expectedOutcome;
18965
+ verificationCriteria;
18966
+ evidence;
18967
+ status;
18968
+ revision;
18969
+ createdAt;
18970
+ };
18971
+ __name(Proposal, "Proposal");
18972
+ __decorateClass([
18973
+ typeorm.PrimaryColumn("text")
18974
+ ], Proposal.prototype, "id", 2);
18975
+ __decorateClass([
18976
+ typeorm.Column({ name: "pattern_id", type: "text", nullable: true })
18977
+ ], Proposal.prototype, "patternId", 2);
18978
+ __decorateClass([
18979
+ typeorm.Column("text")
18980
+ ], Proposal.prototype, "problem", 2);
18981
+ __decorateClass([
18982
+ typeorm.Column({ name: "proposed_strategy", type: "text" })
18983
+ ], Proposal.prototype, "proposedStrategy", 2);
18984
+ __decorateClass([
18985
+ typeorm.Column({ name: "applicable_context", type: "text" })
18986
+ ], Proposal.prototype, "applicableContext", 2);
18987
+ __decorateClass([
18988
+ typeorm.Column({ name: "expected_outcome", type: "text" })
18989
+ ], Proposal.prototype, "expectedOutcome", 2);
18990
+ __decorateClass([
18991
+ typeorm.Column({ name: "verification_criteria", type: "text" })
18992
+ ], Proposal.prototype, "verificationCriteria", 2);
18993
+ __decorateClass([
18994
+ typeorm.Column("text")
18995
+ ], Proposal.prototype, "evidence", 2);
18996
+ __decorateClass([
18997
+ typeorm.Column("text")
18998
+ ], Proposal.prototype, "status", 2);
18999
+ __decorateClass([
19000
+ typeorm.Column("integer")
19001
+ ], Proposal.prototype, "revision", 2);
19002
+ __decorateClass([
19003
+ typeorm.Column({ name: "created_at", type: "text" })
19004
+ ], Proposal.prototype, "createdAt", 2);
19005
+ Proposal = __decorateClass([
19006
+ typeorm.Entity("proposals")
19007
+ ], Proposal);
19008
+ Adaptation = class {
19009
+ id;
19010
+ proposalId;
19011
+ strategyVersion;
19012
+ activationScope;
19013
+ status;
19014
+ approvedBy;
19015
+ activatedAt;
19016
+ deactivatedAt;
19017
+ };
19018
+ __name(Adaptation, "Adaptation");
19019
+ __decorateClass([
19020
+ typeorm.PrimaryColumn("text")
19021
+ ], Adaptation.prototype, "id", 2);
19022
+ __decorateClass([
19023
+ typeorm.Column({ name: "proposal_id", type: "text" })
19024
+ ], Adaptation.prototype, "proposalId", 2);
19025
+ __decorateClass([
19026
+ typeorm.Column({ name: "strategy_version", type: "integer" })
19027
+ ], Adaptation.prototype, "strategyVersion", 2);
19028
+ __decorateClass([
19029
+ typeorm.Column({ name: "activation_scope", type: "text" })
19030
+ ], Adaptation.prototype, "activationScope", 2);
19031
+ __decorateClass([
19032
+ typeorm.Column("text")
19033
+ ], Adaptation.prototype, "status", 2);
19034
+ __decorateClass([
19035
+ typeorm.Column({ name: "approved_by", type: "text", nullable: true })
19036
+ ], Adaptation.prototype, "approvedBy", 2);
19037
+ __decorateClass([
19038
+ typeorm.Column({ name: "activated_at", type: "text" })
19039
+ ], Adaptation.prototype, "activatedAt", 2);
19040
+ __decorateClass([
19041
+ typeorm.Column({ name: "deactivated_at", type: "text", nullable: true })
19042
+ ], Adaptation.prototype, "deactivatedAt", 2);
19043
+ Adaptation = __decorateClass([
19044
+ typeorm.Entity("adaptations")
19045
+ ], Adaptation);
19046
+ Verification = class {
19047
+ id;
19048
+ adaptationId;
19049
+ measurement;
19050
+ baseline;
19051
+ observedOutcome;
19052
+ comparisonContext;
19053
+ conclusion;
19054
+ limitations;
19055
+ verifiedAt;
19056
+ };
19057
+ __name(Verification, "Verification");
19058
+ __decorateClass([
19059
+ typeorm.PrimaryColumn("text")
19060
+ ], Verification.prototype, "id", 2);
19061
+ __decorateClass([
19062
+ typeorm.Column({ name: "adaptation_id", type: "text" })
19063
+ ], Verification.prototype, "adaptationId", 2);
19064
+ __decorateClass([
19065
+ typeorm.Column("text")
19066
+ ], Verification.prototype, "measurement", 2);
19067
+ __decorateClass([
19068
+ typeorm.Column("text")
19069
+ ], Verification.prototype, "baseline", 2);
19070
+ __decorateClass([
19071
+ typeorm.Column({ name: "observed_outcome", type: "text" })
19072
+ ], Verification.prototype, "observedOutcome", 2);
19073
+ __decorateClass([
19074
+ typeorm.Column({ name: "comparison_context", type: "text" })
19075
+ ], Verification.prototype, "comparisonContext", 2);
19076
+ __decorateClass([
19077
+ typeorm.Column("text")
19078
+ ], Verification.prototype, "conclusion", 2);
19079
+ __decorateClass([
19080
+ typeorm.Column("text")
19081
+ ], Verification.prototype, "limitations", 2);
19082
+ __decorateClass([
19083
+ typeorm.Column({ name: "verified_at", type: "text" })
19084
+ ], Verification.prototype, "verifiedAt", 2);
19085
+ Verification = __decorateClass([
19086
+ typeorm.Entity("verifications")
19087
+ ], Verification);
19088
+ resolveDbPath = /* @__PURE__ */ __name((override) => {
19089
+ if (override) return override;
19090
+ const root = resolveDotMemStorageRoot();
19091
+ const dir = path5__default.default.join(root, "neurocore");
19092
+ if (!fs6__default.default.existsSync(dir)) fs6__default.default.mkdirSync(dir, { recursive: true });
19093
+ return path5__default.default.join(dir, "neurocore.db");
19094
+ }, "resolveDbPath");
19095
+ ENTITIES = [
19096
+ SchemaVersion,
19097
+ Episode,
19098
+ Assessment,
19099
+ Pattern,
19100
+ Proposal,
19101
+ Adaptation,
19102
+ Verification
19103
+ ];
18095
19104
  NeuroCoreSqliteStore = class {
18096
19105
  static {
18097
19106
  __name(this, "NeuroCoreSqliteStore");
18098
19107
  }
18099
- db;
19108
+ ds = null;
18100
19109
  dbPath;
19110
+ initialized = false;
18101
19111
  constructor(dbPath) {
18102
19112
  this.dbPath = resolveDbPath(dbPath);
18103
- const dir = path8__default.default.dirname(this.dbPath);
18104
- if (!fs__default.default.existsSync(dir)) fs__default.default.mkdirSync(dir, { recursive: true });
18105
- this.db = new DatabaseSync(this.dbPath);
18106
- this.db.exec("PRAGMA journal_mode = WAL;");
18107
- this.db.exec("PRAGMA busy_timeout = 5000;");
18108
- this.migrate();
18109
- }
18110
- migrate() {
18111
- this.db.exec(`CREATE TABLE IF NOT EXISTS schema_version (version INTEGER PRIMARY KEY);`);
18112
- const row = this.db.prepare("SELECT version FROM schema_version LIMIT 1").get();
19113
+ const dir = path5__default.default.dirname(this.dbPath);
19114
+ if (!fs6__default.default.existsSync(dir)) fs6__default.default.mkdirSync(dir, { recursive: true });
19115
+ }
19116
+ async init() {
19117
+ if (this.initialized) return;
19118
+ this.ds = new typeorm.DataSource({
19119
+ type: "better-sqlite3",
19120
+ database: this.dbPath,
19121
+ entities: ENTITIES,
19122
+ synchronize: true,
19123
+ logging: false
19124
+ });
19125
+ await this.ds.initialize();
19126
+ await this.migrate();
19127
+ this.initialized = true;
19128
+ }
19129
+ async migrate() {
19130
+ if (!this.ds) throw new Error("DataSource not initialized");
19131
+ const svRepo = this.ds.getRepository(SchemaVersion);
19132
+ const row = await svRepo.findOne({ where: {} });
18113
19133
  const current = row ? row.version : 0;
18114
- if (current === 0) {
18115
- this.db.exec(`
18116
- CREATE TABLE episodes (
18117
- id TEXT PRIMARY KEY,
18118
- scope TEXT NOT NULL,
18119
- context TEXT NOT NULL,
18120
- objective TEXT NOT NULL,
18121
- observation TEXT NOT NULL,
18122
- outcome TEXT NOT NULL,
18123
- provenance TEXT NOT NULL,
18124
- created_at TEXT NOT NULL,
18125
- memory_refs TEXT,
18126
- evidence TEXT
18127
- );
18128
- CREATE TABLE assessments (
18129
- id TEXT PRIMARY KEY,
18130
- episode_id TEXT NOT NULL,
18131
- assessment_type TEXT NOT NULL,
18132
- findings TEXT NOT NULL,
18133
- evidence TEXT NOT NULL,
18134
- structured_evidence TEXT,
18135
- confidence REAL NOT NULL,
18136
- limitations TEXT NOT NULL,
18137
- assessed_at TEXT NOT NULL,
18138
- assessor TEXT NOT NULL,
18139
- FOREIGN KEY (episode_id) REFERENCES episodes(id)
18140
- );
18141
- CREATE TABLE patterns (
18142
- id TEXT PRIMARY KEY,
18143
- scope TEXT NOT NULL,
18144
- description TEXT NOT NULL,
18145
- episode_ids TEXT NOT NULL,
18146
- supporting_evidence TEXT NOT NULL,
18147
- contradicting_evidence TEXT NOT NULL,
18148
- confidence REAL NOT NULL,
18149
- status TEXT NOT NULL,
18150
- revision INTEGER NOT NULL,
18151
- first_observed TEXT,
18152
- last_observed TEXT
18153
- );
18154
- CREATE TABLE proposals (
18155
- id TEXT PRIMARY KEY,
18156
- pattern_id TEXT,
18157
- problem TEXT NOT NULL,
18158
- proposed_strategy TEXT NOT NULL,
18159
- applicable_context TEXT NOT NULL,
18160
- expected_outcome TEXT NOT NULL,
18161
- verification_criteria TEXT NOT NULL,
18162
- evidence TEXT NOT NULL,
18163
- status TEXT NOT NULL,
18164
- revision INTEGER NOT NULL,
18165
- created_at TEXT NOT NULL
18166
- );
18167
- CREATE TABLE adaptations (
18168
- id TEXT PRIMARY KEY,
18169
- proposal_id TEXT NOT NULL,
18170
- strategy_version INTEGER NOT NULL,
18171
- activation_scope TEXT NOT NULL,
18172
- status TEXT NOT NULL,
18173
- approved_by TEXT,
18174
- activated_at TEXT NOT NULL,
18175
- deactivated_at TEXT
18176
- );
18177
- CREATE TABLE verifications (
18178
- id TEXT PRIMARY KEY,
18179
- adaptation_id TEXT NOT NULL,
18180
- measurement TEXT NOT NULL,
18181
- baseline TEXT NOT NULL,
18182
- observed_outcome TEXT NOT NULL,
18183
- comparison_context TEXT NOT NULL,
18184
- conclusion TEXT NOT NULL,
18185
- limitations TEXT NOT NULL,
18186
- verified_at TEXT NOT NULL
18187
- );
18188
- INSERT INTO schema_version (version) VALUES (${SCHEMA_VERSION});
18189
- `);
18190
- } else if (current !== SCHEMA_VERSION) {
18191
- throw new Error(`Unsupported NeuroCore schema version: ${current}`);
19134
+ if (current !== SCHEMA_VERSION) {
19135
+ if (current === 0) {
19136
+ await svRepo.insert({ version: SCHEMA_VERSION });
19137
+ } else {
19138
+ throw new Error(`Unsupported NeuroCore schema version: ${current}`);
19139
+ }
19140
+ }
19141
+ }
19142
+ ensureInit() {
19143
+ if (!this.initialized || !this.ds) {
19144
+ throw new Error("Store not initialized. Call init() before using the store.");
18192
19145
  }
18193
19146
  }
18194
- // NeuroCoreStore implementation
18195
- saveEpisode(episode) {
18196
- const stmt = this.db.prepare(`INSERT INTO episodes (id, scope, context, objective, observation, outcome, provenance, created_at, memory_refs, evidence) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
19147
+ async saveEpisode(episode) {
19148
+ this.ensureInit();
19149
+ const repo = this.ds.getRepository(Episode);
18197
19150
  try {
18198
- stmt.run(
18199
- episode.id,
18200
- episode.scope,
18201
- episode.context,
18202
- episode.objective,
18203
- episode.observation,
18204
- episode.outcome,
18205
- episode.provenance,
18206
- episode.createdAt,
18207
- JSON.stringify(episode.memoryRefs ?? []),
18208
- JSON.stringify(episode.evidence ?? null)
18209
- );
19151
+ await repo.insert({
19152
+ id: episode.id,
19153
+ scope: episode.scope,
19154
+ context: episode.context,
19155
+ objective: episode.objective,
19156
+ observation: episode.observation,
19157
+ outcome: episode.outcome,
19158
+ provenance: episode.provenance,
19159
+ createdAt: episode.createdAt,
19160
+ memoryRefs: JSON.stringify(episode.memoryRefs ?? []),
19161
+ evidence: episode.evidence != null ? JSON.stringify(episode.evidence) : null
19162
+ });
18210
19163
  } catch (e) {
18211
19164
  if (String(e).includes("UNIQUE") || String(e).includes("PRIMARY KEY")) throw new Error(`duplicate episode id: ${episode.id}`);
18212
19165
  throw e;
18213
19166
  }
18214
19167
  }
18215
- getEpisode(id) {
18216
- const row = this.db.prepare("SELECT * FROM episodes WHERE id = ?").get(id);
19168
+ async getEpisode(id) {
19169
+ this.ensureInit();
19170
+ const repo = this.ds.getRepository(Episode);
19171
+ const row = await repo.findOne({ where: { id } });
18217
19172
  if (!row) return void 0;
18218
19173
  return {
18219
19174
  id: row.id,
@@ -18223,24 +19178,17 @@ var init_sqlite = __esm({
18223
19178
  observation: row.observation,
18224
19179
  outcome: row.outcome,
18225
19180
  provenance: row.provenance,
18226
- createdAt: row.created_at,
18227
- memoryRefs: JSON.parse(row.memory_refs || "[]"),
19181
+ createdAt: row.createdAt,
19182
+ memoryRefs: JSON.parse(row.memoryRefs ?? "[]"),
18228
19183
  evidence: row.evidence ? JSON.parse(row.evidence) : void 0
18229
19184
  };
18230
19185
  }
18231
- listEpisodes(options) {
18232
- let sql = "SELECT * FROM episodes";
18233
- const params = [];
18234
- if (options?.scope) {
18235
- sql += " WHERE scope = ?";
18236
- params.push(options.scope);
18237
- }
18238
- sql += " ORDER BY created_at ASC";
18239
- if (options?.limit && options.limit > 0) {
18240
- sql += " LIMIT ?";
18241
- params.push(options.limit);
18242
- }
18243
- const rows = this.db.prepare(sql).all(...params);
19186
+ async listEpisodes(options) {
19187
+ this.ensureInit();
19188
+ const repo = this.ds.getRepository(Episode);
19189
+ const where = {};
19190
+ if (options?.scope) where.scope = options.scope;
19191
+ const rows = await repo.find({ where, order: { createdAt: "ASC" }, take: options?.limit });
18244
19192
  return rows.map((row) => ({
18245
19193
  id: row.id,
18246
19194
  scope: row.scope,
@@ -18249,226 +19197,256 @@ var init_sqlite = __esm({
18249
19197
  observation: row.observation,
18250
19198
  outcome: row.outcome,
18251
19199
  provenance: row.provenance,
18252
- createdAt: row.created_at,
18253
- memoryRefs: JSON.parse(row.memory_refs || "[]"),
19200
+ createdAt: row.createdAt,
19201
+ memoryRefs: JSON.parse(row.memoryRefs ?? "[]"),
18254
19202
  evidence: row.evidence ? JSON.parse(row.evidence) : void 0
18255
19203
  }));
18256
19204
  }
18257
- saveAssessment(a) {
18258
- const stmt = this.db.prepare(`INSERT INTO assessments (id, episode_id, assessment_type, findings, evidence, structured_evidence, confidence, limitations, assessed_at, assessor) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
19205
+ async saveAssessment(a) {
19206
+ this.ensureInit();
19207
+ const repo = this.ds.getRepository(Assessment);
18259
19208
  try {
18260
- stmt.run(
18261
- a.id,
18262
- a.episodeId,
18263
- a.assessmentType,
18264
- JSON.stringify(a.findings ?? []),
18265
- JSON.stringify(a.evidence ?? []),
18266
- a.structuredEvidence ? JSON.stringify(a.structuredEvidence) : null,
18267
- a.confidence,
18268
- JSON.stringify(a.limitations ?? []),
18269
- a.assessedAt,
18270
- a.assessor
18271
- );
19209
+ await repo.insert({
19210
+ id: a.id,
19211
+ episodeId: a.episodeId,
19212
+ assessmentType: a.assessmentType,
19213
+ findings: JSON.stringify(a.findings ?? []),
19214
+ evidence: JSON.stringify(a.evidence ?? []),
19215
+ structuredEvidence: a.structuredEvidence != null ? JSON.stringify(a.structuredEvidence) : null,
19216
+ confidence: a.confidence,
19217
+ limitations: JSON.stringify(a.limitations ?? []),
19218
+ assessedAt: a.assessedAt,
19219
+ assessor: a.assessor
19220
+ });
18272
19221
  } catch (e) {
18273
19222
  if (String(e).includes("UNIQUE") || String(e).includes("PRIMARY KEY")) throw new Error(`duplicate assessment id: ${a.id}`);
18274
19223
  throw e;
18275
19224
  }
18276
19225
  }
18277
- getAssessment(id) {
18278
- const row = this.db.prepare("SELECT * FROM assessments WHERE id = ?").get(id);
19226
+ async getAssessment(id) {
19227
+ this.ensureInit();
19228
+ const repo = this.ds.getRepository(Assessment);
19229
+ const row = await repo.findOne({ where: { id } });
18279
19230
  if (!row) return void 0;
18280
19231
  return {
18281
19232
  id: row.id,
18282
- episodeId: row.episode_id,
18283
- assessmentType: row.assessment_type,
19233
+ episodeId: row.episodeId,
19234
+ assessmentType: row.assessmentType,
18284
19235
  findings: JSON.parse(row.findings),
18285
19236
  evidence: JSON.parse(row.evidence),
18286
- structuredEvidence: row.structured_evidence ? JSON.parse(row.structured_evidence) : void 0,
19237
+ structuredEvidence: row.structuredEvidence ? JSON.parse(row.structuredEvidence) : void 0,
18287
19238
  confidence: row.confidence,
18288
19239
  limitations: JSON.parse(row.limitations),
18289
- assessedAt: row.assessed_at,
19240
+ assessedAt: row.assessedAt,
18290
19241
  assessor: row.assessor
18291
19242
  };
18292
19243
  }
18293
- listAssessmentsByEpisode(episodeId) {
18294
- const rows = this.db.prepare("SELECT * FROM assessments WHERE episode_id = ? ORDER BY assessed_at ASC").all(episodeId);
19244
+ async listAssessmentsByEpisode(episodeId) {
19245
+ this.ensureInit();
19246
+ const repo = this.ds.getRepository(Assessment);
19247
+ const rows = await repo.find({ where: { episodeId }, order: { assessedAt: "ASC" } });
18295
19248
  return rows.map((row) => ({
18296
19249
  id: row.id,
18297
- episodeId: row.episode_id,
18298
- assessmentType: row.assessment_type,
19250
+ episodeId: row.episodeId,
19251
+ assessmentType: row.assessmentType,
18299
19252
  findings: JSON.parse(row.findings),
18300
19253
  evidence: JSON.parse(row.evidence),
18301
- structuredEvidence: row.structured_evidence ? JSON.parse(row.structured_evidence) : void 0,
19254
+ structuredEvidence: row.structuredEvidence ? JSON.parse(row.structuredEvidence) : void 0,
18302
19255
  confidence: row.confidence,
18303
19256
  limitations: JSON.parse(row.limitations),
18304
- assessedAt: row.assessed_at,
19257
+ assessedAt: row.assessedAt,
18305
19258
  assessor: row.assessor
18306
19259
  }));
18307
19260
  }
18308
- // Patterns
18309
- savePattern(p) {
18310
- const stmt = this.db.prepare(`INSERT INTO patterns (id, scope, description, episode_ids, supporting_evidence, contradicting_evidence, confidence, status, revision, first_observed, last_observed) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
19261
+ async savePattern(p) {
19262
+ this.ensureInit();
19263
+ const repo = this.ds.getRepository(Pattern);
18311
19264
  try {
18312
- stmt.run(
18313
- p.id,
18314
- p.scope,
18315
- p.description,
18316
- JSON.stringify(p.episodeIds ?? []),
18317
- JSON.stringify(p.supportingEvidence ?? []),
18318
- JSON.stringify(p.contradictingEvidence ?? []),
18319
- p.confidence,
18320
- p.status,
18321
- p.revision,
18322
- p.firstObserved ?? null,
18323
- p.lastObserved ?? null
18324
- );
19265
+ await repo.insert({
19266
+ id: p.id,
19267
+ scope: p.scope,
19268
+ description: p.description,
19269
+ episodeIds: JSON.stringify(p.episodeIds ?? []),
19270
+ supportingEvidence: JSON.stringify(p.supportingEvidence ?? []),
19271
+ contradictingEvidence: JSON.stringify(p.contradictingEvidence ?? []),
19272
+ confidence: p.confidence,
19273
+ status: p.status,
19274
+ revision: p.revision,
19275
+ firstObserved: p.firstObserved ?? null,
19276
+ lastObserved: p.lastObserved ?? null
19277
+ });
18325
19278
  } catch (e) {
18326
19279
  if (String(e).includes("UNIQUE") || String(e).includes("PRIMARY KEY")) throw new Error(`duplicate pattern id: ${p.id}`);
18327
19280
  throw e;
18328
19281
  }
18329
19282
  }
18330
- getPattern(id) {
18331
- const row = this.db.prepare("SELECT * FROM patterns WHERE id = ?").get(id);
19283
+ async getPattern(id) {
19284
+ this.ensureInit();
19285
+ const repo = this.ds.getRepository(Pattern);
19286
+ const row = await repo.findOne({ where: { id } });
18332
19287
  if (!row) return void 0;
18333
19288
  return {
18334
19289
  id: row.id,
18335
19290
  scope: row.scope,
18336
19291
  description: row.description,
18337
- episodeIds: JSON.parse(row.episode_ids),
18338
- supportingEvidence: JSON.parse(row.supporting_evidence),
18339
- contradictingEvidence: JSON.parse(row.contradicting_evidence),
19292
+ episodeIds: JSON.parse(row.episodeIds),
19293
+ supportingEvidence: JSON.parse(row.supportingEvidence),
19294
+ contradictingEvidence: JSON.parse(row.contradictingEvidence),
18340
19295
  confidence: row.confidence,
18341
19296
  status: row.status,
18342
19297
  revision: row.revision,
18343
- firstObserved: row.first_observed,
18344
- lastObserved: row.last_observed
19298
+ firstObserved: row.firstObserved,
19299
+ lastObserved: row.lastObserved
18345
19300
  };
18346
19301
  }
18347
- listPatterns() {
18348
- const rows = this.db.prepare("SELECT * FROM patterns").all();
19302
+ async listPatterns() {
19303
+ this.ensureInit();
19304
+ const repo = this.ds.getRepository(Pattern);
19305
+ const rows = await repo.find();
18349
19306
  return rows.map((row) => ({
18350
19307
  id: row.id,
18351
19308
  scope: row.scope,
18352
19309
  description: row.description,
18353
- episodeIds: JSON.parse(row.episode_ids),
18354
- supportingEvidence: JSON.parse(row.supporting_evidence),
18355
- contradictingEvidence: JSON.parse(row.contradicting_evidence),
19310
+ episodeIds: JSON.parse(row.episodeIds),
19311
+ supportingEvidence: JSON.parse(row.supportingEvidence),
19312
+ contradictingEvidence: JSON.parse(row.contradictingEvidence),
18356
19313
  confidence: row.confidence,
18357
19314
  status: row.status,
18358
19315
  revision: row.revision,
18359
- firstObserved: row.first_observed,
18360
- lastObserved: row.last_observed
19316
+ firstObserved: row.firstObserved,
19317
+ lastObserved: row.lastObserved
18361
19318
  }));
18362
19319
  }
18363
- // Proposals
18364
- saveProposal(p) {
18365
- const stmt = this.db.prepare(`INSERT INTO proposals (id, pattern_id, problem, proposed_strategy, applicable_context, expected_outcome, verification_criteria, evidence, status, revision, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
19320
+ async saveProposal(p) {
19321
+ this.ensureInit();
19322
+ const repo = this.ds.getRepository(Proposal);
18366
19323
  try {
18367
- stmt.run(
18368
- p.id,
18369
- p.patternId ?? null,
18370
- p.problem,
18371
- p.proposedStrategy,
18372
- p.applicableContext,
18373
- p.expectedOutcome,
18374
- p.verificationCriteria,
18375
- JSON.stringify(p.evidence ?? []),
18376
- p.status,
18377
- p.revision,
18378
- p.createdAt
18379
- );
19324
+ await repo.insert({
19325
+ id: p.id,
19326
+ patternId: p.patternId ?? null,
19327
+ problem: p.problem,
19328
+ proposedStrategy: p.proposedStrategy,
19329
+ applicableContext: p.applicableContext,
19330
+ expectedOutcome: p.expectedOutcome,
19331
+ verificationCriteria: p.verificationCriteria,
19332
+ evidence: JSON.stringify(p.evidence ?? []),
19333
+ status: p.status,
19334
+ revision: p.revision,
19335
+ createdAt: p.createdAt
19336
+ });
18380
19337
  } catch (e) {
18381
19338
  if (String(e).includes("UNIQUE") || String(e).includes("PRIMARY KEY")) throw new Error(`duplicate proposal id: ${p.id}`);
18382
19339
  throw e;
18383
19340
  }
18384
19341
  }
18385
- getProposal(id) {
18386
- const row = this.db.prepare("SELECT * FROM proposals WHERE id = ?").get(id);
19342
+ async getProposal(id) {
19343
+ this.ensureInit();
19344
+ const repo = this.ds.getRepository(Proposal);
19345
+ const row = await repo.findOne({ where: { id } });
18387
19346
  if (!row) return void 0;
18388
19347
  return {
18389
19348
  id: row.id,
18390
- patternId: row.pattern_id,
19349
+ patternId: row.patternId,
18391
19350
  problem: row.problem,
18392
- proposedStrategy: row.proposed_strategy,
18393
- applicableContext: row.applicable_context,
18394
- expectedOutcome: row.expected_outcome,
18395
- verificationCriteria: row.verification_criteria,
19351
+ proposedStrategy: row.proposedStrategy,
19352
+ applicableContext: row.applicableContext,
19353
+ expectedOutcome: row.expectedOutcome,
19354
+ verificationCriteria: row.verificationCriteria,
18396
19355
  evidence: JSON.parse(row.evidence),
18397
19356
  status: row.status,
18398
19357
  revision: row.revision,
18399
- createdAt: row.created_at
19358
+ createdAt: row.createdAt
18400
19359
  };
18401
19360
  }
18402
- // Adaptations
18403
- saveAdaptation(a) {
18404
- const stmt = this.db.prepare(`INSERT INTO adaptations (id, proposal_id, strategy_version, activation_scope, status, approved_by, activated_at, deactivated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);
19361
+ async saveAdaptation(a) {
19362
+ this.ensureInit();
19363
+ const repo = this.ds.getRepository(Adaptation);
18405
19364
  try {
18406
- stmt.run(a.id, a.proposalId, a.strategyVersion, a.activationScope, a.status, a.approvedBy ?? null, a.activatedAt, a.deactivatedAt ?? null);
19365
+ await repo.insert({
19366
+ id: a.id,
19367
+ proposalId: a.proposalId,
19368
+ strategyVersion: a.strategyVersion,
19369
+ activationScope: a.activationScope,
19370
+ status: a.status,
19371
+ approvedBy: a.approvedBy ?? null,
19372
+ activatedAt: a.activatedAt,
19373
+ deactivatedAt: a.deactivatedAt ?? null
19374
+ });
18407
19375
  } catch (e) {
18408
19376
  if (String(e).includes("UNIQUE") || String(e).includes("PRIMARY KEY")) throw new Error(`duplicate adaptation id: ${a.id}`);
18409
19377
  throw e;
18410
19378
  }
18411
19379
  }
18412
- getAdaptation(id) {
18413
- const row = this.db.prepare("SELECT * FROM adaptations WHERE id = ?").get(id);
19380
+ async getAdaptation(id) {
19381
+ this.ensureInit();
19382
+ const repo = this.ds.getRepository(Adaptation);
19383
+ const row = await repo.findOne({ where: { id } });
18414
19384
  if (!row) return void 0;
18415
19385
  return {
18416
19386
  id: row.id,
18417
- proposalId: row.proposal_id,
18418
- strategyVersion: row.strategy_version,
18419
- activationScope: row.activation_scope,
19387
+ proposalId: row.proposalId,
19388
+ strategyVersion: row.strategyVersion,
19389
+ activationScope: row.activationScope,
18420
19390
  status: row.status,
18421
- approvedBy: row.approved_by,
18422
- activatedAt: row.activated_at,
18423
- deactivatedAt: row.deactivated_at
19391
+ approvedBy: row.approvedBy,
19392
+ activatedAt: row.activatedAt,
19393
+ deactivatedAt: row.deactivatedAt
18424
19394
  };
18425
19395
  }
18426
- // Verifications
18427
- saveVerification(v) {
18428
- const stmt = this.db.prepare(`INSERT INTO verifications (id, adaptation_id, measurement, baseline, observed_outcome, comparison_context, conclusion, limitations, verified_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`);
19396
+ async saveVerification(v) {
19397
+ this.ensureInit();
19398
+ const repo = this.ds.getRepository(Verification);
18429
19399
  try {
18430
- stmt.run(
18431
- v.id,
18432
- v.adaptationId,
18433
- v.measurement,
18434
- v.baseline,
18435
- v.observedOutcome,
18436
- v.comparisonContext,
18437
- v.conclusion,
18438
- JSON.stringify(v.limitations ?? []),
18439
- v.verifiedAt
18440
- );
19400
+ await repo.insert({
19401
+ id: v.id,
19402
+ adaptationId: v.adaptationId,
19403
+ measurement: v.measurement,
19404
+ baseline: v.baseline,
19405
+ observedOutcome: v.observedOutcome,
19406
+ comparisonContext: v.comparisonContext,
19407
+ conclusion: v.conclusion,
19408
+ limitations: JSON.stringify(v.limitations ?? []),
19409
+ verifiedAt: v.verifiedAt
19410
+ });
18441
19411
  } catch (e) {
18442
19412
  if (String(e).includes("UNIQUE") || String(e).includes("PRIMARY KEY")) throw new Error(`duplicate verification id: ${v.id}`);
18443
19413
  throw e;
18444
19414
  }
18445
19415
  }
18446
- getVerification(id) {
18447
- const row = this.db.prepare("SELECT * FROM verifications WHERE id = ?").get(id);
19416
+ async getVerification(id) {
19417
+ this.ensureInit();
19418
+ const repo = this.ds.getRepository(Verification);
19419
+ const row = await repo.findOne({ where: { id } });
18448
19420
  if (!row) return void 0;
18449
19421
  return {
18450
19422
  id: row.id,
18451
- adaptationId: row.adaptation_id,
19423
+ adaptationId: row.adaptationId,
18452
19424
  measurement: row.measurement,
18453
19425
  baseline: row.baseline,
18454
- observedOutcome: row.observed_outcome,
18455
- comparisonContext: row.comparison_context,
19426
+ observedOutcome: row.observedOutcome,
19427
+ comparisonContext: row.comparisonContext,
18456
19428
  conclusion: row.conclusion,
18457
19429
  limitations: JSON.parse(row.limitations),
18458
- verifiedAt: row.verified_at
19430
+ verifiedAt: row.verifiedAt
18459
19431
  };
18460
19432
  }
18461
- close() {
19433
+ async close() {
18462
19434
  try {
18463
- this.db.close();
19435
+ await this.ds?.destroy();
18464
19436
  } catch {
18465
19437
  }
19438
+ this.ds = null;
19439
+ this.initialized = false;
18466
19440
  }
18467
19441
  getPath() {
18468
19442
  return this.dbPath;
18469
19443
  }
18470
19444
  };
18471
- createSqliteStore = /* @__PURE__ */ __name((dbPath) => new NeuroCoreSqliteStore(dbPath), "createSqliteStore");
19445
+ createSqliteStore = /* @__PURE__ */ __name(async (dbPath) => {
19446
+ const store7 = new NeuroCoreSqliteStore(dbPath);
19447
+ await store7.init();
19448
+ return store7;
19449
+ }, "createSqliteStore");
18472
19450
  }
18473
19451
  });
18474
19452
 
@@ -18941,7 +19919,7 @@ var init_handshake = __esm({
18941
19919
  const binding = candidate.authorityBinding;
18942
19920
  if (!binding || typeof binding !== "object") return null;
18943
19921
  if (binding.format !== "dotmem.authority-binding") return null;
18944
- if (binding.currentSpeakerBinding !== "trusted-hi" && binding.currentSpeakerBinding !== "unknown" && binding.currentSpeakerBinding !== "untrusted") return null;
19922
+ if (binding.currentSpeakerBinding !== "trusted-hi" && binding.currentSpeakerBinding !== "any" && binding.currentSpeakerBinding !== "untrusted") return null;
18945
19923
  if (binding.currentAuthorityBinding !== "BOUND" && binding.currentAuthorityBinding !== "UNBOUND") return null;
18946
19924
  if (typeof binding.requestedOperationalRole !== "string" || !binding.requestedOperationalRole) return null;
18947
19925
  return candidate;
@@ -19085,7 +20063,7 @@ __export(session_registry_exports, {
19085
20063
  sessionRegistry: () => sessionRegistry,
19086
20064
  updateSessionScope: () => updateSessionScope
19087
20065
  });
19088
- var SESSIONS_FILE, LEASE_MS, readAll3, writeAll3, nowIso3, parentDir2, registerSession, heartbeatSession, updateSessionScope, getSession, listActiveSessions, acknowledgeCursor, closeSession, reapExpiredSessions, sessionRegistry, session_registry_default;
20066
+ var SESSIONS_FILE, LEASE_MS, readAll3, writeAll3, nowIso4, parentDir2, registerSession, heartbeatSession, updateSessionScope, getSession, listActiveSessions, acknowledgeCursor, closeSession, reapExpiredSessions, sessionRegistry, session_registry_default;
19089
20067
  var init_session_registry = __esm({
19090
20068
  "core/memory/session-registry.ts"() {
19091
20069
  init_user_paths();
@@ -19114,29 +20092,29 @@ var init_session_registry = __esm({
19114
20092
  writeAll3 = /* @__PURE__ */ __name((items) => {
19115
20093
  const fs16 = getSyncFs();
19116
20094
  if (!fs16) return;
19117
- const path10 = SESSIONS_FILE();
19118
- const parent = path10.substring(0, Math.max(path10.lastIndexOf("/"), path10.lastIndexOf("\\")));
20095
+ const path11 = SESSIONS_FILE();
20096
+ const parent = path11.substring(0, Math.max(path11.lastIndexOf("/"), path11.lastIndexOf("\\")));
19119
20097
  try {
19120
20098
  fs16.mkdirSync(parent, { recursive: true });
19121
20099
  } catch {
19122
20100
  }
19123
- const tmp = `${path10}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
20101
+ const tmp = `${path11}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
19124
20102
  fs16.writeFileSync(tmp, JSON.stringify(items, null, 2));
19125
20103
  try {
19126
- if (fs16.existsSync(path10)) fs16.copyFileSync(path10, `${path10}.bak`);
20104
+ if (fs16.existsSync(path11)) fs16.copyFileSync(path11, `${path11}.bak`);
19127
20105
  } catch {
19128
20106
  }
19129
20107
  try {
19130
- fs16.renameSync(tmp, path10);
20108
+ fs16.renameSync(tmp, path11);
19131
20109
  } catch {
19132
- fs16.copyFileSync(tmp, path10);
20110
+ fs16.copyFileSync(tmp, path11);
19133
20111
  try {
19134
20112
  fs16.unlinkSync(tmp);
19135
20113
  } catch {
19136
20114
  }
19137
20115
  }
19138
20116
  }, "writeAll");
19139
- nowIso3 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
20117
+ nowIso4 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
19140
20118
  parentDir2 = /* @__PURE__ */ __name((p) => p.substring(0, Math.max(p.lastIndexOf("/"), p.lastIndexOf("\\"))), "parentDir");
19141
20119
  registerSession = /* @__PURE__ */ __name(async (input) => {
19142
20120
  const run = /* @__PURE__ */ __name(async () => {
@@ -19153,10 +20131,10 @@ var init_session_registry = __esm({
19153
20131
  projectId: input.projectId ?? null,
19154
20132
  dayKey: input.dayKey,
19155
20133
  status: "active",
19156
- startedAt: idx >= 0 ? items[idx].startedAt : input.startedAt ?? nowIso3(),
19157
- lastSeenAt: nowIso3(),
20134
+ startedAt: idx >= 0 ? items[idx].startedAt : input.startedAt ?? nowIso4(),
20135
+ lastSeenAt: nowIso4(),
19158
20136
  cursor: idx >= 0 ? items[idx].cursor : input.cursor ?? input.lastCursor ?? 0,
19159
- metadata: { ...idx >= 0 ? items[idx].metadata : {}, ...input.metadata ?? {} }
20137
+ metadata: { ...idx >= 0 ? items[idx].metadata : {}, ...input.metadata }
19160
20138
  };
19161
20139
  if (idx >= 0) items[idx] = rec;
19162
20140
  else items.push(rec);
@@ -19174,9 +20152,9 @@ var init_session_registry = __esm({
19174
20152
  const items = readAll3();
19175
20153
  const idx = items.findIndex((s) => s.sessionId === sessionId);
19176
20154
  if (idx < 0) return;
19177
- items[idx].lastSeenAt = nowIso3();
20155
+ items[idx].lastSeenAt = nowIso4();
19178
20156
  items[idx].status = "active";
19179
- if (metadata) items[idx].metadata = { ...items[idx].metadata ?? {}, ...metadata };
20157
+ if (metadata) items[idx].metadata = { ...items[idx].metadata, ...metadata };
19180
20158
  writeAll3(items);
19181
20159
  }, "run");
19182
20160
  try {
@@ -19197,7 +20175,7 @@ var init_session_registry = __esm({
19197
20175
  if (scope?.conversationId !== void 0) items[idx].conversationId = scope.conversationId;
19198
20176
  if (scope?.agentId !== void 0) items[idx].agentId = scope.agentId;
19199
20177
  if (scope?.dayKey !== void 0) items[idx].dayKey = scope.dayKey;
19200
- items[idx].lastSeenAt = nowIso3();
20178
+ items[idx].lastSeenAt = nowIso4();
19201
20179
  writeAll3(items);
19202
20180
  }, "run");
19203
20181
  try {
@@ -19232,7 +20210,7 @@ var init_session_registry = __esm({
19232
20210
  return;
19233
20211
  }
19234
20212
  items[idx].cursor = cursor;
19235
- items[idx].lastSeenAt = nowIso3();
20213
+ items[idx].lastSeenAt = nowIso4();
19236
20214
  writeAll3(items);
19237
20215
  }, "run");
19238
20216
  try {
@@ -19247,8 +20225,8 @@ var init_session_registry = __esm({
19247
20225
  const idx = items.findIndex((s) => s.sessionId === sessionId);
19248
20226
  if (idx < 0) return;
19249
20227
  items[idx].status = "closed";
19250
- items[idx].lastSeenAt = nowIso3();
19251
- if (reason) items[idx].metadata = { ...items[idx].metadata ?? {}, closeReason: reason };
20228
+ items[idx].lastSeenAt = nowIso4();
20229
+ if (reason) items[idx].metadata = { ...items[idx].metadata, closeReason: reason };
19252
20230
  writeAll3(items);
19253
20231
  }, "run");
19254
20232
  try {
@@ -19302,7 +20280,7 @@ __export(cross_chat_propagation_exports, {
19302
20280
  readCrossChatPropagationState: () => readCrossChatPropagationState,
19303
20281
  writeCrossChatPropagationState: () => writeCrossChatPropagationState
19304
20282
  });
19305
- var CROSS_CHAT_PROPAGATION_FILE_NAME, CROSS_CHAT_PROPAGATION_FORMAT_VERSION, emptyState, joinPath7, resolveFilePath, readRaw, writeRaw, validateState, readCrossChatPropagationState, writeCrossChatPropagationState, getCrossChatPropagationStatus, isCrossChatPropagationEnabled, getCrossChatPropagationChangeMarker;
20283
+ var CROSS_CHAT_PROPAGATION_FILE_NAME, CROSS_CHAT_PROPAGATION_FORMAT_VERSION, emptyState, joinPath8, resolveFilePath, readRaw, writeRaw, validateState, readCrossChatPropagationState, writeCrossChatPropagationState, getCrossChatPropagationStatus, isCrossChatPropagationEnabled, getCrossChatPropagationChangeMarker;
19306
20284
  var init_cross_chat_propagation = __esm({
19307
20285
  "core/continuity/cross-chat-propagation.ts"() {
19308
20286
  init_user_paths();
@@ -19314,12 +20292,12 @@ var init_cross_chat_propagation = __esm({
19314
20292
  configured: false,
19315
20293
  changeMarker: 0
19316
20294
  }), "emptyState");
19317
- joinPath7 = /* @__PURE__ */ __name((base, child) => {
20295
+ joinPath8 = /* @__PURE__ */ __name((base, child) => {
19318
20296
  const separator3 = process.platform === "win32" ? "\\" : "/";
19319
20297
  return `${base.replace(/[\\/]+/g, separator3)}${separator3}${child}`;
19320
20298
  }, "joinPath");
19321
20299
  resolveFilePath = /* @__PURE__ */ __name(() => {
19322
- return joinPath7(resolveUserDotMemPath(), CROSS_CHAT_PROPAGATION_FILE_NAME);
20300
+ return joinPath8(resolveUserDotMemPath(), CROSS_CHAT_PROPAGATION_FILE_NAME);
19323
20301
  }, "resolveFilePath");
19324
20302
  readRaw = /* @__PURE__ */ __name(async () => {
19325
20303
  const fs16 = await import('fs/promises');
@@ -19333,16 +20311,16 @@ var init_cross_chat_propagation = __esm({
19333
20311
  }, "readRaw");
19334
20312
  writeRaw = /* @__PURE__ */ __name(async (content) => {
19335
20313
  const fs16 = await import('fs/promises');
19336
- const path10 = resolveFilePath();
19337
- const dir = path10.replace(/[\\/][^\\/]+$/, "");
20314
+ const path11 = resolveFilePath();
20315
+ const dir = path11.replace(/[\\/][^\\/]+$/, "");
19338
20316
  await fs16.mkdir(dir, { recursive: true });
19339
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
20317
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
19340
20318
  try {
19341
20319
  await fs16.writeFile(temporary, content, "utf8");
19342
- await fs16.rename(temporary, path10);
20320
+ await fs16.rename(temporary, path11);
19343
20321
  } catch {
19344
20322
  await fs16.rm(temporary, { force: true }).catch(() => void 0);
19345
- throw new Error(`Failed to write cross-chat propagation config at ${path10}`);
20323
+ throw new Error(`Failed to write cross-chat propagation config at ${path11}`);
19346
20324
  }
19347
20325
  }, "writeRaw");
19348
20326
  validateState = /* @__PURE__ */ __name((value) => {
@@ -19417,213 +20395,6 @@ var init_cross_chat_propagation = __esm({
19417
20395
  }
19418
20396
  });
19419
20397
 
19420
- // core/context-compiler/index.ts
19421
- var CHARS_PER_TOKEN, estimateTokens, DEFAULT_BUDGETS, dedupe, ContextCompiler, compileContext;
19422
- var init_context_compiler = __esm({
19423
- "core/context-compiler/index.ts"() {
19424
- CHARS_PER_TOKEN = 4;
19425
- estimateTokens = /* @__PURE__ */ __name((text) => Math.ceil((text || "").length / CHARS_PER_TOKEN), "estimateTokens");
19426
- DEFAULT_BUDGETS = {
19427
- identity: 0.1,
19428
- rules: 0.15,
19429
- conversationalState: 0.3,
19430
- retrievedKnowledge: 0.45
19431
- };
19432
- dedupe = /* @__PURE__ */ __name((items) => {
19433
- const seen = /* @__PURE__ */ new Set();
19434
- const result = [];
19435
- for (const item of items) {
19436
- const key = item.trim().toLowerCase();
19437
- if (seen.has(key)) continue;
19438
- seen.add(key);
19439
- result.push(item);
19440
- }
19441
- return result;
19442
- }, "dedupe");
19443
- ContextCompiler = class {
19444
- static {
19445
- __name(this, "ContextCompiler");
19446
- }
19447
- compile(input) {
19448
- const totalBudget = input.tokenBudget ?? 4096;
19449
- const totalChars = totalBudget * CHARS_PER_TOKEN;
19450
- const budgets = {
19451
- identity: Math.floor(totalChars * (input.categoryBudgets?.identity ?? DEFAULT_BUDGETS.identity)),
19452
- rules: Math.floor(totalChars * (input.categoryBudgets?.rules ?? DEFAULT_BUDGETS.rules)),
19453
- conversationalState: Math.floor(totalChars * (input.categoryBudgets?.conversationalState ?? DEFAULT_BUDGETS.conversationalState)),
19454
- retrievedKnowledge: Math.floor(totalChars * (input.categoryBudgets?.retrievedKnowledge ?? DEFAULT_BUDGETS.retrievedKnowledge))
19455
- };
19456
- const omissions = [];
19457
- const identityText = (input.identity ?? "").trim();
19458
- let identityUsed = 0;
19459
- const mandatoryParts = [];
19460
- if (identityText) {
19461
- if (identityText.length <= budgets.identity) {
19462
- mandatoryParts.push(identityText);
19463
- identityUsed = identityText.length;
19464
- } else {
19465
- omissions.push({
19466
- category: "identity",
19467
- whatWasOmitted: identityText,
19468
- whyOmitted: "token budget exceeded",
19469
- wouldBreakContinuity: true
19470
- });
19471
- }
19472
- }
19473
- const rules = input.rules ?? [];
19474
- const activeRules = [];
19475
- let rulesUsed = 0;
19476
- for (const rule of rules) {
19477
- if (rulesUsed + rule.length <= budgets.rules) {
19478
- activeRules.push(rule);
19479
- rulesUsed += rule.length;
19480
- } else {
19481
- omissions.push({
19482
- category: "rules",
19483
- whatWasOmitted: rule,
19484
- whyOmitted: "token budget exceeded",
19485
- wouldBreakContinuity: false
19486
- });
19487
- }
19488
- }
19489
- const state3 = input.conversationalState ?? null;
19490
- const mandatoryStateParts = [];
19491
- if (state3) {
19492
- if (state3.objective) mandatoryStateParts.push(`Objective: ${state3.objective}`);
19493
- if (state3.currentWorkingPosition) mandatoryStateParts.push(`Working position: ${state3.currentWorkingPosition}`);
19494
- if (state3.openLoops.length > 0) {
19495
- mandatoryStateParts.push(`Open loops: ${state3.openLoops.map((l) => l.description).join("; ")}`);
19496
- }
19497
- if (state3.rejectedApproaches.length > 0) {
19498
- mandatoryStateParts.push(`Rejected approaches: ${state3.rejectedApproaches.map((r) => `${r.approach} (${r.reason})`).join("; ")}`);
19499
- }
19500
- }
19501
- const activeParts = [];
19502
- if (state3) {
19503
- if (state3.currentProblem) activeParts.push(`Current problem: ${state3.currentProblem}`);
19504
- if (state3.establishedUnderstanding) activeParts.push(`Established understanding: ${state3.establishedUnderstanding}`);
19505
- if (state3.decisionsMade.length > 0) {
19506
- activeParts.push(`Decisions: ${state3.decisionsMade.map((d) => `${d.decision} (rationale: ${d.rationale})`).join("; ")}`);
19507
- }
19508
- if (state3.pendingDecisions.length > 0) {
19509
- activeParts.push(`Pending decisions: ${state3.pendingDecisions.map((d) => `${d.decision} [${d.options.join(", ")}]`).join("; ")}`);
19510
- }
19511
- if (state3.unresolvedQuestions.length > 0) {
19512
- activeParts.push(`Unresolved questions: ${state3.unresolvedQuestions.map((q) => q.question).join("; ")}`);
19513
- }
19514
- if (state3.reasoningTrajectory.length > 0) {
19515
- activeParts.push(`Reasoning trajectory: ${state3.reasoningTrajectory.map((r) => r.conclusion).join(" -> ")}`);
19516
- }
19517
- if (state3.nextConversationalStep) {
19518
- activeParts.push(`Next step: ${state3.nextConversationalStep}`);
19519
- }
19520
- if (state3.lastCompletedAction) {
19521
- activeParts.push(`Last completed action: ${state3.lastCompletedAction}`);
19522
- }
19523
- }
19524
- const dedupedActive = dedupe(activeParts.filter((part) => !mandatoryStateParts.includes(part)));
19525
- let stateUsed = 0;
19526
- const admittedMandatoryState = [];
19527
- const admittedActive = [];
19528
- for (const part of mandatoryStateParts) {
19529
- if (stateUsed + part.length <= budgets.conversationalState) {
19530
- admittedMandatoryState.push(part);
19531
- stateUsed += part.length;
19532
- } else {
19533
- omissions.push({
19534
- category: "conversationalState",
19535
- whatWasOmitted: part,
19536
- whyOmitted: "token budget exceeded",
19537
- wouldBreakContinuity: true
19538
- });
19539
- }
19540
- }
19541
- for (const part of dedupedActive) {
19542
- if (stateUsed + part.length <= budgets.conversationalState) {
19543
- admittedActive.push(part);
19544
- stateUsed += part.length;
19545
- } else {
19546
- omissions.push({
19547
- category: "conversationalState",
19548
- whatWasOmitted: part,
19549
- whyOmitted: "token budget exceeded",
19550
- wouldBreakContinuity: false
19551
- });
19552
- }
19553
- }
19554
- const refs = [...input.knowledgeReferences ?? []].sort((a, b) => b.relevance - a.relevance);
19555
- const retrievedParts = [];
19556
- let retrievedUsed = 0;
19557
- for (const ref of refs) {
19558
- const text2 = ref.summary ? `${ref.kind}:${ref.identifier} - ${ref.summary}` : `${ref.kind}:${ref.identifier}`;
19559
- if (retrievedUsed + text2.length <= budgets.retrievedKnowledge) {
19560
- retrievedParts.push(text2);
19561
- retrievedUsed += text2.length;
19562
- } else {
19563
- omissions.push({
19564
- category: "retrievedKnowledge",
19565
- whatWasOmitted: text2,
19566
- whyOmitted: "token budget exceeded",
19567
- wouldBreakContinuity: false
19568
- });
19569
- }
19570
- }
19571
- const optionalParts = [];
19572
- let optionalUsed = 0;
19573
- const remainingBudget = totalChars - (identityUsed + rulesUsed + stateUsed + retrievedUsed);
19574
- for (const item of input.historicalContext ?? []) {
19575
- if (optionalUsed + item.length <= remainingBudget) {
19576
- optionalParts.push(item);
19577
- optionalUsed += item.length;
19578
- } else {
19579
- omissions.push({
19580
- category: "historical",
19581
- whatWasOmitted: item,
19582
- whyOmitted: "token budget exceeded",
19583
- wouldBreakContinuity: false
19584
- });
19585
- }
19586
- }
19587
- const admittedSet = new Set([...mandatoryParts, ...admittedMandatoryState, ...admittedActive].map((s) => s.trim().toLowerCase()));
19588
- const isDuplicate = /* @__PURE__ */ __name((item) => {
19589
- const normalized = item.trim().toLowerCase();
19590
- for (const existing of admittedSet) {
19591
- if (existing.includes(normalized) || normalized.includes(existing)) return true;
19592
- }
19593
- return false;
19594
- }, "isDuplicate");
19595
- const finalRetrieved = dedupe(retrievedParts.filter((p) => !isDuplicate(p)));
19596
- const finalOptional = dedupe(optionalParts.filter((p) => !isDuplicate(p) && !finalRetrieved.includes(p)));
19597
- const mandatory = [...mandatoryParts, ...admittedMandatoryState].join("\n");
19598
- const active = [...admittedActive];
19599
- const retrieved = finalRetrieved;
19600
- const optional = finalOptional;
19601
- const text = [mandatory ? `## MANDATORY
19602
- ${mandatory}` : "", active.length ? `## ACTIVE
19603
- ${active.join("\n")}` : "", retrieved.length ? `## RETRIEVED
19604
- ${retrieved.join("\n")}` : "", optional.length ? `## OPTIONAL
19605
- ${optional.join("\n")}` : "", rules.length ? `## RULES
19606
- ${activeRules.join("\n")}` : ""].filter(Boolean).join("\n\n");
19607
- const budgetUsed = estimateTokens(text);
19608
- return {
19609
- mandatory,
19610
- active,
19611
- retrieved,
19612
- optional,
19613
- omissions,
19614
- budgetUsed,
19615
- budgetAvailable: totalBudget,
19616
- text
19617
- };
19618
- }
19619
- };
19620
- compileContext = /* @__PURE__ */ __name((input) => {
19621
- const compiler = new ContextCompiler();
19622
- return compiler.compile(input);
19623
- }, "compileContext");
19624
- }
19625
- });
19626
-
19627
20398
  // core/recovery-service/index.ts
19628
20399
  var RecoveryService;
19629
20400
  var init_recovery_service = __esm({
@@ -19716,7 +20487,7 @@ __export(consolidation_engine_exports, {
19716
20487
  consolidationEngine: () => consolidationEngine,
19717
20488
  getConsolidationEngine: () => getConsolidationEngine
19718
20489
  });
19719
- var DEFAULT_CONFIG3, nowIso4, generateId2, normalizeText2, tokenize3, jaccardSimilarity2, detectOutcome, detectConditions, isDoNotRemember, CONSOLIDATION_STORE_KEY, ConsolidationPersistence, ConsolidationEngine, defaultEngine, getConsolidationEngine, consolidationEngine;
20490
+ var DEFAULT_CONFIG3, nowIso5, generateId2, normalizeText2, tokenize3, jaccardSimilarity2, detectOutcome, detectConditions, isDoNotRemember, CONSOLIDATION_STORE_KEY, ConsolidationPersistence, ConsolidationEngine, defaultEngine, getConsolidationEngine, consolidationEngine;
19720
20491
  var init_consolidation_engine = __esm({
19721
20492
  "core/memory/consolidation-engine.ts"() {
19722
20493
  init_durable_store();
@@ -19727,7 +20498,7 @@ var init_consolidation_engine = __esm({
19727
20498
  similarityThreshold: 0.5,
19728
20499
  minConfidenceForConsolidated: 0.7
19729
20500
  };
19730
- nowIso4 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
20501
+ nowIso5 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
19731
20502
  generateId2 = /* @__PURE__ */ __name(() => `cons-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`, "generateId");
19732
20503
  normalizeText2 = /* @__PURE__ */ __name((text) => {
19733
20504
  return text.normalize("NFKC").toLocaleLowerCase("en-US").replace(/[^\w\s]/g, " ").replace(/\s+/g, " ").trim();
@@ -19752,7 +20523,7 @@ var init_consolidation_engine = __esm({
19752
20523
  if (/if |when |only when|provided that|as long as/i.test(lower)) return "conditional";
19753
20524
  if (/succ(eed|ess)|works|passed|completed|resolved|fixed/i.test(lower)) return "success";
19754
20525
  if (category === "decision") return "success";
19755
- return "unknown";
20526
+ return "any";
19756
20527
  }, "detectOutcome");
19757
20528
  detectConditions = /* @__PURE__ */ __name((statement) => {
19758
20529
  const conditions = [];
@@ -19829,7 +20600,7 @@ var init_consolidation_engine = __esm({
19829
20600
  new DurableMemoryStore({
19830
20601
  filePath: `${resolveUserDotMemPath()}/consolidation-records.kv`,
19831
20602
  storeKey: CONSOLIDATION_STORE_KEY,
19832
- tenantId: this.tenantId
20603
+ tenantId: this.tenantId ?? void 0
19833
20604
  })
19834
20605
  );
19835
20606
  }
@@ -19946,7 +20717,7 @@ var init_consolidation_engine = __esm({
19946
20717
  }
19947
20718
  /** Create a new consolidation record from a group of experiences. */
19948
20719
  async createRecordFromGroup(group) {
19949
- const now3 = nowIso4();
20720
+ const now3 = nowIso5();
19950
20721
  const evidence = group.experiences.map((e) => ({
19951
20722
  experienceId: e.id,
19952
20723
  statement: e.statement,
@@ -19964,7 +20735,7 @@ var init_consolidation_engine = __esm({
19964
20735
  const outcomes = uniqueEvidence.map((e) => e.outcome);
19965
20736
  const hasFailure = outcomes.includes("failure");
19966
20737
  const hasSuccess = outcomes.includes("success");
19967
- const hasUnknown = outcomes.includes("unknown");
20738
+ const hasUnknown = outcomes.includes("any");
19968
20739
  const hasConditional = outcomes.includes("conditional");
19969
20740
  let lifecycleState = "pending";
19970
20741
  if (uniqueEvidence.length < this.config.minExperiencesForAcquired) {
@@ -19980,7 +20751,7 @@ var init_consolidation_engine = __esm({
19980
20751
  applicability["conditions"] = conditions.join("; ");
19981
20752
  }
19982
20753
  const limitations = [];
19983
- if (hasUnknown) limitations.push("Outcome unknown for some experiences");
20754
+ if (hasUnknown) limitations.push("Outcome any for some experiences");
19984
20755
  if (hasConditional) limitations.push("Success is conditional on specific circumstances");
19985
20756
  if (uniqueEvidence.length < this.config.minExperiencesForConsolidated) {
19986
20757
  limitations.push(`Only ${uniqueEvidence.length} supporting experience(s); ${this.config.minExperiencesForConsolidated} required for consolidation`);
@@ -20023,7 +20794,7 @@ var init_consolidation_engine = __esm({
20023
20794
  async updateRecordWithEvidence(record, newExperiences) {
20024
20795
  const newExpIds = newExperiences.map((e) => e.id).filter((id) => !record.supportingExperiences.includes(id));
20025
20796
  if (newExpIds.length === 0) return null;
20026
- const now3 = nowIso4();
20797
+ const now3 = nowIso5();
20027
20798
  const newEvidence = newExperiences.filter((e) => !record.supportingExperiences.includes(e.id)).map((e) => ({
20028
20799
  experienceId: e.id,
20029
20800
  statement: e.statement,
@@ -20081,7 +20852,7 @@ var init_consolidation_engine = __esm({
20081
20852
  if (record.doNotRemember) return false;
20082
20853
  const uniqueEvidence = this.deduplicateEvidence([...record.supportingEvidence, ...record.contradictingEvidence]);
20083
20854
  if (record.lifecycleState === "acquired" && uniqueEvidence.length >= this.config.minExperiencesForConsolidated && record.confidence >= this.config.minConfidenceForConsolidated && record.contradictingEvidence.length === 0) {
20084
- const now3 = nowIso4();
20855
+ const now3 = nowIso5();
20085
20856
  const promoted = {
20086
20857
  ...record,
20087
20858
  lifecycleState: "consolidated",
@@ -20103,7 +20874,7 @@ var init_consolidation_engine = __esm({
20103
20874
  return true;
20104
20875
  }
20105
20876
  if (record.lifecycleState === "insufficient_evidence" && uniqueEvidence.length >= this.config.minExperiencesForAcquired) {
20106
- const now3 = nowIso4();
20877
+ const now3 = nowIso5();
20107
20878
  const promoted = {
20108
20879
  ...record,
20109
20880
  lifecycleState: "acquired",
@@ -20143,7 +20914,7 @@ var init_consolidation_engine = __esm({
20143
20914
  a.history.push({
20144
20915
  from: a.lifecycleState,
20145
20916
  to: "conflicting",
20146
- at: nowIso4(),
20917
+ at: nowIso5(),
20147
20918
  reason: `Contradiction detected with record ${b.id}`
20148
20919
  });
20149
20920
  await this.persistence.saveRecord(a);
@@ -20171,11 +20942,11 @@ var init_consolidation_engine = __esm({
20171
20942
  if (evidence.length === 0) return 0;
20172
20943
  const successes = evidence.filter((e) => e.outcome === "success").length;
20173
20944
  const failures = evidence.filter((e) => e.outcome === "failure").length;
20174
- const unknowns = evidence.filter((e) => e.outcome === "unknown").length;
20945
+ const anys = evidence.filter((e) => e.outcome === "any").length;
20175
20946
  const conditionals = evidence.filter((e) => e.outcome === "conditional").length;
20176
20947
  let confidence = evidence.length > 0 ? successes / evidence.length : 0;
20177
- if (unknowns > 0) {
20178
- confidence *= 1 - unknowns / (evidence.length * 2);
20948
+ if (anys > 0) {
20949
+ confidence *= 1 - anys / (evidence.length * 2);
20179
20950
  }
20180
20951
  if (conditionals > 0) {
20181
20952
  confidence *= 0.9;
@@ -20191,14 +20962,14 @@ var init_consolidation_engine = __esm({
20191
20962
  buildConfidenceJustification(evidence, confidence) {
20192
20963
  const successes = evidence.filter((e) => e.outcome === "success").length;
20193
20964
  const failures = evidence.filter((e) => e.outcome === "failure").length;
20194
- const unknowns = evidence.filter((e) => e.outcome === "unknown").length;
20195
- return `Based on ${evidence.length} unique experience(s): ${successes} success, ${failures} failure, ${unknowns} unknown. Confidence: ${confidence}`;
20965
+ const anys = evidence.filter((e) => e.outcome === "any").length;
20966
+ return `Based on ${evidence.length} unique experience(s): ${successes} success, ${failures} failure, ${anys} any. Confidence: ${confidence}`;
20196
20967
  }
20197
20968
  /** Build limitations list. */
20198
20969
  buildLimitations(evidence, confidence) {
20199
20970
  const limitations = [];
20200
- const unknowns = evidence.filter((e) => e.outcome === "unknown").length;
20201
- if (unknowns > 0) limitations.push(`${unknowns} experience(s) with unknown outcome`);
20971
+ const anys = evidence.filter((e) => e.outcome === "any").length;
20972
+ if (anys > 0) limitations.push(`${anys} experience(s) with any outcome`);
20202
20973
  const conditionals = evidence.filter((e) => e.outcome === "conditional").length;
20203
20974
  if (conditionals > 0) limitations.push(`${conditionals} experience(s) with conditional success`);
20204
20975
  if (confidence < 0.5) limitations.push("Low confidence due to insufficient or conflicting evidence");
@@ -20213,7 +20984,7 @@ var init_consolidation_engine = __esm({
20213
20984
  const record = this.records.get(id);
20214
20985
  if (!record) throw new Error(`Record not found: ${id}`);
20215
20986
  if (record.doNotRemember) throw new Error(`Cannot promote do-not-remember record: ${id}`);
20216
- const now3 = nowIso4();
20987
+ const now3 = nowIso5();
20217
20988
  const promoted = {
20218
20989
  ...record,
20219
20990
  lifecycleState: "consolidated",
@@ -20239,7 +21010,7 @@ var init_consolidation_engine = __esm({
20239
21010
  await this.load();
20240
21011
  const record = this.records.get(id);
20241
21012
  if (!record) throw new Error(`Record not found: ${id}`);
20242
- const now3 = nowIso4();
21013
+ const now3 = nowIso5();
20243
21014
  const superseded = {
20244
21015
  ...record,
20245
21016
  lifecycleState: "superseded",
@@ -20264,7 +21035,7 @@ var init_consolidation_engine = __esm({
20264
21035
  await this.load();
20265
21036
  const record = this.records.get(id);
20266
21037
  if (!record) throw new Error(`Record not found: ${id}`);
20267
- const now3 = nowIso4();
21038
+ const now3 = nowIso5();
20268
21039
  const invalidated = {
20269
21040
  ...record,
20270
21041
  lifecycleState: "invalidated",
@@ -20289,7 +21060,7 @@ var init_consolidation_engine = __esm({
20289
21060
  await this.load();
20290
21061
  const record = this.records.get(id);
20291
21062
  if (!record) throw new Error(`Record not found: ${id}`);
20292
- const now3 = nowIso4();
21063
+ const now3 = nowIso5();
20293
21064
  const reassessed = {
20294
21065
  ...record,
20295
21066
  lifecycleState: "reassessment_required",
@@ -20362,20 +21133,20 @@ __export(session_bootstrap_exports, {
20362
21133
  bootstrapSession: () => bootstrapSession,
20363
21134
  createSessionBootstrap: () => createSessionBootstrap
20364
21135
  });
20365
- var nowIso5, defaultSubject, bootstrapSession, createSessionBootstrap;
21136
+ var nowIso6, defaultSubject, bootstrapSession, createSessionBootstrap;
20366
21137
  var init_session_bootstrap = __esm({
20367
21138
  "core/memory/session-bootstrap.ts"() {
20368
21139
  init_discover();
20369
21140
  init_project();
20370
- init_rules_loader();
21141
+ init_rule_enforcement();
20371
21142
  init_context_constants();
20372
21143
  init_context_compiler();
20373
21144
  init_conversational_state();
20374
21145
  init_recovery_service();
20375
- nowIso5 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
21146
+ nowIso6 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
20376
21147
  defaultSubject = "__default__";
20377
21148
  bootstrapSession = /* @__PURE__ */ __name(async (options = {}) => {
20378
- const { userId, projectId, agentId, sessionId = `session-${nowIso5()}-${Math.random().toString(36).slice(2, 10)}`, conversationId, scope = "project", subject = defaultSubject, tokenBudget = 4096, situation, rules: inputRules, taskManager, tenantId } = options;
21149
+ const { userId, projectId, agentId, sessionId = `session-${nowIso6()}-${Math.random().toString(36).slice(2, 10)}`, conversationId, scope = "project", subject = defaultSubject, tokenBudget = 4096, situation, rules: inputRules, taskManager, tenantId } = options;
20379
21150
  const scopes = {
20380
21151
  userId,
20381
21152
  projectId,
@@ -20433,6 +21204,7 @@ var init_session_bootstrap = __esm({
20433
21204
  let rulesCount = 0;
20434
21205
  let rulesSignature = "";
20435
21206
  let consolidatedKnowledge = [];
21207
+ let enforcementRules = [];
20436
21208
  try {
20437
21209
  const dynamicMemory = await Promise.resolve().then(() => (init_memory(), memory_exports));
20438
21210
  const state3 = await dynamicMemory.loadCombinedKnowledgeState();
@@ -20450,9 +21222,12 @@ var init_session_bootstrap = __esm({
20450
21222
  relevance: 1
20451
21223
  });
20452
21224
  }
20453
- const rules = loadIronRules(state3).rules;
20454
- rulesCount = rules.length;
20455
- rulesSignature = ruleSetSignature(rules);
21225
+ try {
21226
+ enforcementRules = await resolveApplicableRules(situation ?? "", scope);
21227
+ rulesCount = enforcementRules.length;
21228
+ rulesSignature = enforcementRules.map((r) => `${r.id}\0${r.text}`).join("");
21229
+ } catch {
21230
+ }
20456
21231
  try {
20457
21232
  const { consolidationEngine: consolidationEngine2 } = await Promise.resolve().then(() => (init_consolidation_engine(), consolidation_engine_exports));
20458
21233
  await consolidationEngine2.load();
@@ -20482,7 +21257,7 @@ var init_session_bootstrap = __esm({
20482
21257
  }
20483
21258
  const context2 = compileContext({
20484
21259
  conversationalState: recovery?.context?.conversationalState,
20485
- rules: inputRules,
21260
+ rules: enforcementRules.map((r) => `[${r.source.toUpperCase()}] ${r.text}` + (r.appliesWhen ? ` (quando: ${r.appliesWhen})` : "")),
20486
21261
  knowledgeReferences: knowledgeReferences.map((r) => ({
20487
21262
  id: r.id,
20488
21263
  kind: r.kind,
@@ -20860,11 +21635,11 @@ var init_memory = __esm({
20860
21635
  const byTrust = {};
20861
21636
  const byArea = {};
20862
21637
  for (const claim of state3.claims ?? []) {
20863
- const scope = claim.scope ?? "unknown";
21638
+ const scope = claim.scope ?? "any";
20864
21639
  byScope[scope] = (byScope[scope] || 0) + 1;
20865
- const trust = claim.trustBasis ?? "unknown";
21640
+ const trust = claim.trustBasis ?? "any";
20866
21641
  byTrust[trust] = (byTrust[trust] || 0) + 1;
20867
- const area = claim.applicability?.area ?? "unknown";
21642
+ const area = claim.applicability?.area ?? "any";
20868
21643
  byArea[area] = (byArea[area] || 0) + 1;
20869
21644
  }
20870
21645
  return { total: (state3.claims ?? []).length, byScope, byTrust, byArea };
@@ -20974,7 +21749,7 @@ var init_memory = __esm({
20974
21749
  const ids = [];
20975
21750
  for (const stmt of statements) {
20976
21751
  const id = await acquire.acquire({
20977
- knowledge: { hypothesis: stmt, situation: context2?.situation },
21752
+ knowledge: { hypothesis: stmt, ...context2?.situation !== void 0 ? { situation: context2.situation } : {} },
20978
21753
  applicability: context2?.applicability ?? { area: "hypothesis" },
20979
21754
  evidence: [{ id: `hyp-${Date.now()}`, source: "tree-of-thoughts", observedAt: (/* @__PURE__ */ new Date()).toISOString() }],
20980
21755
  epistemicType: "inferred",
@@ -21020,7 +21795,7 @@ var init_memory = __esm({
21020
21795
  },
21021
21796
  async learnFromFailure(claimId, failure, correction) {
21022
21797
  return acquire.acquire({
21023
- knowledge: { failedClaim: claimId, failure, correction },
21798
+ knowledge: { failedClaim: claimId, failure, ...correction !== void 0 ? { correction } : {} },
21024
21799
  applicability: { area: "continual-learning", kind: "correction" },
21025
21800
  evidence: [{ id: `fail-${Date.now()}`, source: "experience", observedAt: (/* @__PURE__ */ new Date()).toISOString() }],
21026
21801
  epistemicType: "observed",
@@ -21035,7 +21810,7 @@ var init_memory = __esm({
21035
21810
  const state3 = await loadCombinedKnowledgeState();
21036
21811
  const groups = {};
21037
21812
  for (const c of state3.claims ?? []) {
21038
- const area = c.applicability?.area ?? "unknown";
21813
+ const area = c.applicability?.area ?? "any";
21039
21814
  if (!groups[area]) groups[area] = [];
21040
21815
  groups[area].push(c.id);
21041
21816
  }
@@ -21105,7 +21880,7 @@ var init_memory = __esm({
21105
21880
  });
21106
21881
  const lines = ["Autobiography:"];
21107
21882
  for (const c of claims) {
21108
- const area = c.applicability?.area ?? "unknown";
21883
+ const area = c.applicability?.area ?? "any";
21109
21884
  lines.push(`- [${c.acquiredAt ?? "?"}] (${area}) ${JSON.stringify(c.knowledge).slice(0, 120)}`);
21110
21885
  }
21111
21886
  return lines.join("\n");
@@ -22195,7 +22970,7 @@ var traceModelContext = /* @__PURE__ */ __name((context2) => buildReasoningTrace
22195
22970
  var evaluateRef = /* @__PURE__ */ __name((ref, current) => {
22196
22971
  if (ref.version !== void 0 && current.version !== void 0 && ref.version !== current.version) return "changed";
22197
22972
  if (ref.digest !== void 0 && current.digest !== void 0 && ref.digest !== current.digest) return "changed";
22198
- if (ref.version === void 0 && current.version === void 0 && ref.digest === void 0 && current.digest === void 0) return "unknown";
22973
+ if (ref.version === void 0 && current.version === void 0 && ref.digest === void 0 && current.digest === void 0) return "any";
22199
22974
  return "same";
22200
22975
  }, "evaluateRef");
22201
22976
  var evaluateFreshness = /* @__PURE__ */ __name((input) => {
@@ -22203,10 +22978,10 @@ var evaluateFreshness = /* @__PURE__ */ __name((input) => {
22203
22978
  return { state: "stale", reason: "explicit invalidation", checkedAt: input.checkedAt };
22204
22979
  }
22205
22980
  if (input.sourceRefs.length === 0) {
22206
- return { state: "unknown", reason: "no source references recorded", checkedAt: input.checkedAt };
22981
+ return { state: "any", reason: "no source references recorded", checkedAt: input.checkedAt };
22207
22982
  }
22208
22983
  const staleReasons = [];
22209
- let unknown = false;
22984
+ let any = false;
22210
22985
  for (const ref of input.sourceRefs) {
22211
22986
  const current = input.currentSources.find((candidate) => candidate.kind === ref.kind && candidate.id === ref.id);
22212
22987
  if (!current) {
@@ -22218,15 +22993,15 @@ var evaluateFreshness = /* @__PURE__ */ __name((input) => {
22218
22993
  staleReasons.push(`${ref.kind}:${ref.id} version ${ref.version ?? "?"} -> ${current.version ?? "?"}, digest ${ref.digest ?? "?"} -> ${current.digest ?? "?"}`);
22219
22994
  continue;
22220
22995
  }
22221
- if (comparison === "unknown") {
22222
- unknown = true;
22996
+ if (comparison === "any") {
22997
+ any = true;
22223
22998
  }
22224
22999
  }
22225
23000
  if (staleReasons.length > 0) {
22226
23001
  return { state: "stale", reason: staleReasons.join("; "), checkedAt: input.checkedAt };
22227
23002
  }
22228
- if (unknown) {
22229
- return { state: "unknown", reason: "sources without comparable identity", checkedAt: input.checkedAt };
23003
+ if (any) {
23004
+ return { state: "any", reason: "sources without comparable identity", checkedAt: input.checkedAt };
22230
23005
  }
22231
23006
  return { state: "fresh", checkedAt: input.checkedAt };
22232
23007
  }, "evaluateFreshness");
@@ -22331,31 +23106,31 @@ var validateContinuityDocument = /* @__PURE__ */ __name((value) => {
22331
23106
  snapshots: document.snapshots
22332
23107
  };
22333
23108
  }, "validateContinuityDocument");
22334
- var deleteContinuityArtifact = /* @__PURE__ */ __name(async (path10) => {
23109
+ var deleteContinuityArtifact = /* @__PURE__ */ __name(async (path11) => {
22335
23110
  const fs16 = getSyncFs();
22336
23111
  if (!fs16) return;
22337
- await fs16.promises.rm(path10, { force: true });
23112
+ await fs16.promises.rm(path11, { force: true });
22338
23113
  }, "deleteContinuityArtifact");
22339
- var loadContinuityDocument = /* @__PURE__ */ __name(async (path10) => {
23114
+ var loadContinuityDocument = /* @__PURE__ */ __name(async (path11) => {
22340
23115
  const fs16 = getSyncFs();
22341
23116
  if (!fs16) return emptyContinuityDocument();
22342
23117
  try {
22343
- const raw = await fs16.promises.readFile(path10, "utf8");
23118
+ const raw = await fs16.promises.readFile(path11, "utf8");
22344
23119
  return validateContinuityDocument(JSON.parse(raw));
22345
23120
  } catch {
22346
23121
  return emptyContinuityDocument();
22347
23122
  }
22348
23123
  }, "loadContinuityDocument");
22349
- var saveContinuityDocument = /* @__PURE__ */ __name(async (path10, document) => {
23124
+ var saveContinuityDocument = /* @__PURE__ */ __name(async (path11, document) => {
22350
23125
  const fs16 = getSyncFs();
22351
23126
  if (!fs16) return;
22352
23127
  const validated = validateContinuityDocument(document);
22353
23128
  await fs16.promises.mkdir(resolveUserContinuityDir(), { recursive: true });
22354
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
23129
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
22355
23130
  try {
22356
23131
  await fs16.promises.writeFile(temporary, `${JSON.stringify(validated, null, 2)}
22357
23132
  `, "utf8");
22358
- await fs16.promises.rename(temporary, path10);
23133
+ await fs16.promises.rename(temporary, path11);
22359
23134
  } catch (error) {
22360
23135
  await fs16.promises.rm(temporary, { force: true }).catch(() => void 0);
22361
23136
  throw error;