dotmem 0.3.2 → 0.3.4

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.js CHANGED
@@ -1,26 +1,23 @@
1
1
  import { hlc, dispatch, session, store, state, temporal } from 'memorio';
2
2
  export { dispatch, hlc, session, state, store } from 'memorio';
3
3
  import crypto5 from 'crypto';
4
- import fs, { readFileSync, readdirSync } from 'fs';
5
- import path8, { relative, extname, join } from 'path';
4
+ import fs6, { readFileSync, readdirSync } from 'fs';
5
+ import path5, { join, relative, extname } from 'path';
6
6
  import { fileURLToPath } from 'url';
7
7
  import fs14 from 'fs/promises';
8
- import { execFileSync, spawnSync } from 'child_process';
8
+ import { spawnSync, execFileSync } from 'child_process';
9
+ import { tmpdir } from 'os';
9
10
  import '@noble/post-quantum/ml-dsa.js';
10
11
  import { ml_kem768_x25519 } from '@noble/post-quantum/hybrid.js';
11
12
  import { createRequire } from 'module';
13
+ import 'reflect-metadata';
14
+ import { PrimaryColumn, Entity, Column, DataSource } from 'typeorm';
12
15
 
13
16
  var __defProp = Object.defineProperty;
14
17
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
15
18
  var __getOwnPropNames = Object.getOwnPropertyNames;
16
19
  var __hasOwnProp = Object.prototype.hasOwnProperty;
17
20
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
18
- var __require = /* @__PURE__ */ ((x3) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x3, {
19
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
20
- }) : x3)(function(x3) {
21
- if (typeof require !== "undefined") return require.apply(this, arguments);
22
- throw Error('Dynamic require of "' + x3 + '" is not supported');
23
- });
24
21
  var __esm = (fn, res, err3) => function __init() {
25
22
  if (err3) throw err3[0];
26
23
  try {
@@ -42,6 +39,14 @@ var __copyProps = (to, from, except, desc) => {
42
39
  return to;
43
40
  };
44
41
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
42
+ var __decorateClass = (decorators, target, key, kind) => {
43
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
44
+ for (var i3 = decorators.length - 1, decorator; i3 >= 0; i3--)
45
+ if (decorator = decorators[i3])
46
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
47
+ if (kind && result) __defProp(target, key, result);
48
+ return result;
49
+ };
45
50
 
46
51
  // core/security/privacy-gate.ts
47
52
  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;
@@ -843,18 +848,18 @@ var init_storage_settings = __esm({
843
848
  throw invalidSettings(file2, "must contain a JSON object");
844
849
  }
845
850
  const document = parsed;
846
- const unknownFields = Object.keys(document).filter((key) => key !== "storage");
847
- if (unknownFields.length > 0) {
848
- throw invalidSettings(file2, `contains unsupported top-level fields (${unknownFields.join(", ")})`);
851
+ const anyFields = Object.keys(document).filter((key) => key !== "storage");
852
+ if (anyFields.length > 0) {
853
+ throw invalidSettings(file2, `contains unsupported top-level fields (${anyFields.join(", ")})`);
849
854
  }
850
855
  const storage = document.storage;
851
856
  if (storage === void 0) return {};
852
857
  if (!storage || typeof storage !== "object" || Array.isArray(storage)) {
853
858
  throw invalidSettings(file2, "has a storage field that is not an object");
854
859
  }
855
- const unknownStorageFields = Object.keys(storage).filter((key) => key !== "root" && key !== "mode");
856
- if (unknownStorageFields.length > 0) {
857
- throw invalidSettings(file2, `storage contains unsupported fields (${unknownStorageFields.join(", ")})`);
860
+ const anyStorageFields = Object.keys(storage).filter((key) => key !== "root" && key !== "mode");
861
+ if (anyStorageFields.length > 0) {
862
+ throw invalidSettings(file2, `storage contains unsupported fields (${anyStorageFields.join(", ")})`);
858
863
  }
859
864
  if (storage.mode !== void 0 && (typeof storage.mode !== "string" || !SETTINGS_MODES.includes(storage.mode))) {
860
865
  throw invalidSettings(file2, `storage.mode must be one of ${SETTINGS_MODES.join(", ")} (received ${JSON.stringify(storage.mode)})`);
@@ -902,7 +907,7 @@ var init_storage_settings = __esm({
902
907
  if (code === "EACCES" || code === "EPERM") {
903
908
  throw invalidSettings(file2, `cannot be read (${code})`);
904
909
  }
905
- throw invalidSettings(file2, `cannot be read (${code ?? "unknown error"})`);
910
+ throw invalidSettings(file2, `cannot be read (${code ?? "any error"})`);
906
911
  }
907
912
  return raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw;
908
913
  }, "readTextFile");
@@ -951,7 +956,7 @@ var init_text_encoding = __esm({
951
956
  decodeText = /* @__PURE__ */ __name((bytes, options = {}) => {
952
957
  const bom = detectBom(bytes);
953
958
  if (bom === "utf-16le" || bom === "utf-16be") {
954
- 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.`);
959
+ 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.`);
955
960
  }
956
961
  let content = bytes;
957
962
  if (bom === "utf-8") {
@@ -1034,7 +1039,7 @@ var init_storage_location = __esm({
1034
1039
  if (code === "ENOENT") return "the directory does not exist";
1035
1040
  if (code === "EACCES" || code === "EPERM") return `the directory is not accessible (${code})`;
1036
1041
  if (code === "ENOTDIR") return "the path is not a directory";
1037
- return `the directory cannot be accessed (${code ?? "unknown error"})`;
1042
+ return `the directory cannot be accessed (${code ?? "any error"})`;
1038
1043
  }, "describeAccessFailure");
1039
1044
  validateConfiguredStorageRoot = /* @__PURE__ */ __name((value, source) => {
1040
1045
  if (typeof value !== "string" || !value.trim()) {
@@ -1085,9 +1090,9 @@ var init_storage_location = __esm({
1085
1090
  throw new DotMemStorageLocationError(`dotmem storage location cannot be resolved: the user locator file at ${locatorFile} must contain a JSON object.`);
1086
1091
  }
1087
1092
  const locator = parsed;
1088
- const unknownFields = Object.keys(locator).filter((key) => key !== "version" && key !== "storageRoot");
1089
- if (unknownFields.length > 0) {
1090
- 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.`);
1093
+ const anyFields = Object.keys(locator).filter((key) => key !== "version" && key !== "storageRoot");
1094
+ if (anyFields.length > 0) {
1095
+ 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.`);
1091
1096
  }
1092
1097
  if (locator.version !== DOTMEM_STORAGE_LOCATOR_VERSION) {
1093
1098
  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}.`);
@@ -1435,22 +1440,22 @@ var init_conversation_events = __esm({
1435
1440
  const fs16 = fsSync();
1436
1441
  if (fs16) {
1437
1442
  try {
1438
- const path10 = EVENTS_FILE();
1439
- const parent = path10.substring(0, Math.max(path10.lastIndexOf("/"), path10.lastIndexOf("\\")));
1443
+ const path11 = EVENTS_FILE();
1444
+ const parent = path11.substring(0, Math.max(path11.lastIndexOf("/"), path11.lastIndexOf("\\")));
1440
1445
  try {
1441
1446
  fs16.mkdirSync(parent, { recursive: true });
1442
1447
  } catch {
1443
1448
  }
1444
- const tmp = `${path10}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
1449
+ const tmp = `${path11}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
1445
1450
  fs16.writeFileSync(tmp, JSON.stringify(events));
1446
1451
  try {
1447
- if (fs16.existsSync(path10)) fs16.copyFileSync(path10, `${path10}.bak`);
1452
+ if (fs16.existsSync(path11)) fs16.copyFileSync(path11, `${path11}.bak`);
1448
1453
  } catch {
1449
1454
  }
1450
1455
  try {
1451
- fs16.renameSync(tmp, path10);
1456
+ fs16.renameSync(tmp, path11);
1452
1457
  } catch {
1453
- fs16.copyFileSync(tmp, path10);
1458
+ fs16.copyFileSync(tmp, path11);
1454
1459
  try {
1455
1460
  fs16.unlinkSync(tmp);
1456
1461
  } catch {
@@ -1591,8 +1596,8 @@ var init_conversation_events = __esm({
1591
1596
  try {
1592
1597
  const fs16 = fsSync();
1593
1598
  if (fs16) {
1594
- const path10 = EVENTS_FILE();
1595
- const parent = path10.substring(0, Math.max(path10.lastIndexOf("/"), path10.lastIndexOf("\\")));
1599
+ const path11 = EVENTS_FILE();
1600
+ const parent = path11.substring(0, Math.max(path11.lastIndexOf("/"), path11.lastIndexOf("\\")));
1596
1601
  return await withStorageLock(parent, run);
1597
1602
  }
1598
1603
  } catch {
@@ -1788,9 +1793,9 @@ var init_policy_namespace_lock = __esm({
1788
1793
  currentHost = /* @__PURE__ */ __name(async () => {
1789
1794
  try {
1790
1795
  const os = await import('os');
1791
- return typeof os.hostname === "function" && os.hostname() ? os.hostname() : "unknown";
1796
+ return typeof os.hostname === "function" && os.hostname() ? os.hostname() : "any";
1792
1797
  } catch {
1793
- return "unknown";
1798
+ return "any";
1794
1799
  }
1795
1800
  }, "currentHost");
1796
1801
  delay = /* @__PURE__ */ __name(async (milliseconds) => {
@@ -1809,7 +1814,7 @@ var init_policy_namespace_lock = __esm({
1809
1814
  if (!parsed || typeof parsed !== "object") return null;
1810
1815
  return {
1811
1816
  pid: typeof parsed.pid === "number" ? parsed.pid : 0,
1812
- host: typeof parsed.host === "string" ? parsed.host : "unknown",
1817
+ host: typeof parsed.host === "string" ? parsed.host : "any",
1813
1818
  acquiredAt: typeof parsed.acquiredAt === "string" ? parsed.acquiredAt : "",
1814
1819
  token: typeof parsed.token === "string" ? parsed.token : ""
1815
1820
  };
@@ -1832,7 +1837,7 @@ var init_policy_namespace_lock = __esm({
1832
1837
  const acquiredAt = held ? Date.parse(held.acquiredAt) : Number.NaN;
1833
1838
  const age = Number.isFinite(acquiredAt) ? Date.now() - acquiredAt : Number.POSITIVE_INFINITY;
1834
1839
  if (age > POLICY_LOCK_TTL_MS) {
1835
- const stale = held ?? { pid: 0, host: "unknown", acquiredAt: "", token: "" };
1840
+ const stale = held ?? { pid: 0, host: "any", acquiredAt: "", token: "" };
1836
1841
  const outcome = await breakStalePolicyLock(fs16, lockPath, stale);
1837
1842
  if (outcome === "broken") {
1838
1843
  brokenOwner = stale;
@@ -1849,7 +1854,7 @@ var init_policy_namespace_lock = __esm({
1849
1854
  throw new PolicyNamespaceLockError(`Policy namespace lock could not be acquired after ${POLICY_LOCK_RETRY_ATTEMPTS} bounded retries; policy mutation fails closed`);
1850
1855
  }, "acquireLock");
1851
1856
  breakStalePolicyLock = /* @__PURE__ */ __name(async (fs16, lockPath, staleOwner) => {
1852
- const candidate = `${lockPath}.breaking-${staleOwner.token || "unknown"}`;
1857
+ const candidate = `${lockPath}.breaking-${staleOwner.token || "any"}`;
1853
1858
  try {
1854
1859
  await fs16.rename(lockPath, candidate);
1855
1860
  } catch (error) {
@@ -2071,11 +2076,11 @@ var init_state = __esm({
2071
2076
  if (evidence.length === 0) return;
2072
2077
  for (let index = 0; index < evidence.length; index++) {
2073
2078
  const entry = evidence[index];
2074
- const path10 = `evidence[${index}]`;
2079
+ const path11 = `evidence[${index}]`;
2075
2080
  if (Array.isArray(entry)) {
2076
2081
  throw canonicalEvidenceError({
2077
2082
  claimId: claim.id,
2078
- path: path10,
2083
+ path: path11,
2079
2084
  problem: CANONICAL_EVIDENCE_PROBLEMS.tupleEntry,
2080
2085
  received: entry,
2081
2086
  fix: CANONICAL_EVIDENCE_FIX.tupleEntry
@@ -2084,7 +2089,7 @@ var init_state = __esm({
2084
2089
  if (!entry || typeof entry !== "object") {
2085
2090
  throw canonicalEvidenceError({
2086
2091
  claimId: claim.id,
2087
- path: path10,
2092
+ path: path11,
2088
2093
  problem: CANONICAL_EVIDENCE_PROBLEMS.nonObjectEntry,
2089
2094
  received: entry,
2090
2095
  fix: CANONICAL_EVIDENCE_FIX.nonObjectEntry
@@ -2093,7 +2098,7 @@ var init_state = __esm({
2093
2098
  if (!requiredText(entry.id)) {
2094
2099
  throw canonicalEvidenceError({
2095
2100
  claimId: claim.id,
2096
- path: `${path10}.id`,
2101
+ path: `${path11}.id`,
2097
2102
  problem: CANONICAL_EVIDENCE_PROBLEMS.missingId,
2098
2103
  received: entry,
2099
2104
  fix: CANONICAL_EVIDENCE_FIX.missingId
@@ -2104,7 +2109,7 @@ var init_state = __esm({
2104
2109
  if (fieldValue !== void 0 && !requiredText(fieldValue)) {
2105
2110
  throw canonicalEvidenceError({
2106
2111
  claimId: claim.id,
2107
- path: `${path10}.${field}`,
2112
+ path: `${path11}.${field}`,
2108
2113
  problem: CANONICAL_EVIDENCE_PROBLEMS.invalidOptionalField(field),
2109
2114
  received: fieldValue,
2110
2115
  fix: CANONICAL_EVIDENCE_FIX.invalidOptionalField(field)
@@ -2167,7 +2172,7 @@ var init_state = __esm({
2167
2172
  if (options?.allowUnresolvedRevisions !== true) {
2168
2173
  for (const claim of state3.claims) {
2169
2174
  for (const relatedId of claim.revision?.claimIds || []) {
2170
- if (!ids.has(relatedId)) throw new Error(`Claim ${claim.id} references unknown claim ${relatedId}`);
2175
+ if (!ids.has(relatedId)) throw new Error(`Claim ${claim.id} references any claim ${relatedId}`);
2171
2176
  }
2172
2177
  }
2173
2178
  }
@@ -2191,7 +2196,7 @@ var init_state = __esm({
2191
2196
  }
2192
2197
  for (const claim of update.claims) {
2193
2198
  for (const relatedId of claim.revision?.claimIds || []) {
2194
- if (!known.has(relatedId)) throw new Error(`Claim ${claim.id} references unknown prior claim ${relatedId}`);
2199
+ if (!known.has(relatedId)) throw new Error(`Claim ${claim.id} references any prior claim ${relatedId}`);
2195
2200
  }
2196
2201
  }
2197
2202
  return structuredClone({ version: state3.version + 1, claims: [...state3.claims, ...update.claims] });
@@ -2924,7 +2929,7 @@ var init_policy_store = __esm({
2924
2929
  authority: { kind: "system", source: "policy-namespace-lock" },
2925
2930
  target: resolvePolicyNamespaceLockPath(directory),
2926
2931
  outcome: "applied",
2927
- detail: `stale policy namespace lock broken; previous owner pid ${lockBreak.brokenOwner.pid} host ${lockBreak.brokenOwner.host} acquiredAt ${lockBreak.brokenOwner.acquiredAt || "unknown"}`
2932
+ detail: `stale policy namespace lock broken; previous owner pid ${lockBreak.brokenOwner.pid} host ${lockBreak.brokenOwner.host} acquiredAt ${lockBreak.brokenOwner.acquiredAt || "any"}`
2928
2933
  })
2929
2934
  );
2930
2935
  next = { ...next, audit: boundedAudit([...next.audit, ...breakEntries], next.overrides) };
@@ -3244,7 +3249,7 @@ var init_policy_store = __esm({
3244
3249
  });
3245
3250
 
3246
3251
  // core/knowledge/sanitizer.ts
3247
- var SECRET_KEY_INDICATORS, isSecretKey, looksLikeSecretValue, looksLikeMojibake, collectMojibake, semanticizeSecret, sanitizeObject, sanitizeArray, sanitizeKnowledge;
3252
+ var SECRET_KEY_INDICATORS, isSecretKey, looksLikeSecretValue, looksLikeMojibake, collectMojibake, semanticizeSecret, sanitizeObject, sanitizeArray, sanitizeKnowledge, createSanitizedEnv;
3248
3253
  var init_sanitizer = __esm({
3249
3254
  "core/knowledge/sanitizer.ts"() {
3250
3255
  SECRET_KEY_INDICATORS = ["password", "passwd", "pwd", "secret", "apikey", "api_key", "token", "accesstoken", "refreshtoken", "privatekey", "private_key", "clientsecret", "authorization", "bearer", "credential", "credentials", "recoverycode", "sessionsecret", "jwtsecret"];
@@ -3369,6 +3374,15 @@ var init_sanitizer = __esm({
3369
3374
  disposition: "persist"
3370
3375
  };
3371
3376
  }, "sanitizeKnowledge");
3377
+ createSanitizedEnv = /* @__PURE__ */ __name(() => {
3378
+ const env = {};
3379
+ for (const [key, value] of Object.entries(process.env)) {
3380
+ if (isSecretKey(key)) continue;
3381
+ if (value === void 0 || value === null) continue;
3382
+ env[key] = value;
3383
+ }
3384
+ return env;
3385
+ }, "createSanitizedEnv");
3372
3386
  }
3373
3387
  });
3374
3388
 
@@ -3520,7 +3534,7 @@ var init_built_in_context = __esm({
3520
3534
  return __dirname;
3521
3535
  }
3522
3536
  try {
3523
- return path8.dirname(fileURLToPath(import.meta.url));
3537
+ return path5.dirname(fileURLToPath(import.meta.url));
3524
3538
  } catch {
3525
3539
  return process.cwd();
3526
3540
  }
@@ -3528,7 +3542,7 @@ var init_built_in_context = __esm({
3528
3542
  candidatePaths = /* @__PURE__ */ __name(() => {
3529
3543
  const paths = [];
3530
3544
  try {
3531
- paths.push(path8.join(pkgDirname(), "built-in-context.json"));
3545
+ paths.push(path5.join(pkgDirname(), "built-in-context.json"));
3532
3546
  } catch {
3533
3547
  }
3534
3548
  return paths;
@@ -3597,11 +3611,11 @@ var init_built_in_context = __esm({
3597
3611
  let lastError = "Built-in context artifact not found";
3598
3612
  const candidates = _artifactPathOverride ? [_artifactPathOverride] : candidatePaths();
3599
3613
  for (const candidate of candidates) {
3600
- if (!fs.existsSync(candidate)) continue;
3614
+ if (!fs6.existsSync(candidate)) continue;
3601
3615
  let readAttempts = 0;
3602
3616
  while (readAttempts < 60) {
3603
3617
  try {
3604
- const raw = fs.readFileSync(candidate);
3618
+ const raw = fs6.readFileSync(candidate);
3605
3619
  const parsed = JSON.parse(decodeText(raw, { source: candidate }));
3606
3620
  const artifact = validateArtifact(parsed);
3607
3621
  cached = artifact;
@@ -3638,15 +3652,15 @@ var init_built_in_context = __esm({
3638
3652
  }
3639
3653
  let attemptedPath = "";
3640
3654
  try {
3641
- attemptedPath = path8.join(pkgDirname(), "built-in-context.json");
3655
+ attemptedPath = path5.join(pkgDirname(), "built-in-context.json");
3642
3656
  } catch {
3643
3657
  }
3644
- let packageVersion = "unknown";
3658
+ let packageVersion = "any";
3645
3659
  try {
3646
- const pkgPath = path8.join(pkgDirname(), "package.json");
3647
- if (fs.existsSync(pkgPath)) {
3648
- const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
3649
- packageVersion = typeof pkg.version === "string" ? pkg.version : "unknown";
3660
+ const pkgPath = path5.join(pkgDirname(), "package.json");
3661
+ if (fs6.existsSync(pkgPath)) {
3662
+ const pkg = JSON.parse(fs6.readFileSync(pkgPath, "utf8"));
3663
+ packageVersion = typeof pkg.version === "string" ? pkg.version : "any";
3650
3664
  }
3651
3665
  } catch {
3652
3666
  }
@@ -5247,14 +5261,14 @@ var init_mem_package = __esm({
5247
5261
  const digest = await globalThis.crypto.subtle.digest("SHA-256", data);
5248
5262
  return `sha256:${[...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
5249
5263
  }, "sha256");
5250
- parseJson = /* @__PURE__ */ __name((bytes, path10) => {
5264
+ parseJson = /* @__PURE__ */ __name((bytes, path11) => {
5251
5265
  try {
5252
5266
  return JSON.parse(decodeText(bytes));
5253
5267
  } catch (error) {
5254
- throw new MemArtifactError("invalid", `Invalid UTF-8 JSON in ${path10}: ${error.message}`);
5268
+ throw new MemArtifactError("invalid", `Invalid UTF-8 JSON in ${path11}: ${error.message}`);
5255
5269
  }
5256
5270
  }, "parseJson");
5257
- 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");
5271
+ 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");
5258
5272
  concatenate = /* @__PURE__ */ __name((chunks, size) => {
5259
5273
  const result = new Uint8Array(size);
5260
5274
  let offset = 0;
@@ -5330,24 +5344,24 @@ var init_mem_package = __esm({
5330
5344
  [DATA_PATH]: jsonBytes(memory2.data),
5331
5345
  ...structuredClone(preservedPackage?.extensions ?? {})
5332
5346
  };
5333
- for (const path10 of Object.keys(protectedParts)) {
5334
- if (!requiredParts.includes(path10) && !path10.startsWith("extensions/")) {
5335
- throw new MemArtifactError("invalid", `Unsupported preserved package part: ${path10}`);
5347
+ for (const path11 of Object.keys(protectedParts)) {
5348
+ if (!requiredParts.includes(path11) && !path11.startsWith("extensions/")) {
5349
+ throw new MemArtifactError("invalid", `Unsupported preserved package part: ${path11}`);
5336
5350
  }
5337
- if (!validEntryPath(path10)) throw new MemArtifactError("invalid", `Unsafe MEM package path: ${path10}`);
5351
+ if (!validEntryPath(path11)) throw new MemArtifactError("invalid", `Unsafe MEM package path: ${path11}`);
5338
5352
  }
5339
- for (const path10 of Object.keys(signatures)) {
5340
- if (!/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path10)) {
5341
- throw new MemArtifactError("invalid", `Invalid MEM signature path: ${path10}`);
5353
+ for (const path11 of Object.keys(signatures)) {
5354
+ if (!/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path11)) {
5355
+ throw new MemArtifactError("invalid", `Invalid MEM signature path: ${path11}`);
5342
5356
  }
5343
5357
  }
5344
5358
  const files = {};
5345
- for (const path10 of Object.keys(protectedParts).sort()) files[path10] = await sha2562(protectedParts[path10]);
5359
+ for (const path11 of Object.keys(protectedParts).sort()) files[path11] = await sha2562(protectedParts[path11]);
5346
5360
  const integrity = { algorithm: "sha256", files, contentId: await digestTableIdentity(files) };
5347
5361
  const parts = { ...protectedParts, [INTEGRITY_PATH]: jsonBytes(integrity), ...signatures };
5348
- for (const [path10, bytes] of Object.entries(parts)) {
5362
+ for (const [path11, bytes] of Object.entries(parts)) {
5349
5363
  if (bytes.length > MEM_PACKAGE_WRITE_LIMITS.maximumEntryBytes) {
5350
- throw new MemArtifactError("invalid", `MEM package entry exceeds the write limit: ${path10}`);
5364
+ throw new MemArtifactError("invalid", `MEM package entry exceeds the write limit: ${path11}`);
5351
5365
  }
5352
5366
  }
5353
5367
  const uncompressedBytes = Object.values(parts).reduce((total, bytes) => total + bytes.length, 0);
@@ -5355,10 +5369,10 @@ var init_mem_package = __esm({
5355
5369
  throw new MemArtifactError("invalid", "MEM package exceeds the write limit for uncompressed content");
5356
5370
  }
5357
5371
  const zippable = Object.fromEntries(
5358
- Object.keys(parts).sort().map((path10) => [
5359
- path10,
5372
+ Object.keys(parts).sort().map((path11) => [
5373
+ path11,
5360
5374
  [
5361
- parts[path10],
5375
+ parts[path11],
5362
5376
  {
5363
5377
  level: 6,
5364
5378
  mtime: /* @__PURE__ */ new Date("1980-01-02T00:00:00.000Z")
@@ -5378,8 +5392,8 @@ var init_mem_package = __esm({
5378
5392
  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");
5379
5393
  decodePackage = /* @__PURE__ */ __name(async (bytes) => {
5380
5394
  const parts = readZipParts(bytes);
5381
- for (const path10 of [...requiredParts, INTEGRITY_PATH]) {
5382
- if (!parts[path10]) throw new MemArtifactError("invalid", `Missing MEM package part: ${path10}`);
5395
+ for (const path11 of [...requiredParts, INTEGRITY_PATH]) {
5396
+ if (!parts[path11]) throw new MemArtifactError("invalid", `Missing MEM package part: ${path11}`);
5383
5397
  }
5384
5398
  const manifest = parseJson(parts[MANIFEST_PATH], MANIFEST_PATH);
5385
5399
  if (manifest.format !== MEM_PACKAGE_FORMAT && manifest.format !== MEM_PACKAGE_FORMAT_LEGACY || manifest.version !== MEM_PACKAGE_VERSION) {
@@ -5390,8 +5404,8 @@ var init_mem_package = __esm({
5390
5404
  }
5391
5405
  const integrity = parseJson(parts[INTEGRITY_PATH], INTEGRITY_PATH);
5392
5406
  if (integrity.algorithm !== "sha256") throw new MemArtifactError("unsupported", "Unsupported MEM package integrity algorithm");
5393
- const signaturePaths = Object.keys(parts).filter((path10) => path10.startsWith("security/signatures/")).sort();
5394
- if (signaturePaths.some((path10) => !/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path10))) {
5407
+ const signaturePaths = Object.keys(parts).filter((path11) => path11.startsWith("security/signatures/")).sort();
5408
+ if (signaturePaths.some((path11) => !/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path11))) {
5395
5409
  throw new MemArtifactError("invalid", "Invalid MEM signature entry path");
5396
5410
  }
5397
5411
  if (manifest.authenticity !== void 0 && manifest.authenticity.signed !== true) {
@@ -5400,14 +5414,14 @@ var init_mem_package = __esm({
5400
5414
  if (manifest.authenticity?.signed === true !== signaturePaths.length > 0) {
5401
5415
  throw new MemArtifactError("invalid", "Declared MEM signatures do not match package entries");
5402
5416
  }
5403
- const archivePaths = Object.keys(parts).filter((path10) => path10 !== INTEGRITY_PATH && !path10.startsWith("security/signatures/")).sort();
5417
+ const archivePaths = Object.keys(parts).filter((path11) => path11 !== INTEGRITY_PATH && !path11.startsWith("security/signatures/")).sort();
5404
5418
  const protectedPaths = Object.keys(integrity.files ?? {}).sort();
5405
5419
  if (JSON.stringify(archivePaths) !== JSON.stringify(protectedPaths)) {
5406
5420
  throw new MemArtifactError("invalid", "MEM package protected-parts table does not match archive contents");
5407
5421
  }
5408
- for (const path10 of protectedPaths) {
5409
- const actual = await sha2562(parts[path10]);
5410
- if (integrity.files[path10] !== actual) throw new MemArtifactError("checksum_mismatch", `Checksum mismatch for ${path10}`);
5422
+ for (const path11 of protectedPaths) {
5423
+ const actual = await sha2562(parts[path11]);
5424
+ if (integrity.files[path11] !== actual) throw new MemArtifactError("checksum_mismatch", `Checksum mismatch for ${path11}`);
5411
5425
  }
5412
5426
  if (integrity.contentId !== await digestTableIdentity(integrity.files)) {
5413
5427
  throw new MemArtifactError("checksum_mismatch", "MEM package content identity mismatch");
@@ -5420,8 +5434,8 @@ var init_mem_package = __esm({
5420
5434
  } catch (error) {
5421
5435
  throw new MemArtifactError("invalid", `Invalid packaged MEM semantics: ${error.message}`);
5422
5436
  }
5423
- const extensions = Object.fromEntries(Object.entries(parts).filter(([path10]) => path10.startsWith("extensions/")));
5424
- const signatures = Object.fromEntries(signaturePaths.map((path10) => [path10, parts[path10]]));
5437
+ const extensions = Object.fromEntries(Object.entries(parts).filter(([path11]) => path11.startsWith("extensions/")));
5438
+ const signatures = Object.fromEntries(signaturePaths.map((path11) => [path11, parts[path11]]));
5425
5439
  return { ...decoded, representation: "package-v1", package: { manifest, extensions, signatures }, parts, integrity };
5426
5440
  }, "decodePackage");
5427
5441
  decodeMemArtifact = /* @__PURE__ */ __name(async (input) => {
@@ -5460,13 +5474,13 @@ var init_quarantine = __esm({
5460
5474
  quarantineClaimRecord = /* @__PURE__ */ __name(async (record) => {
5461
5475
  if (!record.filePath) return null;
5462
5476
  try {
5463
- const dir = path8.dirname(record.filePath);
5464
- const quarantineDir = path8.join(dir, "quarantine");
5477
+ const dir = path5.dirname(record.filePath);
5478
+ const quarantineDir = path5.join(dir, "quarantine");
5465
5479
  await fs14.mkdir(quarantineDir, { recursive: true });
5466
- const safeId = String(record.claimId ?? "unknown").replace(/[^a-zA-Z0-9._-]/g, "-");
5480
+ const safeId = String(record.claimId ?? "any").replace(/[^a-zA-Z0-9._-]/g, "-");
5467
5481
  const timestamp = record.timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
5468
5482
  const fileName = `${safeId}-${Date.now()}.json`;
5469
- const fullPath = path8.join(quarantineDir, fileName);
5483
+ const fullPath = path5.join(quarantineDir, fileName);
5470
5484
  const payload = {
5471
5485
  claimId: record.claimId,
5472
5486
  store: record.store,
@@ -5507,7 +5521,7 @@ var init_store_registry = __esm({
5507
5521
  }
5508
5522
  for (const dirent of dirents) {
5509
5523
  if (!dirent.isFile()) continue;
5510
- const filePath = path8.join(directory, dirent.name);
5524
+ const filePath = path5.join(directory, dirent.name);
5511
5525
  if (isMemFile(dirent.name)) {
5512
5526
  entries2.push({ id: dirent.name, path: filePath, kind: "active", active: true, reason: "active .mem store" });
5513
5527
  continue;
@@ -5670,7 +5684,7 @@ var init_claim_delete = __esm({
5670
5684
  }
5671
5685
  let deleted = false;
5672
5686
  for (const location of selected) {
5673
- await withStorageLock(path8.dirname(location.filePath), async () => {
5687
+ await withStorageLock(path5.dirname(location.filePath), async () => {
5674
5688
  const bytes = await fs14.readFile(location.filePath);
5675
5689
  const artifact = await decodeMemArtifact(bytes);
5676
5690
  if (!artifact.state) throw new Error(`Unable to read store ${location.filePath}`);
@@ -6151,31 +6165,6 @@ var init_mem_repository = __esm({
6151
6165
  };
6152
6166
  }
6153
6167
  });
6154
- function parseProbe(probe) {
6155
- if (!probe) return null;
6156
- if (typeof probe === "string") {
6157
- const parts = probe.trim().split(/\s+/);
6158
- return { type: parts[0], args: parts.slice(1) };
6159
- }
6160
- if (typeof probe === "object") {
6161
- const type = String(probe.type ?? probe.kind ?? probe.name ?? "");
6162
- if (type === "file-exists") return { type, args: [String(probe.path ?? probe.file ?? probe.target ?? "")] };
6163
- if (type === "file-contains") return { type, args: [String(probe.path ?? probe.file ?? ""), String(probe.literal ?? probe.contains ?? probe.value ?? "")] };
6164
- if (type === "json-path") return { type, args: [String(probe.file ?? probe.path ?? ""), String(probe.path ?? probe.jsonPath ?? ""), String(probe.expected ?? probe.value ?? "")] };
6165
- 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) };
6166
- return { type, args: [] };
6167
- }
6168
- return null;
6169
- }
6170
- function allowlist() {
6171
- try {
6172
- const raw = fs.readFileSync(`${resolveUserDotMemPath()}/probe-allowlist.json`, "utf8");
6173
- const parsed = JSON.parse(raw);
6174
- if (Array.isArray(parsed)) return parsed.map(String);
6175
- } catch {
6176
- }
6177
- return ["node", "git", "bun"];
6178
- }
6179
6168
  function runProbe(probe) {
6180
6169
  const spec = parseProbe(probe);
6181
6170
  if (!spec) return true;
@@ -6185,23 +6174,54 @@ function runProbe(probe) {
6185
6174
  let ok = false;
6186
6175
  try {
6187
6176
  if (spec.type === "file-exists") {
6188
- ok = fs.existsSync(spec.args[0]);
6177
+ const target = spec.args[0];
6178
+ if (!isAuthorizedPath(target)) {
6179
+ cache.set(key, { at: Date.now(), ok: false });
6180
+ return false;
6181
+ }
6182
+ ok = fs6.existsSync(target);
6189
6183
  } else if (spec.type === "file-contains") {
6190
- const content = fs.readFileSync(spec.args[0], "utf8");
6184
+ const target = spec.args[0];
6185
+ if (!isAuthorizedPath(target)) {
6186
+ cache.set(key, { at: Date.now(), ok: false });
6187
+ return false;
6188
+ }
6189
+ const stat = fs6.statSync(target);
6190
+ if (stat.size > MAX_PROBE_FILE_BYTES) {
6191
+ cache.set(key, { at: Date.now(), ok: false });
6192
+ return false;
6193
+ }
6194
+ const content = fs6.readFileSync(target, "utf8");
6191
6195
  ok = content.includes(spec.args[1]);
6192
6196
  } else if (spec.type === "json-path") {
6193
- const obj = JSON.parse(fs.readFileSync(spec.args[0], "utf8"));
6197
+ const target = spec.args[0];
6198
+ if (!isAuthorizedPath(target)) {
6199
+ cache.set(key, { at: Date.now(), ok: false });
6200
+ return false;
6201
+ }
6202
+ const stat = fs6.statSync(target);
6203
+ if (stat.size > MAX_PROBE_FILE_BYTES) {
6204
+ cache.set(key, { at: Date.now(), ok: false });
6205
+ return false;
6206
+ }
6207
+ const obj = JSON.parse(fs6.readFileSync(target, "utf8"));
6194
6208
  const pathParts = spec.args[1].split(".");
6195
6209
  let cur = obj;
6196
6210
  for (const p of pathParts) cur = cur?.[p];
6197
6211
  ok = String(cur) === spec.args[2];
6198
6212
  } else if (spec.type === "command") {
6199
6213
  const cmd = spec.args[0];
6200
- if (!allowlist().includes(cmd)) {
6214
+ const args = spec.args.slice(1);
6215
+ if (args.some((a) => DANGEROUS_FLAGS.has(a))) {
6216
+ cache.set(key, { at: Date.now(), ok: false });
6217
+ return false;
6218
+ }
6219
+ const handler = isTrustedCommand(cmd, args);
6220
+ if (!handler) {
6201
6221
  cache.set(key, { at: Date.now(), ok: false });
6202
6222
  return false;
6203
6223
  }
6204
- const res = spawnSync(cmd, spec.args.slice(1), { timeout: 5e3, encoding: "utf8", shell: false, maxBuffer: 64 * 1024 });
6224
+ const res = spawnSync(handler.cmd, handler.args, { timeout: 5e3, encoding: "utf8", shell: false, maxBuffer: 64 * 1024, env: createSanitizedEnv() });
6205
6225
  ok = res.status === 0;
6206
6226
  } else {
6207
6227
  ok = false;
@@ -6212,12 +6232,91 @@ function runProbe(probe) {
6212
6232
  cache.set(key, { at: Date.now(), ok });
6213
6233
  return ok;
6214
6234
  }
6215
- var cache, CACHE_MS;
6235
+ var TRUSTED_PROBES, DANGEROUS_FLAGS, MAX_PROBE_FILE_BYTES, AUTHORIZED_ROOTS, isAuthorizedPath, isTrustedCommand, parseProbe, cache, CACHE_MS;
6216
6236
  var init_probe = __esm({
6217
6237
  "core/knowledge/probe.ts"() {
6218
- init_user_paths();
6219
- __name(parseProbe, "parseProbe");
6220
- __name(allowlist, "allowlist");
6238
+ init_sanitizer();
6239
+ TRUSTED_PROBES = [
6240
+ { id: "node-version", cmd: "node", args: ["--version"] },
6241
+ { id: "git-version", cmd: "git", args: ["--version"] }
6242
+ ];
6243
+ DANGEROUS_FLAGS = /* @__PURE__ */ new Set(["-e", "--eval", "-p", "--print", "-r", "--require", "--loader", "--input-type", "--experimental-vm-modules", "--experimental-loader"]);
6244
+ MAX_PROBE_FILE_BYTES = 10 * 1024 * 1024;
6245
+ AUTHORIZED_ROOTS = Array.from(/* @__PURE__ */ new Set([
6246
+ path5.resolve(process.cwd()),
6247
+ path5.resolve(tmpdir())
6248
+ ]));
6249
+ isAuthorizedPath = /* @__PURE__ */ __name((candidate) => {
6250
+ if (typeof candidate !== "string" || candidate.length === 0) return false;
6251
+ if (candidate.includes("\0")) return false;
6252
+ if (candidate.startsWith("\\\\") || candidate.startsWith("//")) return false;
6253
+ const resolved = path5.resolve(candidate);
6254
+ const lexicallyAllowed = AUTHORIZED_ROOTS.some((root) => {
6255
+ const rel = path5.relative(root, resolved);
6256
+ return rel === "" || !rel.startsWith("..") && !path5.isAbsolute(rel);
6257
+ });
6258
+ if (!lexicallyAllowed) return false;
6259
+ try {
6260
+ if (fs6.existsSync(resolved)) {
6261
+ const real = fs6.realpathSync(resolved);
6262
+ const reallyAllowed = AUTHORIZED_ROOTS.some((root) => {
6263
+ let realRoot = root;
6264
+ try {
6265
+ realRoot = fs6.realpathSync(root);
6266
+ } catch {
6267
+ }
6268
+ const rel = path5.relative(realRoot, real);
6269
+ return rel === "" || !rel.startsWith("..") && !path5.isAbsolute(rel);
6270
+ });
6271
+ if (!reallyAllowed) return false;
6272
+ }
6273
+ } catch {
6274
+ return false;
6275
+ }
6276
+ return true;
6277
+ }, "isAuthorizedPath");
6278
+ isTrustedCommand = /* @__PURE__ */ __name((cmd, args) => {
6279
+ return TRUSTED_PROBES.find((p) => p.cmd === cmd && JSON.stringify(p.args) === JSON.stringify(args)) ?? null;
6280
+ }, "isTrustedCommand");
6281
+ parseProbe = /* @__PURE__ */ __name((probe) => {
6282
+ if (!probe) return null;
6283
+ if (typeof probe === "string") {
6284
+ const parts = probe.trim().split(/\s+/);
6285
+ return { type: parts[0], args: parts.slice(1) };
6286
+ }
6287
+ if (typeof probe === "object") {
6288
+ const type = String(probe.type ?? probe.kind ?? probe.name ?? "");
6289
+ if (type === "file-exists") return { type, args: [String(probe.path ?? probe.file ?? probe.target ?? "")] };
6290
+ if (type === "file-contains") return { type, args: [String(probe.path ?? probe.file ?? ""), String(probe.literal ?? probe.contains ?? probe.value ?? "")] };
6291
+ if (type === "json-path") return { type, args: [String(probe.file ?? probe.path ?? ""), String(probe.path ?? probe.jsonPath ?? ""), String(probe.expected ?? probe.value ?? "")] };
6292
+ if (type === "command" || type === "probe") {
6293
+ if (typeof probe.id === "string") {
6294
+ const found = TRUSTED_PROBES.find((p) => p.id === probe.id);
6295
+ if (found) return { type: "command", args: [found.cmd, ...found.args] };
6296
+ return { type: "command", args: [] };
6297
+ }
6298
+ let cmd;
6299
+ let args = [];
6300
+ if (Array.isArray(probe.args) && probe.args.length > 0) {
6301
+ cmd = String(probe.args[0]);
6302
+ args = probe.args.slice(1).map(String);
6303
+ } else if (Array.isArray(probe.command)) {
6304
+ cmd = String(probe.command[0]);
6305
+ args = probe.command.slice(1).map(String);
6306
+ } else if (typeof probe.command === "string") {
6307
+ const parts = probe.command.trim().split(/\s+/);
6308
+ cmd = parts[0];
6309
+ args = parts.slice(1);
6310
+ }
6311
+ if (cmd) {
6312
+ return { type: "command", args: [cmd, ...args] };
6313
+ }
6314
+ return { type: "command", args: [] };
6315
+ }
6316
+ return { type, args: [] };
6317
+ }
6318
+ return null;
6319
+ }, "parseProbe");
6221
6320
  cache = /* @__PURE__ */ new Map();
6222
6321
  CACHE_MS = 6e4;
6223
6322
  __name(runProbe, "runProbe");
@@ -6232,19 +6331,6 @@ __export(telemetry_exports, {
6232
6331
  recordProjection: () => recordProjection,
6233
6332
  recordRetraction: () => recordRetraction
6234
6333
  });
6235
- function load() {
6236
- try {
6237
- return JSON.parse(fs.readFileSync(file(), "utf8"));
6238
- } catch {
6239
- return {};
6240
- }
6241
- }
6242
- function save(store7) {
6243
- try {
6244
- fs.writeFileSync(file(), JSON.stringify(store7, null, 2), "utf8");
6245
- } catch {
6246
- }
6247
- }
6248
6334
  function recordProjection(ids) {
6249
6335
  const store7 = load();
6250
6336
  const now3 = (/* @__PURE__ */ new Date()).toISOString();
@@ -6273,13 +6359,24 @@ function recordRetraction(id) {
6273
6359
  function readTelemetry() {
6274
6360
  return load();
6275
6361
  }
6276
- var file;
6362
+ var file, load, save;
6277
6363
  var init_telemetry = __esm({
6278
6364
  "core/knowledge/telemetry.ts"() {
6279
6365
  init_user_paths();
6280
6366
  file = /* @__PURE__ */ __name(() => `${resolveUserDotMemPath()}/telemetry.json`, "file");
6281
- __name(load, "load");
6282
- __name(save, "save");
6367
+ load = /* @__PURE__ */ __name(() => {
6368
+ try {
6369
+ return JSON.parse(fs6.readFileSync(file(), "utf8"));
6370
+ } catch {
6371
+ return {};
6372
+ }
6373
+ }, "load");
6374
+ save = /* @__PURE__ */ __name((store7) => {
6375
+ try {
6376
+ fs6.writeFileSync(file(), JSON.stringify(store7, null, 2), "utf8");
6377
+ } catch {
6378
+ }
6379
+ }, "save");
6283
6380
  __name(recordProjection, "recordProjection");
6284
6381
  __name(recordFeedback, "recordFeedback");
6285
6382
  __name(recordRetraction, "recordRetraction");
@@ -6326,7 +6423,7 @@ var init_currentness = __esm({
6326
6423
  const verifiedAt = verifiedAtOf(claim);
6327
6424
  if (verifiedAt !== void 0) return "verified";
6328
6425
  if (claim.epistemicType === "verified") return "unverified";
6329
- return "unknown-currentness";
6426
+ return "any-currentness";
6330
6427
  }, "deriveCurrentness");
6331
6428
  }
6332
6429
  });
@@ -7170,7 +7267,7 @@ var init_staging = __esm({
7170
7267
  throw new Error("Stage file must contain a claim object");
7171
7268
  }
7172
7269
  const claimValidation = buildClaimRecord({
7173
- id: s.claim.id,
7270
+ id: typeof s.claim.id === "string" ? s.claim.id : "",
7174
7271
  knowledge: s.claim.knowledge,
7175
7272
  applicability: s.claim.applicability,
7176
7273
  evidence: s.claim.evidence,
@@ -7587,7 +7684,7 @@ var init_violations = __esm({
7587
7684
  VIOLATION_FILE_NAME = "violations.json";
7588
7685
  }
7589
7686
  });
7590
- var isRuleClaim, isIronRule, extractIronRules, readViolationCounts, sortRulesByViolationFrequency, loadIronRules, ruleSetSignature;
7687
+ var isRuleClaim, isIronRule, extractIronRules, readViolationCounts, sortRulesByViolationFrequency, loadIronRules;
7591
7688
  var init_rules_loader = __esm({
7592
7689
  "core/knowledge/rules-loader.ts"() {
7593
7690
  init_state();
@@ -7653,15 +7750,6 @@ var init_rules_loader = __esm({
7653
7750
  sortedBy: "violation-frequency"
7654
7751
  };
7655
7752
  }, "loadIronRules");
7656
- ruleSetSignature = /* @__PURE__ */ __name((rules) => {
7657
- const material = rules.map((rule) => `${rule.id}\0${rule.text}`).join("");
7658
- let hash = 2166136261;
7659
- for (let index = 0; index < material.length; index += 1) {
7660
- hash ^= material.charCodeAt(index);
7661
- hash = Math.imul(hash, 16777619) >>> 0;
7662
- }
7663
- return hash.toString(16).padStart(8, "0");
7664
- }, "ruleSetSignature");
7665
7753
  }
7666
7754
  });
7667
7755
 
@@ -7845,25 +7933,25 @@ var init_exemplars = __esm({
7845
7933
  resolveExemplarsPath = /* @__PURE__ */ __name(() => {
7846
7934
  return joinPath3(resolveUserDotMemPath(), EXEMPLARS_FILE_NAME);
7847
7935
  }, "resolveExemplarsPath");
7848
- readFile = /* @__PURE__ */ __name(async (path10) => {
7936
+ readFile = /* @__PURE__ */ __name(async (path11) => {
7849
7937
  try {
7850
7938
  const fs16 = await import('fs/promises');
7851
- return await fs16.readFile(path10, "utf8");
7939
+ return await fs16.readFile(path11, "utf8");
7852
7940
  } catch {
7853
7941
  return null;
7854
7942
  }
7855
7943
  }, "readFile");
7856
- writeFile = /* @__PURE__ */ __name(async (path10, content) => {
7944
+ writeFile = /* @__PURE__ */ __name(async (path11, content) => {
7857
7945
  const fs16 = await import('fs/promises');
7858
- const dir = path10.replace(/[\\/][^\\/]+$/, "");
7946
+ const dir = path11.replace(/[\\/][^\\/]+$/, "");
7859
7947
  await fs16.mkdir(dir, { recursive: true });
7860
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
7948
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
7861
7949
  try {
7862
7950
  await fs16.writeFile(temporary, content, "utf8");
7863
- await fs16.rename(temporary, path10);
7951
+ await fs16.rename(temporary, path11);
7864
7952
  } catch {
7865
7953
  await fs16.rm(temporary, { force: true }).catch(() => void 0);
7866
- throw new Error(`Failed to write exemplars file at ${path10}`);
7954
+ throw new Error(`Failed to write exemplars file at ${path11}`);
7867
7955
  }
7868
7956
  }, "writeFile");
7869
7957
  emptyStore = /* @__PURE__ */ __name(() => {
@@ -11401,25 +11489,25 @@ var init_loops = __esm({
11401
11489
  release();
11402
11490
  }
11403
11491
  }, "withLoopLock");
11404
- readFile2 = /* @__PURE__ */ __name(async (path10) => {
11492
+ readFile2 = /* @__PURE__ */ __name(async (path11) => {
11405
11493
  try {
11406
11494
  const fs16 = await import('fs/promises');
11407
- return await fs16.readFile(path10, "utf8");
11495
+ return await fs16.readFile(path11, "utf8");
11408
11496
  } catch {
11409
11497
  return null;
11410
11498
  }
11411
11499
  }, "readFile");
11412
- writeFile2 = /* @__PURE__ */ __name(async (path10, content) => {
11500
+ writeFile2 = /* @__PURE__ */ __name(async (path11, content) => {
11413
11501
  const fs16 = await import('fs/promises');
11414
- const dir = path10.replace(/[\\/][^\\/]+$/, "");
11502
+ const dir = path11.replace(/[\\/][^\\/]+$/, "");
11415
11503
  await fs16.mkdir(dir, { recursive: true });
11416
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
11504
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
11417
11505
  try {
11418
11506
  await fs16.writeFile(temporary, content, "utf8");
11419
- await fs16.rename(temporary, path10);
11507
+ await fs16.rename(temporary, path11);
11420
11508
  } catch {
11421
11509
  await fs16.rm(temporary, { force: true }).catch(() => void 0);
11422
- throw new Error(`Failed to write loops file at ${path10}`);
11510
+ throw new Error(`Failed to write loops file at ${path11}`);
11423
11511
  }
11424
11512
  }, "writeFile");
11425
11513
  emptyDocument = /* @__PURE__ */ __name(() => {
@@ -11503,7 +11591,7 @@ var init_loops = __esm({
11503
11591
  text: input.text,
11504
11592
  waitor: input.waitor,
11505
11593
  openedAt: input.openedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
11506
- authorAgent: input.authorAgent ?? "unknown",
11594
+ authorAgent: input.authorAgent ?? "any",
11507
11595
  targetRole: input.targetRole ?? "any",
11508
11596
  status: input.status ?? "open",
11509
11597
  projectId: input.projectId,
@@ -11569,25 +11657,25 @@ var init_personality_anchor = __esm({
11569
11657
  resolvePersonalityAnchorPath = /* @__PURE__ */ __name(() => {
11570
11658
  return joinPath5(resolveUserDotMemPath(), PERSONALITY_ANCHOR_FILE_NAME);
11571
11659
  }, "resolvePersonalityAnchorPath");
11572
- readFile3 = /* @__PURE__ */ __name(async (path10) => {
11660
+ readFile3 = /* @__PURE__ */ __name(async (path11) => {
11573
11661
  try {
11574
11662
  const fs16 = await import('fs/promises');
11575
- return await fs16.readFile(path10, "utf8");
11663
+ return await fs16.readFile(path11, "utf8");
11576
11664
  } catch {
11577
11665
  return null;
11578
11666
  }
11579
11667
  }, "readFile");
11580
- writeFile3 = /* @__PURE__ */ __name(async (path10, content) => {
11668
+ writeFile3 = /* @__PURE__ */ __name(async (path11, content) => {
11581
11669
  const fs16 = await import('fs/promises');
11582
- const dir = path10.replace(/[\\/][^\\/]+$/, "");
11670
+ const dir = path11.replace(/[\\/][^\\/]+$/, "");
11583
11671
  await fs16.mkdir(dir, { recursive: true });
11584
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
11672
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
11585
11673
  try {
11586
11674
  await fs16.writeFile(temporary, content, "utf8");
11587
- await fs16.rename(temporary, path10);
11675
+ await fs16.rename(temporary, path11);
11588
11676
  } catch {
11589
11677
  await fs16.rm(temporary, { force: true }).catch(() => void 0);
11590
- throw new Error(`Failed to write personality anchor at ${path10}`);
11678
+ throw new Error(`Failed to write personality anchor at ${path11}`);
11591
11679
  }
11592
11680
  }, "writeFile");
11593
11681
  emptyAnchor = /* @__PURE__ */ __name(() => {
@@ -11796,6 +11884,7 @@ var init_repository = __esm({
11796
11884
  var init_rule_checker = __esm({
11797
11885
  "core/knowledge/rule-checker.ts"() {
11798
11886
  init_state();
11887
+ init_sanitizer();
11799
11888
  }
11800
11889
  });
11801
11890
 
@@ -11886,12 +11975,12 @@ var init_user_language = __esm({
11886
11975
  resolveLanguagePreferencePath = /* @__PURE__ */ __name(() => {
11887
11976
  return resolveUserLanguagePath();
11888
11977
  }, "resolveLanguagePreferencePath");
11889
- readJsonFile = /* @__PURE__ */ __name((path10) => {
11978
+ readJsonFile = /* @__PURE__ */ __name((path11) => {
11890
11979
  const fs16 = getSyncFs();
11891
11980
  if (!fs16) return null;
11892
11981
  let raw;
11893
11982
  try {
11894
- raw = decodeText(fs16.readFileSync(path10), { source: path10 });
11983
+ raw = decodeText(fs16.readFileSync(path11), { source: path11 });
11895
11984
  } catch {
11896
11985
  return null;
11897
11986
  }
@@ -11988,14 +12077,14 @@ var init_user_language = __esm({
11988
12077
  }, "getResponseLanguage");
11989
12078
  setUserLanguage = /* @__PURE__ */ __name(async (language2) => {
11990
12079
  const fsMod = await import('fs/promises');
11991
- const path10 = resolveUserLanguagePath();
11992
- const dir = parentStoragePath(path10);
12080
+ const path11 = resolveUserLanguagePath();
12081
+ const dir = parentStoragePath(path11);
11993
12082
  await fsMod.mkdir(dir, { recursive: true });
11994
12083
  const payload = { format: "dotmem.language", version: 1, language: String(language2).trim() };
11995
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
12084
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
11996
12085
  await fsMod.writeFile(temporary, `${JSON.stringify(payload, null, 2)}
11997
12086
  `, "utf8");
11998
- await fsMod.rename(temporary, path10);
12087
+ await fsMod.rename(temporary, path11);
11999
12088
  return payload.language;
12000
12089
  }, "setUserLanguage");
12001
12090
  saveUserLanguage = /* @__PURE__ */ __name(async (language2) => {
@@ -12049,115 +12138,755 @@ var init_session_metrics = __esm({
12049
12138
  }
12050
12139
  });
12051
12140
 
12052
- // core/knowledge/loading-policy.ts
12053
- var init_loading_policy = __esm({
12054
- "core/knowledge/loading-policy.ts"() {
12055
- }
12056
- });
12057
-
12058
- // core/knowledge/index.ts
12059
- var init_knowledge = __esm({
12060
- "core/knowledge/index.ts"() {
12061
- init_acquisition_boundary();
12062
- init_acquisition_limits();
12063
- init_applicability();
12064
- init_behavioral_invariants();
12065
- init_bootstrap();
12066
- init_built_in_context();
12067
- init_built_in_context_rules();
12068
- init_canonical_hash();
12069
- init_canonical_reconstruction();
12070
- init_canonical_schema();
12071
- init_context_budget();
12072
- init_contract();
12073
- init_correction();
12074
- init_currentness();
12141
+ // core/knowledge/hard-rules-registry.ts
12142
+ 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;
12143
+ var init_hard_rules_registry = __esm({
12144
+ "core/knowledge/hard-rules-registry.ts"() {
12075
12145
  init_detection_events();
12076
- init_detection_journal();
12077
- init_discover();
12078
- init_solvers();
12079
- init_signatures();
12080
- init_probe();
12081
- init_semantic_provider();
12082
- init_effective_contract();
12083
- init_exemplars();
12084
- init_explain();
12085
- init_feedback();
12086
- init_fingerprint();
12087
- init_identity_governance();
12088
- init_identity_resolution();
12089
- init_incidents();
12090
- init_inspect_report();
12091
- init_language_detect();
12092
- init_loops();
12093
- init_mem_package();
12094
- init_personality_anchor();
12095
12146
  init_policy();
12096
12147
  init_policy_namespace_lock();
12097
- init_policy_store();
12098
- init_project();
12099
- init_project_anchor();
12100
- init_read_only();
12101
- init_renderer();
12102
- init_repository();
12103
- init_rule_checker();
12104
- init_rules_loader();
12105
- init_runtime();
12106
- init_scope_eligibility();
12107
- init_select();
12108
- init_session();
12109
- init_staging();
12110
- init_state();
12111
- init_storage_location();
12112
- init_storage_settings();
12113
- init_tool_guard();
12114
- init_user_identity();
12115
- init_user_language();
12116
12148
  init_user_paths();
12117
- init_vault();
12118
- init_verification();
12119
- init_verify();
12120
- init_violations();
12121
- init_claim_identity();
12122
- init_store_registry();
12123
- init_migration_audit();
12124
- init_session_metrics();
12125
- init_loading_policy();
12126
- init_session_metrics();
12127
- init_session_metrics();
12128
- init_session_metrics();
12129
- }
12130
- });
12131
-
12132
- // core/logic/helpers.ts
12133
- var normalizeClaimIds2, revisionFromAcquire;
12134
- var init_helpers = __esm({
12135
- "core/logic/helpers.ts"() {
12136
- normalizeClaimIds2 = /* @__PURE__ */ __name((value) => {
12137
- if (!value) return [];
12138
- return Array.isArray(value) ? value : [value];
12139
- }, "normalizeClaimIds");
12140
- revisionFromAcquire = /* @__PURE__ */ __name((opts) => {
12141
- const refines = normalizeClaimIds2(opts.refines);
12142
- const supersedes = normalizeClaimIds2(opts.supersedes);
12143
- const retracts = normalizeClaimIds2(opts.retracts);
12144
- if ([refines, supersedes, retracts].filter((ids) => ids.length > 0).length > 1) {
12145
- throw new Error("Acquired knowledge can refine, supersede, or retract prior knowledge, not more than one");
12149
+ HARD_RULES_REGISTRY_FORMAT = "dotmem.hard-rules";
12150
+ HARD_RULES_REGISTRY_VERSION = 1;
12151
+ HARD_RULES_REGISTRY_AUDIT_RETENTION = 200;
12152
+ HARD_RULES_REGISTRY_FILE_NAME = "hard-rules.registry.json";
12153
+ HardRulesRegistryError = class extends Error {
12154
+ static {
12155
+ __name(this, "HardRulesRegistryError");
12146
12156
  }
12147
- if (refines.length > 0) return { kind: "refines", claimIds: refines, ...opts.reason ? { reason: opts.reason } : {} };
12148
- if (supersedes.length > 0) return { kind: "supersedes", claimIds: supersedes, ...opts.reason ? { reason: opts.reason } : {} };
12149
- if (retracts.length > 0) return { kind: "retracts", claimIds: retracts, ...opts.reason ? { reason: opts.reason } : {} };
12150
- return void 0;
12151
- }, "revisionFromAcquire");
12157
+ constructor(message) {
12158
+ super(message);
12159
+ this.name = "HardRulesRegistryError";
12160
+ }
12161
+ };
12162
+ requiredText3 = /* @__PURE__ */ __name((v) => typeof v === "string" && v.trim().length > 0, "requiredText");
12163
+ nowIso = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
12164
+ joinPath7 = /* @__PURE__ */ __name((base, child) => {
12165
+ const sep = process.platform === "win32" ? "\\" : "/";
12166
+ return `${base.replace(/[\\/]+/g, sep)}${sep}${child}`;
12167
+ }, "joinPath");
12168
+ resolveRegistryDir = /* @__PURE__ */ __name((directory) => directory ?? joinPath7(resolveUserDotMemPath(), "policy"), "resolveRegistryDir");
12169
+ resolveRegistryFilePath = /* @__PURE__ */ __name((directory) => joinPath7(resolveRegistryDir(directory), HARD_RULES_REGISTRY_FILE_NAME), "resolveRegistryFilePath");
12170
+ validateHardRuleAuthority = /* @__PURE__ */ __name((value) => {
12171
+ try {
12172
+ return validatePolicyAuthority(value);
12173
+ } catch (err3) {
12174
+ void detectAuthorityEscalationAttempt({ claimed: "invalid hard-rule authority", channel: "hard-rules" }).catch(() => void 0);
12175
+ throw err3 instanceof HardRulesRegistryError ? err3 : new HardRulesRegistryError(err3.message);
12176
+ }
12177
+ }, "validateHardRuleAuthority");
12178
+ canonicalFingerprint = /* @__PURE__ */ __name((rule) => {
12179
+ const payload = {
12180
+ id: rule.id,
12181
+ version: rule.version,
12182
+ ruleClass: rule.ruleClass,
12183
+ status: rule.status,
12184
+ scope: rule.scope,
12185
+ statement: rule.statement,
12186
+ applicability: rule.applicability ?? null,
12187
+ authority: rule.authority
12188
+ };
12189
+ return `hr.${rule.id}@v${rule.version}.${Buffer.from(JSON.stringify(payload)).toString("base64").slice(0, 16)}`;
12190
+ }, "canonicalFingerprint");
12191
+ validateRule = /* @__PURE__ */ __name((value) => {
12192
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new HardRulesRegistryError("Hard rule must be an object");
12193
+ const r = value;
12194
+ if (!requiredText3(r.id)) throw new HardRulesRegistryError("id is required");
12195
+ if (typeof r.version !== "number" || !Number.isInteger(r.version) || r.version < 1) throw new HardRulesRegistryError("version must be a positive integer");
12196
+ if (typeof r.revision !== "number" || !Number.isInteger(r.revision) || r.revision < 0) throw new HardRulesRegistryError("revision must be a non-negative integer");
12197
+ if (typeof r.ruleClass !== "string" || !["IMMUTABLE", "OWNER_CONTROLLED", "USER_OVERRIDEABLE", "SESSION"].includes(r.ruleClass)) throw new HardRulesRegistryError("invalid ruleClass");
12198
+ if (typeof r.status !== "string" || !["proposed", "under_review", "approved", "active", "suspended", "retired", "rejected"].includes(r.status)) throw new HardRulesRegistryError("invalid status");
12199
+ if (!requiredText3(r.scope)) throw new HardRulesRegistryError("scope is required");
12200
+ if (!requiredText3(r.statement)) throw new HardRulesRegistryError("statement is required");
12201
+ if (!requiredText3(r.grantedAt)) throw new HardRulesRegistryError("grantedAt is required");
12202
+ if (!requiredText3(r.createdAt)) throw new HardRulesRegistryError("createdAt is required");
12203
+ const authority = validateHardRuleAuthority(r.authority);
12204
+ const validated = {
12205
+ id: r.id,
12206
+ version: r.version,
12207
+ revision: r.revision,
12208
+ ruleClass: r.ruleClass,
12209
+ status: r.status,
12210
+ scope: r.scope,
12211
+ statement: r.statement,
12212
+ ...r.applicability && typeof r.applicability === "object" ? { applicability: r.applicability } : {},
12213
+ authority,
12214
+ grantedAt: r.grantedAt,
12215
+ createdAt: r.createdAt,
12216
+ ...requiredText3(r.updatedAt) ? { updatedAt: r.updatedAt } : {},
12217
+ fingerprint: ""
12218
+ };
12219
+ const fp = canonicalFingerprint(validated);
12220
+ if (requiredText3(r.fingerprint) && r.fingerprint !== fp) {
12221
+ throw new HardRulesRegistryError(`Hard rule fingerprint mismatch for ${validated.id}`);
12222
+ }
12223
+ validated.fingerprint = fp;
12224
+ if (requiredText3(r.provenance) === false && r.provenance !== void 0) ;
12225
+ if (r.provenance && typeof r.provenance === "object") validated.provenance = r.provenance;
12226
+ if (requiredText3(r.auditRef)) validated.auditRef = r.auditRef;
12227
+ return validated;
12228
+ }, "validateRule");
12229
+ validateDocument2 = /* @__PURE__ */ __name((value) => {
12230
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new HardRulesRegistryError("document must be an object");
12231
+ const d = value;
12232
+ if (d.format !== HARD_RULES_REGISTRY_FORMAT) throw new HardRulesRegistryError("invalid format");
12233
+ if (d.version !== HARD_RULES_REGISTRY_VERSION) throw new HardRulesRegistryError("invalid version");
12234
+ if (typeof d.revision !== "number" || !Number.isInteger(d.revision) || d.revision < 0) throw new HardRulesRegistryError("invalid revision");
12235
+ if (!Array.isArray(d.rules)) throw new HardRulesRegistryError("rules must be an array");
12236
+ if (!Array.isArray(d.audit)) throw new HardRulesRegistryError("audit must be an array");
12237
+ const ids = /* @__PURE__ */ new Set();
12238
+ const rules = d.rules.map(validateRule);
12239
+ for (const rule of rules) {
12240
+ if (ids.has(rule.id + "@" + rule.version)) throw new HardRulesRegistryError(`Duplicate hard rule ${rule.id} v${rule.version}`);
12241
+ ids.add(rule.id + "@" + rule.version);
12242
+ }
12243
+ const audit2 = d.audit.map((e) => {
12244
+ if (!e || typeof e !== "object" || Array.isArray(e)) throw new HardRulesRegistryError("audit entry must be an object");
12245
+ const r = e;
12246
+ if (!requiredText3(r.id)) throw new HardRulesRegistryError("audit id required");
12247
+ if (!requiredText3(r.action)) throw new HardRulesRegistryError("audit action required");
12248
+ if (!requiredText3(r.at)) throw new HardRulesRegistryError("audit at required");
12249
+ if (r.outcome !== "applied" && r.outcome !== "rejected") throw new HardRulesRegistryError("audit outcome invalid");
12250
+ return r;
12251
+ });
12252
+ return { format: HARD_RULES_REGISTRY_FORMAT, version: HARD_RULES_REGISTRY_VERSION, revision: d.revision, rules, audit: audit2 };
12253
+ }, "validateDocument");
12254
+ emptyDocument2 = /* @__PURE__ */ __name(() => ({
12255
+ format: HARD_RULES_REGISTRY_FORMAT,
12256
+ version: HARD_RULES_REGISTRY_VERSION,
12257
+ revision: 0,
12258
+ rules: [],
12259
+ audit: []
12260
+ }), "emptyDocument");
12261
+ boundedAudit2 = /* @__PURE__ */ __name((entries2) => {
12262
+ if (entries2.length <= HARD_RULES_REGISTRY_AUDIT_RETENTION) return [...entries2];
12263
+ const kept = [];
12264
+ let budget = HARD_RULES_REGISTRY_AUDIT_RETENTION;
12265
+ for (let i3 = entries2.length - 1; i3 >= 0; i3--) {
12266
+ const e = entries2[i3];
12267
+ if (e.mandatory === true || budget > 0) {
12268
+ kept.unshift(e);
12269
+ if (e.mandatory !== true) budget--;
12270
+ }
12271
+ }
12272
+ return kept;
12273
+ }, "boundedAudit");
12274
+ buildAudit = /* @__PURE__ */ __name((entry) => ({
12275
+ id: entry.id ?? `hr-audit.${entry.action}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}`,
12276
+ action: entry.action,
12277
+ at: entry.at,
12278
+ ...entry.actorPrincipal !== void 0 ? { actorPrincipal: entry.actorPrincipal } : {},
12279
+ ...entry.targetRuleId !== void 0 ? { targetRuleId: entry.targetRuleId } : {},
12280
+ ...entry.targetVersion !== void 0 ? { targetVersion: entry.targetVersion } : {},
12281
+ ...entry.scope !== void 0 ? { scope: entry.scope } : {},
12282
+ outcome: entry.outcome,
12283
+ ...entry.reason !== void 0 ? { reason: entry.reason } : {},
12284
+ ...entry.detail !== void 0 ? { detail: entry.detail } : {},
12285
+ ...entry.mandatory !== void 0 ? { mandatory: entry.mandatory } : {}
12286
+ }), "buildAudit");
12287
+ HardRulesRegistry = class {
12288
+ constructor(directory) {
12289
+ this.directory = directory;
12290
+ }
12291
+ directory;
12292
+ static {
12293
+ __name(this, "HardRulesRegistry");
12294
+ }
12295
+ dir() {
12296
+ return resolveRegistryDir(this.directory);
12297
+ }
12298
+ filePath() {
12299
+ return resolveRegistryFilePath(this.directory);
12300
+ }
12301
+ async load() {
12302
+ const fs16 = await import('fs/promises');
12303
+ try {
12304
+ const raw = await fs16.readFile(this.filePath(), "utf8");
12305
+ return validateDocument2(JSON.parse(raw));
12306
+ } catch (err3) {
12307
+ if (err3.code === "ENOENT") return emptyDocument2();
12308
+ throw err3;
12309
+ }
12310
+ }
12311
+ async readDoc(fs16) {
12312
+ try {
12313
+ const raw = await fs16.readFile(this.filePath(), "utf8");
12314
+ return validateDocument2(JSON.parse(raw));
12315
+ } catch (err3) {
12316
+ if (err3.code === "ENOENT") return emptyDocument2();
12317
+ throw err3;
12318
+ }
12319
+ }
12320
+ async writeDoc(fs16, doc) {
12321
+ await fs16.mkdir(this.dir(), { recursive: true });
12322
+ const fp = this.filePath();
12323
+ const tmp = `${fp}.${process.pid}.${Date.now().toString(36)}.tmp`;
12324
+ try {
12325
+ await fs16.writeFile(tmp, `${JSON.stringify(doc, null, 2)}
12326
+ `, "utf8");
12327
+ const handle = await fs16.open(tmp, "r+");
12328
+ try {
12329
+ await handle.sync();
12330
+ } finally {
12331
+ await handle.close();
12332
+ }
12333
+ await fs16.rename(tmp, fp);
12334
+ } catch (err3) {
12335
+ await fs16.rm(tmp, { force: true }).catch(() => void 0);
12336
+ throw err3;
12337
+ }
12338
+ }
12339
+ async mutate(operation, options = {}) {
12340
+ const directory = this.dir();
12341
+ return withPolicyNamespaceLock(
12342
+ async (session3) => {
12343
+ const fs16 = await import('fs/promises');
12344
+ const doc = await this.readDoc(fs16);
12345
+ if (options.basedOnRevision !== void 0 && options.basedOnRevision !== doc.revision) {
12346
+ throw new HardRulesRegistryError(`Stale hard-rules revision: expected ${options.basedOnRevision}, current ${doc.revision}`);
12347
+ }
12348
+ const outcome = operation(doc);
12349
+ let next = outcome.document;
12350
+ validateDocument2(next);
12351
+ await session3.assertOwnership();
12352
+ await this.writeDoc(fs16, next);
12353
+ return outcome.result;
12354
+ },
12355
+ { directory }
12356
+ );
12357
+ }
12358
+ async listRules() {
12359
+ const doc = await this.load();
12360
+ return [...doc.rules].sort((a, b) => a.id.localeCompare(b.id) || a.version - b.version);
12361
+ }
12362
+ async activeRules(scope) {
12363
+ const doc = await this.load();
12364
+ return doc.rules.filter((r) => r.status === "active" && (!scope || r.scope === "*" || r.scope === scope || scope.startsWith(r.scope.endsWith("/") ? r.scope : r.scope + "/")));
12365
+ }
12366
+ async failClosedResolve(scope) {
12367
+ const actives = await this.activeRules(scope);
12368
+ if (actives.length === 0) return { outcome: "none", rule: null, reason: "no applicable hard rule" };
12369
+ if (actives.length > 1) return { outcome: "conflicting", rule: null, reason: "conflicting active hard rules" };
12370
+ const r = actives[0];
12371
+ if (r.ruleClass === "IMMUTABLE" || r.ruleClass === "OWNER_CONTROLLED") {
12372
+ if (r.authority.kind !== "HI" && r.authority.kind !== "operator") {
12373
+ return { outcome: "unresolved-authority", rule: null, reason: "unresolved authority" };
12374
+ }
12375
+ }
12376
+ return { outcome: "applicable", rule: r, reason: "applicable" };
12377
+ }
12378
+ async assign(input, basedOnRevision) {
12379
+ const authority = validateHardRuleAuthority(input.authority);
12380
+ if (!requiredText3(input.scope)) throw new HardRulesRegistryError("scope is required");
12381
+ if (!requiredText3(input.statement)) throw new HardRulesRegistryError("statement is required");
12382
+ if (!["IMMUTABLE", "OWNER_CONTROLLED", "USER_OVERRIDEABLE", "SESSION"].includes(input.ruleClass)) throw new HardRulesRegistryError("invalid ruleClass");
12383
+ const doc0 = await this.load();
12384
+ const ruleId = input.id ?? `hr.${Date.now()}.${Math.random().toString(36).slice(2, 8)}`;
12385
+ const existing = doc0.rules.filter((r) => r.id === ruleId);
12386
+ const version = input.version ?? (existing.length > 0 ? Math.max(...existing.map((r) => r.version)) + 1 : 1);
12387
+ const priorActive = existing.find((r) => r.status === "active" && r.ruleClass === "IMMUTABLE");
12388
+ if (priorActive && input.ruleClass !== "IMMUTABLE") {
12389
+ throw new HardRulesRegistryError("cannot weaken immutable rule");
12390
+ }
12391
+ if (priorActive && authority.kind !== "HI") {
12392
+ throw new HardRulesRegistryError("immutable rule requires HI authority to amend");
12393
+ }
12394
+ const createdAt = nowIso();
12395
+ const grantedAt = input.grantedAt ?? createdAt;
12396
+ const rule = {
12397
+ id: ruleId,
12398
+ version,
12399
+ revision: 0,
12400
+ ruleClass: input.ruleClass,
12401
+ status: "proposed",
12402
+ scope: input.scope,
12403
+ statement: input.statement,
12404
+ ...input.applicability ? { applicability: input.applicability } : {},
12405
+ authority,
12406
+ grantedAt,
12407
+ createdAt,
12408
+ fingerprint: ""
12409
+ };
12410
+ rule.fingerprint = canonicalFingerprint({ ...rule, fingerprint: "" });
12411
+ return this.mutate(
12412
+ (doc) => {
12413
+ const revision = doc.revision + 1;
12414
+ const stored = { ...rule, revision, fingerprint: canonicalFingerprint({ ...rule, revision, fingerprint: "" }) };
12415
+ const rules = doc.rules.map((r) => {
12416
+ if (r.id === stored.id && r.version !== stored.version && r.status === "active") {
12417
+ return { ...r, status: "retired", updatedAt: nowIso() };
12418
+ }
12419
+ return r;
12420
+ });
12421
+ rules.push(stored);
12422
+ const audit2 = boundedAudit2([
12423
+ ...doc.audit,
12424
+ buildAudit({
12425
+ action: "rule.assigned",
12426
+ at: stored.grantedAt,
12427
+ actorPrincipal: authority.kind,
12428
+ targetRuleId: stored.id,
12429
+ targetVersion: stored.version,
12430
+ scope: stored.scope,
12431
+ outcome: "applied",
12432
+ detail: `hard rule ${stored.id} v${stored.version} assigned (${stored.ruleClass})`,
12433
+ mandatory: true
12434
+ })
12435
+ ]);
12436
+ return { document: { ...doc, revision, rules, audit: audit2 }, result: stored };
12437
+ },
12438
+ { basedOnRevision }
12439
+ );
12440
+ }
12441
+ async activate(input, basedOnRevision) {
12442
+ const doc0 = await this.load();
12443
+ const rule = doc0.rules.find((r) => r.id === input.id && r.version === input.version);
12444
+ if (!rule) throw new HardRulesRegistryError("rule not found");
12445
+ if (rule.status !== "approved" && rule.status !== "proposed") ;
12446
+ const authority = input.authority ? validateHardRuleAuthority(input.authority) : rule.authority;
12447
+ if ((rule.ruleClass === "IMMUTABLE" || rule.ruleClass === "OWNER_CONTROLLED") && authority.kind !== "HI" && authority.kind !== "operator") {
12448
+ throw new HardRulesRegistryError("activation requires HI or operator authority");
12449
+ }
12450
+ const actives = doc0.rules.filter((r) => r.status === "active" && r.scope === rule.scope && r.id !== rule.id);
12451
+ if (actives.length > 0 && (rule.ruleClass === "IMMUTABLE" || rule.ruleClass === "OWNER_CONTROLLED")) {
12452
+ throw new HardRulesRegistryError("conflicting active mandatory rules");
12453
+ }
12454
+ return this.mutate(
12455
+ (doc) => {
12456
+ const idx = doc.rules.findIndex((r) => r.id === input.id && r.version === input.version);
12457
+ if (idx < 0) throw new HardRulesRegistryError("rule not found");
12458
+ const current = doc.rules[idx];
12459
+ const rules = doc.rules.map((r) => {
12460
+ if (r.id === current.id && r.version !== current.version && r.status === "active") {
12461
+ return { ...r, status: "retired", updatedAt: nowIso() };
12462
+ }
12463
+ return r;
12464
+ });
12465
+ const now3 = nowIso();
12466
+ rules[idx >= rules.length ? rules.length - 1 : idx] = { ...current, status: "active", updatedAt: now3 };
12467
+ const targetIndex = rules.findIndex((r) => r.id === current.id && r.version === current.version);
12468
+ if (targetIndex >= 0) rules[targetIndex] = { ...current, status: "active", updatedAt: now3 };
12469
+ const updated = rules.find((r) => r.id === current.id && r.version === current.version);
12470
+ const revision = doc.revision + 1;
12471
+ const audit2 = boundedAudit2([
12472
+ ...doc.audit,
12473
+ buildAudit({
12474
+ action: "rule.activated",
12475
+ at: now3,
12476
+ actorPrincipal: input.actorPrincipal ?? authority.kind,
12477
+ targetRuleId: updated.id,
12478
+ targetVersion: updated.version,
12479
+ scope: updated.scope,
12480
+ outcome: "applied",
12481
+ mandatory: true
12482
+ })
12483
+ ]);
12484
+ return { document: { ...doc, revision, rules, audit: audit2 }, result: updated };
12485
+ },
12486
+ { basedOnRevision }
12487
+ );
12488
+ }
12489
+ async remove(id, authority, basedOnRevision) {
12490
+ const auth = validateHardRuleAuthority(authority);
12491
+ const doc0 = await this.load();
12492
+ const rule = doc0.rules.find((r) => r.id === id && r.status === "active");
12493
+ if (rule) {
12494
+ if (rule.ruleClass === "IMMUTABLE") throw new HardRulesRegistryError("cannot remove immutable rule");
12495
+ if (rule.ruleClass === "OWNER_CONTROLLED" && auth.kind !== "HI" && auth.kind !== "operator") throw new HardRulesRegistryError("unauthenticated cannot remove owner-controlled rule");
12496
+ }
12497
+ await this.mutate(
12498
+ (doc) => {
12499
+ const rules = doc.rules.filter((r) => r.id !== id);
12500
+ if (rules.length === doc.rules.length) return { document: doc, result: void 0 };
12501
+ const revision = doc.revision + 1;
12502
+ const audit2 = boundedAudit2([
12503
+ ...doc.audit,
12504
+ buildAudit({
12505
+ action: "rule.removed",
12506
+ at: nowIso(),
12507
+ actorPrincipal: auth.kind,
12508
+ targetRuleId: id,
12509
+ scope: rule?.scope,
12510
+ outcome: "applied",
12511
+ mandatory: true
12512
+ })
12513
+ ]);
12514
+ return { document: { ...doc, revision, rules, audit: audit2 }, result: void 0 };
12515
+ },
12516
+ { basedOnRevision }
12517
+ );
12518
+ }
12519
+ async auditTrail() {
12520
+ const doc = await this.load();
12521
+ return [...doc.audit];
12522
+ }
12523
+ async revision() {
12524
+ const doc = await this.load();
12525
+ return doc.revision;
12526
+ }
12527
+ };
12152
12528
  }
12153
12529
  });
12154
12530
 
12155
- // core/logic/index.ts
12156
- var logic_exports = {};
12157
- __export(logic_exports, {
12158
- LogicEngine: () => LogicEngine,
12159
- default: () => logic_default,
12160
- getLogicRuntime: () => getLogicRuntime,
12531
+ // core/context-compiler/index.ts
12532
+ var CHARS_PER_TOKEN, estimateTokens, DEFAULT_BUDGETS, dedupe, ContextCompiler, compileContext;
12533
+ var init_context_compiler = __esm({
12534
+ "core/context-compiler/index.ts"() {
12535
+ CHARS_PER_TOKEN = 4;
12536
+ estimateTokens = /* @__PURE__ */ __name((text) => Math.ceil((text || "").length / CHARS_PER_TOKEN), "estimateTokens");
12537
+ DEFAULT_BUDGETS = {
12538
+ identity: 0.1,
12539
+ rules: 0.15,
12540
+ conversationalState: 0.3,
12541
+ retrievedKnowledge: 0.45
12542
+ };
12543
+ dedupe = /* @__PURE__ */ __name((items) => {
12544
+ const seen = /* @__PURE__ */ new Set();
12545
+ const result = [];
12546
+ for (const item of items) {
12547
+ const key = item.trim().toLowerCase();
12548
+ if (seen.has(key)) continue;
12549
+ seen.add(key);
12550
+ result.push(item);
12551
+ }
12552
+ return result;
12553
+ }, "dedupe");
12554
+ ContextCompiler = class {
12555
+ static {
12556
+ __name(this, "ContextCompiler");
12557
+ }
12558
+ compile(input) {
12559
+ const totalBudget = input.tokenBudget ?? 4096;
12560
+ const totalChars = totalBudget * CHARS_PER_TOKEN;
12561
+ const budgets = {
12562
+ identity: Math.floor(totalChars * (input.categoryBudgets?.identity ?? DEFAULT_BUDGETS.identity)),
12563
+ rules: Math.floor(totalChars * (input.categoryBudgets?.rules ?? DEFAULT_BUDGETS.rules)),
12564
+ conversationalState: Math.floor(totalChars * (input.categoryBudgets?.conversationalState ?? DEFAULT_BUDGETS.conversationalState)),
12565
+ retrievedKnowledge: Math.floor(totalChars * (input.categoryBudgets?.retrievedKnowledge ?? DEFAULT_BUDGETS.retrievedKnowledge))
12566
+ };
12567
+ const omissions = [];
12568
+ const identityText = (input.identity ?? "").trim();
12569
+ let identityUsed = 0;
12570
+ const mandatoryParts = [];
12571
+ if (identityText) {
12572
+ if (identityText.length <= budgets.identity) {
12573
+ mandatoryParts.push(identityText);
12574
+ identityUsed = identityText.length;
12575
+ } else {
12576
+ omissions.push({
12577
+ category: "identity",
12578
+ whatWasOmitted: identityText,
12579
+ whyOmitted: "token budget exceeded",
12580
+ wouldBreakContinuity: true
12581
+ });
12582
+ }
12583
+ }
12584
+ const rules = input.rules ?? [];
12585
+ const activeRules = [];
12586
+ let rulesUsed = 0;
12587
+ for (const rule of rules) {
12588
+ if (rulesUsed + rule.length <= budgets.rules) {
12589
+ activeRules.push(rule);
12590
+ rulesUsed += rule.length;
12591
+ } else {
12592
+ omissions.push({
12593
+ category: "rules",
12594
+ whatWasOmitted: rule,
12595
+ whyOmitted: "token budget exceeded",
12596
+ wouldBreakContinuity: false
12597
+ });
12598
+ }
12599
+ }
12600
+ const state3 = input.conversationalState ?? null;
12601
+ const mandatoryStateParts = [];
12602
+ if (state3) {
12603
+ if (state3.objective) mandatoryStateParts.push(`Objective: ${state3.objective}`);
12604
+ if (state3.currentWorkingPosition) mandatoryStateParts.push(`Working position: ${state3.currentWorkingPosition}`);
12605
+ if (state3.openLoops.length > 0) {
12606
+ mandatoryStateParts.push(`Open loops: ${state3.openLoops.map((l) => l.description).join("; ")}`);
12607
+ }
12608
+ if (state3.rejectedApproaches.length > 0) {
12609
+ mandatoryStateParts.push(`Rejected approaches: ${state3.rejectedApproaches.map((r) => `${r.approach} (${r.reason})`).join("; ")}`);
12610
+ }
12611
+ }
12612
+ const activeParts = [];
12613
+ if (state3) {
12614
+ if (state3.currentProblem) activeParts.push(`Current problem: ${state3.currentProblem}`);
12615
+ if (state3.establishedUnderstanding) activeParts.push(`Established understanding: ${state3.establishedUnderstanding}`);
12616
+ if (state3.decisionsMade.length > 0) {
12617
+ activeParts.push(`Decisions: ${state3.decisionsMade.map((d) => `${d.decision} (rationale: ${d.rationale})`).join("; ")}`);
12618
+ }
12619
+ if (state3.pendingDecisions.length > 0) {
12620
+ activeParts.push(`Pending decisions: ${state3.pendingDecisions.map((d) => `${d.decision} [${d.options.join(", ")}]`).join("; ")}`);
12621
+ }
12622
+ if (state3.unresolvedQuestions.length > 0) {
12623
+ activeParts.push(`Unresolved questions: ${state3.unresolvedQuestions.map((q) => q.question).join("; ")}`);
12624
+ }
12625
+ if (state3.reasoningTrajectory.length > 0) {
12626
+ activeParts.push(`Reasoning trajectory: ${state3.reasoningTrajectory.map((r) => r.conclusion).join(" -> ")}`);
12627
+ }
12628
+ if (state3.nextConversationalStep) {
12629
+ activeParts.push(`Next step: ${state3.nextConversationalStep}`);
12630
+ }
12631
+ if (state3.lastCompletedAction) {
12632
+ activeParts.push(`Last completed action: ${state3.lastCompletedAction}`);
12633
+ }
12634
+ }
12635
+ const dedupedActive = dedupe(activeParts.filter((part) => !mandatoryStateParts.includes(part)));
12636
+ let stateUsed = 0;
12637
+ const admittedMandatoryState = [];
12638
+ const admittedActive = [];
12639
+ for (const part of mandatoryStateParts) {
12640
+ if (stateUsed + part.length <= budgets.conversationalState) {
12641
+ admittedMandatoryState.push(part);
12642
+ stateUsed += part.length;
12643
+ } else {
12644
+ omissions.push({
12645
+ category: "conversationalState",
12646
+ whatWasOmitted: part,
12647
+ whyOmitted: "token budget exceeded",
12648
+ wouldBreakContinuity: true
12649
+ });
12650
+ }
12651
+ }
12652
+ for (const part of dedupedActive) {
12653
+ if (stateUsed + part.length <= budgets.conversationalState) {
12654
+ admittedActive.push(part);
12655
+ stateUsed += part.length;
12656
+ } else {
12657
+ omissions.push({
12658
+ category: "conversationalState",
12659
+ whatWasOmitted: part,
12660
+ whyOmitted: "token budget exceeded",
12661
+ wouldBreakContinuity: false
12662
+ });
12663
+ }
12664
+ }
12665
+ const refs = [...input.knowledgeReferences ?? []].sort((a, b) => b.relevance - a.relevance);
12666
+ const retrievedParts = [];
12667
+ let retrievedUsed = 0;
12668
+ for (const ref of refs) {
12669
+ const text2 = ref.summary ? `${ref.kind}:${ref.identifier} - ${ref.summary}` : `${ref.kind}:${ref.identifier}`;
12670
+ if (retrievedUsed + text2.length <= budgets.retrievedKnowledge) {
12671
+ retrievedParts.push(text2);
12672
+ retrievedUsed += text2.length;
12673
+ } else {
12674
+ omissions.push({
12675
+ category: "retrievedKnowledge",
12676
+ whatWasOmitted: text2,
12677
+ whyOmitted: "token budget exceeded",
12678
+ wouldBreakContinuity: false
12679
+ });
12680
+ }
12681
+ }
12682
+ const optionalParts = [];
12683
+ let optionalUsed = 0;
12684
+ const remainingBudget = totalChars - (identityUsed + rulesUsed + stateUsed + retrievedUsed);
12685
+ for (const item of input.historicalContext ?? []) {
12686
+ if (optionalUsed + item.length <= remainingBudget) {
12687
+ optionalParts.push(item);
12688
+ optionalUsed += item.length;
12689
+ } else {
12690
+ omissions.push({
12691
+ category: "historical",
12692
+ whatWasOmitted: item,
12693
+ whyOmitted: "token budget exceeded",
12694
+ wouldBreakContinuity: false
12695
+ });
12696
+ }
12697
+ }
12698
+ const admittedSet = new Set([...mandatoryParts, ...admittedMandatoryState, ...admittedActive].map((s) => s.trim().toLowerCase()));
12699
+ const isDuplicate = /* @__PURE__ */ __name((item) => {
12700
+ const normalized = item.trim().toLowerCase();
12701
+ for (const existing of admittedSet) {
12702
+ if (existing.includes(normalized) || normalized.includes(existing)) return true;
12703
+ }
12704
+ return false;
12705
+ }, "isDuplicate");
12706
+ const finalRetrieved = dedupe(retrievedParts.filter((p) => !isDuplicate(p)));
12707
+ const finalOptional = dedupe(optionalParts.filter((p) => !isDuplicate(p) && !finalRetrieved.includes(p)));
12708
+ const mandatory = [...mandatoryParts, ...admittedMandatoryState].join("\n");
12709
+ const active = [...admittedActive];
12710
+ const retrieved = finalRetrieved;
12711
+ const optional = finalOptional;
12712
+ const text = [mandatory ? `## MANDATORY
12713
+ ${mandatory}` : "", active.length ? `## ACTIVE
12714
+ ${active.join("\n")}` : "", retrieved.length ? `## RETRIEVED
12715
+ ${retrieved.join("\n")}` : "", optional.length ? `## OPTIONAL
12716
+ ${optional.join("\n")}` : "", rules.length ? `## RULES
12717
+ ${activeRules.join("\n")}` : ""].filter(Boolean).join("\n\n");
12718
+ const budgetUsed = estimateTokens(text);
12719
+ return {
12720
+ mandatory,
12721
+ active,
12722
+ retrieved,
12723
+ optional,
12724
+ omissions,
12725
+ budgetUsed,
12726
+ budgetAvailable: totalBudget,
12727
+ text
12728
+ };
12729
+ }
12730
+ };
12731
+ compileContext = /* @__PURE__ */ __name((input) => {
12732
+ const compiler = new ContextCompiler();
12733
+ return compiler.compile(input);
12734
+ }, "compileContext");
12735
+ }
12736
+ });
12737
+
12738
+ // core/knowledge/rule-enforcement.ts
12739
+ var resolveApplicableRules;
12740
+ var init_rule_enforcement = __esm({
12741
+ "core/knowledge/rule-enforcement.ts"() {
12742
+ init_rules_loader();
12743
+ init_violations();
12744
+ init_hard_rules_registry();
12745
+ init_memory();
12746
+ init_context_compiler();
12747
+ resolveApplicableRules = /* @__PURE__ */ __name(async (situation, scope) => {
12748
+ const state3 = await loadCombinedKnowledgeState();
12749
+ const rules = [];
12750
+ const seen = /* @__PURE__ */ new Set();
12751
+ const ironReport = loadIronRules(state3);
12752
+ for (const rule of ironReport.rules) {
12753
+ if (seen.has(rule.id)) continue;
12754
+ seen.add(rule.id);
12755
+ const claim = state3.claims.find((c) => c.id === rule.id);
12756
+ rules.push({
12757
+ id: rule.id,
12758
+ text: rule.text,
12759
+ tier: "context",
12760
+ source: "iron",
12761
+ appliesWhen: rule.appliesWhen || void 0,
12762
+ hasCheck: !!claim?.check
12763
+ });
12764
+ }
12765
+ try {
12766
+ const registry = new HardRulesRegistry();
12767
+ const active = scope ? await registry.activeRules(scope) : await registry.activeRules();
12768
+ for (const rule of active) {
12769
+ if (seen.has(rule.id)) continue;
12770
+ seen.add(rule.id);
12771
+ rules.push({
12772
+ id: rule.id,
12773
+ text: rule.statement,
12774
+ tier: rule.ruleClass === "IMMUTABLE" || rule.ruleClass === "OWNER_CONTROLLED" ? "hard-precondition" : "precondition",
12775
+ source: "hard",
12776
+ appliesWhen: rule.scope,
12777
+ hasCheck: false
12778
+ });
12779
+ }
12780
+ } catch {
12781
+ }
12782
+ return rules;
12783
+ }, "resolveApplicableRules");
12784
+ }
12785
+ });
12786
+
12787
+ // core/knowledge/index.ts
12788
+ var init_knowledge = __esm({
12789
+ "core/knowledge/index.ts"() {
12790
+ init_acquisition_boundary();
12791
+ init_acquisition_limits();
12792
+ init_applicability();
12793
+ init_behavioral_invariants();
12794
+ init_bootstrap();
12795
+ init_built_in_context();
12796
+ init_built_in_context_rules();
12797
+ init_canonical_hash();
12798
+ init_canonical_reconstruction();
12799
+ init_canonical_schema();
12800
+ init_context_budget();
12801
+ init_contract();
12802
+ init_correction();
12803
+ init_currentness();
12804
+ init_detection_events();
12805
+ init_detection_journal();
12806
+ init_discover();
12807
+ init_solvers();
12808
+ init_signatures();
12809
+ init_probe();
12810
+ init_semantic_provider();
12811
+ init_effective_contract();
12812
+ init_exemplars();
12813
+ init_explain();
12814
+ init_feedback();
12815
+ init_fingerprint();
12816
+ init_identity_governance();
12817
+ init_identity_resolution();
12818
+ init_incidents();
12819
+ init_inspect_report();
12820
+ init_language_detect();
12821
+ init_loops();
12822
+ init_mem_package();
12823
+ init_personality_anchor();
12824
+ init_policy();
12825
+ init_policy_namespace_lock();
12826
+ init_policy_store();
12827
+ init_project();
12828
+ init_project_anchor();
12829
+ init_read_only();
12830
+ init_renderer();
12831
+ init_repository();
12832
+ init_rule_checker();
12833
+ init_rules_loader();
12834
+ init_runtime();
12835
+ init_scope_eligibility();
12836
+ init_select();
12837
+ init_session();
12838
+ init_staging();
12839
+ init_state();
12840
+ init_storage_location();
12841
+ init_storage_settings();
12842
+ init_tool_guard();
12843
+ init_user_identity();
12844
+ init_user_language();
12845
+ init_user_paths();
12846
+ init_vault();
12847
+ init_verification();
12848
+ init_verify();
12849
+ init_violations();
12850
+ init_claim_identity();
12851
+ init_store_registry();
12852
+ init_migration_audit();
12853
+ init_session_metrics();
12854
+ init_session_metrics();
12855
+ init_session_metrics();
12856
+ init_session_metrics();
12857
+ init_rule_enforcement();
12858
+ }
12859
+ });
12860
+
12861
+ // core/logic/helpers.ts
12862
+ var normalizeClaimIds2, revisionFromAcquire;
12863
+ var init_helpers = __esm({
12864
+ "core/logic/helpers.ts"() {
12865
+ normalizeClaimIds2 = /* @__PURE__ */ __name((value) => {
12866
+ if (!value) return [];
12867
+ return Array.isArray(value) ? value : [value];
12868
+ }, "normalizeClaimIds");
12869
+ revisionFromAcquire = /* @__PURE__ */ __name((opts) => {
12870
+ const refines = normalizeClaimIds2(opts.refines);
12871
+ const supersedes = normalizeClaimIds2(opts.supersedes);
12872
+ const retracts = normalizeClaimIds2(opts.retracts);
12873
+ if ([refines, supersedes, retracts].filter((ids) => ids.length > 0).length > 1) {
12874
+ throw new Error("Acquired knowledge can refine, supersede, or retract prior knowledge, not more than one");
12875
+ }
12876
+ if (refines.length > 0) return { kind: "refines", claimIds: refines, ...opts.reason ? { reason: opts.reason } : {} };
12877
+ if (supersedes.length > 0) return { kind: "supersedes", claimIds: supersedes, ...opts.reason ? { reason: opts.reason } : {} };
12878
+ if (retracts.length > 0) return { kind: "retracts", claimIds: retracts, ...opts.reason ? { reason: opts.reason } : {} };
12879
+ return void 0;
12880
+ }, "revisionFromAcquire");
12881
+ }
12882
+ });
12883
+
12884
+ // core/logic/index.ts
12885
+ var logic_exports = {};
12886
+ __export(logic_exports, {
12887
+ LogicEngine: () => LogicEngine,
12888
+ default: () => logic_default,
12889
+ getLogicRuntime: () => getLogicRuntime,
12161
12890
  logic: () => logic
12162
12891
  });
12163
12892
  var LOGIC_MEM_FILE, nodeCwd2, cachedRuntime, resetLogicRuntime, getLogicRuntime, LogicEngine, _inferConfidence, logic, logic_default;
@@ -12458,21 +13187,6 @@ __export(encryption_exports, {
12458
13187
  decryptPayload: () => decryptPayload,
12459
13188
  encryptPayload: () => encryptPayload
12460
13189
  });
12461
- function getHybridKeys() {
12462
- const dir = `${resolveUserDotMemPath()}/keys`;
12463
- try {
12464
- fs.mkdirSync(dir, { recursive: true });
12465
- } catch {
12466
- }
12467
- try {
12468
- const raw = JSON.parse(fs.readFileSync(hybridKeyFile(), "utf8"));
12469
- return { publicKey: Buffer.from(raw.publicKey, "hex"), secretKey: Buffer.from(raw.secretKey, "hex") };
12470
- } catch {
12471
- }
12472
- const keys = ml_kem768_x25519.keygen();
12473
- fs.writeFileSync(hybridKeyFile(), JSON.stringify({ publicKey: Buffer.from(keys.publicKey).toString("hex"), secretKey: Buffer.from(keys.secretKey).toString("hex") }), { mode: 384 });
12474
- return { publicKey: keys.publicKey, secretKey: keys.secretKey };
12475
- }
12476
13190
  function encryptPayload(plaintext) {
12477
13191
  const keys = getHybridKeys();
12478
13192
  const { sharedSecret, cipherText: kemCt } = ml_kem768_x25519.encapsulate(keys.publicKey);
@@ -12488,7 +13202,7 @@ function decryptPayload(envelope) {
12488
13202
  try {
12489
13203
  if (!envelope.startsWith("{")) {
12490
13204
  const keyFile = `${resolveUserDotMemPath()}/keys/local.key`;
12491
- const hex = fs.readFileSync(keyFile, "utf8").trim();
13205
+ const hex = fs6.readFileSync(keyFile, "utf8").trim();
12492
13206
  const key2 = Buffer.from(hex, "hex");
12493
13207
  const [ivB64, tagB64, ctB64] = envelope.split(":");
12494
13208
  const iv2 = Buffer.from(ivB64, "base64");
@@ -12515,12 +13229,26 @@ function decryptPayload(envelope) {
12515
13229
  return null;
12516
13230
  }
12517
13231
  }
12518
- var hybridKeyFile;
13232
+ var hybridKeyFile, getHybridKeys;
12519
13233
  var init_encryption = __esm({
12520
13234
  "core/knowledge/encryption.ts"() {
12521
13235
  init_user_paths();
12522
13236
  hybridKeyFile = /* @__PURE__ */ __name(() => `${resolveUserDotMemPath()}/keys/hybrid.key`, "hybridKeyFile");
12523
- __name(getHybridKeys, "getHybridKeys");
13237
+ getHybridKeys = /* @__PURE__ */ __name(() => {
13238
+ const dir = `${resolveUserDotMemPath()}/keys`;
13239
+ try {
13240
+ fs6.mkdirSync(dir, { recursive: true });
13241
+ } catch {
13242
+ }
13243
+ try {
13244
+ const raw = JSON.parse(fs6.readFileSync(hybridKeyFile(), "utf8"));
13245
+ return { publicKey: Buffer.from(raw.publicKey, "hex"), secretKey: Buffer.from(raw.secretKey, "hex") };
13246
+ } catch {
13247
+ }
13248
+ const keys = ml_kem768_x25519.keygen();
13249
+ fs6.writeFileSync(hybridKeyFile(), JSON.stringify({ publicKey: Buffer.from(keys.publicKey).toString("hex"), secretKey: Buffer.from(keys.secretKey).toString("hex") }), { mode: 384 });
13250
+ return { publicKey: keys.publicKey, secretKey: keys.secretKey };
13251
+ }, "getHybridKeys");
12524
13252
  __name(encryptPayload, "encryptPayload");
12525
13253
  __name(decryptPayload, "decryptPayload");
12526
13254
  }
@@ -12571,13 +13299,13 @@ var init_brain = __esm({
12571
13299
  }, "brainSave");
12572
13300
  cachedBrainPath = null;
12573
13301
  getBrainDocument = /* @__PURE__ */ __name(async () => {
12574
- const path10 = getBrainPath();
12575
- cachedBrainPath = path10;
12576
- return brainLoad(path10);
13302
+ const path11 = getBrainPath();
13303
+ cachedBrainPath = path11;
13304
+ return brainLoad(path11);
12577
13305
  }, "getBrainDocument");
12578
13306
  saveBrainDocument = /* @__PURE__ */ __name(async (document) => {
12579
- const path10 = cachedBrainPath || getBrainPath();
12580
- await brainSave(path10, document);
13307
+ const path11 = cachedBrainPath || getBrainPath();
13308
+ await brainSave(path11, document);
12581
13309
  }, "saveBrainDocument");
12582
13310
  resetBrainPathCache = /* @__PURE__ */ __name(() => {
12583
13311
  cachedBrainPath = null;
@@ -14122,7 +14850,7 @@ ${content}`);
14122
14850
  for (const file2 of files) {
14123
14851
  if (!file2.endsWith(".arch.mem")) continue;
14124
14852
  try {
14125
- const bytes = await fs14.readFile(path8.join(dir, file2));
14853
+ const bytes = await fs14.readFile(path5.join(dir, file2));
14126
14854
  const { metadata } = readZip(bytes);
14127
14855
  entries2.push(metadata);
14128
14856
  } catch {
@@ -14384,7 +15112,7 @@ var init_acquire = __esm({
14384
15112
  const { findClaimLocations: findClaimLocations2 } = await Promise.resolve().then(() => (init_claim_identity(), claim_identity_exports));
14385
15113
  const locations = await findClaimLocations2(targetId);
14386
15114
  if (locations.length === 0) {
14387
- throw new Error(`Claim ${claimId} references unknown prior claim ${targetId}. Searched all stores.`);
15115
+ throw new Error(`Claim ${claimId} references any prior claim ${targetId}. Searched all stores.`);
14388
15116
  }
14389
15117
  if (locations.length > 1) {
14390
15118
  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(", "));
@@ -14779,11 +15507,11 @@ var init_durable_store = __esm({
14779
15507
  writeFile: writeFile4,
14780
15508
  rename,
14781
15509
  copyFile,
14782
- rm: /* @__PURE__ */ __name((path10, opts) => rm(path10, opts), "rm"),
15510
+ rm: /* @__PURE__ */ __name((path11, opts) => rm(path11, opts), "rm"),
14783
15511
  mkdir,
14784
- open: /* @__PURE__ */ __name(async (path10, flags) => {
15512
+ open: /* @__PURE__ */ __name(async (path11, flags) => {
14785
15513
  if (!Deno.open) throw new Error("Deno.open is unavailable");
14786
- const file2 = await Deno.open(path10, flags);
15514
+ const file2 = await Deno.open(path11, flags);
14787
15515
  return {
14788
15516
  writeFile: /* @__PURE__ */ __name(async (data) => {
14789
15517
  const written = await file2.write(data);
@@ -15098,9 +15826,9 @@ var init_entries = __esm({
15098
15826
  };
15099
15827
  return recencyScore * confidenceScore * accessScore * typeBoost[entry.type] * scopeBoost[entry.scope];
15100
15828
  }, "computeRelevance");
15101
- getNestedPath = /* @__PURE__ */ __name((obj, path10) => {
15102
- if (!path10 || typeof path10 !== "string") return void 0;
15103
- const parts = path10.replace(/^state\./, "").split(".");
15829
+ getNestedPath = /* @__PURE__ */ __name((obj, path11) => {
15830
+ if (!path11 || typeof path11 !== "string") return void 0;
15831
+ const parts = path11.replace(/^state\./, "").split(".");
15104
15832
  let current = obj;
15105
15833
  for (const part of parts) {
15106
15834
  if (current === null || current === void 0) return void 0;
@@ -15108,9 +15836,9 @@ var init_entries = __esm({
15108
15836
  }
15109
15837
  return current;
15110
15838
  }, "getNestedPath");
15111
- setNestedPath = /* @__PURE__ */ __name((obj, path10, value) => {
15112
- if (!path10 || typeof path10 !== "string") return;
15113
- const parts = path10.replace(/^state\./, "").split(".");
15839
+ setNestedPath = /* @__PURE__ */ __name((obj, path11, value) => {
15840
+ if (!path11 || typeof path11 !== "string") return;
15841
+ const parts = path11.replace(/^state\./, "").split(".");
15114
15842
  let current = obj;
15115
15843
  for (let i3 = 0; i3 < parts.length - 1; i3++) {
15116
15844
  const part = parts[i3];
@@ -15121,9 +15849,9 @@ var init_entries = __esm({
15121
15849
  }
15122
15850
  current[parts[parts.length - 1]] = value;
15123
15851
  }, "setNestedPath");
15124
- deleteNestedPath = /* @__PURE__ */ __name((obj, path10) => {
15125
- if (!path10 || typeof path10 !== "string") return;
15126
- const parts = path10.replace(/^state\./, "").split(".");
15852
+ deleteNestedPath = /* @__PURE__ */ __name((obj, path11) => {
15853
+ if (!path11 || typeof path11 !== "string") return;
15854
+ const parts = path11.replace(/^state\./, "").split(".");
15127
15855
  let current = obj;
15128
15856
  for (let i3 = 0; i3 < parts.length - 1; i3++) {
15129
15857
  const part = parts[i3];
@@ -15597,14 +16325,14 @@ var init_store = __esm({
15597
16325
  const fs16 = getSyncFs();
15598
16326
  if (!fs16) return;
15599
16327
  const validated = validateConversationalState(state3);
15600
- const path10 = resolveConversationalStatePath(validated.scope, validated.subject, validated.conversationId, tenantId);
16328
+ const path11 = resolveConversationalStatePath(validated.scope, validated.subject, validated.conversationId, tenantId);
15601
16329
  const fsPromises = await import('fs/promises');
15602
16330
  await fsPromises.mkdir(resolveConversationalStateDir(tenantId), { recursive: true });
15603
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
16331
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
15604
16332
  try {
15605
16333
  await fsPromises.writeFile(temporary, `${JSON.stringify(validated, null, 2)}
15606
16334
  `, "utf8");
15607
- await fsPromises.rename(temporary, path10);
16335
+ await fsPromises.rename(temporary, path11);
15608
16336
  } catch (error) {
15609
16337
  await fsPromises.rm(temporary, { force: true }).catch(() => void 0);
15610
16338
  throw error;
@@ -15752,7 +16480,7 @@ var init_conversational_state = __esm({
15752
16480
  });
15753
16481
 
15754
16482
  // core/memory/capture-persistence.ts
15755
- var CAPTURE_STORE_KEY, CAPTURE_KEY_PREFIX, sessionRecordKey, nowIso, CapturePersistence, defaultPersistence, getCapturePersistence;
16483
+ var CAPTURE_STORE_KEY, CAPTURE_KEY_PREFIX, sessionRecordKey, nowIso2, CapturePersistence, defaultPersistence, getCapturePersistence;
15756
16484
  var init_capture_persistence = __esm({
15757
16485
  "core/memory/capture-persistence.ts"() {
15758
16486
  init_durable_store();
@@ -15760,7 +16488,7 @@ var init_capture_persistence = __esm({
15760
16488
  CAPTURE_STORE_KEY = "capture-items";
15761
16489
  CAPTURE_KEY_PREFIX = "capture:";
15762
16490
  sessionRecordKey = /* @__PURE__ */ __name((conversationId) => `${CAPTURE_KEY_PREFIX}${conversationId}`, "sessionRecordKey");
15763
- nowIso = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
16491
+ nowIso2 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
15764
16492
  CapturePersistence = class {
15765
16493
  static {
15766
16494
  __name(this, "CapturePersistence");
@@ -15775,7 +16503,7 @@ var init_capture_persistence = __esm({
15775
16503
  conversationId,
15776
16504
  items,
15777
16505
  explicitInstructions,
15778
- updatedAt: nowIso()
16506
+ updatedAt: nowIso2()
15779
16507
  };
15780
16508
  await this.store.set({
15781
16509
  id: sessionRecordKey(conversationId),
@@ -15835,7 +16563,7 @@ var init_capture_persistence = __esm({
15835
16563
  }, "getCapturePersistence");
15836
16564
  }
15837
16565
  });
15838
- 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;
16566
+ 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;
15839
16567
  var init_capture_engine = __esm({
15840
16568
  "core/memory/capture-engine.ts"() {
15841
16569
  init_exemplars();
@@ -15871,7 +16599,7 @@ var init_capture_engine = __esm({
15871
16599
  generateId = /* @__PURE__ */ __name(() => {
15872
16600
  return `capture-${hlc.serialize(hlc.tick())}-${Math.random().toString(36).slice(2, 10)}`;
15873
16601
  }, "generateId");
15874
- nowIso2 = /* @__PURE__ */ __name(() => {
16602
+ nowIso3 = /* @__PURE__ */ __name(() => {
15875
16603
  return (/* @__PURE__ */ new Date()).toISOString();
15876
16604
  }, "nowIso");
15877
16605
  normalizeText = /* @__PURE__ */ __name((text) => {
@@ -15904,7 +16632,7 @@ var init_capture_engine = __esm({
15904
16632
  type: "remember",
15905
16633
  content: text,
15906
16634
  source,
15907
- timestamp: nowIso2()
16635
+ timestamp: nowIso3()
15908
16636
  });
15909
16637
  break;
15910
16638
  }
@@ -15915,7 +16643,7 @@ var init_capture_engine = __esm({
15915
16643
  type: "do-not-remember",
15916
16644
  content: text,
15917
16645
  source,
15918
- timestamp: nowIso2()
16646
+ timestamp: nowIso3()
15919
16647
  });
15920
16648
  break;
15921
16649
  }
@@ -16268,7 +16996,7 @@ var init_capture_engine = __esm({
16268
16996
  const source = {
16269
16997
  conversationId: options.conversationId,
16270
16998
  messageIds: options.messageIds ?? [],
16271
- timestamp: nowIso2(),
16999
+ timestamp: nowIso3(),
16272
17000
  turnIndex: 0
16273
17001
  };
16274
17002
  const instructions = detectExplicitInstructions(text, source);
@@ -16288,7 +17016,7 @@ var init_capture_engine = __esm({
16288
17016
  classification: "temporary_context",
16289
17017
  confidence: "low",
16290
17018
  epistemicType: "observed",
16291
- capturedAt: nowIso2(),
17019
+ capturedAt: nowIso3(),
16292
17020
  method: "automatic"
16293
17021
  },
16294
17022
  confidence: "low",
@@ -16308,7 +17036,7 @@ var init_capture_engine = __esm({
16308
17036
  classification: category,
16309
17037
  confidence,
16310
17038
  epistemicType,
16311
- capturedAt: nowIso2(),
17039
+ capturedAt: nowIso3(),
16312
17040
  method: hasExplicitRemember ? "explicit" : "automatic"
16313
17041
  };
16314
17042
  const item = {
@@ -16370,7 +17098,7 @@ var init_capture_engine = __esm({
16370
17098
  const source = {
16371
17099
  conversationId: options.conversationId,
16372
17100
  messageIds: [msg.id ?? `msg-${index}`],
16373
- timestamp: msg.timestamp ?? nowIso2(),
17101
+ timestamp: msg.timestamp ?? nowIso3(),
16374
17102
  turnIndex: index
16375
17103
  };
16376
17104
  const instructions = detectExplicitInstructions(msg.content, source);
@@ -16390,7 +17118,7 @@ var init_capture_engine = __esm({
16390
17118
  classification: "temporary_context",
16391
17119
  confidence: "low",
16392
17120
  epistemicType: "observed",
16393
- capturedAt: nowIso2(),
17121
+ capturedAt: nowIso3(),
16394
17122
  method: "automatic"
16395
17123
  },
16396
17124
  confidence: "low",
@@ -16410,7 +17138,7 @@ var init_capture_engine = __esm({
16410
17138
  classification: category,
16411
17139
  confidence,
16412
17140
  epistemicType,
16413
- capturedAt: nowIso2(),
17141
+ capturedAt: nowIso3(),
16414
17142
  method: hasExplicitRemember ? "explicit" : "automatic"
16415
17143
  };
16416
17144
  const item = {
@@ -16567,7 +17295,7 @@ var init_capture_engine = __esm({
16567
17295
  if (this.clearedConversations.has(conversationId)) {
16568
17296
  ctx = {
16569
17297
  conversationId,
16570
- startedAt: nowIso2(),
17298
+ startedAt: nowIso3(),
16571
17299
  items: [],
16572
17300
  explicitInstructions: []
16573
17301
  };
@@ -16587,7 +17315,7 @@ var init_capture_engine = __esm({
16587
17315
  }
16588
17316
  ctx = {
16589
17317
  conversationId,
16590
- startedAt: nowIso2(),
17318
+ startedAt: nowIso3(),
16591
17319
  items: [],
16592
17320
  explicitInstructions: []
16593
17321
  };
@@ -16759,7 +17487,7 @@ var init_note = __esm({
16759
17487
  init_storage_coordinator();
16760
17488
  init_claim_identity();
16761
17489
  TOMBSTONE_FILE = "deleted-notes.tombstones.json";
16762
- tombstonePath = /* @__PURE__ */ __name(() => path8.join(resolveUserDotMemPath(), TOMBSTONE_FILE), "tombstonePath");
17490
+ tombstonePath = /* @__PURE__ */ __name(() => path5.join(resolveUserDotMemPath(), TOMBSTONE_FILE), "tombstonePath");
16763
17491
  loadNoteTombstones = /* @__PURE__ */ __name(async () => {
16764
17492
  try {
16765
17493
  const raw = await fs14.readFile(tombstonePath(), "utf8");
@@ -16775,7 +17503,7 @@ var init_note = __esm({
16775
17503
  if (!existing.some((t) => t.id === id)) {
16776
17504
  existing.push({ id, deletedAt: (/* @__PURE__ */ new Date()).toISOString() });
16777
17505
  }
16778
- await fs14.mkdir(path8.dirname(tombstonePath()), { recursive: true });
17506
+ await fs14.mkdir(path5.dirname(tombstonePath()), { recursive: true });
16779
17507
  await fs14.writeFile(tombstonePath(), JSON.stringify({ deletedNotes: existing }, null, 2), "utf8");
16780
17508
  const g2 = globalThis.__dotmemDeletedNotes || /* @__PURE__ */ new Set();
16781
17509
  g2.add(id);
@@ -16802,7 +17530,7 @@ var init_note = __esm({
16802
17530
  if (referencing.length === 0) continue;
16803
17531
  const newClaims = artifact.state.claims.filter((claim) => !(claim.revision?.claimIds ?? []).includes(noteId));
16804
17532
  const newState = { version: artifact.state.version + 1, claims: newClaims };
16805
- await withStorageLock(path8.dirname(filePath), async () => {
17533
+ await withStorageLock(path5.dirname(filePath), async () => {
16806
17534
  const currentBytes = await fs14.readFile(filePath);
16807
17535
  const currentArtifact = await decodeMemArtifact(currentBytes);
16808
17536
  if (!currentArtifact.state || currentArtifact.state.version !== artifact.state.version) {
@@ -16810,7 +17538,7 @@ var init_note = __esm({
16810
17538
  }
16811
17539
  const tmp = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
16812
17540
  try {
16813
- await fs14.mkdir(path8.dirname(filePath), { recursive: true });
17541
+ await fs14.mkdir(path5.dirname(filePath), { recursive: true });
16814
17542
  const { quarantineClaimRecord: quarantineClaimRecord2 } = await Promise.resolve().then(() => (init_quarantine(), quarantine_exports));
16815
17543
  for (const claim of referencing) {
16816
17544
  await quarantineClaimRecord2({
@@ -16943,7 +17671,7 @@ var init_note = __esm({
16943
17671
  return { deleted: 0, byStore: {}, allDeleted: finalOccurrences2.length === 0, remaining: finalOccurrences2 };
16944
17672
  }
16945
17673
  for (const [filePath, occs] of byFile) {
16946
- const storeId = occs[0]?.store ?? "unknown";
17674
+ const storeId = occs[0]?.store ?? "any";
16947
17675
  try {
16948
17676
  const bytes = await fs14.readFile(filePath);
16949
17677
  const artifact = await decodeMemArtifact(bytes);
@@ -16959,7 +17687,7 @@ var init_note = __esm({
16959
17687
  }
16960
17688
  const newClaims = artifact.state.claims.filter((c) => !(c.id === id && c.kind === "note"));
16961
17689
  const newState = { version: artifact.state.version + 1, claims: newClaims };
16962
- await withStorageLock(path8.dirname(filePath), async () => {
17690
+ await withStorageLock(path5.dirname(filePath), async () => {
16963
17691
  const currentBytes = await fs14.readFile(filePath);
16964
17692
  const currentArtifact = await decodeMemArtifact(currentBytes);
16965
17693
  if (!currentArtifact.state || currentArtifact.state.version !== artifact.state.version) {
@@ -16967,7 +17695,7 @@ var init_note = __esm({
16967
17695
  }
16968
17696
  const tmp = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
16969
17697
  try {
16970
- await fs14.mkdir(path8.dirname(filePath), { recursive: true });
17698
+ await fs14.mkdir(path5.dirname(filePath), { recursive: true });
16971
17699
  const encoded = await encodeMemPackage(newState, currentArtifact.preserved, currentArtifact.package);
16972
17700
  await fs14.writeFile(tmp, encoded);
16973
17701
  await decodeMemArtifact(await fs14.readFile(tmp));
@@ -17061,9 +17789,9 @@ var init_note = __esm({
17061
17789
  };
17062
17790
  }, "noteDeleteAll");
17063
17791
  try {
17064
- const tp = path8.join(resolveUserDotMemPath(), TOMBSTONE_FILE);
17065
- if (fs.existsSync(tp)) {
17066
- const raw = fs.readFileSync(tp, "utf8");
17792
+ const tp = path5.join(resolveUserDotMemPath(), TOMBSTONE_FILE);
17793
+ if (fs6.existsSync(tp)) {
17794
+ const raw = fs6.readFileSync(tp, "utf8");
17067
17795
  const parsed = JSON.parse(raw);
17068
17796
  const arr = Array.isArray(parsed) ? parsed : parsed.deletedNotes ?? [];
17069
17797
  const g2 = globalThis.__dotmemDeletedNotes || /* @__PURE__ */ new Set();
@@ -17396,8 +18124,8 @@ var init_ontology = __esm({
17396
18124
  errors.push("relation must be object");
17397
18125
  continue;
17398
18126
  }
17399
- if (!ids.has(r.from)) errors.push(`relation.from unknown: ${r.from}`);
17400
- if (!ids.has(r.to)) errors.push(`relation.to unknown: ${r.to}`);
18127
+ if (!ids.has(r.from)) errors.push(`relation.from any: ${r.from}`);
18128
+ if (!ids.has(r.to)) errors.push(`relation.to any: ${r.to}`);
17401
18129
  if (!RELATION_TYPES.includes(r.type)) errors.push(`relation.type invalid: ${r.type}`);
17402
18130
  }
17403
18131
  return { valid: errors.length === 0, errors };
@@ -17414,7 +18142,7 @@ var init_ontology = __esm({
17414
18142
  ),
17415
18143
  byPos: graph.concepts.reduce(
17416
18144
  (acc, c) => {
17417
- const k = c.pos || "unknown";
18145
+ const k = c.pos || "any";
17418
18146
  acc[k] = (acc[k] || 0) + 1;
17419
18147
  return acc;
17420
18148
  },
@@ -17474,7 +18202,7 @@ var init_anthology = __esm({
17474
18202
  errors.push("provenance must be an object");
17475
18203
  return { valid: false, errors };
17476
18204
  }
17477
- const kinds = ["user-statement", "system-observation", "imported-document", "external-source", "agent-inference", "model-summary", "human-correction", "system-event", "unknown"];
18205
+ const kinds = ["user-statement", "system-observation", "imported-document", "external-source", "agent-inference", "model-summary", "human-correction", "system-event", "any"];
17478
18206
  if (!kinds.includes(p.kind)) errors.push("invalid provenance kind");
17479
18207
  if (p.observedAt !== void 0 && (typeof p.observedAt !== "string" || isNaN(Date.parse(p.observedAt)))) {
17480
18208
  errors.push("observedAt must be valid ISO timestamp if provided");
@@ -17528,681 +18256,908 @@ var init_anthology = __esm({
17528
18256
  schemaVersion: 0,
17529
18257
  category: "legacy",
17530
18258
  payload: item,
17531
- scope: item?.scope ?? "unknown",
17532
- provenance: { kind: "unknown" },
18259
+ scope: item?.scope ?? "any",
18260
+ provenance: { kind: "any" },
17533
18261
  epistemicStatus: "unassessed",
17534
- sensitivity: "unknown",
18262
+ sensitivity: "any",
17535
18263
  temporal: { recordedAt: item?.createdAt ? new Date(item.createdAt).toISOString() : (/* @__PURE__ */ new Date(0)).toISOString() },
17536
18264
  revision: { revision: 0 }
17537
18265
  };
17538
18266
  }, "normalizeLegacyRecord");
17539
- MEMORY_CATEGORIES = ["observation", "claim", "fact-candidate", "hypothesis", "decision", "preference", "instruction", "experience", "goal", "relationship", "derived-summary", "unknown-disputed", "legacy"];
18267
+ MEMORY_CATEGORIES = ["observation", "claim", "fact-candidate", "hypothesis", "decision", "preference", "instruction", "experience", "goal", "relationship", "derived-summary", "any-disputed", "legacy"];
17540
18268
  EPISTEMIC_STATUSES = ["unassessed", "asserted", "corroborated", "reviewed", "disputed", "refuted", "superseded"];
17541
18269
  }
17542
- });
17543
- function stripCode(content) {
17544
- let out = "";
17545
- let i3 = 0;
17546
- const n = content.length;
17547
- while (i3 < n) {
17548
- const c = content[i3];
17549
- const next = content[i3 + 1];
17550
- if (c === "/" && next === "/") {
17551
- const nl = content.indexOf("\n", i3);
17552
- if (nl === -1) break;
17553
- out += "\n";
17554
- i3 = nl + 1;
17555
- continue;
17556
- }
17557
- if (c === "/" && next === "*") {
17558
- const end = content.indexOf("*/", i3 + 2);
17559
- if (end === -1) break;
17560
- const seg = content.slice(i3, end + 2);
17561
- out += seg.replace(/[^\n]/g, " ");
17562
- i3 = end + 2;
17563
- continue;
18270
+ });
18271
+ function audit(options = {}) {
18272
+ const projectPath = options.projectPath ?? process.cwd();
18273
+ const allFindings = scanDir(projectPath, projectPath);
18274
+ allFindings.push(...runNpmAudit(projectPath));
18275
+ const quality = allFindings.filter((f) => f.category === "quality");
18276
+ const security2 = allFindings.filter((f) => f.category === "security");
18277
+ const performance = allFindings.filter((f) => f.category === "performance");
18278
+ const errorCount = allFindings.filter((f) => f.severity === "critical" || f.severity === "high").length;
18279
+ const totalFindings = allFindings.length;
18280
+ const score = Math.max(0, 100 - errorCount * 10 - (totalFindings - errorCount) * 2);
18281
+ const grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : score >= 60 ? "D" : "F";
18282
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
18283
+ const result = {
18284
+ projectPath,
18285
+ timestamp,
18286
+ quality,
18287
+ security: security2,
18288
+ performance,
18289
+ score,
18290
+ grade,
18291
+ summary: `Audit complete: ${totalFindings} findings (${errorCount} critical/high). Score: ${score}/100 (Grade: ${grade}).`,
18292
+ report: ""
18293
+ };
18294
+ result.report = generateReport({ quality, security: security2, performance, score, grade, projectPath, timestamp });
18295
+ if (options.onFinding) {
18296
+ for (const f of allFindings) {
18297
+ options.onFinding(f);
17564
18298
  }
17565
- if (c === '"' || c === "'" || c === "`") {
17566
- const quote = c;
17567
- let j = i3 + 1;
17568
- while (j < n) {
17569
- if (content[j] === "\\") {
17570
- j += 2;
18299
+ }
18300
+ return {
18301
+ name: "audit",
18302
+ version: "0.3.0",
18303
+ description: "Professional IT audit: quality, security, performance, npm vulnerabilities.",
18304
+ hooks: {
18305
+ onAudit(_result) {
18306
+ }
18307
+ },
18308
+ run: /* @__PURE__ */ __name(() => result, "run"),
18309
+ report: /* @__PURE__ */ __name(() => result.report, "report")
18310
+ };
18311
+ }
18312
+ var stripCode, hasEval, isInNonCode, collectDangerousNames, hasProcessExec, scanFile, scanDir, runNpmAudit, generateReport;
18313
+ var init_audit = __esm({
18314
+ "plugins/audit/index.ts"() {
18315
+ stripCode = /* @__PURE__ */ __name((content) => {
18316
+ let out = "";
18317
+ let i3 = 0;
18318
+ const n = content.length;
18319
+ while (i3 < n) {
18320
+ const c = content[i3];
18321
+ const next = content[i3 + 1];
18322
+ if (c === "/" && next === "/") {
18323
+ const nl = content.indexOf("\n", i3);
18324
+ if (nl === -1) break;
18325
+ out += "\n";
18326
+ i3 = nl + 1;
17571
18327
  continue;
17572
18328
  }
17573
- if (content[j] === quote) {
17574
- j++;
17575
- break;
18329
+ if (c === "/" && next === "*") {
18330
+ const end = content.indexOf("*/", i3 + 2);
18331
+ if (end === -1) break;
18332
+ const seg = content.slice(i3, end + 2);
18333
+ out += seg.replace(/[^\n]/g, " ");
18334
+ i3 = end + 2;
18335
+ continue;
17576
18336
  }
17577
- if (content[j] === "\n") break;
17578
- j++;
17579
- }
17580
- const seg = content.slice(i3, j);
17581
- out += seg.replace(/[^\n]/g, " ");
17582
- i3 = j;
17583
- continue;
17584
- }
17585
- if (c === "/") {
17586
- let k = out.length - 1;
17587
- while (k >= 0 && /\s/.test(out[k])) k--;
17588
- const prev = k >= 0 ? out[k] : "";
17589
- const regexStartChars = "(,=:[!&|?{;+-*/%^~";
17590
- if (regexStartChars.includes(prev) || prev === "") {
17591
- let j = i3 + 1;
17592
- let inClass = false;
17593
- while (j < n) {
17594
- if (content[j] === "\\") {
17595
- j += 2;
18337
+ if (c === '"' || c === "'" || c === "`") {
18338
+ const quote = c;
18339
+ let j = i3 + 1;
18340
+ while (j < n) {
18341
+ if (content[j] === "\\") {
18342
+ j += 2;
18343
+ continue;
18344
+ }
18345
+ if (content[j] === quote) {
18346
+ j++;
18347
+ break;
18348
+ }
18349
+ if (content[j] === "\n") break;
18350
+ j++;
18351
+ }
18352
+ const seg = content.slice(i3, j);
18353
+ out += seg.replace(/[^\n]/g, " ");
18354
+ i3 = j;
18355
+ continue;
18356
+ }
18357
+ if (c === "/") {
18358
+ let k = out.length - 1;
18359
+ while (k >= 0 && /\s/.test(out[k])) k--;
18360
+ const prev = k >= 0 ? out[k] : "";
18361
+ const regexStartChars = "(,=:[!&|?{;+-*/%^~";
18362
+ if (regexStartChars.includes(prev) || prev === "") {
18363
+ let j = i3 + 1;
18364
+ let inClass = false;
18365
+ while (j < n) {
18366
+ if (content[j] === "\\") {
18367
+ j += 2;
18368
+ continue;
18369
+ }
18370
+ if (content[j] === "[") {
18371
+ inClass = true;
18372
+ j++;
18373
+ continue;
18374
+ }
18375
+ if (content[j] === "]") {
18376
+ inClass = false;
18377
+ j++;
18378
+ continue;
18379
+ }
18380
+ if (content[j] === "/" && !inClass) {
18381
+ j++;
18382
+ break;
18383
+ }
18384
+ if (content[j] === "\n") break;
18385
+ j++;
18386
+ }
18387
+ const seg = content.slice(i3, j);
18388
+ out += seg.replace(/[^\n]/g, " ");
18389
+ i3 = j;
17596
18390
  continue;
17597
18391
  }
17598
- if (content[j] === "[") {
17599
- inClass = true;
17600
- j++;
18392
+ }
18393
+ out += c;
18394
+ i3++;
18395
+ }
18396
+ return out;
18397
+ }, "stripCode");
18398
+ hasEval = /* @__PURE__ */ __name((content) => {
18399
+ const code = stripCode(content);
18400
+ if (/\b(?:globalThis|global|window|self)\s*\.\s*eval\s*\(/.test(code)) return true;
18401
+ if (/\beval\s*\(/.test(code)) return true;
18402
+ return false;
18403
+ }, "hasEval");
18404
+ isInNonCode = /* @__PURE__ */ __name((content, index) => {
18405
+ let i3 = 0;
18406
+ let inLineComment = false;
18407
+ let inBlockComment = false;
18408
+ let inString = null;
18409
+ while (i3 < index) {
18410
+ const c = content[i3];
18411
+ const next = content[i3 + 1];
18412
+ if (inLineComment) {
18413
+ if (c === "\n") inLineComment = false;
18414
+ i3++;
18415
+ continue;
18416
+ }
18417
+ if (inBlockComment) {
18418
+ if (c === "*" && next === "/") {
18419
+ inBlockComment = false;
18420
+ i3 += 2;
17601
18421
  continue;
17602
18422
  }
17603
- if (content[j] === "]") {
17604
- inClass = false;
17605
- j++;
18423
+ i3++;
18424
+ continue;
18425
+ }
18426
+ if (inString) {
18427
+ if (c === "\\") {
18428
+ i3 += 2;
17606
18429
  continue;
17607
18430
  }
17608
- if (content[j] === "/" && !inClass) {
17609
- j++;
17610
- break;
18431
+ if (c === inString) inString = null;
18432
+ i3++;
18433
+ continue;
18434
+ }
18435
+ if (c === "/" && next === "/") {
18436
+ inLineComment = true;
18437
+ i3 += 2;
18438
+ continue;
18439
+ }
18440
+ if (c === "/" && next === "*") {
18441
+ inBlockComment = true;
18442
+ i3 += 2;
18443
+ continue;
18444
+ }
18445
+ if (c === '"' || c === "'" || c === "`") {
18446
+ inString = c;
18447
+ i3++;
18448
+ continue;
18449
+ }
18450
+ i3++;
18451
+ }
18452
+ return inLineComment || inBlockComment || inString !== null;
18453
+ }, "isInNonCode");
18454
+ collectDangerousNames = /* @__PURE__ */ __name((content) => {
18455
+ const names = /* @__PURE__ */ new Set();
18456
+ const namespaces = /* @__PURE__ */ new Set();
18457
+ const addName = /* @__PURE__ */ __name((name, local) => {
18458
+ if (["exec", "execSync", "spawn", "spawnSync"].includes(name)) {
18459
+ names.add(local);
18460
+ }
18461
+ }, "addName");
18462
+ let m;
18463
+ const esImport = /import\s*\{([^}]+)\}\s*from\s*['"](?:node:)?child_process['"]/g;
18464
+ while ((m = esImport.exec(content)) !== null) {
18465
+ if (isInNonCode(content, m.index)) continue;
18466
+ for (const part of m[1].split(",")) {
18467
+ const p = part.trim();
18468
+ if (!p) continue;
18469
+ const alias = p.match(/^(\w+)\s+as\s+(\w+)$/);
18470
+ if (alias) addName(alias[1], alias[2]);
18471
+ else addName(p, p);
18472
+ }
18473
+ }
18474
+ const esNs = /import\s*\*\s*as\s+(\w+)\s*from\s*['"](?:node:)?child_process['"]/g;
18475
+ while ((m = esNs.exec(content)) !== null) {
18476
+ if (isInNonCode(content, m.index)) continue;
18477
+ namespaces.add(m[1]);
18478
+ }
18479
+ const cjsDestruct = /(?:const|let|var)\s*\{([^}]+)\}\s*=\s*require\(\s*['"](?:node:)?child_process['"]\s*\)/g;
18480
+ while ((m = cjsDestruct.exec(content)) !== null) {
18481
+ if (isInNonCode(content, m.index)) continue;
18482
+ for (const part of m[1].split(",")) {
18483
+ const p = part.trim();
18484
+ if (!p) continue;
18485
+ const colon = p.match(/^(\w+)\s*:\s*(\w+)$/);
18486
+ if (colon) {
18487
+ addName(colon[1], colon[2]);
18488
+ continue;
17611
18489
  }
17612
- if (content[j] === "\n") break;
17613
- j++;
18490
+ const alias = p.match(/^(\w+)\s+as\s+(\w+)$/);
18491
+ if (alias) addName(alias[1], alias[2]);
18492
+ else addName(p, p);
18493
+ }
18494
+ }
18495
+ const cjsNs = /(?:const|let|var)\s+(\w+)\s*=\s*require\(\s*['"](?:node:)?child_process['"]\s*\)/g;
18496
+ while ((m = cjsNs.exec(content)) !== null) {
18497
+ if (isInNonCode(content, m.index)) continue;
18498
+ namespaces.add(m[1]);
18499
+ }
18500
+ const cjsProp = /(?:const|let|var)\s+(\w+)\s*=\s*require\(\s*['"](?:node:)?child_process['"]\s*\)\s*\.\s*(exec|execSync|spawn|spawnSync)\b/g;
18501
+ while ((m = cjsProp.exec(content)) !== null) {
18502
+ if (isInNonCode(content, m.index)) continue;
18503
+ names.add(m[1]);
18504
+ }
18505
+ return { names, namespaces };
18506
+ }, "collectDangerousNames");
18507
+ hasProcessExec = /* @__PURE__ */ __name((content) => {
18508
+ const code = stripCode(content);
18509
+ const { names, namespaces } = collectDangerousNames(content);
18510
+ for (const ns of namespaces) {
18511
+ const re = new RegExp("\\b" + ns + "\\s*\\.\\s*(exec|execSync|spawn|spawnSync)\\s*\\(");
18512
+ if (re.test(code)) return true;
18513
+ }
18514
+ for (const name of names) {
18515
+ const re = new RegExp("\\b" + name + "\\s*\\(");
18516
+ if (re.test(code)) return true;
18517
+ }
18518
+ if (/\b(?:child_process|childProcess)\s*\.\s*(exec|execSync|spawn|spawnSync)\s*\(/.test(code)) return true;
18519
+ if (/require\(\s*['"](?:node:)?child_process['"]\s*\)\s*\.\s*(exec|execSync|spawn|spawnSync)\s*\(/.test(code)) return true;
18520
+ return false;
18521
+ }, "hasProcessExec");
18522
+ scanFile = /* @__PURE__ */ __name((filePath, content, projectPath) => {
18523
+ const findings = [];
18524
+ const lines = content.split("\n");
18525
+ const relPath = relative(projectPath, filePath);
18526
+ const ext = extname(filePath);
18527
+ if (/password\s*=\s*['"]/i.test(content)) {
18528
+ 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)" });
18529
+ }
18530
+ if (/api[_-]?key\s*=\s*['"]/i.test(content)) {
18531
+ 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)" });
18532
+ }
18533
+ if (/secret\s*=\s*['"]/i.test(content)) {
18534
+ 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)" });
18535
+ }
18536
+ if (hasEval(content)) {
18537
+ 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)" });
18538
+ }
18539
+ if (/innerHTML\s*=/.test(content)) {
18540
+ 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)" });
18541
+ }
18542
+ if (/document\.write\s*\(/.test(content)) {
18543
+ 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" });
18544
+ }
18545
+ if (hasProcessExec(content)) {
18546
+ 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)" });
18547
+ }
18548
+ if (/cors\s*\(\s*\{\s*origin:\s*['"]\*['"]/.test(content)) {
18549
+ 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)" });
18550
+ }
18551
+ if (/debug\s*:\s*true/.test(content)) {
18552
+ 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)" });
18553
+ }
18554
+ const consoleCount = (content.match(/console\.log/g) || []).length;
18555
+ if (consoleCount > 5 && !filePath.includes("test")) {
18556
+ 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)" });
18557
+ }
18558
+ if (ext === ".c" || ext === ".cpp" || ext === ".rs") {
18559
+ if (/strcpy|strcat|sprintf|gets\s*\(/.test(content)) {
18560
+ 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)" });
17614
18561
  }
17615
- const seg = content.slice(i3, j);
17616
- out += seg.replace(/[^\n]/g, " ");
17617
- i3 = j;
17618
- continue;
17619
18562
  }
17620
- }
17621
- out += c;
17622
- i3++;
17623
- }
17624
- return out;
17625
- }
17626
- function hasEval(content) {
17627
- const code = stripCode(content);
17628
- if (/\b(?:globalThis|global|window|self)\s*\.\s*eval\s*\(/.test(code)) return true;
17629
- if (/\beval\s*\(/.test(code)) return true;
17630
- return false;
17631
- }
17632
- function isInNonCode(content, index) {
17633
- let i3 = 0;
17634
- let inLineComment = false;
17635
- let inBlockComment = false;
17636
- let inString = null;
17637
- while (i3 < index) {
17638
- const c = content[i3];
17639
- const next = content[i3 + 1];
17640
- if (inLineComment) {
17641
- if (c === "\n") inLineComment = false;
17642
- i3++;
17643
- continue;
17644
- }
17645
- if (inBlockComment) {
17646
- if (c === "*" && next === "/") {
17647
- inBlockComment = false;
17648
- i3 += 2;
17649
- continue;
18563
+ if (lines.length > 500) {
18564
+ 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)" });
17650
18565
  }
17651
- i3++;
17652
- continue;
17653
- }
17654
- if (inString) {
17655
- if (c === "\\") {
17656
- i3 += 2;
17657
- continue;
18566
+ const todoCount = (content.match(/TODO|FIXME|HACK|XXX/gi) || []).length;
18567
+ if (todoCount > 3) {
18568
+ 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" });
17658
18569
  }
17659
- if (c === inString) inString = null;
17660
- i3++;
17661
- continue;
17662
- }
17663
- if (c === "/" && next === "/") {
17664
- inLineComment = true;
17665
- i3 += 2;
17666
- continue;
17667
- }
17668
- if (c === "/" && next === "*") {
17669
- inBlockComment = true;
17670
- i3 += 2;
17671
- continue;
17672
- }
17673
- if (c === '"' || c === "'" || c === "`") {
17674
- inString = c;
17675
- i3++;
17676
- continue;
17677
- }
17678
- i3++;
17679
- }
17680
- return inLineComment || inBlockComment || inString !== null;
17681
- }
17682
- function collectDangerousNames(content) {
17683
- const names = /* @__PURE__ */ new Set();
17684
- const namespaces = /* @__PURE__ */ new Set();
17685
- const addName = /* @__PURE__ */ __name((name, local) => {
17686
- if (["exec", "execSync", "spawn", "spawnSync"].includes(name)) {
17687
- names.add(local);
17688
- }
17689
- }, "addName");
17690
- let m;
17691
- const esImport = /import\s*\{([^}]+)\}\s*from\s*['"](?:node:)?child_process['"]/g;
17692
- while ((m = esImport.exec(content)) !== null) {
17693
- if (isInNonCode(content, m.index)) continue;
17694
- for (const part of m[1].split(",")) {
17695
- const p = part.trim();
17696
- if (!p) continue;
17697
- const alias = p.match(/^(\w+)\s+as\s+(\w+)$/);
17698
- if (alias) addName(alias[1], alias[2]);
17699
- else addName(p, p);
17700
- }
17701
- }
17702
- const esNs = /import\s*\*\s*as\s+(\w+)\s*from\s*['"](?:node:)?child_process['"]/g;
17703
- while ((m = esNs.exec(content)) !== null) {
17704
- if (isInNonCode(content, m.index)) continue;
17705
- namespaces.add(m[1]);
17706
- }
17707
- const cjsDestruct = /(?:const|let|var)\s*\{([^}]+)\}\s*=\s*require\(\s*['"](?:node:)?child_process['"]\s*\)/g;
17708
- while ((m = cjsDestruct.exec(content)) !== null) {
17709
- if (isInNonCode(content, m.index)) continue;
17710
- for (const part of m[1].split(",")) {
17711
- const p = part.trim();
17712
- if (!p) continue;
17713
- const colon = p.match(/^(\w+)\s*:\s*(\w+)$/);
17714
- if (colon) {
17715
- addName(colon[1], colon[2]);
17716
- continue;
17717
- }
17718
- const alias = p.match(/^(\w+)\s+as\s+(\w+)$/);
17719
- if (alias) addName(alias[1], alias[2]);
17720
- else addName(p, p);
17721
- }
17722
- }
17723
- const cjsNs = /(?:const|let|var)\s+(\w+)\s*=\s*require\(\s*['"](?:node:)?child_process['"]\s*\)/g;
17724
- while ((m = cjsNs.exec(content)) !== null) {
17725
- if (isInNonCode(content, m.index)) continue;
17726
- namespaces.add(m[1]);
17727
- }
17728
- const cjsProp = /(?:const|let|var)\s+(\w+)\s*=\s*require\(\s*['"](?:node:)?child_process['"]\s*\)\s*\.\s*(exec|execSync|spawn|spawnSync)\b/g;
17729
- while ((m = cjsProp.exec(content)) !== null) {
17730
- if (isInNonCode(content, m.index)) continue;
17731
- names.add(m[1]);
17732
- }
17733
- return { names, namespaces };
17734
- }
17735
- function hasProcessExec(content) {
17736
- const code = stripCode(content);
17737
- const { names, namespaces } = collectDangerousNames(content);
17738
- for (const ns of namespaces) {
17739
- const re = new RegExp("\\b" + ns + "\\s*\\.\\s*(exec|execSync|spawn|spawnSync)\\s*\\(");
17740
- if (re.test(code)) return true;
17741
- }
17742
- for (const name of names) {
17743
- const re = new RegExp("\\b" + name + "\\s*\\(");
17744
- if (re.test(code)) return true;
17745
- }
17746
- if (/\b(?:child_process|childProcess)\s*\.\s*(exec|execSync|spawn|spawnSync)\s*\(/.test(code)) return true;
17747
- if (/require\(\s*['"](?:node:)?child_process['"]\s*\)\s*\.\s*(exec|execSync|spawn|spawnSync)\s*\(/.test(code)) return true;
17748
- return false;
17749
- }
17750
- function scanFile(filePath, content, projectPath) {
17751
- const findings = [];
17752
- const lines = content.split("\n");
17753
- const relPath = relative(projectPath, filePath);
17754
- const ext = extname(filePath);
17755
- if (/password\s*=\s*['"]/i.test(content)) {
17756
- 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)" });
17757
- }
17758
- if (/api[_-]?key\s*=\s*['"]/i.test(content)) {
17759
- 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)" });
17760
- }
17761
- if (/secret\s*=\s*['"]/i.test(content)) {
17762
- 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)" });
17763
- }
17764
- if (hasEval(content)) {
17765
- 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)" });
17766
- }
17767
- if (/innerHTML\s*=/.test(content)) {
17768
- 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)" });
17769
- }
17770
- if (/document\.write\s*\(/.test(content)) {
17771
- 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" });
17772
- }
17773
- if (hasProcessExec(content)) {
17774
- 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)" });
17775
- }
17776
- if (/cors\s*\(\s*\{\s*origin:\s*['"]\*['"]/.test(content)) {
17777
- 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)" });
17778
- }
17779
- if (/debug\s*:\s*true/.test(content)) {
17780
- 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)" });
17781
- }
17782
- const consoleCount = (content.match(/console\.log/g) || []).length;
17783
- if (consoleCount > 5 && !filePath.includes("test")) {
17784
- 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)" });
17785
- }
17786
- if (ext === ".c" || ext === ".cpp" || ext === ".rs") {
17787
- if (/strcpy|strcat|sprintf|gets\s*\(/.test(content)) {
17788
- 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)" });
17789
- }
17790
- }
17791
- if (lines.length > 500) {
17792
- 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)" });
17793
- }
17794
- const todoCount = (content.match(/TODO|FIXME|HACK|XXX/gi) || []).length;
17795
- if (todoCount > 3) {
17796
- 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" });
17797
- }
17798
- if (!content.includes("test") && (ext === ".ts" || ext === ".js") && !filePath.includes("test") && !filePath.includes("spec")) {
17799
- 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" });
17800
- }
17801
- if (/await\s+\w+\(/.test(content) && !content.includes("try") && !content.includes("catch")) {
17802
- 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" });
17803
- }
17804
- const nestedLoops = content.match(/for\s*\(.*\)\s*\{[^}]*for\s*\(/g);
17805
- if (nestedLoops && nestedLoops.length > 0) {
17806
- 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" });
17807
- }
17808
- if (/JSON\.parse\(.*JSON\.stringify/.test(content)) {
17809
- 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" });
17810
- }
17811
- const syncReads = (content.match(/readFileSync/g) || []).length;
17812
- if (syncReads > 3) {
17813
- 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" });
17814
- }
17815
- return findings;
17816
- }
17817
- function scanDir(dir, projectPath) {
17818
- const allFindings = [];
17819
- try {
17820
- const entries2 = readdirSync(dir, { withFileTypes: true });
17821
- for (const entry of entries2) {
17822
- if (["node_modules", ".git", "dist", ".cache", "coverage", ".private", ".project", ".dev"].includes(entry.name)) continue;
17823
- const fullPath = join(dir, entry.name);
17824
- if (entry.isDirectory()) {
17825
- allFindings.push(...scanDir(fullPath, projectPath));
17826
- } else if (entry.isFile() && /\.(ts|js|tsx|jsx|py|go|rs|c|cpp|java)$/.test(entry.name)) {
18570
+ if (!content.includes("test") && (ext === ".ts" || ext === ".js") && !filePath.includes("test") && !filePath.includes("spec")) {
18571
+ 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" });
18572
+ }
18573
+ if (/await\s+\w+\(/.test(content) && !content.includes("try") && !content.includes("catch")) {
18574
+ 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" });
18575
+ }
18576
+ const nestedLoops = content.match(/for\s*\(.*\)\s*\{[^}]*for\s*\(/g);
18577
+ if (nestedLoops && nestedLoops.length > 0) {
18578
+ 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" });
18579
+ }
18580
+ if (/JSON\.parse\(.*JSON\.stringify/.test(content)) {
18581
+ 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" });
18582
+ }
18583
+ const syncReads = (content.match(/readFileSync/g) || []).length;
18584
+ if (syncReads > 3) {
18585
+ 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" });
18586
+ }
18587
+ return findings;
18588
+ }, "scanFile");
18589
+ scanDir = /* @__PURE__ */ __name((dir, projectPath) => {
18590
+ const allFindings = [];
18591
+ try {
18592
+ const entries2 = readdirSync(dir, { withFileTypes: true });
18593
+ for (const entry of entries2) {
18594
+ if (["node_modules", ".git", "dist", ".cache", "coverage", ".private", ".project", ".dev"].includes(entry.name)) continue;
18595
+ const fullPath = join(dir, entry.name);
18596
+ if (entry.isDirectory()) {
18597
+ allFindings.push(...scanDir(fullPath, projectPath));
18598
+ } else if (entry.isFile() && /\.(ts|js|tsx|jsx|py|go|rs|c|cpp|java)$/.test(entry.name)) {
18599
+ try {
18600
+ const content = readFileSync(fullPath, "utf-8");
18601
+ allFindings.push(...scanFile(fullPath, content, projectPath));
18602
+ } catch {
18603
+ }
18604
+ }
18605
+ }
18606
+ } catch {
18607
+ }
18608
+ return allFindings;
18609
+ }, "scanDir");
18610
+ runNpmAudit = /* @__PURE__ */ __name((projectPath) => {
18611
+ const findings = [];
18612
+ try {
18613
+ let output = "";
17827
18614
  try {
17828
- const content = readFileSync(fullPath, "utf-8");
17829
- allFindings.push(...scanFile(fullPath, content, projectPath));
17830
- } catch {
18615
+ output = execFileSync("npm", ["audit", "--json"], { cwd: projectPath, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
18616
+ } catch (e) {
18617
+ output = e.stdout || "";
18618
+ }
18619
+ if (!output) return findings;
18620
+ const data = JSON.parse(output);
18621
+ const vulns = data.vulnerabilities ?? {};
18622
+ let idCounter = 1;
18623
+ for (const [name, info] of Object.entries(vulns)) {
18624
+ const severity = (info.severity ?? "low").toLowerCase();
18625
+ const mappedSeverity = severity === "critical" ? "critical" : severity === "high" ? "high" : severity === "moderate" ? "medium" : "low";
18626
+ const via = Array.isArray(info.via) ? info.via.filter((v) => typeof v === "object").map((v) => v.title || v.name).join(", ") : "";
18627
+ findings.push({
18628
+ id: `NPM-${String(idCounter++).padStart(3, "0")}`,
18629
+ category: "security",
18630
+ severity: mappedSeverity,
18631
+ framework: "npm audit",
18632
+ control: "OWASP A06",
18633
+ message: `${name}: ${via || info.name || "vulnerability"} (${severity})`,
18634
+ file: "package.json",
18635
+ remediation: `Run "npm audit fix" or update ${name} to a patched version`
18636
+ });
17831
18637
  }
18638
+ const meta = data.metadata?.vulnerabilities;
18639
+ if (meta && meta.total > 0) {
18640
+ findings.push({
18641
+ id: "NPM-SUM",
18642
+ category: "security",
18643
+ severity: meta.critical > 0 ? "critical" : meta.high > 0 ? "high" : meta.moderate > 0 ? "medium" : "low",
18644
+ framework: "npm audit",
18645
+ control: "OWASP A06",
18646
+ message: `npm audit: ${meta.total} vulnerabilities (${meta.critical} critical, ${meta.high} high, ${meta.moderate} moderate, ${meta.low} low)`,
18647
+ file: "package.json",
18648
+ remediation: 'Run "npm audit fix" to resolve. Review breaking changes before applying.'
18649
+ });
18650
+ }
18651
+ } catch {
17832
18652
  }
17833
- }
17834
- } catch {
17835
- }
17836
- return allFindings;
17837
- }
17838
- function runNpmAudit(projectPath) {
17839
- const findings = [];
17840
- try {
17841
- let output = "";
17842
- try {
17843
- output = execFileSync("npm", ["audit", "--json"], { cwd: projectPath, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
17844
- } catch (e) {
17845
- output = e.stdout || "";
17846
- }
17847
- if (!output) return findings;
17848
- const data = JSON.parse(output);
17849
- const vulns = data.vulnerabilities ?? {};
17850
- let idCounter = 1;
17851
- for (const [name, info] of Object.entries(vulns)) {
17852
- const severity = (info.severity ?? "low").toLowerCase();
17853
- const mappedSeverity = severity === "critical" ? "critical" : severity === "high" ? "high" : severity === "moderate" ? "medium" : "low";
17854
- const via = Array.isArray(info.via) ? info.via.filter((v) => typeof v === "object").map((v) => v.title || v.name).join(", ") : "";
17855
- findings.push({
17856
- id: `NPM-${String(idCounter++).padStart(3, "0")}`,
17857
- category: "security",
17858
- severity: mappedSeverity,
17859
- framework: "npm audit",
17860
- control: "OWASP A06",
17861
- message: `${name}: ${via || info.name || "vulnerability"} (${severity})`,
17862
- file: "package.json",
17863
- remediation: `Run "npm audit fix" or update ${name} to a patched version`
17864
- });
17865
- }
17866
- const meta = data.metadata?.vulnerabilities;
17867
- if (meta && meta.total > 0) {
17868
- findings.push({
17869
- id: "NPM-SUM",
17870
- category: "security",
17871
- severity: meta.critical > 0 ? "critical" : meta.high > 0 ? "high" : meta.moderate > 0 ? "medium" : "low",
17872
- framework: "npm audit",
17873
- control: "OWASP A06",
17874
- message: `npm audit: ${meta.total} vulnerabilities (${meta.critical} critical, ${meta.high} high, ${meta.moderate} moderate, ${meta.low} low)`,
17875
- file: "package.json",
17876
- remediation: 'Run "npm audit fix" to resolve. Review breaking changes before applying.'
17877
- });
17878
- }
17879
- } catch {
17880
- }
17881
- return findings;
17882
- }
17883
- function generateReport(result) {
17884
- const { quality, security: security2, performance, score, grade, projectPath, timestamp } = result;
17885
- const all = [...quality, ...security2, ...performance];
17886
- const critical = all.filter((f) => f.severity === "critical").length;
17887
- const high = all.filter((f) => f.severity === "high").length;
17888
- const medium = all.filter((f) => f.severity === "medium").length;
17889
- const low = all.filter((f) => f.severity === "low" || f.severity === "info").length;
17890
- let report = "";
17891
- 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";
17892
- report += " PROFESSIONAL IT AUDIT REPORT\n";
17893
- 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";
17894
- report += `Project: ${projectPath}
18653
+ return findings;
18654
+ }, "runNpmAudit");
18655
+ generateReport = /* @__PURE__ */ __name((result) => {
18656
+ const { quality, security: security2, performance, score, grade, projectPath, timestamp } = result;
18657
+ const all = [...quality, ...security2, ...performance];
18658
+ const critical = all.filter((f) => f.severity === "critical").length;
18659
+ const high = all.filter((f) => f.severity === "high").length;
18660
+ const medium = all.filter((f) => f.severity === "medium").length;
18661
+ const low = all.filter((f) => f.severity === "low" || f.severity === "info").length;
18662
+ let report = "";
18663
+ 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";
18664
+ report += " PROFESSIONAL IT AUDIT REPORT\n";
18665
+ 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";
18666
+ report += `Project: ${projectPath}
17895
18667
  `;
17896
- report += `Date: ${timestamp}
18668
+ report += `Date: ${timestamp}
17897
18669
  `;
17898
- report += `Auditor: dotmem audit plugin
18670
+ report += `Auditor: dotmem audit plugin
17899
18671
  `;
17900
- report += `Frameworks: OWASP Top 10, NIST SP 800-53, NSA/CISA Guidelines, ISO 25010, npm audit
18672
+ report += `Frameworks: OWASP Top 10, NIST SP 800-53, NSA/CISA Guidelines, ISO 25010, npm audit
17901
18673
  `;
17902
- report += `OSI Layers: L7 (Application) analyzed
18674
+ report += `OSI Layers: L7 (Application) analyzed
17903
18675
 
17904
18676
  `;
17905
- 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";
17906
- report += " EXECUTIVE SUMMARY\n";
17907
- 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";
17908
- report += `Overall Score: ${score}/100 (Grade: ${grade})
18677
+ 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";
18678
+ report += " EXECUTIVE SUMMARY\n";
18679
+ 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";
18680
+ report += `Overall Score: ${score}/100 (Grade: ${grade})
17909
18681
  `;
17910
- report += `Total Findings: ${all.length}
18682
+ report += `Total Findings: ${all.length}
17911
18683
  `;
17912
- report += ` Critical: ${critical} High: ${high} Medium: ${medium} Low/Info: ${low}
18684
+ report += ` Critical: ${critical} High: ${high} Medium: ${medium} Low/Info: ${low}
17913
18685
 
17914
18686
  `;
17915
- report += ` Quality: ${quality.length} findings
18687
+ report += ` Quality: ${quality.length} findings
17916
18688
  `;
17917
- report += ` Security: ${security2.length} findings (incl. npm vulnerabilities)
18689
+ report += ` Security: ${security2.length} findings (incl. npm vulnerabilities)
17918
18690
  `;
17919
- report += ` Performance: ${performance.length} findings
18691
+ report += ` Performance: ${performance.length} findings
17920
18692
 
17921
18693
  `;
17922
- 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";
17923
- report += " 1. SECURITY ASSESSMENT\n";
17924
- 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";
17925
- report += "Frameworks: OWASP Top 10 (2021), NIST SP 800-53 Rev.5, NSA Secure Coding, npm audit\n\n";
17926
- if (security2.length === 0) {
17927
- report += "No security findings. All checks passed.\n\n";
17928
- } else {
17929
- for (const f of security2) {
17930
- report += `[${f.severity.toUpperCase()}] ${f.id}: ${f.message}
18694
+ 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";
18695
+ report += " 1. SECURITY ASSESSMENT\n";
18696
+ 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";
18697
+ report += "Frameworks: OWASP Top 10 (2021), NIST SP 800-53 Rev.5, NSA Secure Coding, npm audit\n\n";
18698
+ if (security2.length === 0) {
18699
+ report += "No security findings. All checks passed.\n\n";
18700
+ } else {
18701
+ for (const f of security2) {
18702
+ report += `[${f.severity.toUpperCase()}] ${f.id}: ${f.message}
17931
18703
  `;
17932
- report += ` Framework: ${f.framework} ${f.control}
18704
+ report += ` Framework: ${f.framework} ${f.control}
17933
18705
  `;
17934
- if (f.file) report += ` File: ${f.file}
18706
+ if (f.file) report += ` File: ${f.file}
17935
18707
  `;
17936
- report += ` Remediation: ${f.remediation}
18708
+ report += ` Remediation: ${f.remediation}
17937
18709
 
17938
18710
  `;
17939
- }
17940
- }
17941
- 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";
17942
- report += " 2. QUALITY ASSESSMENT\n";
17943
- 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";
17944
- report += "Framework: ISO/IEC 25010 Software Quality Model\n\n";
17945
- if (quality.length === 0) {
17946
- report += "No quality findings. All checks passed.\n\n";
17947
- } else {
17948
- for (const f of quality) {
17949
- report += `[${f.severity.toUpperCase()}] ${f.id}: ${f.message}
18711
+ }
18712
+ }
18713
+ 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";
18714
+ report += " 2. QUALITY ASSESSMENT\n";
18715
+ 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";
18716
+ report += "Framework: ISO/IEC 25010 Software Quality Model\n\n";
18717
+ if (quality.length === 0) {
18718
+ report += "No quality findings. All checks passed.\n\n";
18719
+ } else {
18720
+ for (const f of quality) {
18721
+ report += `[${f.severity.toUpperCase()}] ${f.id}: ${f.message}
17950
18722
  `;
17951
- report += ` Framework: ${f.framework} - ${f.control}
18723
+ report += ` Framework: ${f.framework} - ${f.control}
17952
18724
  `;
17953
- if (f.file) report += ` File: ${f.file}
18725
+ if (f.file) report += ` File: ${f.file}
17954
18726
  `;
17955
- report += ` Remediation: ${f.remediation}
18727
+ report += ` Remediation: ${f.remediation}
17956
18728
 
17957
18729
  `;
17958
- }
17959
- }
17960
- 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";
17961
- report += " 3. PERFORMANCE ASSESSMENT\n";
17962
- 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";
17963
- report += "Framework: OSI Model Layer 7 (Application) Analysis\n\n";
17964
- if (performance.length === 0) {
17965
- report += "No performance findings. All checks passed.\n\n";
17966
- } else {
17967
- for (const f of performance) {
17968
- report += `[${f.severity.toUpperCase()}] ${f.id}: ${f.message}
18730
+ }
18731
+ }
18732
+ 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";
18733
+ report += " 3. PERFORMANCE ASSESSMENT\n";
18734
+ 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";
18735
+ report += "Framework: OSI Model Layer 7 (Application) Analysis\n\n";
18736
+ if (performance.length === 0) {
18737
+ report += "No performance findings. All checks passed.\n\n";
18738
+ } else {
18739
+ for (const f of performance) {
18740
+ report += `[${f.severity.toUpperCase()}] ${f.id}: ${f.message}
17969
18741
  `;
17970
- report += ` Framework: ${f.framework} - ${f.control}
18742
+ report += ` Framework: ${f.framework} - ${f.control}
17971
18743
  `;
17972
- if (f.file) report += ` File: ${f.file}
18744
+ if (f.file) report += ` File: ${f.file}
17973
18745
  `;
17974
- report += ` Remediation: ${f.remediation}
18746
+ report += ` Remediation: ${f.remediation}
17975
18747
 
17976
18748
  `;
17977
- }
17978
- }
17979
- 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";
17980
- report += " 4. RECOMMENDATIONS\n";
17981
- 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";
17982
- const criticalFindings = all.filter((f) => f.severity === "critical" || f.severity === "high");
17983
- if (criticalFindings.length === 0) {
17984
- report += "No critical or high-severity findings. Project meets baseline security standards.\n\n";
17985
- } else {
17986
- report += "Priority actions (critical/high severity):\n";
17987
- for (const f of criticalFindings) {
17988
- report += ` - ${f.id}: ${f.message} (${f.file ?? "N/A"})
17989
- `;
17990
- }
17991
- report += "\n";
17992
- }
17993
- 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";
17994
- report += " 5. FRAMEWORK COMPLIANCE MATRIX\n";
17995
- 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";
17996
- report += "OWASP Top 10 (2021):\n";
17997
- const owaspIds = ["A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08", "A09", "A10"];
17998
- const owaspNames = ["Broken Access Control", "Cryptographic Failures", "Injection", "Insecure Design", "Security Misconfiguration", "Vulnerable Components", "Auth Failures", "Integrity Failures", "Logging Failures", "SSRF"];
17999
- for (let i3 = 0; i3 < owaspIds.length; i3++) {
18000
- const found = security2.some((f) => f.control === owaspIds[i3]);
18001
- report += ` ${owaspIds[i3]} ${owaspNames[i3]}: ${found ? "FINDINGS" : "PASS"}
18002
- `;
18003
- }
18004
- report += "\nnpm audit:\n";
18005
- const npmFindings = security2.filter((f) => f.framework === "npm audit");
18006
- report += ` Total vulnerabilities: ${npmFindings.filter((f) => f.id !== "NPM-SUM").length}
18007
- `;
18008
- report += ` Status: ${npmFindings.length > 0 ? "FINDINGS" : "PASS"}
18009
- `;
18010
- 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";
18011
- report += " END OF REPORT\n";
18012
- 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";
18013
- return report;
18014
- }
18015
- function audit(options = {}) {
18016
- const projectPath = options.projectPath ?? process.cwd();
18017
- const allFindings = scanDir(projectPath, projectPath);
18018
- allFindings.push(...runNpmAudit(projectPath));
18019
- const quality = allFindings.filter((f) => f.category === "quality");
18020
- const security2 = allFindings.filter((f) => f.category === "security");
18021
- const performance = allFindings.filter((f) => f.category === "performance");
18022
- const errorCount = allFindings.filter((f) => f.severity === "critical" || f.severity === "high").length;
18023
- const totalFindings = allFindings.length;
18024
- const score = Math.max(0, 100 - errorCount * 10 - (totalFindings - errorCount) * 2);
18025
- const grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : score >= 60 ? "D" : "F";
18026
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
18027
- const result = {
18028
- projectPath,
18029
- timestamp,
18030
- quality,
18031
- security: security2,
18032
- performance,
18033
- score,
18034
- grade,
18035
- summary: `Audit complete: ${totalFindings} findings (${errorCount} critical/high). Score: ${score}/100 (Grade: ${grade}).`,
18036
- report: ""
18037
- };
18038
- result.report = generateReport({ quality, security: security2, performance, score, grade, projectPath, timestamp });
18039
- if (options.onFinding) {
18040
- for (const f of allFindings) {
18041
- options.onFinding(f);
18042
- }
18043
- }
18044
- return {
18045
- name: "audit",
18046
- version: "0.3.0",
18047
- description: "Professional IT audit: quality, security, performance, npm vulnerabilities.",
18048
- hooks: {
18049
- onAudit(_result) {
18749
+ }
18050
18750
  }
18051
- },
18052
- run: /* @__PURE__ */ __name(() => result, "run"),
18053
- report: /* @__PURE__ */ __name(() => result.report, "report")
18054
- };
18055
- }
18056
- var init_audit = __esm({
18057
- "plugins/audit/index.ts"() {
18058
- __name(stripCode, "stripCode");
18059
- __name(hasEval, "hasEval");
18060
- __name(isInNonCode, "isInNonCode");
18061
- __name(collectDangerousNames, "collectDangerousNames");
18062
- __name(hasProcessExec, "hasProcessExec");
18063
- __name(scanFile, "scanFile");
18064
- __name(scanDir, "scanDir");
18065
- __name(runNpmAudit, "runNpmAudit");
18066
- __name(generateReport, "generateReport");
18751
+ 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";
18752
+ report += " 4. RECOMMENDATIONS\n";
18753
+ 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";
18754
+ const criticalFindings = all.filter((f) => f.severity === "critical" || f.severity === "high");
18755
+ if (criticalFindings.length === 0) {
18756
+ report += "No critical or high-severity findings. Project meets baseline security standards.\n\n";
18757
+ } else {
18758
+ report += "Priority actions (critical/high severity):\n";
18759
+ for (const f of criticalFindings) {
18760
+ report += ` - ${f.id}: ${f.message} (${f.file ?? "N/A"})
18761
+ `;
18762
+ }
18763
+ report += "\n";
18764
+ }
18765
+ 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";
18766
+ report += " 5. FRAMEWORK COMPLIANCE MATRIX\n";
18767
+ 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";
18768
+ report += "OWASP Top 10 (2021):\n";
18769
+ const owaspIds = ["A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08", "A09", "A10"];
18770
+ const owaspNames = ["Broken Access Control", "Cryptographic Failures", "Injection", "Insecure Design", "Security Misconfiguration", "Vulnerable Components", "Auth Failures", "Integrity Failures", "Logging Failures", "SSRF"];
18771
+ for (let i3 = 0; i3 < owaspIds.length; i3++) {
18772
+ const found = security2.some((f) => f.control === owaspIds[i3]);
18773
+ report += ` ${owaspIds[i3]} ${owaspNames[i3]}: ${found ? "FINDINGS" : "PASS"}
18774
+ `;
18775
+ }
18776
+ report += "\nnpm audit:\n";
18777
+ const npmFindings = security2.filter((f) => f.framework === "npm audit");
18778
+ report += ` Total vulnerabilities: ${npmFindings.filter((f) => f.id !== "NPM-SUM").length}
18779
+ `;
18780
+ report += ` Status: ${npmFindings.length > 0 ? "FINDINGS" : "PASS"}
18781
+ `;
18782
+ 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";
18783
+ report += " END OF REPORT\n";
18784
+ 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";
18785
+ return report;
18786
+ }, "generateReport");
18067
18787
  __name(audit, "audit");
18068
18788
  }
18069
18789
  });
18070
- function resolveDbPath(override) {
18071
- if (override) return override;
18072
- const root = resolveDotMemStorageRoot();
18073
- const dir = path8.join(root, "neurocore");
18074
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
18075
- return path8.join(dir, "neurocore.db");
18076
- }
18077
- var DatabaseSync, SCHEMA_VERSION, NeuroCoreSqliteStore, createSqliteStore;
18790
+ var SCHEMA_VERSION, SchemaVersion, Episode, Assessment, Pattern, Proposal, Adaptation, Verification, resolveDbPath, ENTITIES, NeuroCoreSqliteStore, createSqliteStore;
18078
18791
  var init_sqlite = __esm({
18079
18792
  "plugins/neurocore/storage/sqlite.ts"() {
18080
18793
  init_storage_location();
18081
- ({ DatabaseSync } = globalThis.process?.getBuiltinModule?.("node:sqlite") ?? __require("sqlite"));
18082
18794
  SCHEMA_VERSION = 1;
18083
- __name(resolveDbPath, "resolveDbPath");
18795
+ SchemaVersion = class {
18796
+ version;
18797
+ };
18798
+ __name(SchemaVersion, "SchemaVersion");
18799
+ __decorateClass([
18800
+ PrimaryColumn("integer")
18801
+ ], SchemaVersion.prototype, "version", 2);
18802
+ SchemaVersion = __decorateClass([
18803
+ Entity("schema_version")
18804
+ ], SchemaVersion);
18805
+ Episode = class {
18806
+ id;
18807
+ scope;
18808
+ context;
18809
+ objective;
18810
+ observation;
18811
+ outcome;
18812
+ provenance;
18813
+ createdAt;
18814
+ memoryRefs;
18815
+ evidence;
18816
+ };
18817
+ __name(Episode, "Episode");
18818
+ __decorateClass([
18819
+ PrimaryColumn("text")
18820
+ ], Episode.prototype, "id", 2);
18821
+ __decorateClass([
18822
+ Column("text")
18823
+ ], Episode.prototype, "scope", 2);
18824
+ __decorateClass([
18825
+ Column("text")
18826
+ ], Episode.prototype, "context", 2);
18827
+ __decorateClass([
18828
+ Column("text")
18829
+ ], Episode.prototype, "objective", 2);
18830
+ __decorateClass([
18831
+ Column("text")
18832
+ ], Episode.prototype, "observation", 2);
18833
+ __decorateClass([
18834
+ Column("text")
18835
+ ], Episode.prototype, "outcome", 2);
18836
+ __decorateClass([
18837
+ Column("text")
18838
+ ], Episode.prototype, "provenance", 2);
18839
+ __decorateClass([
18840
+ Column({ name: "created_at", type: "text" })
18841
+ ], Episode.prototype, "createdAt", 2);
18842
+ __decorateClass([
18843
+ Column({ name: "memory_refs", type: "text", nullable: true })
18844
+ ], Episode.prototype, "memoryRefs", 2);
18845
+ __decorateClass([
18846
+ Column({ name: "evidence", type: "text", nullable: true })
18847
+ ], Episode.prototype, "evidence", 2);
18848
+ Episode = __decorateClass([
18849
+ Entity("episodes")
18850
+ ], Episode);
18851
+ Assessment = class {
18852
+ id;
18853
+ episodeId;
18854
+ assessmentType;
18855
+ findings;
18856
+ evidence;
18857
+ structuredEvidence;
18858
+ confidence;
18859
+ limitations;
18860
+ assessedAt;
18861
+ assessor;
18862
+ };
18863
+ __name(Assessment, "Assessment");
18864
+ __decorateClass([
18865
+ PrimaryColumn("text")
18866
+ ], Assessment.prototype, "id", 2);
18867
+ __decorateClass([
18868
+ Column({ name: "episode_id", type: "text" })
18869
+ ], Assessment.prototype, "episodeId", 2);
18870
+ __decorateClass([
18871
+ Column({ name: "assessment_type", type: "text" })
18872
+ ], Assessment.prototype, "assessmentType", 2);
18873
+ __decorateClass([
18874
+ Column("text")
18875
+ ], Assessment.prototype, "findings", 2);
18876
+ __decorateClass([
18877
+ Column("text")
18878
+ ], Assessment.prototype, "evidence", 2);
18879
+ __decorateClass([
18880
+ Column({ name: "structured_evidence", type: "text", nullable: true })
18881
+ ], Assessment.prototype, "structuredEvidence", 2);
18882
+ __decorateClass([
18883
+ Column("real")
18884
+ ], Assessment.prototype, "confidence", 2);
18885
+ __decorateClass([
18886
+ Column("text")
18887
+ ], Assessment.prototype, "limitations", 2);
18888
+ __decorateClass([
18889
+ Column({ name: "assessed_at", type: "text" })
18890
+ ], Assessment.prototype, "assessedAt", 2);
18891
+ __decorateClass([
18892
+ Column("text")
18893
+ ], Assessment.prototype, "assessor", 2);
18894
+ Assessment = __decorateClass([
18895
+ Entity("assessments")
18896
+ ], Assessment);
18897
+ Pattern = class {
18898
+ id;
18899
+ scope;
18900
+ description;
18901
+ episodeIds;
18902
+ supportingEvidence;
18903
+ contradictingEvidence;
18904
+ confidence;
18905
+ status;
18906
+ revision;
18907
+ firstObserved;
18908
+ lastObserved;
18909
+ };
18910
+ __name(Pattern, "Pattern");
18911
+ __decorateClass([
18912
+ PrimaryColumn("text")
18913
+ ], Pattern.prototype, "id", 2);
18914
+ __decorateClass([
18915
+ Column("text")
18916
+ ], Pattern.prototype, "scope", 2);
18917
+ __decorateClass([
18918
+ Column("text")
18919
+ ], Pattern.prototype, "description", 2);
18920
+ __decorateClass([
18921
+ Column({ name: "episode_ids", type: "text" })
18922
+ ], Pattern.prototype, "episodeIds", 2);
18923
+ __decorateClass([
18924
+ Column({ name: "supporting_evidence", type: "text" })
18925
+ ], Pattern.prototype, "supportingEvidence", 2);
18926
+ __decorateClass([
18927
+ Column({ name: "contradicting_evidence", type: "text" })
18928
+ ], Pattern.prototype, "contradictingEvidence", 2);
18929
+ __decorateClass([
18930
+ Column("real")
18931
+ ], Pattern.prototype, "confidence", 2);
18932
+ __decorateClass([
18933
+ Column("text")
18934
+ ], Pattern.prototype, "status", 2);
18935
+ __decorateClass([
18936
+ Column("integer")
18937
+ ], Pattern.prototype, "revision", 2);
18938
+ __decorateClass([
18939
+ Column({ name: "first_observed", type: "text", nullable: true })
18940
+ ], Pattern.prototype, "firstObserved", 2);
18941
+ __decorateClass([
18942
+ Column({ name: "last_observed", type: "text", nullable: true })
18943
+ ], Pattern.prototype, "lastObserved", 2);
18944
+ Pattern = __decorateClass([
18945
+ Entity("patterns")
18946
+ ], Pattern);
18947
+ Proposal = class {
18948
+ id;
18949
+ patternId;
18950
+ problem;
18951
+ proposedStrategy;
18952
+ applicableContext;
18953
+ expectedOutcome;
18954
+ verificationCriteria;
18955
+ evidence;
18956
+ status;
18957
+ revision;
18958
+ createdAt;
18959
+ };
18960
+ __name(Proposal, "Proposal");
18961
+ __decorateClass([
18962
+ PrimaryColumn("text")
18963
+ ], Proposal.prototype, "id", 2);
18964
+ __decorateClass([
18965
+ Column({ name: "pattern_id", type: "text", nullable: true })
18966
+ ], Proposal.prototype, "patternId", 2);
18967
+ __decorateClass([
18968
+ Column("text")
18969
+ ], Proposal.prototype, "problem", 2);
18970
+ __decorateClass([
18971
+ Column({ name: "proposed_strategy", type: "text" })
18972
+ ], Proposal.prototype, "proposedStrategy", 2);
18973
+ __decorateClass([
18974
+ Column({ name: "applicable_context", type: "text" })
18975
+ ], Proposal.prototype, "applicableContext", 2);
18976
+ __decorateClass([
18977
+ Column({ name: "expected_outcome", type: "text" })
18978
+ ], Proposal.prototype, "expectedOutcome", 2);
18979
+ __decorateClass([
18980
+ Column({ name: "verification_criteria", type: "text" })
18981
+ ], Proposal.prototype, "verificationCriteria", 2);
18982
+ __decorateClass([
18983
+ Column("text")
18984
+ ], Proposal.prototype, "evidence", 2);
18985
+ __decorateClass([
18986
+ Column("text")
18987
+ ], Proposal.prototype, "status", 2);
18988
+ __decorateClass([
18989
+ Column("integer")
18990
+ ], Proposal.prototype, "revision", 2);
18991
+ __decorateClass([
18992
+ Column({ name: "created_at", type: "text" })
18993
+ ], Proposal.prototype, "createdAt", 2);
18994
+ Proposal = __decorateClass([
18995
+ Entity("proposals")
18996
+ ], Proposal);
18997
+ Adaptation = class {
18998
+ id;
18999
+ proposalId;
19000
+ strategyVersion;
19001
+ activationScope;
19002
+ status;
19003
+ approvedBy;
19004
+ activatedAt;
19005
+ deactivatedAt;
19006
+ };
19007
+ __name(Adaptation, "Adaptation");
19008
+ __decorateClass([
19009
+ PrimaryColumn("text")
19010
+ ], Adaptation.prototype, "id", 2);
19011
+ __decorateClass([
19012
+ Column({ name: "proposal_id", type: "text" })
19013
+ ], Adaptation.prototype, "proposalId", 2);
19014
+ __decorateClass([
19015
+ Column({ name: "strategy_version", type: "integer" })
19016
+ ], Adaptation.prototype, "strategyVersion", 2);
19017
+ __decorateClass([
19018
+ Column({ name: "activation_scope", type: "text" })
19019
+ ], Adaptation.prototype, "activationScope", 2);
19020
+ __decorateClass([
19021
+ Column("text")
19022
+ ], Adaptation.prototype, "status", 2);
19023
+ __decorateClass([
19024
+ Column({ name: "approved_by", type: "text", nullable: true })
19025
+ ], Adaptation.prototype, "approvedBy", 2);
19026
+ __decorateClass([
19027
+ Column({ name: "activated_at", type: "text" })
19028
+ ], Adaptation.prototype, "activatedAt", 2);
19029
+ __decorateClass([
19030
+ Column({ name: "deactivated_at", type: "text", nullable: true })
19031
+ ], Adaptation.prototype, "deactivatedAt", 2);
19032
+ Adaptation = __decorateClass([
19033
+ Entity("adaptations")
19034
+ ], Adaptation);
19035
+ Verification = class {
19036
+ id;
19037
+ adaptationId;
19038
+ measurement;
19039
+ baseline;
19040
+ observedOutcome;
19041
+ comparisonContext;
19042
+ conclusion;
19043
+ limitations;
19044
+ verifiedAt;
19045
+ };
19046
+ __name(Verification, "Verification");
19047
+ __decorateClass([
19048
+ PrimaryColumn("text")
19049
+ ], Verification.prototype, "id", 2);
19050
+ __decorateClass([
19051
+ Column({ name: "adaptation_id", type: "text" })
19052
+ ], Verification.prototype, "adaptationId", 2);
19053
+ __decorateClass([
19054
+ Column("text")
19055
+ ], Verification.prototype, "measurement", 2);
19056
+ __decorateClass([
19057
+ Column("text")
19058
+ ], Verification.prototype, "baseline", 2);
19059
+ __decorateClass([
19060
+ Column({ name: "observed_outcome", type: "text" })
19061
+ ], Verification.prototype, "observedOutcome", 2);
19062
+ __decorateClass([
19063
+ Column({ name: "comparison_context", type: "text" })
19064
+ ], Verification.prototype, "comparisonContext", 2);
19065
+ __decorateClass([
19066
+ Column("text")
19067
+ ], Verification.prototype, "conclusion", 2);
19068
+ __decorateClass([
19069
+ Column("text")
19070
+ ], Verification.prototype, "limitations", 2);
19071
+ __decorateClass([
19072
+ Column({ name: "verified_at", type: "text" })
19073
+ ], Verification.prototype, "verifiedAt", 2);
19074
+ Verification = __decorateClass([
19075
+ Entity("verifications")
19076
+ ], Verification);
19077
+ resolveDbPath = /* @__PURE__ */ __name((override) => {
19078
+ if (override) return override;
19079
+ const root = resolveDotMemStorageRoot();
19080
+ const dir = path5.join(root, "neurocore");
19081
+ if (!fs6.existsSync(dir)) fs6.mkdirSync(dir, { recursive: true });
19082
+ return path5.join(dir, "neurocore.db");
19083
+ }, "resolveDbPath");
19084
+ ENTITIES = [
19085
+ SchemaVersion,
19086
+ Episode,
19087
+ Assessment,
19088
+ Pattern,
19089
+ Proposal,
19090
+ Adaptation,
19091
+ Verification
19092
+ ];
18084
19093
  NeuroCoreSqliteStore = class {
18085
19094
  static {
18086
19095
  __name(this, "NeuroCoreSqliteStore");
18087
19096
  }
18088
- db;
19097
+ ds = null;
18089
19098
  dbPath;
19099
+ initialized = false;
18090
19100
  constructor(dbPath) {
18091
19101
  this.dbPath = resolveDbPath(dbPath);
18092
- const dir = path8.dirname(this.dbPath);
18093
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
18094
- this.db = new DatabaseSync(this.dbPath);
18095
- this.db.exec("PRAGMA journal_mode = WAL;");
18096
- this.db.exec("PRAGMA busy_timeout = 5000;");
18097
- this.migrate();
18098
- }
18099
- migrate() {
18100
- this.db.exec(`CREATE TABLE IF NOT EXISTS schema_version (version INTEGER PRIMARY KEY);`);
18101
- const row = this.db.prepare("SELECT version FROM schema_version LIMIT 1").get();
19102
+ const dir = path5.dirname(this.dbPath);
19103
+ if (!fs6.existsSync(dir)) fs6.mkdirSync(dir, { recursive: true });
19104
+ }
19105
+ async init() {
19106
+ if (this.initialized) return;
19107
+ this.ds = new DataSource({
19108
+ type: "better-sqlite3",
19109
+ database: this.dbPath,
19110
+ entities: ENTITIES,
19111
+ synchronize: true,
19112
+ logging: false
19113
+ });
19114
+ await this.ds.initialize();
19115
+ await this.migrate();
19116
+ this.initialized = true;
19117
+ }
19118
+ async migrate() {
19119
+ if (!this.ds) throw new Error("DataSource not initialized");
19120
+ const svRepo = this.ds.getRepository(SchemaVersion);
19121
+ const row = await svRepo.findOne({ where: {} });
18102
19122
  const current = row ? row.version : 0;
18103
- if (current === 0) {
18104
- this.db.exec(`
18105
- CREATE TABLE episodes (
18106
- id TEXT PRIMARY KEY,
18107
- scope TEXT NOT NULL,
18108
- context TEXT NOT NULL,
18109
- objective TEXT NOT NULL,
18110
- observation TEXT NOT NULL,
18111
- outcome TEXT NOT NULL,
18112
- provenance TEXT NOT NULL,
18113
- created_at TEXT NOT NULL,
18114
- memory_refs TEXT,
18115
- evidence TEXT
18116
- );
18117
- CREATE TABLE assessments (
18118
- id TEXT PRIMARY KEY,
18119
- episode_id TEXT NOT NULL,
18120
- assessment_type TEXT NOT NULL,
18121
- findings TEXT NOT NULL,
18122
- evidence TEXT NOT NULL,
18123
- structured_evidence TEXT,
18124
- confidence REAL NOT NULL,
18125
- limitations TEXT NOT NULL,
18126
- assessed_at TEXT NOT NULL,
18127
- assessor TEXT NOT NULL,
18128
- FOREIGN KEY (episode_id) REFERENCES episodes(id)
18129
- );
18130
- CREATE TABLE patterns (
18131
- id TEXT PRIMARY KEY,
18132
- scope TEXT NOT NULL,
18133
- description TEXT NOT NULL,
18134
- episode_ids TEXT NOT NULL,
18135
- supporting_evidence TEXT NOT NULL,
18136
- contradicting_evidence TEXT NOT NULL,
18137
- confidence REAL NOT NULL,
18138
- status TEXT NOT NULL,
18139
- revision INTEGER NOT NULL,
18140
- first_observed TEXT,
18141
- last_observed TEXT
18142
- );
18143
- CREATE TABLE proposals (
18144
- id TEXT PRIMARY KEY,
18145
- pattern_id TEXT,
18146
- problem TEXT NOT NULL,
18147
- proposed_strategy TEXT NOT NULL,
18148
- applicable_context TEXT NOT NULL,
18149
- expected_outcome TEXT NOT NULL,
18150
- verification_criteria TEXT NOT NULL,
18151
- evidence TEXT NOT NULL,
18152
- status TEXT NOT NULL,
18153
- revision INTEGER NOT NULL,
18154
- created_at TEXT NOT NULL
18155
- );
18156
- CREATE TABLE adaptations (
18157
- id TEXT PRIMARY KEY,
18158
- proposal_id TEXT NOT NULL,
18159
- strategy_version INTEGER NOT NULL,
18160
- activation_scope TEXT NOT NULL,
18161
- status TEXT NOT NULL,
18162
- approved_by TEXT,
18163
- activated_at TEXT NOT NULL,
18164
- deactivated_at TEXT
18165
- );
18166
- CREATE TABLE verifications (
18167
- id TEXT PRIMARY KEY,
18168
- adaptation_id TEXT NOT NULL,
18169
- measurement TEXT NOT NULL,
18170
- baseline TEXT NOT NULL,
18171
- observed_outcome TEXT NOT NULL,
18172
- comparison_context TEXT NOT NULL,
18173
- conclusion TEXT NOT NULL,
18174
- limitations TEXT NOT NULL,
18175
- verified_at TEXT NOT NULL
18176
- );
18177
- INSERT INTO schema_version (version) VALUES (${SCHEMA_VERSION});
18178
- `);
18179
- } else if (current !== SCHEMA_VERSION) {
18180
- throw new Error(`Unsupported NeuroCore schema version: ${current}`);
19123
+ if (current !== SCHEMA_VERSION) {
19124
+ if (current === 0) {
19125
+ await svRepo.insert({ version: SCHEMA_VERSION });
19126
+ } else {
19127
+ throw new Error(`Unsupported NeuroCore schema version: ${current}`);
19128
+ }
19129
+ }
19130
+ }
19131
+ ensureInit() {
19132
+ if (!this.initialized || !this.ds) {
19133
+ throw new Error("Store not initialized. Call init() before using the store.");
18181
19134
  }
18182
19135
  }
18183
- // NeuroCoreStore implementation
18184
- saveEpisode(episode) {
18185
- const stmt = this.db.prepare(`INSERT INTO episodes (id, scope, context, objective, observation, outcome, provenance, created_at, memory_refs, evidence) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
19136
+ async saveEpisode(episode) {
19137
+ this.ensureInit();
19138
+ const repo = this.ds.getRepository(Episode);
18186
19139
  try {
18187
- stmt.run(
18188
- episode.id,
18189
- episode.scope,
18190
- episode.context,
18191
- episode.objective,
18192
- episode.observation,
18193
- episode.outcome,
18194
- episode.provenance,
18195
- episode.createdAt,
18196
- JSON.stringify(episode.memoryRefs ?? []),
18197
- JSON.stringify(episode.evidence ?? null)
18198
- );
19140
+ await repo.insert({
19141
+ id: episode.id,
19142
+ scope: episode.scope,
19143
+ context: episode.context,
19144
+ objective: episode.objective,
19145
+ observation: episode.observation,
19146
+ outcome: episode.outcome,
19147
+ provenance: episode.provenance,
19148
+ createdAt: episode.createdAt,
19149
+ memoryRefs: JSON.stringify(episode.memoryRefs ?? []),
19150
+ evidence: episode.evidence != null ? JSON.stringify(episode.evidence) : null
19151
+ });
18199
19152
  } catch (e) {
18200
19153
  if (String(e).includes("UNIQUE") || String(e).includes("PRIMARY KEY")) throw new Error(`duplicate episode id: ${episode.id}`);
18201
19154
  throw e;
18202
19155
  }
18203
19156
  }
18204
- getEpisode(id) {
18205
- const row = this.db.prepare("SELECT * FROM episodes WHERE id = ?").get(id);
19157
+ async getEpisode(id) {
19158
+ this.ensureInit();
19159
+ const repo = this.ds.getRepository(Episode);
19160
+ const row = await repo.findOne({ where: { id } });
18206
19161
  if (!row) return void 0;
18207
19162
  return {
18208
19163
  id: row.id,
@@ -18212,24 +19167,17 @@ var init_sqlite = __esm({
18212
19167
  observation: row.observation,
18213
19168
  outcome: row.outcome,
18214
19169
  provenance: row.provenance,
18215
- createdAt: row.created_at,
18216
- memoryRefs: JSON.parse(row.memory_refs || "[]"),
19170
+ createdAt: row.createdAt,
19171
+ memoryRefs: JSON.parse(row.memoryRefs ?? "[]"),
18217
19172
  evidence: row.evidence ? JSON.parse(row.evidence) : void 0
18218
19173
  };
18219
19174
  }
18220
- listEpisodes(options) {
18221
- let sql = "SELECT * FROM episodes";
18222
- const params = [];
18223
- if (options?.scope) {
18224
- sql += " WHERE scope = ?";
18225
- params.push(options.scope);
18226
- }
18227
- sql += " ORDER BY created_at ASC";
18228
- if (options?.limit && options.limit > 0) {
18229
- sql += " LIMIT ?";
18230
- params.push(options.limit);
18231
- }
18232
- const rows = this.db.prepare(sql).all(...params);
19175
+ async listEpisodes(options) {
19176
+ this.ensureInit();
19177
+ const repo = this.ds.getRepository(Episode);
19178
+ const where = {};
19179
+ if (options?.scope) where.scope = options.scope;
19180
+ const rows = await repo.find({ where, order: { createdAt: "ASC" }, take: options?.limit });
18233
19181
  return rows.map((row) => ({
18234
19182
  id: row.id,
18235
19183
  scope: row.scope,
@@ -18238,226 +19186,256 @@ var init_sqlite = __esm({
18238
19186
  observation: row.observation,
18239
19187
  outcome: row.outcome,
18240
19188
  provenance: row.provenance,
18241
- createdAt: row.created_at,
18242
- memoryRefs: JSON.parse(row.memory_refs || "[]"),
19189
+ createdAt: row.createdAt,
19190
+ memoryRefs: JSON.parse(row.memoryRefs ?? "[]"),
18243
19191
  evidence: row.evidence ? JSON.parse(row.evidence) : void 0
18244
19192
  }));
18245
19193
  }
18246
- saveAssessment(a) {
18247
- const stmt = this.db.prepare(`INSERT INTO assessments (id, episode_id, assessment_type, findings, evidence, structured_evidence, confidence, limitations, assessed_at, assessor) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
19194
+ async saveAssessment(a) {
19195
+ this.ensureInit();
19196
+ const repo = this.ds.getRepository(Assessment);
18248
19197
  try {
18249
- stmt.run(
18250
- a.id,
18251
- a.episodeId,
18252
- a.assessmentType,
18253
- JSON.stringify(a.findings ?? []),
18254
- JSON.stringify(a.evidence ?? []),
18255
- a.structuredEvidence ? JSON.stringify(a.structuredEvidence) : null,
18256
- a.confidence,
18257
- JSON.stringify(a.limitations ?? []),
18258
- a.assessedAt,
18259
- a.assessor
18260
- );
19198
+ await repo.insert({
19199
+ id: a.id,
19200
+ episodeId: a.episodeId,
19201
+ assessmentType: a.assessmentType,
19202
+ findings: JSON.stringify(a.findings ?? []),
19203
+ evidence: JSON.stringify(a.evidence ?? []),
19204
+ structuredEvidence: a.structuredEvidence != null ? JSON.stringify(a.structuredEvidence) : null,
19205
+ confidence: a.confidence,
19206
+ limitations: JSON.stringify(a.limitations ?? []),
19207
+ assessedAt: a.assessedAt,
19208
+ assessor: a.assessor
19209
+ });
18261
19210
  } catch (e) {
18262
19211
  if (String(e).includes("UNIQUE") || String(e).includes("PRIMARY KEY")) throw new Error(`duplicate assessment id: ${a.id}`);
18263
19212
  throw e;
18264
19213
  }
18265
19214
  }
18266
- getAssessment(id) {
18267
- const row = this.db.prepare("SELECT * FROM assessments WHERE id = ?").get(id);
19215
+ async getAssessment(id) {
19216
+ this.ensureInit();
19217
+ const repo = this.ds.getRepository(Assessment);
19218
+ const row = await repo.findOne({ where: { id } });
18268
19219
  if (!row) return void 0;
18269
19220
  return {
18270
19221
  id: row.id,
18271
- episodeId: row.episode_id,
18272
- assessmentType: row.assessment_type,
19222
+ episodeId: row.episodeId,
19223
+ assessmentType: row.assessmentType,
18273
19224
  findings: JSON.parse(row.findings),
18274
19225
  evidence: JSON.parse(row.evidence),
18275
- structuredEvidence: row.structured_evidence ? JSON.parse(row.structured_evidence) : void 0,
19226
+ structuredEvidence: row.structuredEvidence ? JSON.parse(row.structuredEvidence) : void 0,
18276
19227
  confidence: row.confidence,
18277
19228
  limitations: JSON.parse(row.limitations),
18278
- assessedAt: row.assessed_at,
19229
+ assessedAt: row.assessedAt,
18279
19230
  assessor: row.assessor
18280
19231
  };
18281
19232
  }
18282
- listAssessmentsByEpisode(episodeId) {
18283
- const rows = this.db.prepare("SELECT * FROM assessments WHERE episode_id = ? ORDER BY assessed_at ASC").all(episodeId);
19233
+ async listAssessmentsByEpisode(episodeId) {
19234
+ this.ensureInit();
19235
+ const repo = this.ds.getRepository(Assessment);
19236
+ const rows = await repo.find({ where: { episodeId }, order: { assessedAt: "ASC" } });
18284
19237
  return rows.map((row) => ({
18285
19238
  id: row.id,
18286
- episodeId: row.episode_id,
18287
- assessmentType: row.assessment_type,
19239
+ episodeId: row.episodeId,
19240
+ assessmentType: row.assessmentType,
18288
19241
  findings: JSON.parse(row.findings),
18289
19242
  evidence: JSON.parse(row.evidence),
18290
- structuredEvidence: row.structured_evidence ? JSON.parse(row.structured_evidence) : void 0,
19243
+ structuredEvidence: row.structuredEvidence ? JSON.parse(row.structuredEvidence) : void 0,
18291
19244
  confidence: row.confidence,
18292
19245
  limitations: JSON.parse(row.limitations),
18293
- assessedAt: row.assessed_at,
19246
+ assessedAt: row.assessedAt,
18294
19247
  assessor: row.assessor
18295
19248
  }));
18296
19249
  }
18297
- // Patterns
18298
- savePattern(p) {
18299
- 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
19250
+ async savePattern(p) {
19251
+ this.ensureInit();
19252
+ const repo = this.ds.getRepository(Pattern);
18300
19253
  try {
18301
- stmt.run(
18302
- p.id,
18303
- p.scope,
18304
- p.description,
18305
- JSON.stringify(p.episodeIds ?? []),
18306
- JSON.stringify(p.supportingEvidence ?? []),
18307
- JSON.stringify(p.contradictingEvidence ?? []),
18308
- p.confidence,
18309
- p.status,
18310
- p.revision,
18311
- p.firstObserved ?? null,
18312
- p.lastObserved ?? null
18313
- );
19254
+ await repo.insert({
19255
+ id: p.id,
19256
+ scope: p.scope,
19257
+ description: p.description,
19258
+ episodeIds: JSON.stringify(p.episodeIds ?? []),
19259
+ supportingEvidence: JSON.stringify(p.supportingEvidence ?? []),
19260
+ contradictingEvidence: JSON.stringify(p.contradictingEvidence ?? []),
19261
+ confidence: p.confidence,
19262
+ status: p.status,
19263
+ revision: p.revision,
19264
+ firstObserved: p.firstObserved ?? null,
19265
+ lastObserved: p.lastObserved ?? null
19266
+ });
18314
19267
  } catch (e) {
18315
19268
  if (String(e).includes("UNIQUE") || String(e).includes("PRIMARY KEY")) throw new Error(`duplicate pattern id: ${p.id}`);
18316
19269
  throw e;
18317
19270
  }
18318
19271
  }
18319
- getPattern(id) {
18320
- const row = this.db.prepare("SELECT * FROM patterns WHERE id = ?").get(id);
19272
+ async getPattern(id) {
19273
+ this.ensureInit();
19274
+ const repo = this.ds.getRepository(Pattern);
19275
+ const row = await repo.findOne({ where: { id } });
18321
19276
  if (!row) return void 0;
18322
19277
  return {
18323
19278
  id: row.id,
18324
19279
  scope: row.scope,
18325
19280
  description: row.description,
18326
- episodeIds: JSON.parse(row.episode_ids),
18327
- supportingEvidence: JSON.parse(row.supporting_evidence),
18328
- contradictingEvidence: JSON.parse(row.contradicting_evidence),
19281
+ episodeIds: JSON.parse(row.episodeIds),
19282
+ supportingEvidence: JSON.parse(row.supportingEvidence),
19283
+ contradictingEvidence: JSON.parse(row.contradictingEvidence),
18329
19284
  confidence: row.confidence,
18330
19285
  status: row.status,
18331
19286
  revision: row.revision,
18332
- firstObserved: row.first_observed,
18333
- lastObserved: row.last_observed
19287
+ firstObserved: row.firstObserved,
19288
+ lastObserved: row.lastObserved
18334
19289
  };
18335
19290
  }
18336
- listPatterns() {
18337
- const rows = this.db.prepare("SELECT * FROM patterns").all();
19291
+ async listPatterns() {
19292
+ this.ensureInit();
19293
+ const repo = this.ds.getRepository(Pattern);
19294
+ const rows = await repo.find();
18338
19295
  return rows.map((row) => ({
18339
19296
  id: row.id,
18340
19297
  scope: row.scope,
18341
19298
  description: row.description,
18342
- episodeIds: JSON.parse(row.episode_ids),
18343
- supportingEvidence: JSON.parse(row.supporting_evidence),
18344
- contradictingEvidence: JSON.parse(row.contradicting_evidence),
19299
+ episodeIds: JSON.parse(row.episodeIds),
19300
+ supportingEvidence: JSON.parse(row.supportingEvidence),
19301
+ contradictingEvidence: JSON.parse(row.contradictingEvidence),
18345
19302
  confidence: row.confidence,
18346
19303
  status: row.status,
18347
19304
  revision: row.revision,
18348
- firstObserved: row.first_observed,
18349
- lastObserved: row.last_observed
19305
+ firstObserved: row.firstObserved,
19306
+ lastObserved: row.lastObserved
18350
19307
  }));
18351
19308
  }
18352
- // Proposals
18353
- saveProposal(p) {
18354
- 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
19309
+ async saveProposal(p) {
19310
+ this.ensureInit();
19311
+ const repo = this.ds.getRepository(Proposal);
18355
19312
  try {
18356
- stmt.run(
18357
- p.id,
18358
- p.patternId ?? null,
18359
- p.problem,
18360
- p.proposedStrategy,
18361
- p.applicableContext,
18362
- p.expectedOutcome,
18363
- p.verificationCriteria,
18364
- JSON.stringify(p.evidence ?? []),
18365
- p.status,
18366
- p.revision,
18367
- p.createdAt
18368
- );
19313
+ await repo.insert({
19314
+ id: p.id,
19315
+ patternId: p.patternId ?? null,
19316
+ problem: p.problem,
19317
+ proposedStrategy: p.proposedStrategy,
19318
+ applicableContext: p.applicableContext,
19319
+ expectedOutcome: p.expectedOutcome,
19320
+ verificationCriteria: p.verificationCriteria,
19321
+ evidence: JSON.stringify(p.evidence ?? []),
19322
+ status: p.status,
19323
+ revision: p.revision,
19324
+ createdAt: p.createdAt
19325
+ });
18369
19326
  } catch (e) {
18370
19327
  if (String(e).includes("UNIQUE") || String(e).includes("PRIMARY KEY")) throw new Error(`duplicate proposal id: ${p.id}`);
18371
19328
  throw e;
18372
19329
  }
18373
19330
  }
18374
- getProposal(id) {
18375
- const row = this.db.prepare("SELECT * FROM proposals WHERE id = ?").get(id);
19331
+ async getProposal(id) {
19332
+ this.ensureInit();
19333
+ const repo = this.ds.getRepository(Proposal);
19334
+ const row = await repo.findOne({ where: { id } });
18376
19335
  if (!row) return void 0;
18377
19336
  return {
18378
19337
  id: row.id,
18379
- patternId: row.pattern_id,
19338
+ patternId: row.patternId,
18380
19339
  problem: row.problem,
18381
- proposedStrategy: row.proposed_strategy,
18382
- applicableContext: row.applicable_context,
18383
- expectedOutcome: row.expected_outcome,
18384
- verificationCriteria: row.verification_criteria,
19340
+ proposedStrategy: row.proposedStrategy,
19341
+ applicableContext: row.applicableContext,
19342
+ expectedOutcome: row.expectedOutcome,
19343
+ verificationCriteria: row.verificationCriteria,
18385
19344
  evidence: JSON.parse(row.evidence),
18386
19345
  status: row.status,
18387
19346
  revision: row.revision,
18388
- createdAt: row.created_at
19347
+ createdAt: row.createdAt
18389
19348
  };
18390
19349
  }
18391
- // Adaptations
18392
- saveAdaptation(a) {
18393
- const stmt = this.db.prepare(`INSERT INTO adaptations (id, proposal_id, strategy_version, activation_scope, status, approved_by, activated_at, deactivated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);
19350
+ async saveAdaptation(a) {
19351
+ this.ensureInit();
19352
+ const repo = this.ds.getRepository(Adaptation);
18394
19353
  try {
18395
- stmt.run(a.id, a.proposalId, a.strategyVersion, a.activationScope, a.status, a.approvedBy ?? null, a.activatedAt, a.deactivatedAt ?? null);
19354
+ await repo.insert({
19355
+ id: a.id,
19356
+ proposalId: a.proposalId,
19357
+ strategyVersion: a.strategyVersion,
19358
+ activationScope: a.activationScope,
19359
+ status: a.status,
19360
+ approvedBy: a.approvedBy ?? null,
19361
+ activatedAt: a.activatedAt,
19362
+ deactivatedAt: a.deactivatedAt ?? null
19363
+ });
18396
19364
  } catch (e) {
18397
19365
  if (String(e).includes("UNIQUE") || String(e).includes("PRIMARY KEY")) throw new Error(`duplicate adaptation id: ${a.id}`);
18398
19366
  throw e;
18399
19367
  }
18400
19368
  }
18401
- getAdaptation(id) {
18402
- const row = this.db.prepare("SELECT * FROM adaptations WHERE id = ?").get(id);
19369
+ async getAdaptation(id) {
19370
+ this.ensureInit();
19371
+ const repo = this.ds.getRepository(Adaptation);
19372
+ const row = await repo.findOne({ where: { id } });
18403
19373
  if (!row) return void 0;
18404
19374
  return {
18405
19375
  id: row.id,
18406
- proposalId: row.proposal_id,
18407
- strategyVersion: row.strategy_version,
18408
- activationScope: row.activation_scope,
19376
+ proposalId: row.proposalId,
19377
+ strategyVersion: row.strategyVersion,
19378
+ activationScope: row.activationScope,
18409
19379
  status: row.status,
18410
- approvedBy: row.approved_by,
18411
- activatedAt: row.activated_at,
18412
- deactivatedAt: row.deactivated_at
19380
+ approvedBy: row.approvedBy,
19381
+ activatedAt: row.activatedAt,
19382
+ deactivatedAt: row.deactivatedAt
18413
19383
  };
18414
19384
  }
18415
- // Verifications
18416
- saveVerification(v) {
18417
- const stmt = this.db.prepare(`INSERT INTO verifications (id, adaptation_id, measurement, baseline, observed_outcome, comparison_context, conclusion, limitations, verified_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`);
19385
+ async saveVerification(v) {
19386
+ this.ensureInit();
19387
+ const repo = this.ds.getRepository(Verification);
18418
19388
  try {
18419
- stmt.run(
18420
- v.id,
18421
- v.adaptationId,
18422
- v.measurement,
18423
- v.baseline,
18424
- v.observedOutcome,
18425
- v.comparisonContext,
18426
- v.conclusion,
18427
- JSON.stringify(v.limitations ?? []),
18428
- v.verifiedAt
18429
- );
19389
+ await repo.insert({
19390
+ id: v.id,
19391
+ adaptationId: v.adaptationId,
19392
+ measurement: v.measurement,
19393
+ baseline: v.baseline,
19394
+ observedOutcome: v.observedOutcome,
19395
+ comparisonContext: v.comparisonContext,
19396
+ conclusion: v.conclusion,
19397
+ limitations: JSON.stringify(v.limitations ?? []),
19398
+ verifiedAt: v.verifiedAt
19399
+ });
18430
19400
  } catch (e) {
18431
19401
  if (String(e).includes("UNIQUE") || String(e).includes("PRIMARY KEY")) throw new Error(`duplicate verification id: ${v.id}`);
18432
19402
  throw e;
18433
19403
  }
18434
19404
  }
18435
- getVerification(id) {
18436
- const row = this.db.prepare("SELECT * FROM verifications WHERE id = ?").get(id);
19405
+ async getVerification(id) {
19406
+ this.ensureInit();
19407
+ const repo = this.ds.getRepository(Verification);
19408
+ const row = await repo.findOne({ where: { id } });
18437
19409
  if (!row) return void 0;
18438
19410
  return {
18439
19411
  id: row.id,
18440
- adaptationId: row.adaptation_id,
19412
+ adaptationId: row.adaptationId,
18441
19413
  measurement: row.measurement,
18442
19414
  baseline: row.baseline,
18443
- observedOutcome: row.observed_outcome,
18444
- comparisonContext: row.comparison_context,
19415
+ observedOutcome: row.observedOutcome,
19416
+ comparisonContext: row.comparisonContext,
18445
19417
  conclusion: row.conclusion,
18446
19418
  limitations: JSON.parse(row.limitations),
18447
- verifiedAt: row.verified_at
19419
+ verifiedAt: row.verifiedAt
18448
19420
  };
18449
19421
  }
18450
- close() {
19422
+ async close() {
18451
19423
  try {
18452
- this.db.close();
19424
+ await this.ds?.destroy();
18453
19425
  } catch {
18454
19426
  }
19427
+ this.ds = null;
19428
+ this.initialized = false;
18455
19429
  }
18456
19430
  getPath() {
18457
19431
  return this.dbPath;
18458
19432
  }
18459
19433
  };
18460
- createSqliteStore = /* @__PURE__ */ __name((dbPath) => new NeuroCoreSqliteStore(dbPath), "createSqliteStore");
19434
+ createSqliteStore = /* @__PURE__ */ __name(async (dbPath) => {
19435
+ const store7 = new NeuroCoreSqliteStore(dbPath);
19436
+ await store7.init();
19437
+ return store7;
19438
+ }, "createSqliteStore");
18461
19439
  }
18462
19440
  });
18463
19441
 
@@ -18930,7 +19908,7 @@ var init_handshake = __esm({
18930
19908
  const binding = candidate.authorityBinding;
18931
19909
  if (!binding || typeof binding !== "object") return null;
18932
19910
  if (binding.format !== "dotmem.authority-binding") return null;
18933
- if (binding.currentSpeakerBinding !== "trusted-hi" && binding.currentSpeakerBinding !== "unknown" && binding.currentSpeakerBinding !== "untrusted") return null;
19911
+ if (binding.currentSpeakerBinding !== "trusted-hi" && binding.currentSpeakerBinding !== "any" && binding.currentSpeakerBinding !== "untrusted") return null;
18934
19912
  if (binding.currentAuthorityBinding !== "BOUND" && binding.currentAuthorityBinding !== "UNBOUND") return null;
18935
19913
  if (typeof binding.requestedOperationalRole !== "string" || !binding.requestedOperationalRole) return null;
18936
19914
  return candidate;
@@ -19074,7 +20052,7 @@ __export(session_registry_exports, {
19074
20052
  sessionRegistry: () => sessionRegistry,
19075
20053
  updateSessionScope: () => updateSessionScope
19076
20054
  });
19077
- var SESSIONS_FILE, LEASE_MS, readAll3, writeAll3, nowIso3, parentDir2, registerSession, heartbeatSession, updateSessionScope, getSession, listActiveSessions, acknowledgeCursor, closeSession, reapExpiredSessions, sessionRegistry, session_registry_default;
20055
+ var SESSIONS_FILE, LEASE_MS, readAll3, writeAll3, nowIso4, parentDir2, registerSession, heartbeatSession, updateSessionScope, getSession, listActiveSessions, acknowledgeCursor, closeSession, reapExpiredSessions, sessionRegistry, session_registry_default;
19078
20056
  var init_session_registry = __esm({
19079
20057
  "core/memory/session-registry.ts"() {
19080
20058
  init_user_paths();
@@ -19103,29 +20081,29 @@ var init_session_registry = __esm({
19103
20081
  writeAll3 = /* @__PURE__ */ __name((items) => {
19104
20082
  const fs16 = getSyncFs();
19105
20083
  if (!fs16) return;
19106
- const path10 = SESSIONS_FILE();
19107
- const parent = path10.substring(0, Math.max(path10.lastIndexOf("/"), path10.lastIndexOf("\\")));
20084
+ const path11 = SESSIONS_FILE();
20085
+ const parent = path11.substring(0, Math.max(path11.lastIndexOf("/"), path11.lastIndexOf("\\")));
19108
20086
  try {
19109
20087
  fs16.mkdirSync(parent, { recursive: true });
19110
20088
  } catch {
19111
20089
  }
19112
- const tmp = `${path10}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
20090
+ const tmp = `${path11}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
19113
20091
  fs16.writeFileSync(tmp, JSON.stringify(items, null, 2));
19114
20092
  try {
19115
- if (fs16.existsSync(path10)) fs16.copyFileSync(path10, `${path10}.bak`);
20093
+ if (fs16.existsSync(path11)) fs16.copyFileSync(path11, `${path11}.bak`);
19116
20094
  } catch {
19117
20095
  }
19118
20096
  try {
19119
- fs16.renameSync(tmp, path10);
20097
+ fs16.renameSync(tmp, path11);
19120
20098
  } catch {
19121
- fs16.copyFileSync(tmp, path10);
20099
+ fs16.copyFileSync(tmp, path11);
19122
20100
  try {
19123
20101
  fs16.unlinkSync(tmp);
19124
20102
  } catch {
19125
20103
  }
19126
20104
  }
19127
20105
  }, "writeAll");
19128
- nowIso3 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
20106
+ nowIso4 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
19129
20107
  parentDir2 = /* @__PURE__ */ __name((p) => p.substring(0, Math.max(p.lastIndexOf("/"), p.lastIndexOf("\\"))), "parentDir");
19130
20108
  registerSession = /* @__PURE__ */ __name(async (input) => {
19131
20109
  const run = /* @__PURE__ */ __name(async () => {
@@ -19142,10 +20120,10 @@ var init_session_registry = __esm({
19142
20120
  projectId: input.projectId ?? null,
19143
20121
  dayKey: input.dayKey,
19144
20122
  status: "active",
19145
- startedAt: idx >= 0 ? items[idx].startedAt : input.startedAt ?? nowIso3(),
19146
- lastSeenAt: nowIso3(),
20123
+ startedAt: idx >= 0 ? items[idx].startedAt : input.startedAt ?? nowIso4(),
20124
+ lastSeenAt: nowIso4(),
19147
20125
  cursor: idx >= 0 ? items[idx].cursor : input.cursor ?? input.lastCursor ?? 0,
19148
- metadata: { ...idx >= 0 ? items[idx].metadata : {}, ...input.metadata ?? {} }
20126
+ metadata: { ...idx >= 0 ? items[idx].metadata : {}, ...input.metadata }
19149
20127
  };
19150
20128
  if (idx >= 0) items[idx] = rec;
19151
20129
  else items.push(rec);
@@ -19163,9 +20141,9 @@ var init_session_registry = __esm({
19163
20141
  const items = readAll3();
19164
20142
  const idx = items.findIndex((s) => s.sessionId === sessionId);
19165
20143
  if (idx < 0) return;
19166
- items[idx].lastSeenAt = nowIso3();
20144
+ items[idx].lastSeenAt = nowIso4();
19167
20145
  items[idx].status = "active";
19168
- if (metadata) items[idx].metadata = { ...items[idx].metadata ?? {}, ...metadata };
20146
+ if (metadata) items[idx].metadata = { ...items[idx].metadata, ...metadata };
19169
20147
  writeAll3(items);
19170
20148
  }, "run");
19171
20149
  try {
@@ -19186,7 +20164,7 @@ var init_session_registry = __esm({
19186
20164
  if (scope?.conversationId !== void 0) items[idx].conversationId = scope.conversationId;
19187
20165
  if (scope?.agentId !== void 0) items[idx].agentId = scope.agentId;
19188
20166
  if (scope?.dayKey !== void 0) items[idx].dayKey = scope.dayKey;
19189
- items[idx].lastSeenAt = nowIso3();
20167
+ items[idx].lastSeenAt = nowIso4();
19190
20168
  writeAll3(items);
19191
20169
  }, "run");
19192
20170
  try {
@@ -19221,7 +20199,7 @@ var init_session_registry = __esm({
19221
20199
  return;
19222
20200
  }
19223
20201
  items[idx].cursor = cursor;
19224
- items[idx].lastSeenAt = nowIso3();
20202
+ items[idx].lastSeenAt = nowIso4();
19225
20203
  writeAll3(items);
19226
20204
  }, "run");
19227
20205
  try {
@@ -19236,8 +20214,8 @@ var init_session_registry = __esm({
19236
20214
  const idx = items.findIndex((s) => s.sessionId === sessionId);
19237
20215
  if (idx < 0) return;
19238
20216
  items[idx].status = "closed";
19239
- items[idx].lastSeenAt = nowIso3();
19240
- if (reason) items[idx].metadata = { ...items[idx].metadata ?? {}, closeReason: reason };
20217
+ items[idx].lastSeenAt = nowIso4();
20218
+ if (reason) items[idx].metadata = { ...items[idx].metadata, closeReason: reason };
19241
20219
  writeAll3(items);
19242
20220
  }, "run");
19243
20221
  try {
@@ -19291,7 +20269,7 @@ __export(cross_chat_propagation_exports, {
19291
20269
  readCrossChatPropagationState: () => readCrossChatPropagationState,
19292
20270
  writeCrossChatPropagationState: () => writeCrossChatPropagationState
19293
20271
  });
19294
- var CROSS_CHAT_PROPAGATION_FILE_NAME, CROSS_CHAT_PROPAGATION_FORMAT_VERSION, emptyState, joinPath7, resolveFilePath, readRaw, writeRaw, validateState, readCrossChatPropagationState, writeCrossChatPropagationState, getCrossChatPropagationStatus, isCrossChatPropagationEnabled, getCrossChatPropagationChangeMarker;
20272
+ var CROSS_CHAT_PROPAGATION_FILE_NAME, CROSS_CHAT_PROPAGATION_FORMAT_VERSION, emptyState, joinPath8, resolveFilePath, readRaw, writeRaw, validateState, readCrossChatPropagationState, writeCrossChatPropagationState, getCrossChatPropagationStatus, isCrossChatPropagationEnabled, getCrossChatPropagationChangeMarker;
19295
20273
  var init_cross_chat_propagation = __esm({
19296
20274
  "core/continuity/cross-chat-propagation.ts"() {
19297
20275
  init_user_paths();
@@ -19303,12 +20281,12 @@ var init_cross_chat_propagation = __esm({
19303
20281
  configured: false,
19304
20282
  changeMarker: 0
19305
20283
  }), "emptyState");
19306
- joinPath7 = /* @__PURE__ */ __name((base, child) => {
20284
+ joinPath8 = /* @__PURE__ */ __name((base, child) => {
19307
20285
  const separator3 = process.platform === "win32" ? "\\" : "/";
19308
20286
  return `${base.replace(/[\\/]+/g, separator3)}${separator3}${child}`;
19309
20287
  }, "joinPath");
19310
20288
  resolveFilePath = /* @__PURE__ */ __name(() => {
19311
- return joinPath7(resolveUserDotMemPath(), CROSS_CHAT_PROPAGATION_FILE_NAME);
20289
+ return joinPath8(resolveUserDotMemPath(), CROSS_CHAT_PROPAGATION_FILE_NAME);
19312
20290
  }, "resolveFilePath");
19313
20291
  readRaw = /* @__PURE__ */ __name(async () => {
19314
20292
  const fs16 = await import('fs/promises');
@@ -19322,16 +20300,16 @@ var init_cross_chat_propagation = __esm({
19322
20300
  }, "readRaw");
19323
20301
  writeRaw = /* @__PURE__ */ __name(async (content) => {
19324
20302
  const fs16 = await import('fs/promises');
19325
- const path10 = resolveFilePath();
19326
- const dir = path10.replace(/[\\/][^\\/]+$/, "");
20303
+ const path11 = resolveFilePath();
20304
+ const dir = path11.replace(/[\\/][^\\/]+$/, "");
19327
20305
  await fs16.mkdir(dir, { recursive: true });
19328
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
20306
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
19329
20307
  try {
19330
20308
  await fs16.writeFile(temporary, content, "utf8");
19331
- await fs16.rename(temporary, path10);
20309
+ await fs16.rename(temporary, path11);
19332
20310
  } catch {
19333
20311
  await fs16.rm(temporary, { force: true }).catch(() => void 0);
19334
- throw new Error(`Failed to write cross-chat propagation config at ${path10}`);
20312
+ throw new Error(`Failed to write cross-chat propagation config at ${path11}`);
19335
20313
  }
19336
20314
  }, "writeRaw");
19337
20315
  validateState = /* @__PURE__ */ __name((value) => {
@@ -19406,213 +20384,6 @@ var init_cross_chat_propagation = __esm({
19406
20384
  }
19407
20385
  });
19408
20386
 
19409
- // core/context-compiler/index.ts
19410
- var CHARS_PER_TOKEN, estimateTokens, DEFAULT_BUDGETS, dedupe, ContextCompiler, compileContext;
19411
- var init_context_compiler = __esm({
19412
- "core/context-compiler/index.ts"() {
19413
- CHARS_PER_TOKEN = 4;
19414
- estimateTokens = /* @__PURE__ */ __name((text) => Math.ceil((text || "").length / CHARS_PER_TOKEN), "estimateTokens");
19415
- DEFAULT_BUDGETS = {
19416
- identity: 0.1,
19417
- rules: 0.15,
19418
- conversationalState: 0.3,
19419
- retrievedKnowledge: 0.45
19420
- };
19421
- dedupe = /* @__PURE__ */ __name((items) => {
19422
- const seen = /* @__PURE__ */ new Set();
19423
- const result = [];
19424
- for (const item of items) {
19425
- const key = item.trim().toLowerCase();
19426
- if (seen.has(key)) continue;
19427
- seen.add(key);
19428
- result.push(item);
19429
- }
19430
- return result;
19431
- }, "dedupe");
19432
- ContextCompiler = class {
19433
- static {
19434
- __name(this, "ContextCompiler");
19435
- }
19436
- compile(input) {
19437
- const totalBudget = input.tokenBudget ?? 4096;
19438
- const totalChars = totalBudget * CHARS_PER_TOKEN;
19439
- const budgets = {
19440
- identity: Math.floor(totalChars * (input.categoryBudgets?.identity ?? DEFAULT_BUDGETS.identity)),
19441
- rules: Math.floor(totalChars * (input.categoryBudgets?.rules ?? DEFAULT_BUDGETS.rules)),
19442
- conversationalState: Math.floor(totalChars * (input.categoryBudgets?.conversationalState ?? DEFAULT_BUDGETS.conversationalState)),
19443
- retrievedKnowledge: Math.floor(totalChars * (input.categoryBudgets?.retrievedKnowledge ?? DEFAULT_BUDGETS.retrievedKnowledge))
19444
- };
19445
- const omissions = [];
19446
- const identityText = (input.identity ?? "").trim();
19447
- let identityUsed = 0;
19448
- const mandatoryParts = [];
19449
- if (identityText) {
19450
- if (identityText.length <= budgets.identity) {
19451
- mandatoryParts.push(identityText);
19452
- identityUsed = identityText.length;
19453
- } else {
19454
- omissions.push({
19455
- category: "identity",
19456
- whatWasOmitted: identityText,
19457
- whyOmitted: "token budget exceeded",
19458
- wouldBreakContinuity: true
19459
- });
19460
- }
19461
- }
19462
- const rules = input.rules ?? [];
19463
- const activeRules = [];
19464
- let rulesUsed = 0;
19465
- for (const rule of rules) {
19466
- if (rulesUsed + rule.length <= budgets.rules) {
19467
- activeRules.push(rule);
19468
- rulesUsed += rule.length;
19469
- } else {
19470
- omissions.push({
19471
- category: "rules",
19472
- whatWasOmitted: rule,
19473
- whyOmitted: "token budget exceeded",
19474
- wouldBreakContinuity: false
19475
- });
19476
- }
19477
- }
19478
- const state3 = input.conversationalState ?? null;
19479
- const mandatoryStateParts = [];
19480
- if (state3) {
19481
- if (state3.objective) mandatoryStateParts.push(`Objective: ${state3.objective}`);
19482
- if (state3.currentWorkingPosition) mandatoryStateParts.push(`Working position: ${state3.currentWorkingPosition}`);
19483
- if (state3.openLoops.length > 0) {
19484
- mandatoryStateParts.push(`Open loops: ${state3.openLoops.map((l) => l.description).join("; ")}`);
19485
- }
19486
- if (state3.rejectedApproaches.length > 0) {
19487
- mandatoryStateParts.push(`Rejected approaches: ${state3.rejectedApproaches.map((r) => `${r.approach} (${r.reason})`).join("; ")}`);
19488
- }
19489
- }
19490
- const activeParts = [];
19491
- if (state3) {
19492
- if (state3.currentProblem) activeParts.push(`Current problem: ${state3.currentProblem}`);
19493
- if (state3.establishedUnderstanding) activeParts.push(`Established understanding: ${state3.establishedUnderstanding}`);
19494
- if (state3.decisionsMade.length > 0) {
19495
- activeParts.push(`Decisions: ${state3.decisionsMade.map((d) => `${d.decision} (rationale: ${d.rationale})`).join("; ")}`);
19496
- }
19497
- if (state3.pendingDecisions.length > 0) {
19498
- activeParts.push(`Pending decisions: ${state3.pendingDecisions.map((d) => `${d.decision} [${d.options.join(", ")}]`).join("; ")}`);
19499
- }
19500
- if (state3.unresolvedQuestions.length > 0) {
19501
- activeParts.push(`Unresolved questions: ${state3.unresolvedQuestions.map((q) => q.question).join("; ")}`);
19502
- }
19503
- if (state3.reasoningTrajectory.length > 0) {
19504
- activeParts.push(`Reasoning trajectory: ${state3.reasoningTrajectory.map((r) => r.conclusion).join(" -> ")}`);
19505
- }
19506
- if (state3.nextConversationalStep) {
19507
- activeParts.push(`Next step: ${state3.nextConversationalStep}`);
19508
- }
19509
- if (state3.lastCompletedAction) {
19510
- activeParts.push(`Last completed action: ${state3.lastCompletedAction}`);
19511
- }
19512
- }
19513
- const dedupedActive = dedupe(activeParts.filter((part) => !mandatoryStateParts.includes(part)));
19514
- let stateUsed = 0;
19515
- const admittedMandatoryState = [];
19516
- const admittedActive = [];
19517
- for (const part of mandatoryStateParts) {
19518
- if (stateUsed + part.length <= budgets.conversationalState) {
19519
- admittedMandatoryState.push(part);
19520
- stateUsed += part.length;
19521
- } else {
19522
- omissions.push({
19523
- category: "conversationalState",
19524
- whatWasOmitted: part,
19525
- whyOmitted: "token budget exceeded",
19526
- wouldBreakContinuity: true
19527
- });
19528
- }
19529
- }
19530
- for (const part of dedupedActive) {
19531
- if (stateUsed + part.length <= budgets.conversationalState) {
19532
- admittedActive.push(part);
19533
- stateUsed += part.length;
19534
- } else {
19535
- omissions.push({
19536
- category: "conversationalState",
19537
- whatWasOmitted: part,
19538
- whyOmitted: "token budget exceeded",
19539
- wouldBreakContinuity: false
19540
- });
19541
- }
19542
- }
19543
- const refs = [...input.knowledgeReferences ?? []].sort((a, b) => b.relevance - a.relevance);
19544
- const retrievedParts = [];
19545
- let retrievedUsed = 0;
19546
- for (const ref of refs) {
19547
- const text2 = ref.summary ? `${ref.kind}:${ref.identifier} - ${ref.summary}` : `${ref.kind}:${ref.identifier}`;
19548
- if (retrievedUsed + text2.length <= budgets.retrievedKnowledge) {
19549
- retrievedParts.push(text2);
19550
- retrievedUsed += text2.length;
19551
- } else {
19552
- omissions.push({
19553
- category: "retrievedKnowledge",
19554
- whatWasOmitted: text2,
19555
- whyOmitted: "token budget exceeded",
19556
- wouldBreakContinuity: false
19557
- });
19558
- }
19559
- }
19560
- const optionalParts = [];
19561
- let optionalUsed = 0;
19562
- const remainingBudget = totalChars - (identityUsed + rulesUsed + stateUsed + retrievedUsed);
19563
- for (const item of input.historicalContext ?? []) {
19564
- if (optionalUsed + item.length <= remainingBudget) {
19565
- optionalParts.push(item);
19566
- optionalUsed += item.length;
19567
- } else {
19568
- omissions.push({
19569
- category: "historical",
19570
- whatWasOmitted: item,
19571
- whyOmitted: "token budget exceeded",
19572
- wouldBreakContinuity: false
19573
- });
19574
- }
19575
- }
19576
- const admittedSet = new Set([...mandatoryParts, ...admittedMandatoryState, ...admittedActive].map((s) => s.trim().toLowerCase()));
19577
- const isDuplicate = /* @__PURE__ */ __name((item) => {
19578
- const normalized = item.trim().toLowerCase();
19579
- for (const existing of admittedSet) {
19580
- if (existing.includes(normalized) || normalized.includes(existing)) return true;
19581
- }
19582
- return false;
19583
- }, "isDuplicate");
19584
- const finalRetrieved = dedupe(retrievedParts.filter((p) => !isDuplicate(p)));
19585
- const finalOptional = dedupe(optionalParts.filter((p) => !isDuplicate(p) && !finalRetrieved.includes(p)));
19586
- const mandatory = [...mandatoryParts, ...admittedMandatoryState].join("\n");
19587
- const active = [...admittedActive];
19588
- const retrieved = finalRetrieved;
19589
- const optional = finalOptional;
19590
- const text = [mandatory ? `## MANDATORY
19591
- ${mandatory}` : "", active.length ? `## ACTIVE
19592
- ${active.join("\n")}` : "", retrieved.length ? `## RETRIEVED
19593
- ${retrieved.join("\n")}` : "", optional.length ? `## OPTIONAL
19594
- ${optional.join("\n")}` : "", rules.length ? `## RULES
19595
- ${activeRules.join("\n")}` : ""].filter(Boolean).join("\n\n");
19596
- const budgetUsed = estimateTokens(text);
19597
- return {
19598
- mandatory,
19599
- active,
19600
- retrieved,
19601
- optional,
19602
- omissions,
19603
- budgetUsed,
19604
- budgetAvailable: totalBudget,
19605
- text
19606
- };
19607
- }
19608
- };
19609
- compileContext = /* @__PURE__ */ __name((input) => {
19610
- const compiler = new ContextCompiler();
19611
- return compiler.compile(input);
19612
- }, "compileContext");
19613
- }
19614
- });
19615
-
19616
20387
  // core/recovery-service/index.ts
19617
20388
  var RecoveryService;
19618
20389
  var init_recovery_service = __esm({
@@ -19705,7 +20476,7 @@ __export(consolidation_engine_exports, {
19705
20476
  consolidationEngine: () => consolidationEngine,
19706
20477
  getConsolidationEngine: () => getConsolidationEngine
19707
20478
  });
19708
- var DEFAULT_CONFIG3, nowIso4, generateId2, normalizeText2, tokenize3, jaccardSimilarity2, detectOutcome, detectConditions, isDoNotRemember, CONSOLIDATION_STORE_KEY, ConsolidationPersistence, ConsolidationEngine, defaultEngine, getConsolidationEngine, consolidationEngine;
20479
+ var DEFAULT_CONFIG3, nowIso5, generateId2, normalizeText2, tokenize3, jaccardSimilarity2, detectOutcome, detectConditions, isDoNotRemember, CONSOLIDATION_STORE_KEY, ConsolidationPersistence, ConsolidationEngine, defaultEngine, getConsolidationEngine, consolidationEngine;
19709
20480
  var init_consolidation_engine = __esm({
19710
20481
  "core/memory/consolidation-engine.ts"() {
19711
20482
  init_durable_store();
@@ -19716,7 +20487,7 @@ var init_consolidation_engine = __esm({
19716
20487
  similarityThreshold: 0.5,
19717
20488
  minConfidenceForConsolidated: 0.7
19718
20489
  };
19719
- nowIso4 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
20490
+ nowIso5 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
19720
20491
  generateId2 = /* @__PURE__ */ __name(() => `cons-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`, "generateId");
19721
20492
  normalizeText2 = /* @__PURE__ */ __name((text) => {
19722
20493
  return text.normalize("NFKC").toLocaleLowerCase("en-US").replace(/[^\w\s]/g, " ").replace(/\s+/g, " ").trim();
@@ -19741,7 +20512,7 @@ var init_consolidation_engine = __esm({
19741
20512
  if (/if |when |only when|provided that|as long as/i.test(lower)) return "conditional";
19742
20513
  if (/succ(eed|ess)|works|passed|completed|resolved|fixed/i.test(lower)) return "success";
19743
20514
  if (category === "decision") return "success";
19744
- return "unknown";
20515
+ return "any";
19745
20516
  }, "detectOutcome");
19746
20517
  detectConditions = /* @__PURE__ */ __name((statement) => {
19747
20518
  const conditions = [];
@@ -19818,7 +20589,7 @@ var init_consolidation_engine = __esm({
19818
20589
  new DurableMemoryStore({
19819
20590
  filePath: `${resolveUserDotMemPath()}/consolidation-records.kv`,
19820
20591
  storeKey: CONSOLIDATION_STORE_KEY,
19821
- tenantId: this.tenantId
20592
+ tenantId: this.tenantId ?? void 0
19822
20593
  })
19823
20594
  );
19824
20595
  }
@@ -19935,7 +20706,7 @@ var init_consolidation_engine = __esm({
19935
20706
  }
19936
20707
  /** Create a new consolidation record from a group of experiences. */
19937
20708
  async createRecordFromGroup(group) {
19938
- const now3 = nowIso4();
20709
+ const now3 = nowIso5();
19939
20710
  const evidence = group.experiences.map((e) => ({
19940
20711
  experienceId: e.id,
19941
20712
  statement: e.statement,
@@ -19953,7 +20724,7 @@ var init_consolidation_engine = __esm({
19953
20724
  const outcomes = uniqueEvidence.map((e) => e.outcome);
19954
20725
  const hasFailure = outcomes.includes("failure");
19955
20726
  const hasSuccess = outcomes.includes("success");
19956
- const hasUnknown = outcomes.includes("unknown");
20727
+ const hasUnknown = outcomes.includes("any");
19957
20728
  const hasConditional = outcomes.includes("conditional");
19958
20729
  let lifecycleState = "pending";
19959
20730
  if (uniqueEvidence.length < this.config.minExperiencesForAcquired) {
@@ -19969,7 +20740,7 @@ var init_consolidation_engine = __esm({
19969
20740
  applicability["conditions"] = conditions.join("; ");
19970
20741
  }
19971
20742
  const limitations = [];
19972
- if (hasUnknown) limitations.push("Outcome unknown for some experiences");
20743
+ if (hasUnknown) limitations.push("Outcome any for some experiences");
19973
20744
  if (hasConditional) limitations.push("Success is conditional on specific circumstances");
19974
20745
  if (uniqueEvidence.length < this.config.minExperiencesForConsolidated) {
19975
20746
  limitations.push(`Only ${uniqueEvidence.length} supporting experience(s); ${this.config.minExperiencesForConsolidated} required for consolidation`);
@@ -20012,7 +20783,7 @@ var init_consolidation_engine = __esm({
20012
20783
  async updateRecordWithEvidence(record, newExperiences) {
20013
20784
  const newExpIds = newExperiences.map((e) => e.id).filter((id) => !record.supportingExperiences.includes(id));
20014
20785
  if (newExpIds.length === 0) return null;
20015
- const now3 = nowIso4();
20786
+ const now3 = nowIso5();
20016
20787
  const newEvidence = newExperiences.filter((e) => !record.supportingExperiences.includes(e.id)).map((e) => ({
20017
20788
  experienceId: e.id,
20018
20789
  statement: e.statement,
@@ -20070,7 +20841,7 @@ var init_consolidation_engine = __esm({
20070
20841
  if (record.doNotRemember) return false;
20071
20842
  const uniqueEvidence = this.deduplicateEvidence([...record.supportingEvidence, ...record.contradictingEvidence]);
20072
20843
  if (record.lifecycleState === "acquired" && uniqueEvidence.length >= this.config.minExperiencesForConsolidated && record.confidence >= this.config.minConfidenceForConsolidated && record.contradictingEvidence.length === 0) {
20073
- const now3 = nowIso4();
20844
+ const now3 = nowIso5();
20074
20845
  const promoted = {
20075
20846
  ...record,
20076
20847
  lifecycleState: "consolidated",
@@ -20092,7 +20863,7 @@ var init_consolidation_engine = __esm({
20092
20863
  return true;
20093
20864
  }
20094
20865
  if (record.lifecycleState === "insufficient_evidence" && uniqueEvidence.length >= this.config.minExperiencesForAcquired) {
20095
- const now3 = nowIso4();
20866
+ const now3 = nowIso5();
20096
20867
  const promoted = {
20097
20868
  ...record,
20098
20869
  lifecycleState: "acquired",
@@ -20132,7 +20903,7 @@ var init_consolidation_engine = __esm({
20132
20903
  a.history.push({
20133
20904
  from: a.lifecycleState,
20134
20905
  to: "conflicting",
20135
- at: nowIso4(),
20906
+ at: nowIso5(),
20136
20907
  reason: `Contradiction detected with record ${b.id}`
20137
20908
  });
20138
20909
  await this.persistence.saveRecord(a);
@@ -20160,11 +20931,11 @@ var init_consolidation_engine = __esm({
20160
20931
  if (evidence.length === 0) return 0;
20161
20932
  const successes = evidence.filter((e) => e.outcome === "success").length;
20162
20933
  const failures = evidence.filter((e) => e.outcome === "failure").length;
20163
- const unknowns = evidence.filter((e) => e.outcome === "unknown").length;
20934
+ const anys = evidence.filter((e) => e.outcome === "any").length;
20164
20935
  const conditionals = evidence.filter((e) => e.outcome === "conditional").length;
20165
20936
  let confidence = evidence.length > 0 ? successes / evidence.length : 0;
20166
- if (unknowns > 0) {
20167
- confidence *= 1 - unknowns / (evidence.length * 2);
20937
+ if (anys > 0) {
20938
+ confidence *= 1 - anys / (evidence.length * 2);
20168
20939
  }
20169
20940
  if (conditionals > 0) {
20170
20941
  confidence *= 0.9;
@@ -20180,14 +20951,14 @@ var init_consolidation_engine = __esm({
20180
20951
  buildConfidenceJustification(evidence, confidence) {
20181
20952
  const successes = evidence.filter((e) => e.outcome === "success").length;
20182
20953
  const failures = evidence.filter((e) => e.outcome === "failure").length;
20183
- const unknowns = evidence.filter((e) => e.outcome === "unknown").length;
20184
- return `Based on ${evidence.length} unique experience(s): ${successes} success, ${failures} failure, ${unknowns} unknown. Confidence: ${confidence}`;
20954
+ const anys = evidence.filter((e) => e.outcome === "any").length;
20955
+ return `Based on ${evidence.length} unique experience(s): ${successes} success, ${failures} failure, ${anys} any. Confidence: ${confidence}`;
20185
20956
  }
20186
20957
  /** Build limitations list. */
20187
20958
  buildLimitations(evidence, confidence) {
20188
20959
  const limitations = [];
20189
- const unknowns = evidence.filter((e) => e.outcome === "unknown").length;
20190
- if (unknowns > 0) limitations.push(`${unknowns} experience(s) with unknown outcome`);
20960
+ const anys = evidence.filter((e) => e.outcome === "any").length;
20961
+ if (anys > 0) limitations.push(`${anys} experience(s) with any outcome`);
20191
20962
  const conditionals = evidence.filter((e) => e.outcome === "conditional").length;
20192
20963
  if (conditionals > 0) limitations.push(`${conditionals} experience(s) with conditional success`);
20193
20964
  if (confidence < 0.5) limitations.push("Low confidence due to insufficient or conflicting evidence");
@@ -20202,7 +20973,7 @@ var init_consolidation_engine = __esm({
20202
20973
  const record = this.records.get(id);
20203
20974
  if (!record) throw new Error(`Record not found: ${id}`);
20204
20975
  if (record.doNotRemember) throw new Error(`Cannot promote do-not-remember record: ${id}`);
20205
- const now3 = nowIso4();
20976
+ const now3 = nowIso5();
20206
20977
  const promoted = {
20207
20978
  ...record,
20208
20979
  lifecycleState: "consolidated",
@@ -20228,7 +20999,7 @@ var init_consolidation_engine = __esm({
20228
20999
  await this.load();
20229
21000
  const record = this.records.get(id);
20230
21001
  if (!record) throw new Error(`Record not found: ${id}`);
20231
- const now3 = nowIso4();
21002
+ const now3 = nowIso5();
20232
21003
  const superseded = {
20233
21004
  ...record,
20234
21005
  lifecycleState: "superseded",
@@ -20253,7 +21024,7 @@ var init_consolidation_engine = __esm({
20253
21024
  await this.load();
20254
21025
  const record = this.records.get(id);
20255
21026
  if (!record) throw new Error(`Record not found: ${id}`);
20256
- const now3 = nowIso4();
21027
+ const now3 = nowIso5();
20257
21028
  const invalidated = {
20258
21029
  ...record,
20259
21030
  lifecycleState: "invalidated",
@@ -20278,7 +21049,7 @@ var init_consolidation_engine = __esm({
20278
21049
  await this.load();
20279
21050
  const record = this.records.get(id);
20280
21051
  if (!record) throw new Error(`Record not found: ${id}`);
20281
- const now3 = nowIso4();
21052
+ const now3 = nowIso5();
20282
21053
  const reassessed = {
20283
21054
  ...record,
20284
21055
  lifecycleState: "reassessment_required",
@@ -20351,20 +21122,20 @@ __export(session_bootstrap_exports, {
20351
21122
  bootstrapSession: () => bootstrapSession,
20352
21123
  createSessionBootstrap: () => createSessionBootstrap
20353
21124
  });
20354
- var nowIso5, defaultSubject, bootstrapSession, createSessionBootstrap;
21125
+ var nowIso6, defaultSubject, bootstrapSession, createSessionBootstrap;
20355
21126
  var init_session_bootstrap = __esm({
20356
21127
  "core/memory/session-bootstrap.ts"() {
20357
21128
  init_discover();
20358
21129
  init_project();
20359
- init_rules_loader();
21130
+ init_rule_enforcement();
20360
21131
  init_context_constants();
20361
21132
  init_context_compiler();
20362
21133
  init_conversational_state();
20363
21134
  init_recovery_service();
20364
- nowIso5 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
21135
+ nowIso6 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
20365
21136
  defaultSubject = "__default__";
20366
21137
  bootstrapSession = /* @__PURE__ */ __name(async (options = {}) => {
20367
- 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;
21138
+ 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;
20368
21139
  const scopes = {
20369
21140
  userId,
20370
21141
  projectId,
@@ -20422,6 +21193,7 @@ var init_session_bootstrap = __esm({
20422
21193
  let rulesCount = 0;
20423
21194
  let rulesSignature = "";
20424
21195
  let consolidatedKnowledge = [];
21196
+ let enforcementRules = [];
20425
21197
  try {
20426
21198
  const dynamicMemory = await Promise.resolve().then(() => (init_memory(), memory_exports));
20427
21199
  const state3 = await dynamicMemory.loadCombinedKnowledgeState();
@@ -20439,9 +21211,12 @@ var init_session_bootstrap = __esm({
20439
21211
  relevance: 1
20440
21212
  });
20441
21213
  }
20442
- const rules = loadIronRules(state3).rules;
20443
- rulesCount = rules.length;
20444
- rulesSignature = ruleSetSignature(rules);
21214
+ try {
21215
+ enforcementRules = await resolveApplicableRules(situation ?? "", scope);
21216
+ rulesCount = enforcementRules.length;
21217
+ rulesSignature = enforcementRules.map((r) => `${r.id}\0${r.text}`).join("");
21218
+ } catch {
21219
+ }
20445
21220
  try {
20446
21221
  const { consolidationEngine: consolidationEngine2 } = await Promise.resolve().then(() => (init_consolidation_engine(), consolidation_engine_exports));
20447
21222
  await consolidationEngine2.load();
@@ -20471,7 +21246,7 @@ var init_session_bootstrap = __esm({
20471
21246
  }
20472
21247
  const context2 = compileContext({
20473
21248
  conversationalState: recovery?.context?.conversationalState,
20474
- rules: inputRules,
21249
+ rules: enforcementRules.map((r) => `[${r.source.toUpperCase()}] ${r.text}` + (r.appliesWhen ? ` (quando: ${r.appliesWhen})` : "")),
20475
21250
  knowledgeReferences: knowledgeReferences.map((r) => ({
20476
21251
  id: r.id,
20477
21252
  kind: r.kind,
@@ -20849,11 +21624,11 @@ var init_memory = __esm({
20849
21624
  const byTrust = {};
20850
21625
  const byArea = {};
20851
21626
  for (const claim of state3.claims ?? []) {
20852
- const scope = claim.scope ?? "unknown";
21627
+ const scope = claim.scope ?? "any";
20853
21628
  byScope[scope] = (byScope[scope] || 0) + 1;
20854
- const trust = claim.trustBasis ?? "unknown";
21629
+ const trust = claim.trustBasis ?? "any";
20855
21630
  byTrust[trust] = (byTrust[trust] || 0) + 1;
20856
- const area = claim.applicability?.area ?? "unknown";
21631
+ const area = claim.applicability?.area ?? "any";
20857
21632
  byArea[area] = (byArea[area] || 0) + 1;
20858
21633
  }
20859
21634
  return { total: (state3.claims ?? []).length, byScope, byTrust, byArea };
@@ -20963,7 +21738,7 @@ var init_memory = __esm({
20963
21738
  const ids = [];
20964
21739
  for (const stmt of statements) {
20965
21740
  const id = await acquire.acquire({
20966
- knowledge: { hypothesis: stmt, situation: context2?.situation },
21741
+ knowledge: { hypothesis: stmt, ...context2?.situation !== void 0 ? { situation: context2.situation } : {} },
20967
21742
  applicability: context2?.applicability ?? { area: "hypothesis" },
20968
21743
  evidence: [{ id: `hyp-${Date.now()}`, source: "tree-of-thoughts", observedAt: (/* @__PURE__ */ new Date()).toISOString() }],
20969
21744
  epistemicType: "inferred",
@@ -21009,7 +21784,7 @@ var init_memory = __esm({
21009
21784
  },
21010
21785
  async learnFromFailure(claimId, failure, correction) {
21011
21786
  return acquire.acquire({
21012
- knowledge: { failedClaim: claimId, failure, correction },
21787
+ knowledge: { failedClaim: claimId, failure, ...correction !== void 0 ? { correction } : {} },
21013
21788
  applicability: { area: "continual-learning", kind: "correction" },
21014
21789
  evidence: [{ id: `fail-${Date.now()}`, source: "experience", observedAt: (/* @__PURE__ */ new Date()).toISOString() }],
21015
21790
  epistemicType: "observed",
@@ -21024,7 +21799,7 @@ var init_memory = __esm({
21024
21799
  const state3 = await loadCombinedKnowledgeState();
21025
21800
  const groups = {};
21026
21801
  for (const c of state3.claims ?? []) {
21027
- const area = c.applicability?.area ?? "unknown";
21802
+ const area = c.applicability?.area ?? "any";
21028
21803
  if (!groups[area]) groups[area] = [];
21029
21804
  groups[area].push(c.id);
21030
21805
  }
@@ -21094,7 +21869,7 @@ var init_memory = __esm({
21094
21869
  });
21095
21870
  const lines = ["Autobiography:"];
21096
21871
  for (const c of claims) {
21097
- const area = c.applicability?.area ?? "unknown";
21872
+ const area = c.applicability?.area ?? "any";
21098
21873
  lines.push(`- [${c.acquiredAt ?? "?"}] (${area}) ${JSON.stringify(c.knowledge).slice(0, 120)}`);
21099
21874
  }
21100
21875
  return lines.join("\n");
@@ -22184,7 +22959,7 @@ var traceModelContext = /* @__PURE__ */ __name((context2) => buildReasoningTrace
22184
22959
  var evaluateRef = /* @__PURE__ */ __name((ref, current) => {
22185
22960
  if (ref.version !== void 0 && current.version !== void 0 && ref.version !== current.version) return "changed";
22186
22961
  if (ref.digest !== void 0 && current.digest !== void 0 && ref.digest !== current.digest) return "changed";
22187
- if (ref.version === void 0 && current.version === void 0 && ref.digest === void 0 && current.digest === void 0) return "unknown";
22962
+ if (ref.version === void 0 && current.version === void 0 && ref.digest === void 0 && current.digest === void 0) return "any";
22188
22963
  return "same";
22189
22964
  }, "evaluateRef");
22190
22965
  var evaluateFreshness = /* @__PURE__ */ __name((input) => {
@@ -22192,10 +22967,10 @@ var evaluateFreshness = /* @__PURE__ */ __name((input) => {
22192
22967
  return { state: "stale", reason: "explicit invalidation", checkedAt: input.checkedAt };
22193
22968
  }
22194
22969
  if (input.sourceRefs.length === 0) {
22195
- return { state: "unknown", reason: "no source references recorded", checkedAt: input.checkedAt };
22970
+ return { state: "any", reason: "no source references recorded", checkedAt: input.checkedAt };
22196
22971
  }
22197
22972
  const staleReasons = [];
22198
- let unknown = false;
22973
+ let any = false;
22199
22974
  for (const ref of input.sourceRefs) {
22200
22975
  const current = input.currentSources.find((candidate) => candidate.kind === ref.kind && candidate.id === ref.id);
22201
22976
  if (!current) {
@@ -22207,15 +22982,15 @@ var evaluateFreshness = /* @__PURE__ */ __name((input) => {
22207
22982
  staleReasons.push(`${ref.kind}:${ref.id} version ${ref.version ?? "?"} -> ${current.version ?? "?"}, digest ${ref.digest ?? "?"} -> ${current.digest ?? "?"}`);
22208
22983
  continue;
22209
22984
  }
22210
- if (comparison === "unknown") {
22211
- unknown = true;
22985
+ if (comparison === "any") {
22986
+ any = true;
22212
22987
  }
22213
22988
  }
22214
22989
  if (staleReasons.length > 0) {
22215
22990
  return { state: "stale", reason: staleReasons.join("; "), checkedAt: input.checkedAt };
22216
22991
  }
22217
- if (unknown) {
22218
- return { state: "unknown", reason: "sources without comparable identity", checkedAt: input.checkedAt };
22992
+ if (any) {
22993
+ return { state: "any", reason: "sources without comparable identity", checkedAt: input.checkedAt };
22219
22994
  }
22220
22995
  return { state: "fresh", checkedAt: input.checkedAt };
22221
22996
  }, "evaluateFreshness");
@@ -22320,31 +23095,31 @@ var validateContinuityDocument = /* @__PURE__ */ __name((value) => {
22320
23095
  snapshots: document.snapshots
22321
23096
  };
22322
23097
  }, "validateContinuityDocument");
22323
- var deleteContinuityArtifact = /* @__PURE__ */ __name(async (path10) => {
23098
+ var deleteContinuityArtifact = /* @__PURE__ */ __name(async (path11) => {
22324
23099
  const fs16 = getSyncFs();
22325
23100
  if (!fs16) return;
22326
- await fs16.promises.rm(path10, { force: true });
23101
+ await fs16.promises.rm(path11, { force: true });
22327
23102
  }, "deleteContinuityArtifact");
22328
- var loadContinuityDocument = /* @__PURE__ */ __name(async (path10) => {
23103
+ var loadContinuityDocument = /* @__PURE__ */ __name(async (path11) => {
22329
23104
  const fs16 = getSyncFs();
22330
23105
  if (!fs16) return emptyContinuityDocument();
22331
23106
  try {
22332
- const raw = await fs16.promises.readFile(path10, "utf8");
23107
+ const raw = await fs16.promises.readFile(path11, "utf8");
22333
23108
  return validateContinuityDocument(JSON.parse(raw));
22334
23109
  } catch {
22335
23110
  return emptyContinuityDocument();
22336
23111
  }
22337
23112
  }, "loadContinuityDocument");
22338
- var saveContinuityDocument = /* @__PURE__ */ __name(async (path10, document) => {
23113
+ var saveContinuityDocument = /* @__PURE__ */ __name(async (path11, document) => {
22339
23114
  const fs16 = getSyncFs();
22340
23115
  if (!fs16) return;
22341
23116
  const validated = validateContinuityDocument(document);
22342
23117
  await fs16.promises.mkdir(resolveUserContinuityDir(), { recursive: true });
22343
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
23118
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
22344
23119
  try {
22345
23120
  await fs16.promises.writeFile(temporary, `${JSON.stringify(validated, null, 2)}
22346
23121
  `, "utf8");
22347
- await fs16.promises.rename(temporary, path10);
23122
+ await fs16.promises.rename(temporary, path11);
22348
23123
  } catch (error) {
22349
23124
  await fs16.promises.rm(temporary, { force: true }).catch(() => void 0);
22350
23125
  throw error;