dotmem 0.3.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/agent.cjs CHANGED
@@ -2,21 +2,24 @@
2
2
 
3
3
  var memorio = require('memorio');
4
4
  var crypto5 = require('crypto');
5
- var fs = require('fs');
6
- var path8 = require('path');
5
+ var fs6 = require('fs');
6
+ var path5 = require('path');
7
7
  var url = require('url');
8
8
  var fs14 = require('fs/promises');
9
9
  var child_process = require('child_process');
10
+ var os = require('os');
10
11
  require('@noble/post-quantum/ml-dsa.js');
11
12
  var hybrid_js = require('@noble/post-quantum/hybrid.js');
12
13
  var module$1 = require('module');
14
+ require('reflect-metadata');
15
+ var typeorm = require('typeorm');
13
16
 
14
17
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
15
18
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
16
19
 
17
20
  var crypto5__default = /*#__PURE__*/_interopDefault(crypto5);
18
- var fs__default = /*#__PURE__*/_interopDefault(fs);
19
- var path8__default = /*#__PURE__*/_interopDefault(path8);
21
+ var fs6__default = /*#__PURE__*/_interopDefault(fs6);
22
+ var path5__default = /*#__PURE__*/_interopDefault(path5);
20
23
  var fs14__default = /*#__PURE__*/_interopDefault(fs14);
21
24
 
22
25
  var __defProp = Object.defineProperty;
@@ -24,12 +27,6 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
24
27
  var __getOwnPropNames = Object.getOwnPropertyNames;
25
28
  var __hasOwnProp = Object.prototype.hasOwnProperty;
26
29
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
27
- var __require = /* @__PURE__ */ ((x3) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x3, {
28
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
29
- }) : x3)(function(x3) {
30
- if (typeof require !== "undefined") return require.apply(this, arguments);
31
- throw Error('Dynamic require of "' + x3 + '" is not supported');
32
- });
33
30
  var __esm = (fn, res, err3) => function __init() {
34
31
  if (err3) throw err3[0];
35
32
  try {
@@ -51,6 +48,14 @@ var __copyProps = (to, from, except, desc) => {
51
48
  return to;
52
49
  };
53
50
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
51
+ var __decorateClass = (decorators, target, key, kind) => {
52
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
53
+ for (var i3 = decorators.length - 1, decorator; i3 >= 0; i3--)
54
+ if (decorator = decorators[i3])
55
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
56
+ if (kind && result) __defProp(target, key, result);
57
+ return result;
58
+ };
54
59
 
55
60
  // core/suppress-idb-warn.ts
56
61
  var origWarn;
@@ -864,18 +869,18 @@ var init_storage_settings = __esm({
864
869
  throw invalidSettings(file2, "must contain a JSON object");
865
870
  }
866
871
  const document = parsed;
867
- const unknownFields = Object.keys(document).filter((key) => key !== "storage");
868
- if (unknownFields.length > 0) {
869
- throw invalidSettings(file2, `contains unsupported top-level fields (${unknownFields.join(", ")})`);
872
+ const anyFields = Object.keys(document).filter((key) => key !== "storage");
873
+ if (anyFields.length > 0) {
874
+ throw invalidSettings(file2, `contains unsupported top-level fields (${anyFields.join(", ")})`);
870
875
  }
871
876
  const storage = document.storage;
872
877
  if (storage === void 0) return {};
873
878
  if (!storage || typeof storage !== "object" || Array.isArray(storage)) {
874
879
  throw invalidSettings(file2, "has a storage field that is not an object");
875
880
  }
876
- const unknownStorageFields = Object.keys(storage).filter((key) => key !== "root" && key !== "mode");
877
- if (unknownStorageFields.length > 0) {
878
- throw invalidSettings(file2, `storage contains unsupported fields (${unknownStorageFields.join(", ")})`);
881
+ const anyStorageFields = Object.keys(storage).filter((key) => key !== "root" && key !== "mode");
882
+ if (anyStorageFields.length > 0) {
883
+ throw invalidSettings(file2, `storage contains unsupported fields (${anyStorageFields.join(", ")})`);
879
884
  }
880
885
  if (storage.mode !== void 0 && (typeof storage.mode !== "string" || !SETTINGS_MODES.includes(storage.mode))) {
881
886
  throw invalidSettings(file2, `storage.mode must be one of ${SETTINGS_MODES.join(", ")} (received ${JSON.stringify(storage.mode)})`);
@@ -923,7 +928,7 @@ var init_storage_settings = __esm({
923
928
  if (code === "EACCES" || code === "EPERM") {
924
929
  throw invalidSettings(file2, `cannot be read (${code})`);
925
930
  }
926
- throw invalidSettings(file2, `cannot be read (${code ?? "unknown error"})`);
931
+ throw invalidSettings(file2, `cannot be read (${code ?? "any error"})`);
927
932
  }
928
933
  return raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw;
929
934
  }, "readTextFile");
@@ -972,7 +977,7 @@ var init_text_encoding = __esm({
972
977
  decodeText = /* @__PURE__ */ __name((bytes, options = {}) => {
973
978
  const bom = detectBom(bytes);
974
979
  if (bom === "utf-16le" || bom === "utf-16be") {
975
- 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.`);
980
+ 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.`);
976
981
  }
977
982
  let content = bytes;
978
983
  if (bom === "utf-8") {
@@ -1055,7 +1060,7 @@ var init_storage_location = __esm({
1055
1060
  if (code === "ENOENT") return "the directory does not exist";
1056
1061
  if (code === "EACCES" || code === "EPERM") return `the directory is not accessible (${code})`;
1057
1062
  if (code === "ENOTDIR") return "the path is not a directory";
1058
- return `the directory cannot be accessed (${code ?? "unknown error"})`;
1063
+ return `the directory cannot be accessed (${code ?? "any error"})`;
1059
1064
  }, "describeAccessFailure");
1060
1065
  validateConfiguredStorageRoot = /* @__PURE__ */ __name((value, source) => {
1061
1066
  if (typeof value !== "string" || !value.trim()) {
@@ -1106,9 +1111,9 @@ var init_storage_location = __esm({
1106
1111
  throw new DotMemStorageLocationError(`dotmem storage location cannot be resolved: the user locator file at ${locatorFile} must contain a JSON object.`);
1107
1112
  }
1108
1113
  const locator = parsed;
1109
- const unknownFields = Object.keys(locator).filter((key) => key !== "version" && key !== "storageRoot");
1110
- if (unknownFields.length > 0) {
1111
- 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.`);
1114
+ const anyFields = Object.keys(locator).filter((key) => key !== "version" && key !== "storageRoot");
1115
+ if (anyFields.length > 0) {
1116
+ 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.`);
1112
1117
  }
1113
1118
  if (locator.version !== DOTMEM_STORAGE_LOCATOR_VERSION) {
1114
1119
  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}.`);
@@ -1456,22 +1461,22 @@ var init_conversation_events = __esm({
1456
1461
  const fs16 = fsSync();
1457
1462
  if (fs16) {
1458
1463
  try {
1459
- const path10 = EVENTS_FILE();
1460
- const parent = path10.substring(0, Math.max(path10.lastIndexOf("/"), path10.lastIndexOf("\\")));
1464
+ const path11 = EVENTS_FILE();
1465
+ const parent = path11.substring(0, Math.max(path11.lastIndexOf("/"), path11.lastIndexOf("\\")));
1461
1466
  try {
1462
1467
  fs16.mkdirSync(parent, { recursive: true });
1463
1468
  } catch {
1464
1469
  }
1465
- const tmp = `${path10}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
1470
+ const tmp = `${path11}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
1466
1471
  fs16.writeFileSync(tmp, JSON.stringify(events));
1467
1472
  try {
1468
- if (fs16.existsSync(path10)) fs16.copyFileSync(path10, `${path10}.bak`);
1473
+ if (fs16.existsSync(path11)) fs16.copyFileSync(path11, `${path11}.bak`);
1469
1474
  } catch {
1470
1475
  }
1471
1476
  try {
1472
- fs16.renameSync(tmp, path10);
1477
+ fs16.renameSync(tmp, path11);
1473
1478
  } catch {
1474
- fs16.copyFileSync(tmp, path10);
1479
+ fs16.copyFileSync(tmp, path11);
1475
1480
  try {
1476
1481
  fs16.unlinkSync(tmp);
1477
1482
  } catch {
@@ -1612,8 +1617,8 @@ var init_conversation_events = __esm({
1612
1617
  try {
1613
1618
  const fs16 = fsSync();
1614
1619
  if (fs16) {
1615
- const path10 = EVENTS_FILE();
1616
- const parent = path10.substring(0, Math.max(path10.lastIndexOf("/"), path10.lastIndexOf("\\")));
1620
+ const path11 = EVENTS_FILE();
1621
+ const parent = path11.substring(0, Math.max(path11.lastIndexOf("/"), path11.lastIndexOf("\\")));
1617
1622
  return await withStorageLock(parent, run);
1618
1623
  }
1619
1624
  } catch {
@@ -1834,7 +1839,7 @@ var init_freshness = __esm({
1834
1839
  evaluateRef = /* @__PURE__ */ __name((ref, current) => {
1835
1840
  if (ref.version !== void 0 && current.version !== void 0 && ref.version !== current.version) return "changed";
1836
1841
  if (ref.digest !== void 0 && current.digest !== void 0 && ref.digest !== current.digest) return "changed";
1837
- if (ref.version === void 0 && current.version === void 0 && ref.digest === void 0 && current.digest === void 0) return "unknown";
1842
+ if (ref.version === void 0 && current.version === void 0 && ref.digest === void 0 && current.digest === void 0) return "any";
1838
1843
  return "same";
1839
1844
  }, "evaluateRef");
1840
1845
  evaluateFreshness = /* @__PURE__ */ __name((input) => {
@@ -1842,10 +1847,10 @@ var init_freshness = __esm({
1842
1847
  return { state: "stale", reason: "explicit invalidation", checkedAt: input.checkedAt };
1843
1848
  }
1844
1849
  if (input.sourceRefs.length === 0) {
1845
- return { state: "unknown", reason: "no source references recorded", checkedAt: input.checkedAt };
1850
+ return { state: "any", reason: "no source references recorded", checkedAt: input.checkedAt };
1846
1851
  }
1847
1852
  const staleReasons = [];
1848
- let unknown = false;
1853
+ let any = false;
1849
1854
  for (const ref of input.sourceRefs) {
1850
1855
  const current = input.currentSources.find((candidate) => candidate.kind === ref.kind && candidate.id === ref.id);
1851
1856
  if (!current) {
@@ -1857,15 +1862,15 @@ var init_freshness = __esm({
1857
1862
  staleReasons.push(`${ref.kind}:${ref.id} version ${ref.version ?? "?"} -> ${current.version ?? "?"}, digest ${ref.digest ?? "?"} -> ${current.digest ?? "?"}`);
1858
1863
  continue;
1859
1864
  }
1860
- if (comparison === "unknown") {
1861
- unknown = true;
1865
+ if (comparison === "any") {
1866
+ any = true;
1862
1867
  }
1863
1868
  }
1864
1869
  if (staleReasons.length > 0) {
1865
1870
  return { state: "stale", reason: staleReasons.join("; "), checkedAt: input.checkedAt };
1866
1871
  }
1867
- if (unknown) {
1868
- return { state: "unknown", reason: "sources without comparable identity", checkedAt: input.checkedAt };
1872
+ if (any) {
1873
+ return { state: "any", reason: "sources without comparable identity", checkedAt: input.checkedAt };
1869
1874
  }
1870
1875
  return { state: "fresh", checkedAt: input.checkedAt };
1871
1876
  }, "evaluateFreshness");
@@ -1988,31 +1993,31 @@ var init_store = __esm({
1988
1993
  snapshots: document.snapshots
1989
1994
  };
1990
1995
  }, "validateContinuityDocument");
1991
- deleteContinuityArtifact = /* @__PURE__ */ __name(async (path10) => {
1996
+ deleteContinuityArtifact = /* @__PURE__ */ __name(async (path11) => {
1992
1997
  const fs16 = getSyncFs();
1993
1998
  if (!fs16) return;
1994
- await fs16.promises.rm(path10, { force: true });
1999
+ await fs16.promises.rm(path11, { force: true });
1995
2000
  }, "deleteContinuityArtifact");
1996
- loadContinuityDocument = /* @__PURE__ */ __name(async (path10) => {
2001
+ loadContinuityDocument = /* @__PURE__ */ __name(async (path11) => {
1997
2002
  const fs16 = getSyncFs();
1998
2003
  if (!fs16) return emptyContinuityDocument();
1999
2004
  try {
2000
- const raw = await fs16.promises.readFile(path10, "utf8");
2005
+ const raw = await fs16.promises.readFile(path11, "utf8");
2001
2006
  return validateContinuityDocument(JSON.parse(raw));
2002
2007
  } catch {
2003
2008
  return emptyContinuityDocument();
2004
2009
  }
2005
2010
  }, "loadContinuityDocument");
2006
- saveContinuityDocument = /* @__PURE__ */ __name(async (path10, document) => {
2011
+ saveContinuityDocument = /* @__PURE__ */ __name(async (path11, document) => {
2007
2012
  const fs16 = getSyncFs();
2008
2013
  if (!fs16) return;
2009
2014
  const validated = validateContinuityDocument(document);
2010
2015
  await fs16.promises.mkdir(resolveUserContinuityDir(), { recursive: true });
2011
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
2016
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
2012
2017
  try {
2013
2018
  await fs16.promises.writeFile(temporary, `${JSON.stringify(validated, null, 2)}
2014
2019
  `, "utf8");
2015
- await fs16.promises.rename(temporary, path10);
2020
+ await fs16.promises.rename(temporary, path11);
2016
2021
  } catch (error) {
2017
2022
  await fs16.promises.rm(temporary, { force: true }).catch(() => void 0);
2018
2023
  throw error;
@@ -2058,9 +2063,9 @@ var init_policy_namespace_lock = __esm({
2058
2063
  currentHost = /* @__PURE__ */ __name(async () => {
2059
2064
  try {
2060
2065
  const os = await import('os');
2061
- return typeof os.hostname === "function" && os.hostname() ? os.hostname() : "unknown";
2066
+ return typeof os.hostname === "function" && os.hostname() ? os.hostname() : "any";
2062
2067
  } catch {
2063
- return "unknown";
2068
+ return "any";
2064
2069
  }
2065
2070
  }, "currentHost");
2066
2071
  delay = /* @__PURE__ */ __name(async (milliseconds) => {
@@ -2079,7 +2084,7 @@ var init_policy_namespace_lock = __esm({
2079
2084
  if (!parsed || typeof parsed !== "object") return null;
2080
2085
  return {
2081
2086
  pid: typeof parsed.pid === "number" ? parsed.pid : 0,
2082
- host: typeof parsed.host === "string" ? parsed.host : "unknown",
2087
+ host: typeof parsed.host === "string" ? parsed.host : "any",
2083
2088
  acquiredAt: typeof parsed.acquiredAt === "string" ? parsed.acquiredAt : "",
2084
2089
  token: typeof parsed.token === "string" ? parsed.token : ""
2085
2090
  };
@@ -2102,7 +2107,7 @@ var init_policy_namespace_lock = __esm({
2102
2107
  const acquiredAt = held ? Date.parse(held.acquiredAt) : Number.NaN;
2103
2108
  const age = Number.isFinite(acquiredAt) ? Date.now() - acquiredAt : Number.POSITIVE_INFINITY;
2104
2109
  if (age > POLICY_LOCK_TTL_MS) {
2105
- const stale = held ?? { pid: 0, host: "unknown", acquiredAt: "", token: "" };
2110
+ const stale = held ?? { pid: 0, host: "any", acquiredAt: "", token: "" };
2106
2111
  const outcome = await breakStalePolicyLock(fs16, lockPath, stale);
2107
2112
  if (outcome === "broken") {
2108
2113
  brokenOwner = stale;
@@ -2119,7 +2124,7 @@ var init_policy_namespace_lock = __esm({
2119
2124
  throw new PolicyNamespaceLockError(`Policy namespace lock could not be acquired after ${POLICY_LOCK_RETRY_ATTEMPTS} bounded retries; policy mutation fails closed`);
2120
2125
  }, "acquireLock");
2121
2126
  breakStalePolicyLock = /* @__PURE__ */ __name(async (fs16, lockPath, staleOwner) => {
2122
- const candidate = `${lockPath}.breaking-${staleOwner.token || "unknown"}`;
2127
+ const candidate = `${lockPath}.breaking-${staleOwner.token || "any"}`;
2123
2128
  try {
2124
2129
  await fs16.rename(lockPath, candidate);
2125
2130
  } catch (error) {
@@ -2341,11 +2346,11 @@ var init_state = __esm({
2341
2346
  if (evidence.length === 0) return;
2342
2347
  for (let index = 0; index < evidence.length; index++) {
2343
2348
  const entry = evidence[index];
2344
- const path10 = `evidence[${index}]`;
2349
+ const path11 = `evidence[${index}]`;
2345
2350
  if (Array.isArray(entry)) {
2346
2351
  throw canonicalEvidenceError({
2347
2352
  claimId: claim.id,
2348
- path: path10,
2353
+ path: path11,
2349
2354
  problem: CANONICAL_EVIDENCE_PROBLEMS.tupleEntry,
2350
2355
  received: entry,
2351
2356
  fix: CANONICAL_EVIDENCE_FIX.tupleEntry
@@ -2354,7 +2359,7 @@ var init_state = __esm({
2354
2359
  if (!entry || typeof entry !== "object") {
2355
2360
  throw canonicalEvidenceError({
2356
2361
  claimId: claim.id,
2357
- path: path10,
2362
+ path: path11,
2358
2363
  problem: CANONICAL_EVIDENCE_PROBLEMS.nonObjectEntry,
2359
2364
  received: entry,
2360
2365
  fix: CANONICAL_EVIDENCE_FIX.nonObjectEntry
@@ -2363,7 +2368,7 @@ var init_state = __esm({
2363
2368
  if (!requiredText(entry.id)) {
2364
2369
  throw canonicalEvidenceError({
2365
2370
  claimId: claim.id,
2366
- path: `${path10}.id`,
2371
+ path: `${path11}.id`,
2367
2372
  problem: CANONICAL_EVIDENCE_PROBLEMS.missingId,
2368
2373
  received: entry,
2369
2374
  fix: CANONICAL_EVIDENCE_FIX.missingId
@@ -2374,7 +2379,7 @@ var init_state = __esm({
2374
2379
  if (fieldValue !== void 0 && !requiredText(fieldValue)) {
2375
2380
  throw canonicalEvidenceError({
2376
2381
  claimId: claim.id,
2377
- path: `${path10}.${field}`,
2382
+ path: `${path11}.${field}`,
2378
2383
  problem: CANONICAL_EVIDENCE_PROBLEMS.invalidOptionalField(field),
2379
2384
  received: fieldValue,
2380
2385
  fix: CANONICAL_EVIDENCE_FIX.invalidOptionalField(field)
@@ -2437,7 +2442,7 @@ var init_state = __esm({
2437
2442
  if (options?.allowUnresolvedRevisions !== true) {
2438
2443
  for (const claim of state3.claims) {
2439
2444
  for (const relatedId of claim.revision?.claimIds || []) {
2440
- if (!ids.has(relatedId)) throw new Error(`Claim ${claim.id} references unknown claim ${relatedId}`);
2445
+ if (!ids.has(relatedId)) throw new Error(`Claim ${claim.id} references any claim ${relatedId}`);
2441
2446
  }
2442
2447
  }
2443
2448
  }
@@ -2461,7 +2466,7 @@ var init_state = __esm({
2461
2466
  }
2462
2467
  for (const claim of update.claims) {
2463
2468
  for (const relatedId of claim.revision?.claimIds || []) {
2464
- if (!known.has(relatedId)) throw new Error(`Claim ${claim.id} references unknown prior claim ${relatedId}`);
2469
+ if (!known.has(relatedId)) throw new Error(`Claim ${claim.id} references any prior claim ${relatedId}`);
2465
2470
  }
2466
2471
  }
2467
2472
  return structuredClone({ version: state3.version + 1, claims: [...state3.claims, ...update.claims] });
@@ -3194,7 +3199,7 @@ var init_policy_store = __esm({
3194
3199
  authority: { kind: "system", source: "policy-namespace-lock" },
3195
3200
  target: resolvePolicyNamespaceLockPath(directory),
3196
3201
  outcome: "applied",
3197
- detail: `stale policy namespace lock broken; previous owner pid ${lockBreak.brokenOwner.pid} host ${lockBreak.brokenOwner.host} acquiredAt ${lockBreak.brokenOwner.acquiredAt || "unknown"}`
3202
+ detail: `stale policy namespace lock broken; previous owner pid ${lockBreak.brokenOwner.pid} host ${lockBreak.brokenOwner.host} acquiredAt ${lockBreak.brokenOwner.acquiredAt || "any"}`
3198
3203
  })
3199
3204
  );
3200
3205
  next = { ...next, audit: boundedAudit([...next.audit, ...breakEntries], next.overrides) };
@@ -3514,7 +3519,7 @@ var init_policy_store = __esm({
3514
3519
  });
3515
3520
 
3516
3521
  // core/knowledge/sanitizer.ts
3517
- var SECRET_KEY_INDICATORS, isSecretKey, looksLikeSecretValue, looksLikeMojibake, collectMojibake, semanticizeSecret, sanitizeObject, sanitizeArray, sanitizeKnowledge;
3522
+ var SECRET_KEY_INDICATORS, isSecretKey, looksLikeSecretValue, looksLikeMojibake, collectMojibake, semanticizeSecret, sanitizeObject, sanitizeArray, sanitizeKnowledge, createSanitizedEnv;
3518
3523
  var init_sanitizer = __esm({
3519
3524
  "core/knowledge/sanitizer.ts"() {
3520
3525
  SECRET_KEY_INDICATORS = ["password", "passwd", "pwd", "secret", "apikey", "api_key", "token", "accesstoken", "refreshtoken", "privatekey", "private_key", "clientsecret", "authorization", "bearer", "credential", "credentials", "recoverycode", "sessionsecret", "jwtsecret"];
@@ -3639,6 +3644,15 @@ var init_sanitizer = __esm({
3639
3644
  disposition: "persist"
3640
3645
  };
3641
3646
  }, "sanitizeKnowledge");
3647
+ createSanitizedEnv = /* @__PURE__ */ __name(() => {
3648
+ const env = {};
3649
+ for (const [key, value] of Object.entries(process.env)) {
3650
+ if (isSecretKey(key)) continue;
3651
+ if (value === void 0 || value === null) continue;
3652
+ env[key] = value;
3653
+ }
3654
+ return env;
3655
+ }, "createSanitizedEnv");
3642
3656
  }
3643
3657
  });
3644
3658
 
@@ -3790,7 +3804,7 @@ var init_built_in_context = __esm({
3790
3804
  return __dirname;
3791
3805
  }
3792
3806
  try {
3793
- return path8__default.default.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('agent.cjs', document.baseURI).href))));
3807
+ return path5__default.default.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('agent.cjs', document.baseURI).href))));
3794
3808
  } catch {
3795
3809
  return process.cwd();
3796
3810
  }
@@ -3798,7 +3812,7 @@ var init_built_in_context = __esm({
3798
3812
  candidatePaths = /* @__PURE__ */ __name(() => {
3799
3813
  const paths = [];
3800
3814
  try {
3801
- paths.push(path8__default.default.join(pkgDirname(), "built-in-context.json"));
3815
+ paths.push(path5__default.default.join(pkgDirname(), "built-in-context.json"));
3802
3816
  } catch {
3803
3817
  }
3804
3818
  return paths;
@@ -3867,11 +3881,11 @@ var init_built_in_context = __esm({
3867
3881
  let lastError = "Built-in context artifact not found";
3868
3882
  const candidates = _artifactPathOverride ? [_artifactPathOverride] : candidatePaths();
3869
3883
  for (const candidate of candidates) {
3870
- if (!fs__default.default.existsSync(candidate)) continue;
3884
+ if (!fs6__default.default.existsSync(candidate)) continue;
3871
3885
  let readAttempts = 0;
3872
3886
  while (readAttempts < 60) {
3873
3887
  try {
3874
- const raw = fs__default.default.readFileSync(candidate);
3888
+ const raw = fs6__default.default.readFileSync(candidate);
3875
3889
  const parsed = JSON.parse(decodeText(raw, { source: candidate }));
3876
3890
  const artifact = validateArtifact(parsed);
3877
3891
  cached = artifact;
@@ -3908,15 +3922,15 @@ var init_built_in_context = __esm({
3908
3922
  }
3909
3923
  let attemptedPath = "";
3910
3924
  try {
3911
- attemptedPath = path8__default.default.join(pkgDirname(), "built-in-context.json");
3925
+ attemptedPath = path5__default.default.join(pkgDirname(), "built-in-context.json");
3912
3926
  } catch {
3913
3927
  }
3914
- let packageVersion = "unknown";
3928
+ let packageVersion = "any";
3915
3929
  try {
3916
- const pkgPath = path8__default.default.join(pkgDirname(), "package.json");
3917
- if (fs__default.default.existsSync(pkgPath)) {
3918
- const pkg = JSON.parse(fs__default.default.readFileSync(pkgPath, "utf8"));
3919
- packageVersion = typeof pkg.version === "string" ? pkg.version : "unknown";
3930
+ const pkgPath = path5__default.default.join(pkgDirname(), "package.json");
3931
+ if (fs6__default.default.existsSync(pkgPath)) {
3932
+ const pkg = JSON.parse(fs6__default.default.readFileSync(pkgPath, "utf8"));
3933
+ packageVersion = typeof pkg.version === "string" ? pkg.version : "any";
3920
3934
  }
3921
3935
  } catch {
3922
3936
  }
@@ -5517,14 +5531,14 @@ var init_mem_package = __esm({
5517
5531
  const digest = await globalThis.crypto.subtle.digest("SHA-256", data);
5518
5532
  return `sha256:${[...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
5519
5533
  }, "sha256");
5520
- parseJson = /* @__PURE__ */ __name((bytes, path10) => {
5534
+ parseJson = /* @__PURE__ */ __name((bytes, path11) => {
5521
5535
  try {
5522
5536
  return JSON.parse(decodeText(bytes));
5523
5537
  } catch (error) {
5524
- throw new MemArtifactError("invalid", `Invalid UTF-8 JSON in ${path10}: ${error.message}`);
5538
+ throw new MemArtifactError("invalid", `Invalid UTF-8 JSON in ${path11}: ${error.message}`);
5525
5539
  }
5526
5540
  }, "parseJson");
5527
- 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");
5541
+ 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");
5528
5542
  concatenate = /* @__PURE__ */ __name((chunks, size) => {
5529
5543
  const result = new Uint8Array(size);
5530
5544
  let offset = 0;
@@ -5600,24 +5614,24 @@ var init_mem_package = __esm({
5600
5614
  [DATA_PATH]: jsonBytes(memory2.data),
5601
5615
  ...structuredClone(preservedPackage?.extensions ?? {})
5602
5616
  };
5603
- for (const path10 of Object.keys(protectedParts)) {
5604
- if (!requiredParts.includes(path10) && !path10.startsWith("extensions/")) {
5605
- throw new MemArtifactError("invalid", `Unsupported preserved package part: ${path10}`);
5617
+ for (const path11 of Object.keys(protectedParts)) {
5618
+ if (!requiredParts.includes(path11) && !path11.startsWith("extensions/")) {
5619
+ throw new MemArtifactError("invalid", `Unsupported preserved package part: ${path11}`);
5606
5620
  }
5607
- if (!validEntryPath(path10)) throw new MemArtifactError("invalid", `Unsafe MEM package path: ${path10}`);
5621
+ if (!validEntryPath(path11)) throw new MemArtifactError("invalid", `Unsafe MEM package path: ${path11}`);
5608
5622
  }
5609
- for (const path10 of Object.keys(signatures)) {
5610
- if (!/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path10)) {
5611
- throw new MemArtifactError("invalid", `Invalid MEM signature path: ${path10}`);
5623
+ for (const path11 of Object.keys(signatures)) {
5624
+ if (!/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path11)) {
5625
+ throw new MemArtifactError("invalid", `Invalid MEM signature path: ${path11}`);
5612
5626
  }
5613
5627
  }
5614
5628
  const files = {};
5615
- for (const path10 of Object.keys(protectedParts).sort()) files[path10] = await sha2562(protectedParts[path10]);
5629
+ for (const path11 of Object.keys(protectedParts).sort()) files[path11] = await sha2562(protectedParts[path11]);
5616
5630
  const integrity = { algorithm: "sha256", files, contentId: await digestTableIdentity(files) };
5617
5631
  const parts = { ...protectedParts, [INTEGRITY_PATH]: jsonBytes(integrity), ...signatures };
5618
- for (const [path10, bytes] of Object.entries(parts)) {
5632
+ for (const [path11, bytes] of Object.entries(parts)) {
5619
5633
  if (bytes.length > MEM_PACKAGE_WRITE_LIMITS.maximumEntryBytes) {
5620
- throw new MemArtifactError("invalid", `MEM package entry exceeds the write limit: ${path10}`);
5634
+ throw new MemArtifactError("invalid", `MEM package entry exceeds the write limit: ${path11}`);
5621
5635
  }
5622
5636
  }
5623
5637
  const uncompressedBytes = Object.values(parts).reduce((total, bytes) => total + bytes.length, 0);
@@ -5625,10 +5639,10 @@ var init_mem_package = __esm({
5625
5639
  throw new MemArtifactError("invalid", "MEM package exceeds the write limit for uncompressed content");
5626
5640
  }
5627
5641
  const zippable = Object.fromEntries(
5628
- Object.keys(parts).sort().map((path10) => [
5629
- path10,
5642
+ Object.keys(parts).sort().map((path11) => [
5643
+ path11,
5630
5644
  [
5631
- parts[path10],
5645
+ parts[path11],
5632
5646
  {
5633
5647
  level: 6,
5634
5648
  mtime: /* @__PURE__ */ new Date("1980-01-02T00:00:00.000Z")
@@ -5648,8 +5662,8 @@ var init_mem_package = __esm({
5648
5662
  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");
5649
5663
  decodePackage = /* @__PURE__ */ __name(async (bytes) => {
5650
5664
  const parts = readZipParts(bytes);
5651
- for (const path10 of [...requiredParts, INTEGRITY_PATH]) {
5652
- if (!parts[path10]) throw new MemArtifactError("invalid", `Missing MEM package part: ${path10}`);
5665
+ for (const path11 of [...requiredParts, INTEGRITY_PATH]) {
5666
+ if (!parts[path11]) throw new MemArtifactError("invalid", `Missing MEM package part: ${path11}`);
5653
5667
  }
5654
5668
  const manifest = parseJson(parts[MANIFEST_PATH], MANIFEST_PATH);
5655
5669
  if (manifest.format !== MEM_PACKAGE_FORMAT && manifest.format !== MEM_PACKAGE_FORMAT_LEGACY || manifest.version !== MEM_PACKAGE_VERSION) {
@@ -5660,8 +5674,8 @@ var init_mem_package = __esm({
5660
5674
  }
5661
5675
  const integrity = parseJson(parts[INTEGRITY_PATH], INTEGRITY_PATH);
5662
5676
  if (integrity.algorithm !== "sha256") throw new MemArtifactError("unsupported", "Unsupported MEM package integrity algorithm");
5663
- const signaturePaths = Object.keys(parts).filter((path10) => path10.startsWith("security/signatures/")).sort();
5664
- if (signaturePaths.some((path10) => !/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path10))) {
5677
+ const signaturePaths = Object.keys(parts).filter((path11) => path11.startsWith("security/signatures/")).sort();
5678
+ if (signaturePaths.some((path11) => !/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path11))) {
5665
5679
  throw new MemArtifactError("invalid", "Invalid MEM signature entry path");
5666
5680
  }
5667
5681
  if (manifest.authenticity !== void 0 && manifest.authenticity.signed !== true) {
@@ -5670,14 +5684,14 @@ var init_mem_package = __esm({
5670
5684
  if (manifest.authenticity?.signed === true !== signaturePaths.length > 0) {
5671
5685
  throw new MemArtifactError("invalid", "Declared MEM signatures do not match package entries");
5672
5686
  }
5673
- const archivePaths = Object.keys(parts).filter((path10) => path10 !== INTEGRITY_PATH && !path10.startsWith("security/signatures/")).sort();
5687
+ const archivePaths = Object.keys(parts).filter((path11) => path11 !== INTEGRITY_PATH && !path11.startsWith("security/signatures/")).sort();
5674
5688
  const protectedPaths = Object.keys(integrity.files ?? {}).sort();
5675
5689
  if (JSON.stringify(archivePaths) !== JSON.stringify(protectedPaths)) {
5676
5690
  throw new MemArtifactError("invalid", "MEM package protected-parts table does not match archive contents");
5677
5691
  }
5678
- for (const path10 of protectedPaths) {
5679
- const actual = await sha2562(parts[path10]);
5680
- if (integrity.files[path10] !== actual) throw new MemArtifactError("checksum_mismatch", `Checksum mismatch for ${path10}`);
5692
+ for (const path11 of protectedPaths) {
5693
+ const actual = await sha2562(parts[path11]);
5694
+ if (integrity.files[path11] !== actual) throw new MemArtifactError("checksum_mismatch", `Checksum mismatch for ${path11}`);
5681
5695
  }
5682
5696
  if (integrity.contentId !== await digestTableIdentity(integrity.files)) {
5683
5697
  throw new MemArtifactError("checksum_mismatch", "MEM package content identity mismatch");
@@ -5690,8 +5704,8 @@ var init_mem_package = __esm({
5690
5704
  } catch (error) {
5691
5705
  throw new MemArtifactError("invalid", `Invalid packaged MEM semantics: ${error.message}`);
5692
5706
  }
5693
- const extensions = Object.fromEntries(Object.entries(parts).filter(([path10]) => path10.startsWith("extensions/")));
5694
- const signatures = Object.fromEntries(signaturePaths.map((path10) => [path10, parts[path10]]));
5707
+ const extensions = Object.fromEntries(Object.entries(parts).filter(([path11]) => path11.startsWith("extensions/")));
5708
+ const signatures = Object.fromEntries(signaturePaths.map((path11) => [path11, parts[path11]]));
5695
5709
  return { ...decoded, representation: "package-v1", package: { manifest, extensions, signatures }, parts, integrity };
5696
5710
  }, "decodePackage");
5697
5711
  decodeMemArtifact = /* @__PURE__ */ __name(async (input) => {
@@ -5730,13 +5744,13 @@ var init_quarantine = __esm({
5730
5744
  quarantineClaimRecord = /* @__PURE__ */ __name(async (record) => {
5731
5745
  if (!record.filePath) return null;
5732
5746
  try {
5733
- const dir = path8__default.default.dirname(record.filePath);
5734
- const quarantineDir = path8__default.default.join(dir, "quarantine");
5747
+ const dir = path5__default.default.dirname(record.filePath);
5748
+ const quarantineDir = path5__default.default.join(dir, "quarantine");
5735
5749
  await fs14__default.default.mkdir(quarantineDir, { recursive: true });
5736
- const safeId = String(record.claimId ?? "unknown").replace(/[^a-zA-Z0-9._-]/g, "-");
5750
+ const safeId = String(record.claimId ?? "any").replace(/[^a-zA-Z0-9._-]/g, "-");
5737
5751
  const timestamp = record.timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
5738
5752
  const fileName = `${safeId}-${Date.now()}.json`;
5739
- const fullPath = path8__default.default.join(quarantineDir, fileName);
5753
+ const fullPath = path5__default.default.join(quarantineDir, fileName);
5740
5754
  const payload = {
5741
5755
  claimId: record.claimId,
5742
5756
  store: record.store,
@@ -5777,7 +5791,7 @@ var init_store_registry = __esm({
5777
5791
  }
5778
5792
  for (const dirent of dirents) {
5779
5793
  if (!dirent.isFile()) continue;
5780
- const filePath = path8__default.default.join(directory, dirent.name);
5794
+ const filePath = path5__default.default.join(directory, dirent.name);
5781
5795
  if (isMemFile(dirent.name)) {
5782
5796
  entries2.push({ id: dirent.name, path: filePath, kind: "active", active: true, reason: "active .mem store" });
5783
5797
  continue;
@@ -5940,7 +5954,7 @@ var init_claim_delete = __esm({
5940
5954
  }
5941
5955
  let deleted = false;
5942
5956
  for (const location of selected) {
5943
- await withStorageLock(path8__default.default.dirname(location.filePath), async () => {
5957
+ await withStorageLock(path5__default.default.dirname(location.filePath), async () => {
5944
5958
  const bytes = await fs14__default.default.readFile(location.filePath);
5945
5959
  const artifact = await decodeMemArtifact(bytes);
5946
5960
  if (!artifact.state) throw new Error(`Unable to read store ${location.filePath}`);
@@ -6421,31 +6435,6 @@ var init_mem_repository = __esm({
6421
6435
  };
6422
6436
  }
6423
6437
  });
6424
- function parseProbe(probe) {
6425
- if (!probe) return null;
6426
- if (typeof probe === "string") {
6427
- const parts = probe.trim().split(/\s+/);
6428
- return { type: parts[0], args: parts.slice(1) };
6429
- }
6430
- if (typeof probe === "object") {
6431
- const type = String(probe.type ?? probe.kind ?? probe.name ?? "");
6432
- if (type === "file-exists") return { type, args: [String(probe.path ?? probe.file ?? probe.target ?? "")] };
6433
- if (type === "file-contains") return { type, args: [String(probe.path ?? probe.file ?? ""), String(probe.literal ?? probe.contains ?? probe.value ?? "")] };
6434
- if (type === "json-path") return { type, args: [String(probe.file ?? probe.path ?? ""), String(probe.path ?? probe.jsonPath ?? ""), String(probe.expected ?? probe.value ?? "")] };
6435
- 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) };
6436
- return { type, args: [] };
6437
- }
6438
- return null;
6439
- }
6440
- function allowlist() {
6441
- try {
6442
- const raw = fs__default.default.readFileSync(`${resolveUserDotMemPath()}/probe-allowlist.json`, "utf8");
6443
- const parsed = JSON.parse(raw);
6444
- if (Array.isArray(parsed)) return parsed.map(String);
6445
- } catch {
6446
- }
6447
- return ["node", "git", "bun"];
6448
- }
6449
6438
  function runProbe(probe) {
6450
6439
  const spec = parseProbe(probe);
6451
6440
  if (!spec) return true;
@@ -6455,23 +6444,54 @@ function runProbe(probe) {
6455
6444
  let ok = false;
6456
6445
  try {
6457
6446
  if (spec.type === "file-exists") {
6458
- ok = fs__default.default.existsSync(spec.args[0]);
6447
+ const target = spec.args[0];
6448
+ if (!isAuthorizedPath(target)) {
6449
+ cache.set(key, { at: Date.now(), ok: false });
6450
+ return false;
6451
+ }
6452
+ ok = fs6__default.default.existsSync(target);
6459
6453
  } else if (spec.type === "file-contains") {
6460
- const content = fs__default.default.readFileSync(spec.args[0], "utf8");
6454
+ const target = spec.args[0];
6455
+ if (!isAuthorizedPath(target)) {
6456
+ cache.set(key, { at: Date.now(), ok: false });
6457
+ return false;
6458
+ }
6459
+ const stat = fs6__default.default.statSync(target);
6460
+ if (stat.size > MAX_PROBE_FILE_BYTES) {
6461
+ cache.set(key, { at: Date.now(), ok: false });
6462
+ return false;
6463
+ }
6464
+ const content = fs6__default.default.readFileSync(target, "utf8");
6461
6465
  ok = content.includes(spec.args[1]);
6462
6466
  } else if (spec.type === "json-path") {
6463
- const obj = JSON.parse(fs__default.default.readFileSync(spec.args[0], "utf8"));
6467
+ const target = spec.args[0];
6468
+ if (!isAuthorizedPath(target)) {
6469
+ cache.set(key, { at: Date.now(), ok: false });
6470
+ return false;
6471
+ }
6472
+ const stat = fs6__default.default.statSync(target);
6473
+ if (stat.size > MAX_PROBE_FILE_BYTES) {
6474
+ cache.set(key, { at: Date.now(), ok: false });
6475
+ return false;
6476
+ }
6477
+ const obj = JSON.parse(fs6__default.default.readFileSync(target, "utf8"));
6464
6478
  const pathParts = spec.args[1].split(".");
6465
6479
  let cur = obj;
6466
6480
  for (const p of pathParts) cur = cur?.[p];
6467
6481
  ok = String(cur) === spec.args[2];
6468
6482
  } else if (spec.type === "command") {
6469
6483
  const cmd = spec.args[0];
6470
- if (!allowlist().includes(cmd)) {
6484
+ const args = spec.args.slice(1);
6485
+ if (args.some((a) => DANGEROUS_FLAGS.has(a))) {
6471
6486
  cache.set(key, { at: Date.now(), ok: false });
6472
6487
  return false;
6473
6488
  }
6474
- const res = child_process.spawnSync(cmd, spec.args.slice(1), { timeout: 5e3, encoding: "utf8", shell: false, maxBuffer: 64 * 1024 });
6489
+ const handler = isTrustedCommand(cmd, args);
6490
+ if (!handler) {
6491
+ cache.set(key, { at: Date.now(), ok: false });
6492
+ return false;
6493
+ }
6494
+ const res = child_process.spawnSync(handler.cmd, handler.args, { timeout: 5e3, encoding: "utf8", shell: false, maxBuffer: 64 * 1024, env: createSanitizedEnv() });
6475
6495
  ok = res.status === 0;
6476
6496
  } else {
6477
6497
  ok = false;
@@ -6482,12 +6502,91 @@ function runProbe(probe) {
6482
6502
  cache.set(key, { at: Date.now(), ok });
6483
6503
  return ok;
6484
6504
  }
6485
- var cache, CACHE_MS;
6505
+ var TRUSTED_PROBES, DANGEROUS_FLAGS, MAX_PROBE_FILE_BYTES, AUTHORIZED_ROOTS, isAuthorizedPath, isTrustedCommand, parseProbe, cache, CACHE_MS;
6486
6506
  var init_probe = __esm({
6487
6507
  "core/knowledge/probe.ts"() {
6488
- init_user_paths();
6489
- __name(parseProbe, "parseProbe");
6490
- __name(allowlist, "allowlist");
6508
+ init_sanitizer();
6509
+ TRUSTED_PROBES = [
6510
+ { id: "node-version", cmd: "node", args: ["--version"] },
6511
+ { id: "git-version", cmd: "git", args: ["--version"] }
6512
+ ];
6513
+ DANGEROUS_FLAGS = /* @__PURE__ */ new Set(["-e", "--eval", "-p", "--print", "-r", "--require", "--loader", "--input-type", "--experimental-vm-modules", "--experimental-loader"]);
6514
+ MAX_PROBE_FILE_BYTES = 10 * 1024 * 1024;
6515
+ AUTHORIZED_ROOTS = Array.from(/* @__PURE__ */ new Set([
6516
+ path5__default.default.resolve(process.cwd()),
6517
+ path5__default.default.resolve(os.tmpdir())
6518
+ ]));
6519
+ isAuthorizedPath = /* @__PURE__ */ __name((candidate) => {
6520
+ if (typeof candidate !== "string" || candidate.length === 0) return false;
6521
+ if (candidate.includes("\0")) return false;
6522
+ if (candidate.startsWith("\\\\") || candidate.startsWith("//")) return false;
6523
+ const resolved = path5__default.default.resolve(candidate);
6524
+ const lexicallyAllowed = AUTHORIZED_ROOTS.some((root) => {
6525
+ const rel = path5__default.default.relative(root, resolved);
6526
+ return rel === "" || !rel.startsWith("..") && !path5__default.default.isAbsolute(rel);
6527
+ });
6528
+ if (!lexicallyAllowed) return false;
6529
+ try {
6530
+ if (fs6__default.default.existsSync(resolved)) {
6531
+ const real = fs6__default.default.realpathSync(resolved);
6532
+ const reallyAllowed = AUTHORIZED_ROOTS.some((root) => {
6533
+ let realRoot = root;
6534
+ try {
6535
+ realRoot = fs6__default.default.realpathSync(root);
6536
+ } catch {
6537
+ }
6538
+ const rel = path5__default.default.relative(realRoot, real);
6539
+ return rel === "" || !rel.startsWith("..") && !path5__default.default.isAbsolute(rel);
6540
+ });
6541
+ if (!reallyAllowed) return false;
6542
+ }
6543
+ } catch {
6544
+ return false;
6545
+ }
6546
+ return true;
6547
+ }, "isAuthorizedPath");
6548
+ isTrustedCommand = /* @__PURE__ */ __name((cmd, args) => {
6549
+ return TRUSTED_PROBES.find((p) => p.cmd === cmd && JSON.stringify(p.args) === JSON.stringify(args)) ?? null;
6550
+ }, "isTrustedCommand");
6551
+ parseProbe = /* @__PURE__ */ __name((probe) => {
6552
+ if (!probe) return null;
6553
+ if (typeof probe === "string") {
6554
+ const parts = probe.trim().split(/\s+/);
6555
+ return { type: parts[0], args: parts.slice(1) };
6556
+ }
6557
+ if (typeof probe === "object") {
6558
+ const type = String(probe.type ?? probe.kind ?? probe.name ?? "");
6559
+ if (type === "file-exists") return { type, args: [String(probe.path ?? probe.file ?? probe.target ?? "")] };
6560
+ if (type === "file-contains") return { type, args: [String(probe.path ?? probe.file ?? ""), String(probe.literal ?? probe.contains ?? probe.value ?? "")] };
6561
+ if (type === "json-path") return { type, args: [String(probe.file ?? probe.path ?? ""), String(probe.path ?? probe.jsonPath ?? ""), String(probe.expected ?? probe.value ?? "")] };
6562
+ if (type === "command" || type === "probe") {
6563
+ if (typeof probe.id === "string") {
6564
+ const found = TRUSTED_PROBES.find((p) => p.id === probe.id);
6565
+ if (found) return { type: "command", args: [found.cmd, ...found.args] };
6566
+ return { type: "command", args: [] };
6567
+ }
6568
+ let cmd;
6569
+ let args = [];
6570
+ if (Array.isArray(probe.args) && probe.args.length > 0) {
6571
+ cmd = String(probe.args[0]);
6572
+ args = probe.args.slice(1).map(String);
6573
+ } else if (Array.isArray(probe.command)) {
6574
+ cmd = String(probe.command[0]);
6575
+ args = probe.command.slice(1).map(String);
6576
+ } else if (typeof probe.command === "string") {
6577
+ const parts = probe.command.trim().split(/\s+/);
6578
+ cmd = parts[0];
6579
+ args = parts.slice(1);
6580
+ }
6581
+ if (cmd) {
6582
+ return { type: "command", args: [cmd, ...args] };
6583
+ }
6584
+ return { type: "command", args: [] };
6585
+ }
6586
+ return { type, args: [] };
6587
+ }
6588
+ return null;
6589
+ }, "parseProbe");
6491
6590
  cache = /* @__PURE__ */ new Map();
6492
6591
  CACHE_MS = 6e4;
6493
6592
  __name(runProbe, "runProbe");
@@ -6502,19 +6601,6 @@ __export(telemetry_exports, {
6502
6601
  recordProjection: () => recordProjection,
6503
6602
  recordRetraction: () => recordRetraction
6504
6603
  });
6505
- function load() {
6506
- try {
6507
- return JSON.parse(fs__default.default.readFileSync(file(), "utf8"));
6508
- } catch {
6509
- return {};
6510
- }
6511
- }
6512
- function save(store7) {
6513
- try {
6514
- fs__default.default.writeFileSync(file(), JSON.stringify(store7, null, 2), "utf8");
6515
- } catch {
6516
- }
6517
- }
6518
6604
  function recordProjection(ids) {
6519
6605
  const store7 = load();
6520
6606
  const now3 = (/* @__PURE__ */ new Date()).toISOString();
@@ -6543,13 +6629,24 @@ function recordRetraction(id) {
6543
6629
  function readTelemetry() {
6544
6630
  return load();
6545
6631
  }
6546
- var file;
6632
+ var file, load, save;
6547
6633
  var init_telemetry = __esm({
6548
6634
  "core/knowledge/telemetry.ts"() {
6549
6635
  init_user_paths();
6550
6636
  file = /* @__PURE__ */ __name(() => `${resolveUserDotMemPath()}/telemetry.json`, "file");
6551
- __name(load, "load");
6552
- __name(save, "save");
6637
+ load = /* @__PURE__ */ __name(() => {
6638
+ try {
6639
+ return JSON.parse(fs6__default.default.readFileSync(file(), "utf8"));
6640
+ } catch {
6641
+ return {};
6642
+ }
6643
+ }, "load");
6644
+ save = /* @__PURE__ */ __name((store7) => {
6645
+ try {
6646
+ fs6__default.default.writeFileSync(file(), JSON.stringify(store7, null, 2), "utf8");
6647
+ } catch {
6648
+ }
6649
+ }, "save");
6553
6650
  __name(recordProjection, "recordProjection");
6554
6651
  __name(recordFeedback, "recordFeedback");
6555
6652
  __name(recordRetraction, "recordRetraction");
@@ -6596,7 +6693,7 @@ var init_currentness = __esm({
6596
6693
  const verifiedAt = verifiedAtOf(claim);
6597
6694
  if (verifiedAt !== void 0) return "verified";
6598
6695
  if (claim.epistemicType === "verified") return "unverified";
6599
- return "unknown-currentness";
6696
+ return "any-currentness";
6600
6697
  }, "deriveCurrentness");
6601
6698
  }
6602
6699
  });
@@ -7440,7 +7537,7 @@ var init_staging = __esm({
7440
7537
  throw new Error("Stage file must contain a claim object");
7441
7538
  }
7442
7539
  const claimValidation = buildClaimRecord({
7443
- id: s.claim.id,
7540
+ id: typeof s.claim.id === "string" ? s.claim.id : "",
7444
7541
  knowledge: s.claim.knowledge,
7445
7542
  applicability: s.claim.applicability,
7446
7543
  evidence: s.claim.evidence,
@@ -7857,7 +7954,7 @@ var init_violations = __esm({
7857
7954
  VIOLATION_FILE_NAME = "violations.json";
7858
7955
  }
7859
7956
  });
7860
- var isRuleClaim, isIronRule, extractIronRules, readViolationCounts, sortRulesByViolationFrequency, loadIronRules, ruleSetSignature;
7957
+ var isRuleClaim, isIronRule, extractIronRules, readViolationCounts, sortRulesByViolationFrequency, loadIronRules;
7861
7958
  var init_rules_loader = __esm({
7862
7959
  "core/knowledge/rules-loader.ts"() {
7863
7960
  init_state();
@@ -7894,7 +7991,7 @@ var init_rules_loader = __esm({
7894
7991
  }, "extractIronRules");
7895
7992
  readViolationCounts = /* @__PURE__ */ __name((file2) => {
7896
7993
  try {
7897
- const parsed = JSON.parse(fs.readFileSync(file2, "utf8"));
7994
+ const parsed = JSON.parse(fs6.readFileSync(file2, "utf8"));
7898
7995
  const counts = {};
7899
7996
  for (const violation of Array.isArray(parsed.violations) ? parsed.violations : []) {
7900
7997
  const ruleId = typeof violation?.ruleId === "string" ? violation.ruleId : "";
@@ -7923,15 +8020,6 @@ var init_rules_loader = __esm({
7923
8020
  sortedBy: "violation-frequency"
7924
8021
  };
7925
8022
  }, "loadIronRules");
7926
- ruleSetSignature = /* @__PURE__ */ __name((rules) => {
7927
- const material = rules.map((rule) => `${rule.id}\0${rule.text}`).join("");
7928
- let hash = 2166136261;
7929
- for (let index = 0; index < material.length; index += 1) {
7930
- hash ^= material.charCodeAt(index);
7931
- hash = Math.imul(hash, 16777619) >>> 0;
7932
- }
7933
- return hash.toString(16).padStart(8, "0");
7934
- }, "ruleSetSignature");
7935
8023
  }
7936
8024
  });
7937
8025
 
@@ -8115,25 +8203,25 @@ var init_exemplars = __esm({
8115
8203
  resolveExemplarsPath = /* @__PURE__ */ __name(() => {
8116
8204
  return joinPath3(resolveUserDotMemPath(), EXEMPLARS_FILE_NAME);
8117
8205
  }, "resolveExemplarsPath");
8118
- readFile = /* @__PURE__ */ __name(async (path10) => {
8206
+ readFile = /* @__PURE__ */ __name(async (path11) => {
8119
8207
  try {
8120
8208
  const fs16 = await import('fs/promises');
8121
- return await fs16.readFile(path10, "utf8");
8209
+ return await fs16.readFile(path11, "utf8");
8122
8210
  } catch {
8123
8211
  return null;
8124
8212
  }
8125
8213
  }, "readFile");
8126
- writeFile = /* @__PURE__ */ __name(async (path10, content) => {
8214
+ writeFile = /* @__PURE__ */ __name(async (path11, content) => {
8127
8215
  const fs16 = await import('fs/promises');
8128
- const dir = path10.replace(/[\\/][^\\/]+$/, "");
8216
+ const dir = path11.replace(/[\\/][^\\/]+$/, "");
8129
8217
  await fs16.mkdir(dir, { recursive: true });
8130
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
8218
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
8131
8219
  try {
8132
8220
  await fs16.writeFile(temporary, content, "utf8");
8133
- await fs16.rename(temporary, path10);
8221
+ await fs16.rename(temporary, path11);
8134
8222
  } catch {
8135
8223
  await fs16.rm(temporary, { force: true }).catch(() => void 0);
8136
- throw new Error(`Failed to write exemplars file at ${path10}`);
8224
+ throw new Error(`Failed to write exemplars file at ${path11}`);
8137
8225
  }
8138
8226
  }, "writeFile");
8139
8227
  emptyStore = /* @__PURE__ */ __name(() => {
@@ -11671,25 +11759,25 @@ var init_loops = __esm({
11671
11759
  release();
11672
11760
  }
11673
11761
  }, "withLoopLock");
11674
- readFile2 = /* @__PURE__ */ __name(async (path10) => {
11762
+ readFile2 = /* @__PURE__ */ __name(async (path11) => {
11675
11763
  try {
11676
11764
  const fs16 = await import('fs/promises');
11677
- return await fs16.readFile(path10, "utf8");
11765
+ return await fs16.readFile(path11, "utf8");
11678
11766
  } catch {
11679
11767
  return null;
11680
11768
  }
11681
11769
  }, "readFile");
11682
- writeFile2 = /* @__PURE__ */ __name(async (path10, content) => {
11770
+ writeFile2 = /* @__PURE__ */ __name(async (path11, content) => {
11683
11771
  const fs16 = await import('fs/promises');
11684
- const dir = path10.replace(/[\\/][^\\/]+$/, "");
11772
+ const dir = path11.replace(/[\\/][^\\/]+$/, "");
11685
11773
  await fs16.mkdir(dir, { recursive: true });
11686
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
11774
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
11687
11775
  try {
11688
11776
  await fs16.writeFile(temporary, content, "utf8");
11689
- await fs16.rename(temporary, path10);
11777
+ await fs16.rename(temporary, path11);
11690
11778
  } catch {
11691
11779
  await fs16.rm(temporary, { force: true }).catch(() => void 0);
11692
- throw new Error(`Failed to write loops file at ${path10}`);
11780
+ throw new Error(`Failed to write loops file at ${path11}`);
11693
11781
  }
11694
11782
  }, "writeFile");
11695
11783
  emptyDocument = /* @__PURE__ */ __name(() => {
@@ -11773,7 +11861,7 @@ var init_loops = __esm({
11773
11861
  text: input.text,
11774
11862
  waitor: input.waitor,
11775
11863
  openedAt: input.openedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
11776
- authorAgent: input.authorAgent ?? "unknown",
11864
+ authorAgent: input.authorAgent ?? "any",
11777
11865
  targetRole: input.targetRole ?? "any",
11778
11866
  status: input.status ?? "open",
11779
11867
  projectId: input.projectId,
@@ -11839,25 +11927,25 @@ var init_personality_anchor = __esm({
11839
11927
  resolvePersonalityAnchorPath = /* @__PURE__ */ __name(() => {
11840
11928
  return joinPath5(resolveUserDotMemPath(), PERSONALITY_ANCHOR_FILE_NAME);
11841
11929
  }, "resolvePersonalityAnchorPath");
11842
- readFile3 = /* @__PURE__ */ __name(async (path10) => {
11930
+ readFile3 = /* @__PURE__ */ __name(async (path11) => {
11843
11931
  try {
11844
11932
  const fs16 = await import('fs/promises');
11845
- return await fs16.readFile(path10, "utf8");
11933
+ return await fs16.readFile(path11, "utf8");
11846
11934
  } catch {
11847
11935
  return null;
11848
11936
  }
11849
11937
  }, "readFile");
11850
- writeFile3 = /* @__PURE__ */ __name(async (path10, content) => {
11938
+ writeFile3 = /* @__PURE__ */ __name(async (path11, content) => {
11851
11939
  const fs16 = await import('fs/promises');
11852
- const dir = path10.replace(/[\\/][^\\/]+$/, "");
11940
+ const dir = path11.replace(/[\\/][^\\/]+$/, "");
11853
11941
  await fs16.mkdir(dir, { recursive: true });
11854
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
11942
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
11855
11943
  try {
11856
11944
  await fs16.writeFile(temporary, content, "utf8");
11857
- await fs16.rename(temporary, path10);
11945
+ await fs16.rename(temporary, path11);
11858
11946
  } catch {
11859
11947
  await fs16.rm(temporary, { force: true }).catch(() => void 0);
11860
- throw new Error(`Failed to write personality anchor at ${path10}`);
11948
+ throw new Error(`Failed to write personality anchor at ${path11}`);
11861
11949
  }
11862
11950
  }, "writeFile");
11863
11951
  emptyAnchor = /* @__PURE__ */ __name(() => {
@@ -12066,6 +12154,7 @@ var init_repository = __esm({
12066
12154
  var init_rule_checker = __esm({
12067
12155
  "core/knowledge/rule-checker.ts"() {
12068
12156
  init_state();
12157
+ init_sanitizer();
12069
12158
  }
12070
12159
  });
12071
12160
 
@@ -12156,12 +12245,12 @@ var init_user_language = __esm({
12156
12245
  resolveLanguagePreferencePath = /* @__PURE__ */ __name(() => {
12157
12246
  return resolveUserLanguagePath();
12158
12247
  }, "resolveLanguagePreferencePath");
12159
- readJsonFile = /* @__PURE__ */ __name((path10) => {
12248
+ readJsonFile = /* @__PURE__ */ __name((path11) => {
12160
12249
  const fs16 = getSyncFs();
12161
12250
  if (!fs16) return null;
12162
12251
  let raw;
12163
12252
  try {
12164
- raw = decodeText(fs16.readFileSync(path10), { source: path10 });
12253
+ raw = decodeText(fs16.readFileSync(path11), { source: path11 });
12165
12254
  } catch {
12166
12255
  return null;
12167
12256
  }
@@ -12258,14 +12347,14 @@ var init_user_language = __esm({
12258
12347
  }, "getResponseLanguage");
12259
12348
  setUserLanguage = /* @__PURE__ */ __name(async (language2) => {
12260
12349
  const fsMod = await import('fs/promises');
12261
- const path10 = resolveUserLanguagePath();
12262
- const dir = parentStoragePath(path10);
12350
+ const path11 = resolveUserLanguagePath();
12351
+ const dir = parentStoragePath(path11);
12263
12352
  await fsMod.mkdir(dir, { recursive: true });
12264
12353
  const payload = { format: "dotmem.language", version: 1, language: String(language2).trim() };
12265
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
12354
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
12266
12355
  await fsMod.writeFile(temporary, `${JSON.stringify(payload, null, 2)}
12267
12356
  `, "utf8");
12268
- await fsMod.rename(temporary, path10);
12357
+ await fsMod.rename(temporary, path11);
12269
12358
  return payload.language;
12270
12359
  }, "setUserLanguage");
12271
12360
  saveUserLanguage = /* @__PURE__ */ __name(async (language2) => {
@@ -12319,117 +12408,757 @@ var init_session_metrics = __esm({
12319
12408
  }
12320
12409
  });
12321
12410
 
12322
- // core/knowledge/loading-policy.ts
12323
- var init_loading_policy = __esm({
12324
- "core/knowledge/loading-policy.ts"() {
12325
- }
12326
- });
12327
-
12328
- // core/knowledge/index.ts
12329
- var init_knowledge = __esm({
12330
- "core/knowledge/index.ts"() {
12331
- init_acquisition_boundary();
12332
- init_acquisition_limits();
12333
- init_applicability();
12334
- init_behavioral_invariants();
12335
- init_bootstrap();
12336
- init_built_in_context();
12337
- init_built_in_context_rules();
12338
- init_canonical_hash();
12339
- init_canonical_reconstruction();
12340
- init_canonical_schema();
12341
- init_context_budget();
12342
- init_contract();
12343
- init_correction();
12344
- init_currentness();
12411
+ // core/knowledge/hard-rules-registry.ts
12412
+ 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;
12413
+ var init_hard_rules_registry = __esm({
12414
+ "core/knowledge/hard-rules-registry.ts"() {
12345
12415
  init_detection_events();
12346
- init_detection_journal();
12347
- init_discover();
12348
- init_solvers();
12349
- init_signatures();
12350
- init_probe();
12351
- init_semantic_provider();
12352
- init_effective_contract();
12353
- init_exemplars();
12354
- init_explain();
12355
- init_feedback();
12356
- init_fingerprint();
12357
- init_identity_governance();
12358
- init_identity_resolution();
12359
- init_incidents();
12360
- init_inspect_report();
12361
- init_language_detect();
12362
- init_loops();
12363
- init_mem_package();
12364
- init_personality_anchor();
12365
12416
  init_policy();
12366
12417
  init_policy_namespace_lock();
12367
- init_policy_store();
12368
- init_project();
12369
- init_project_anchor();
12370
- init_read_only();
12371
- init_renderer();
12372
- init_repository();
12373
- init_rule_checker();
12374
- init_rules_loader();
12375
- init_runtime();
12376
- init_scope_eligibility();
12377
- init_select();
12378
- init_session();
12379
- init_staging();
12380
- init_state();
12381
- init_storage_location();
12382
- init_storage_settings();
12383
- init_tool_guard();
12384
- init_user_identity();
12385
- init_user_language();
12386
12418
  init_user_paths();
12387
- init_vault();
12388
- init_verification();
12389
- init_verify();
12390
- init_violations();
12391
- init_claim_identity();
12392
- init_store_registry();
12393
- init_migration_audit();
12394
- init_session_metrics();
12395
- init_loading_policy();
12396
- init_session_metrics();
12397
- init_session_metrics();
12398
- init_session_metrics();
12399
- }
12400
- });
12401
-
12402
- // core/logic/helpers.ts
12403
- var normalizeClaimIds2, revisionFromAcquire;
12404
- var init_helpers = __esm({
12405
- "core/logic/helpers.ts"() {
12406
- normalizeClaimIds2 = /* @__PURE__ */ __name((value) => {
12407
- if (!value) return [];
12408
- return Array.isArray(value) ? value : [value];
12409
- }, "normalizeClaimIds");
12410
- revisionFromAcquire = /* @__PURE__ */ __name((opts) => {
12411
- const refines = normalizeClaimIds2(opts.refines);
12412
- const supersedes = normalizeClaimIds2(opts.supersedes);
12413
- const retracts = normalizeClaimIds2(opts.retracts);
12414
- if ([refines, supersedes, retracts].filter((ids) => ids.length > 0).length > 1) {
12415
- throw new Error("Acquired knowledge can refine, supersede, or retract prior knowledge, not more than one");
12419
+ HARD_RULES_REGISTRY_FORMAT = "dotmem.hard-rules";
12420
+ HARD_RULES_REGISTRY_VERSION = 1;
12421
+ HARD_RULES_REGISTRY_AUDIT_RETENTION = 200;
12422
+ HARD_RULES_REGISTRY_FILE_NAME = "hard-rules.registry.json";
12423
+ HardRulesRegistryError = class extends Error {
12424
+ static {
12425
+ __name(this, "HardRulesRegistryError");
12416
12426
  }
12417
- if (refines.length > 0) return { kind: "refines", claimIds: refines, ...opts.reason ? { reason: opts.reason } : {} };
12418
- if (supersedes.length > 0) return { kind: "supersedes", claimIds: supersedes, ...opts.reason ? { reason: opts.reason } : {} };
12419
- if (retracts.length > 0) return { kind: "retracts", claimIds: retracts, ...opts.reason ? { reason: opts.reason } : {} };
12420
- return void 0;
12421
- }, "revisionFromAcquire");
12427
+ constructor(message) {
12428
+ super(message);
12429
+ this.name = "HardRulesRegistryError";
12430
+ }
12431
+ };
12432
+ requiredText3 = /* @__PURE__ */ __name((v) => typeof v === "string" && v.trim().length > 0, "requiredText");
12433
+ nowIso = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
12434
+ joinPath7 = /* @__PURE__ */ __name((base, child) => {
12435
+ const sep = process.platform === "win32" ? "\\" : "/";
12436
+ return `${base.replace(/[\\/]+/g, sep)}${sep}${child}`;
12437
+ }, "joinPath");
12438
+ resolveRegistryDir = /* @__PURE__ */ __name((directory) => directory ?? joinPath7(resolveUserDotMemPath(), "policy"), "resolveRegistryDir");
12439
+ resolveRegistryFilePath = /* @__PURE__ */ __name((directory) => joinPath7(resolveRegistryDir(directory), HARD_RULES_REGISTRY_FILE_NAME), "resolveRegistryFilePath");
12440
+ validateHardRuleAuthority = /* @__PURE__ */ __name((value) => {
12441
+ try {
12442
+ return validatePolicyAuthority(value);
12443
+ } catch (err3) {
12444
+ void detectAuthorityEscalationAttempt({ claimed: "invalid hard-rule authority", channel: "hard-rules" }).catch(() => void 0);
12445
+ throw err3 instanceof HardRulesRegistryError ? err3 : new HardRulesRegistryError(err3.message);
12446
+ }
12447
+ }, "validateHardRuleAuthority");
12448
+ canonicalFingerprint = /* @__PURE__ */ __name((rule) => {
12449
+ const payload = {
12450
+ id: rule.id,
12451
+ version: rule.version,
12452
+ ruleClass: rule.ruleClass,
12453
+ status: rule.status,
12454
+ scope: rule.scope,
12455
+ statement: rule.statement,
12456
+ applicability: rule.applicability ?? null,
12457
+ authority: rule.authority
12458
+ };
12459
+ return `hr.${rule.id}@v${rule.version}.${Buffer.from(JSON.stringify(payload)).toString("base64").slice(0, 16)}`;
12460
+ }, "canonicalFingerprint");
12461
+ validateRule = /* @__PURE__ */ __name((value) => {
12462
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new HardRulesRegistryError("Hard rule must be an object");
12463
+ const r = value;
12464
+ if (!requiredText3(r.id)) throw new HardRulesRegistryError("id is required");
12465
+ if (typeof r.version !== "number" || !Number.isInteger(r.version) || r.version < 1) throw new HardRulesRegistryError("version must be a positive integer");
12466
+ if (typeof r.revision !== "number" || !Number.isInteger(r.revision) || r.revision < 0) throw new HardRulesRegistryError("revision must be a non-negative integer");
12467
+ if (typeof r.ruleClass !== "string" || !["IMMUTABLE", "OWNER_CONTROLLED", "USER_OVERRIDEABLE", "SESSION"].includes(r.ruleClass)) throw new HardRulesRegistryError("invalid ruleClass");
12468
+ if (typeof r.status !== "string" || !["proposed", "under_review", "approved", "active", "suspended", "retired", "rejected"].includes(r.status)) throw new HardRulesRegistryError("invalid status");
12469
+ if (!requiredText3(r.scope)) throw new HardRulesRegistryError("scope is required");
12470
+ if (!requiredText3(r.statement)) throw new HardRulesRegistryError("statement is required");
12471
+ if (!requiredText3(r.grantedAt)) throw new HardRulesRegistryError("grantedAt is required");
12472
+ if (!requiredText3(r.createdAt)) throw new HardRulesRegistryError("createdAt is required");
12473
+ const authority = validateHardRuleAuthority(r.authority);
12474
+ const validated = {
12475
+ id: r.id,
12476
+ version: r.version,
12477
+ revision: r.revision,
12478
+ ruleClass: r.ruleClass,
12479
+ status: r.status,
12480
+ scope: r.scope,
12481
+ statement: r.statement,
12482
+ ...r.applicability && typeof r.applicability === "object" ? { applicability: r.applicability } : {},
12483
+ authority,
12484
+ grantedAt: r.grantedAt,
12485
+ createdAt: r.createdAt,
12486
+ ...requiredText3(r.updatedAt) ? { updatedAt: r.updatedAt } : {},
12487
+ fingerprint: ""
12488
+ };
12489
+ const fp = canonicalFingerprint(validated);
12490
+ if (requiredText3(r.fingerprint) && r.fingerprint !== fp) {
12491
+ throw new HardRulesRegistryError(`Hard rule fingerprint mismatch for ${validated.id}`);
12492
+ }
12493
+ validated.fingerprint = fp;
12494
+ if (requiredText3(r.provenance) === false && r.provenance !== void 0) ;
12495
+ if (r.provenance && typeof r.provenance === "object") validated.provenance = r.provenance;
12496
+ if (requiredText3(r.auditRef)) validated.auditRef = r.auditRef;
12497
+ return validated;
12498
+ }, "validateRule");
12499
+ validateDocument2 = /* @__PURE__ */ __name((value) => {
12500
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new HardRulesRegistryError("document must be an object");
12501
+ const d = value;
12502
+ if (d.format !== HARD_RULES_REGISTRY_FORMAT) throw new HardRulesRegistryError("invalid format");
12503
+ if (d.version !== HARD_RULES_REGISTRY_VERSION) throw new HardRulesRegistryError("invalid version");
12504
+ if (typeof d.revision !== "number" || !Number.isInteger(d.revision) || d.revision < 0) throw new HardRulesRegistryError("invalid revision");
12505
+ if (!Array.isArray(d.rules)) throw new HardRulesRegistryError("rules must be an array");
12506
+ if (!Array.isArray(d.audit)) throw new HardRulesRegistryError("audit must be an array");
12507
+ const ids = /* @__PURE__ */ new Set();
12508
+ const rules = d.rules.map(validateRule);
12509
+ for (const rule of rules) {
12510
+ if (ids.has(rule.id + "@" + rule.version)) throw new HardRulesRegistryError(`Duplicate hard rule ${rule.id} v${rule.version}`);
12511
+ ids.add(rule.id + "@" + rule.version);
12512
+ }
12513
+ const audit2 = d.audit.map((e) => {
12514
+ if (!e || typeof e !== "object" || Array.isArray(e)) throw new HardRulesRegistryError("audit entry must be an object");
12515
+ const r = e;
12516
+ if (!requiredText3(r.id)) throw new HardRulesRegistryError("audit id required");
12517
+ if (!requiredText3(r.action)) throw new HardRulesRegistryError("audit action required");
12518
+ if (!requiredText3(r.at)) throw new HardRulesRegistryError("audit at required");
12519
+ if (r.outcome !== "applied" && r.outcome !== "rejected") throw new HardRulesRegistryError("audit outcome invalid");
12520
+ return r;
12521
+ });
12522
+ return { format: HARD_RULES_REGISTRY_FORMAT, version: HARD_RULES_REGISTRY_VERSION, revision: d.revision, rules, audit: audit2 };
12523
+ }, "validateDocument");
12524
+ emptyDocument2 = /* @__PURE__ */ __name(() => ({
12525
+ format: HARD_RULES_REGISTRY_FORMAT,
12526
+ version: HARD_RULES_REGISTRY_VERSION,
12527
+ revision: 0,
12528
+ rules: [],
12529
+ audit: []
12530
+ }), "emptyDocument");
12531
+ boundedAudit2 = /* @__PURE__ */ __name((entries2) => {
12532
+ if (entries2.length <= HARD_RULES_REGISTRY_AUDIT_RETENTION) return [...entries2];
12533
+ const kept = [];
12534
+ let budget = HARD_RULES_REGISTRY_AUDIT_RETENTION;
12535
+ for (let i3 = entries2.length - 1; i3 >= 0; i3--) {
12536
+ const e = entries2[i3];
12537
+ if (e.mandatory === true || budget > 0) {
12538
+ kept.unshift(e);
12539
+ if (e.mandatory !== true) budget--;
12540
+ }
12541
+ }
12542
+ return kept;
12543
+ }, "boundedAudit");
12544
+ buildAudit = /* @__PURE__ */ __name((entry) => ({
12545
+ id: entry.id ?? `hr-audit.${entry.action}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}`,
12546
+ action: entry.action,
12547
+ at: entry.at,
12548
+ ...entry.actorPrincipal !== void 0 ? { actorPrincipal: entry.actorPrincipal } : {},
12549
+ ...entry.targetRuleId !== void 0 ? { targetRuleId: entry.targetRuleId } : {},
12550
+ ...entry.targetVersion !== void 0 ? { targetVersion: entry.targetVersion } : {},
12551
+ ...entry.scope !== void 0 ? { scope: entry.scope } : {},
12552
+ outcome: entry.outcome,
12553
+ ...entry.reason !== void 0 ? { reason: entry.reason } : {},
12554
+ ...entry.detail !== void 0 ? { detail: entry.detail } : {},
12555
+ ...entry.mandatory !== void 0 ? { mandatory: entry.mandatory } : {}
12556
+ }), "buildAudit");
12557
+ HardRulesRegistry = class {
12558
+ constructor(directory) {
12559
+ this.directory = directory;
12560
+ }
12561
+ directory;
12562
+ static {
12563
+ __name(this, "HardRulesRegistry");
12564
+ }
12565
+ dir() {
12566
+ return resolveRegistryDir(this.directory);
12567
+ }
12568
+ filePath() {
12569
+ return resolveRegistryFilePath(this.directory);
12570
+ }
12571
+ async load() {
12572
+ const fs16 = await import('fs/promises');
12573
+ try {
12574
+ const raw = await fs16.readFile(this.filePath(), "utf8");
12575
+ return validateDocument2(JSON.parse(raw));
12576
+ } catch (err3) {
12577
+ if (err3.code === "ENOENT") return emptyDocument2();
12578
+ throw err3;
12579
+ }
12580
+ }
12581
+ async readDoc(fs16) {
12582
+ try {
12583
+ const raw = await fs16.readFile(this.filePath(), "utf8");
12584
+ return validateDocument2(JSON.parse(raw));
12585
+ } catch (err3) {
12586
+ if (err3.code === "ENOENT") return emptyDocument2();
12587
+ throw err3;
12588
+ }
12589
+ }
12590
+ async writeDoc(fs16, doc) {
12591
+ await fs16.mkdir(this.dir(), { recursive: true });
12592
+ const fp = this.filePath();
12593
+ const tmp = `${fp}.${process.pid}.${Date.now().toString(36)}.tmp`;
12594
+ try {
12595
+ await fs16.writeFile(tmp, `${JSON.stringify(doc, null, 2)}
12596
+ `, "utf8");
12597
+ const handle = await fs16.open(tmp, "r+");
12598
+ try {
12599
+ await handle.sync();
12600
+ } finally {
12601
+ await handle.close();
12602
+ }
12603
+ await fs16.rename(tmp, fp);
12604
+ } catch (err3) {
12605
+ await fs16.rm(tmp, { force: true }).catch(() => void 0);
12606
+ throw err3;
12607
+ }
12608
+ }
12609
+ async mutate(operation, options = {}) {
12610
+ const directory = this.dir();
12611
+ return withPolicyNamespaceLock(
12612
+ async (session3) => {
12613
+ const fs16 = await import('fs/promises');
12614
+ const doc = await this.readDoc(fs16);
12615
+ if (options.basedOnRevision !== void 0 && options.basedOnRevision !== doc.revision) {
12616
+ throw new HardRulesRegistryError(`Stale hard-rules revision: expected ${options.basedOnRevision}, current ${doc.revision}`);
12617
+ }
12618
+ const outcome = operation(doc);
12619
+ let next = outcome.document;
12620
+ validateDocument2(next);
12621
+ await session3.assertOwnership();
12622
+ await this.writeDoc(fs16, next);
12623
+ return outcome.result;
12624
+ },
12625
+ { directory }
12626
+ );
12627
+ }
12628
+ async listRules() {
12629
+ const doc = await this.load();
12630
+ return [...doc.rules].sort((a, b) => a.id.localeCompare(b.id) || a.version - b.version);
12631
+ }
12632
+ async activeRules(scope) {
12633
+ const doc = await this.load();
12634
+ return doc.rules.filter((r) => r.status === "active" && (!scope || r.scope === "*" || r.scope === scope || scope.startsWith(r.scope.endsWith("/") ? r.scope : r.scope + "/")));
12635
+ }
12636
+ async failClosedResolve(scope) {
12637
+ const actives = await this.activeRules(scope);
12638
+ if (actives.length === 0) return { outcome: "none", rule: null, reason: "no applicable hard rule" };
12639
+ if (actives.length > 1) return { outcome: "conflicting", rule: null, reason: "conflicting active hard rules" };
12640
+ const r = actives[0];
12641
+ if (r.ruleClass === "IMMUTABLE" || r.ruleClass === "OWNER_CONTROLLED") {
12642
+ if (r.authority.kind !== "HI" && r.authority.kind !== "operator") {
12643
+ return { outcome: "unresolved-authority", rule: null, reason: "unresolved authority" };
12644
+ }
12645
+ }
12646
+ return { outcome: "applicable", rule: r, reason: "applicable" };
12647
+ }
12648
+ async assign(input, basedOnRevision) {
12649
+ const authority = validateHardRuleAuthority(input.authority);
12650
+ if (!requiredText3(input.scope)) throw new HardRulesRegistryError("scope is required");
12651
+ if (!requiredText3(input.statement)) throw new HardRulesRegistryError("statement is required");
12652
+ if (!["IMMUTABLE", "OWNER_CONTROLLED", "USER_OVERRIDEABLE", "SESSION"].includes(input.ruleClass)) throw new HardRulesRegistryError("invalid ruleClass");
12653
+ const doc0 = await this.load();
12654
+ const ruleId = input.id ?? `hr.${Date.now()}.${Math.random().toString(36).slice(2, 8)}`;
12655
+ const existing = doc0.rules.filter((r) => r.id === ruleId);
12656
+ const version = input.version ?? (existing.length > 0 ? Math.max(...existing.map((r) => r.version)) + 1 : 1);
12657
+ const priorActive = existing.find((r) => r.status === "active" && r.ruleClass === "IMMUTABLE");
12658
+ if (priorActive && input.ruleClass !== "IMMUTABLE") {
12659
+ throw new HardRulesRegistryError("cannot weaken immutable rule");
12660
+ }
12661
+ if (priorActive && authority.kind !== "HI") {
12662
+ throw new HardRulesRegistryError("immutable rule requires HI authority to amend");
12663
+ }
12664
+ const createdAt = nowIso();
12665
+ const grantedAt = input.grantedAt ?? createdAt;
12666
+ const rule = {
12667
+ id: ruleId,
12668
+ version,
12669
+ revision: 0,
12670
+ ruleClass: input.ruleClass,
12671
+ status: "proposed",
12672
+ scope: input.scope,
12673
+ statement: input.statement,
12674
+ ...input.applicability ? { applicability: input.applicability } : {},
12675
+ authority,
12676
+ grantedAt,
12677
+ createdAt,
12678
+ fingerprint: ""
12679
+ };
12680
+ rule.fingerprint = canonicalFingerprint({ ...rule, fingerprint: "" });
12681
+ return this.mutate(
12682
+ (doc) => {
12683
+ const revision = doc.revision + 1;
12684
+ const stored = { ...rule, revision, fingerprint: canonicalFingerprint({ ...rule, revision, fingerprint: "" }) };
12685
+ const rules = doc.rules.map((r) => {
12686
+ if (r.id === stored.id && r.version !== stored.version && r.status === "active") {
12687
+ return { ...r, status: "retired", updatedAt: nowIso() };
12688
+ }
12689
+ return r;
12690
+ });
12691
+ rules.push(stored);
12692
+ const audit2 = boundedAudit2([
12693
+ ...doc.audit,
12694
+ buildAudit({
12695
+ action: "rule.assigned",
12696
+ at: stored.grantedAt,
12697
+ actorPrincipal: authority.kind,
12698
+ targetRuleId: stored.id,
12699
+ targetVersion: stored.version,
12700
+ scope: stored.scope,
12701
+ outcome: "applied",
12702
+ detail: `hard rule ${stored.id} v${stored.version} assigned (${stored.ruleClass})`,
12703
+ mandatory: true
12704
+ })
12705
+ ]);
12706
+ return { document: { ...doc, revision, rules, audit: audit2 }, result: stored };
12707
+ },
12708
+ { basedOnRevision }
12709
+ );
12710
+ }
12711
+ async activate(input, basedOnRevision) {
12712
+ const doc0 = await this.load();
12713
+ const rule = doc0.rules.find((r) => r.id === input.id && r.version === input.version);
12714
+ if (!rule) throw new HardRulesRegistryError("rule not found");
12715
+ if (rule.status !== "approved" && rule.status !== "proposed") ;
12716
+ const authority = input.authority ? validateHardRuleAuthority(input.authority) : rule.authority;
12717
+ if ((rule.ruleClass === "IMMUTABLE" || rule.ruleClass === "OWNER_CONTROLLED") && authority.kind !== "HI" && authority.kind !== "operator") {
12718
+ throw new HardRulesRegistryError("activation requires HI or operator authority");
12719
+ }
12720
+ const actives = doc0.rules.filter((r) => r.status === "active" && r.scope === rule.scope && r.id !== rule.id);
12721
+ if (actives.length > 0 && (rule.ruleClass === "IMMUTABLE" || rule.ruleClass === "OWNER_CONTROLLED")) {
12722
+ throw new HardRulesRegistryError("conflicting active mandatory rules");
12723
+ }
12724
+ return this.mutate(
12725
+ (doc) => {
12726
+ const idx = doc.rules.findIndex((r) => r.id === input.id && r.version === input.version);
12727
+ if (idx < 0) throw new HardRulesRegistryError("rule not found");
12728
+ const current = doc.rules[idx];
12729
+ const rules = doc.rules.map((r) => {
12730
+ if (r.id === current.id && r.version !== current.version && r.status === "active") {
12731
+ return { ...r, status: "retired", updatedAt: nowIso() };
12732
+ }
12733
+ return r;
12734
+ });
12735
+ const now3 = nowIso();
12736
+ rules[idx >= rules.length ? rules.length - 1 : idx] = { ...current, status: "active", updatedAt: now3 };
12737
+ const targetIndex = rules.findIndex((r) => r.id === current.id && r.version === current.version);
12738
+ if (targetIndex >= 0) rules[targetIndex] = { ...current, status: "active", updatedAt: now3 };
12739
+ const updated = rules.find((r) => r.id === current.id && r.version === current.version);
12740
+ const revision = doc.revision + 1;
12741
+ const audit2 = boundedAudit2([
12742
+ ...doc.audit,
12743
+ buildAudit({
12744
+ action: "rule.activated",
12745
+ at: now3,
12746
+ actorPrincipal: input.actorPrincipal ?? authority.kind,
12747
+ targetRuleId: updated.id,
12748
+ targetVersion: updated.version,
12749
+ scope: updated.scope,
12750
+ outcome: "applied",
12751
+ mandatory: true
12752
+ })
12753
+ ]);
12754
+ return { document: { ...doc, revision, rules, audit: audit2 }, result: updated };
12755
+ },
12756
+ { basedOnRevision }
12757
+ );
12758
+ }
12759
+ async remove(id, authority, basedOnRevision) {
12760
+ const auth = validateHardRuleAuthority(authority);
12761
+ const doc0 = await this.load();
12762
+ const rule = doc0.rules.find((r) => r.id === id && r.status === "active");
12763
+ if (rule) {
12764
+ if (rule.ruleClass === "IMMUTABLE") throw new HardRulesRegistryError("cannot remove immutable rule");
12765
+ if (rule.ruleClass === "OWNER_CONTROLLED" && auth.kind !== "HI" && auth.kind !== "operator") throw new HardRulesRegistryError("unauthenticated cannot remove owner-controlled rule");
12766
+ }
12767
+ await this.mutate(
12768
+ (doc) => {
12769
+ const rules = doc.rules.filter((r) => r.id !== id);
12770
+ if (rules.length === doc.rules.length) return { document: doc, result: void 0 };
12771
+ const revision = doc.revision + 1;
12772
+ const audit2 = boundedAudit2([
12773
+ ...doc.audit,
12774
+ buildAudit({
12775
+ action: "rule.removed",
12776
+ at: nowIso(),
12777
+ actorPrincipal: auth.kind,
12778
+ targetRuleId: id,
12779
+ scope: rule?.scope,
12780
+ outcome: "applied",
12781
+ mandatory: true
12782
+ })
12783
+ ]);
12784
+ return { document: { ...doc, revision, rules, audit: audit2 }, result: void 0 };
12785
+ },
12786
+ { basedOnRevision }
12787
+ );
12788
+ }
12789
+ async auditTrail() {
12790
+ const doc = await this.load();
12791
+ return [...doc.audit];
12792
+ }
12793
+ async revision() {
12794
+ const doc = await this.load();
12795
+ return doc.revision;
12796
+ }
12797
+ };
12422
12798
  }
12423
12799
  });
12424
12800
 
12425
- // core/logic/index.ts
12426
- var logic_exports = {};
12427
- __export(logic_exports, {
12428
- LogicEngine: () => LogicEngine,
12429
- default: () => logic_default,
12430
- getLogicRuntime: () => getLogicRuntime,
12431
- logic: () => logic
12432
- });
12801
+ // core/context-compiler/index.ts
12802
+ var CHARS_PER_TOKEN, estimateTokens, DEFAULT_BUDGETS, dedupe, ContextCompiler, compileContext;
12803
+ var init_context_compiler = __esm({
12804
+ "core/context-compiler/index.ts"() {
12805
+ CHARS_PER_TOKEN = 4;
12806
+ estimateTokens = /* @__PURE__ */ __name((text) => Math.ceil((text || "").length / CHARS_PER_TOKEN), "estimateTokens");
12807
+ DEFAULT_BUDGETS = {
12808
+ identity: 0.1,
12809
+ rules: 0.15,
12810
+ conversationalState: 0.3,
12811
+ retrievedKnowledge: 0.45
12812
+ };
12813
+ dedupe = /* @__PURE__ */ __name((items) => {
12814
+ const seen = /* @__PURE__ */ new Set();
12815
+ const result = [];
12816
+ for (const item of items) {
12817
+ const key = item.trim().toLowerCase();
12818
+ if (seen.has(key)) continue;
12819
+ seen.add(key);
12820
+ result.push(item);
12821
+ }
12822
+ return result;
12823
+ }, "dedupe");
12824
+ ContextCompiler = class {
12825
+ static {
12826
+ __name(this, "ContextCompiler");
12827
+ }
12828
+ compile(input) {
12829
+ const totalBudget = input.tokenBudget ?? 4096;
12830
+ const totalChars = totalBudget * CHARS_PER_TOKEN;
12831
+ const budgets = {
12832
+ identity: Math.floor(totalChars * (input.categoryBudgets?.identity ?? DEFAULT_BUDGETS.identity)),
12833
+ rules: Math.floor(totalChars * (input.categoryBudgets?.rules ?? DEFAULT_BUDGETS.rules)),
12834
+ conversationalState: Math.floor(totalChars * (input.categoryBudgets?.conversationalState ?? DEFAULT_BUDGETS.conversationalState)),
12835
+ retrievedKnowledge: Math.floor(totalChars * (input.categoryBudgets?.retrievedKnowledge ?? DEFAULT_BUDGETS.retrievedKnowledge))
12836
+ };
12837
+ const omissions = [];
12838
+ const identityText = (input.identity ?? "").trim();
12839
+ let identityUsed = 0;
12840
+ const mandatoryParts = [];
12841
+ if (identityText) {
12842
+ if (identityText.length <= budgets.identity) {
12843
+ mandatoryParts.push(identityText);
12844
+ identityUsed = identityText.length;
12845
+ } else {
12846
+ omissions.push({
12847
+ category: "identity",
12848
+ whatWasOmitted: identityText,
12849
+ whyOmitted: "token budget exceeded",
12850
+ wouldBreakContinuity: true
12851
+ });
12852
+ }
12853
+ }
12854
+ const rules = input.rules ?? [];
12855
+ const activeRules = [];
12856
+ let rulesUsed = 0;
12857
+ for (const rule of rules) {
12858
+ if (rulesUsed + rule.length <= budgets.rules) {
12859
+ activeRules.push(rule);
12860
+ rulesUsed += rule.length;
12861
+ } else {
12862
+ omissions.push({
12863
+ category: "rules",
12864
+ whatWasOmitted: rule,
12865
+ whyOmitted: "token budget exceeded",
12866
+ wouldBreakContinuity: false
12867
+ });
12868
+ }
12869
+ }
12870
+ const state3 = input.conversationalState ?? null;
12871
+ const mandatoryStateParts = [];
12872
+ if (state3) {
12873
+ if (state3.objective) mandatoryStateParts.push(`Objective: ${state3.objective}`);
12874
+ if (state3.currentWorkingPosition) mandatoryStateParts.push(`Working position: ${state3.currentWorkingPosition}`);
12875
+ if (state3.openLoops.length > 0) {
12876
+ mandatoryStateParts.push(`Open loops: ${state3.openLoops.map((l) => l.description).join("; ")}`);
12877
+ }
12878
+ if (state3.rejectedApproaches.length > 0) {
12879
+ mandatoryStateParts.push(`Rejected approaches: ${state3.rejectedApproaches.map((r) => `${r.approach} (${r.reason})`).join("; ")}`);
12880
+ }
12881
+ }
12882
+ const activeParts = [];
12883
+ if (state3) {
12884
+ if (state3.currentProblem) activeParts.push(`Current problem: ${state3.currentProblem}`);
12885
+ if (state3.establishedUnderstanding) activeParts.push(`Established understanding: ${state3.establishedUnderstanding}`);
12886
+ if (state3.decisionsMade.length > 0) {
12887
+ activeParts.push(`Decisions: ${state3.decisionsMade.map((d) => `${d.decision} (rationale: ${d.rationale})`).join("; ")}`);
12888
+ }
12889
+ if (state3.pendingDecisions.length > 0) {
12890
+ activeParts.push(`Pending decisions: ${state3.pendingDecisions.map((d) => `${d.decision} [${d.options.join(", ")}]`).join("; ")}`);
12891
+ }
12892
+ if (state3.unresolvedQuestions.length > 0) {
12893
+ activeParts.push(`Unresolved questions: ${state3.unresolvedQuestions.map((q) => q.question).join("; ")}`);
12894
+ }
12895
+ if (state3.reasoningTrajectory.length > 0) {
12896
+ activeParts.push(`Reasoning trajectory: ${state3.reasoningTrajectory.map((r) => r.conclusion).join(" -> ")}`);
12897
+ }
12898
+ if (state3.nextConversationalStep) {
12899
+ activeParts.push(`Next step: ${state3.nextConversationalStep}`);
12900
+ }
12901
+ if (state3.lastCompletedAction) {
12902
+ activeParts.push(`Last completed action: ${state3.lastCompletedAction}`);
12903
+ }
12904
+ }
12905
+ const dedupedActive = dedupe(activeParts.filter((part) => !mandatoryStateParts.includes(part)));
12906
+ let stateUsed = 0;
12907
+ const admittedMandatoryState = [];
12908
+ const admittedActive = [];
12909
+ for (const part of mandatoryStateParts) {
12910
+ if (stateUsed + part.length <= budgets.conversationalState) {
12911
+ admittedMandatoryState.push(part);
12912
+ stateUsed += part.length;
12913
+ } else {
12914
+ omissions.push({
12915
+ category: "conversationalState",
12916
+ whatWasOmitted: part,
12917
+ whyOmitted: "token budget exceeded",
12918
+ wouldBreakContinuity: true
12919
+ });
12920
+ }
12921
+ }
12922
+ for (const part of dedupedActive) {
12923
+ if (stateUsed + part.length <= budgets.conversationalState) {
12924
+ admittedActive.push(part);
12925
+ stateUsed += part.length;
12926
+ } else {
12927
+ omissions.push({
12928
+ category: "conversationalState",
12929
+ whatWasOmitted: part,
12930
+ whyOmitted: "token budget exceeded",
12931
+ wouldBreakContinuity: false
12932
+ });
12933
+ }
12934
+ }
12935
+ const refs = [...input.knowledgeReferences ?? []].sort((a, b) => b.relevance - a.relevance);
12936
+ const retrievedParts = [];
12937
+ let retrievedUsed = 0;
12938
+ for (const ref of refs) {
12939
+ const text2 = ref.summary ? `${ref.kind}:${ref.identifier} - ${ref.summary}` : `${ref.kind}:${ref.identifier}`;
12940
+ if (retrievedUsed + text2.length <= budgets.retrievedKnowledge) {
12941
+ retrievedParts.push(text2);
12942
+ retrievedUsed += text2.length;
12943
+ } else {
12944
+ omissions.push({
12945
+ category: "retrievedKnowledge",
12946
+ whatWasOmitted: text2,
12947
+ whyOmitted: "token budget exceeded",
12948
+ wouldBreakContinuity: false
12949
+ });
12950
+ }
12951
+ }
12952
+ const optionalParts = [];
12953
+ let optionalUsed = 0;
12954
+ const remainingBudget = totalChars - (identityUsed + rulesUsed + stateUsed + retrievedUsed);
12955
+ for (const item of input.historicalContext ?? []) {
12956
+ if (optionalUsed + item.length <= remainingBudget) {
12957
+ optionalParts.push(item);
12958
+ optionalUsed += item.length;
12959
+ } else {
12960
+ omissions.push({
12961
+ category: "historical",
12962
+ whatWasOmitted: item,
12963
+ whyOmitted: "token budget exceeded",
12964
+ wouldBreakContinuity: false
12965
+ });
12966
+ }
12967
+ }
12968
+ const admittedSet = new Set([...mandatoryParts, ...admittedMandatoryState, ...admittedActive].map((s) => s.trim().toLowerCase()));
12969
+ const isDuplicate = /* @__PURE__ */ __name((item) => {
12970
+ const normalized = item.trim().toLowerCase();
12971
+ for (const existing of admittedSet) {
12972
+ if (existing.includes(normalized) || normalized.includes(existing)) return true;
12973
+ }
12974
+ return false;
12975
+ }, "isDuplicate");
12976
+ const finalRetrieved = dedupe(retrievedParts.filter((p) => !isDuplicate(p)));
12977
+ const finalOptional = dedupe(optionalParts.filter((p) => !isDuplicate(p) && !finalRetrieved.includes(p)));
12978
+ const mandatory = [...mandatoryParts, ...admittedMandatoryState].join("\n");
12979
+ const active = [...admittedActive];
12980
+ const retrieved = finalRetrieved;
12981
+ const optional = finalOptional;
12982
+ const text = [mandatory ? `## MANDATORY
12983
+ ${mandatory}` : "", active.length ? `## ACTIVE
12984
+ ${active.join("\n")}` : "", retrieved.length ? `## RETRIEVED
12985
+ ${retrieved.join("\n")}` : "", optional.length ? `## OPTIONAL
12986
+ ${optional.join("\n")}` : "", rules.length ? `## RULES
12987
+ ${activeRules.join("\n")}` : ""].filter(Boolean).join("\n\n");
12988
+ const budgetUsed = estimateTokens(text);
12989
+ return {
12990
+ mandatory,
12991
+ active,
12992
+ retrieved,
12993
+ optional,
12994
+ omissions,
12995
+ budgetUsed,
12996
+ budgetAvailable: totalBudget,
12997
+ text
12998
+ };
12999
+ }
13000
+ };
13001
+ compileContext = /* @__PURE__ */ __name((input) => {
13002
+ const compiler = new ContextCompiler();
13003
+ return compiler.compile(input);
13004
+ }, "compileContext");
13005
+ }
13006
+ });
13007
+
13008
+ // core/knowledge/rule-enforcement.ts
13009
+ var resolveApplicableRules;
13010
+ var init_rule_enforcement = __esm({
13011
+ "core/knowledge/rule-enforcement.ts"() {
13012
+ init_rules_loader();
13013
+ init_violations();
13014
+ init_hard_rules_registry();
13015
+ init_memory();
13016
+ init_context_compiler();
13017
+ resolveApplicableRules = /* @__PURE__ */ __name(async (situation, scope) => {
13018
+ const state3 = await loadCombinedKnowledgeState();
13019
+ const rules = [];
13020
+ const seen = /* @__PURE__ */ new Set();
13021
+ const ironReport = loadIronRules(state3);
13022
+ for (const rule of ironReport.rules) {
13023
+ if (seen.has(rule.id)) continue;
13024
+ seen.add(rule.id);
13025
+ const claim = state3.claims.find((c) => c.id === rule.id);
13026
+ rules.push({
13027
+ id: rule.id,
13028
+ text: rule.text,
13029
+ tier: "context",
13030
+ source: "iron",
13031
+ appliesWhen: rule.appliesWhen || void 0,
13032
+ hasCheck: !!claim?.check
13033
+ });
13034
+ }
13035
+ try {
13036
+ const registry = new HardRulesRegistry();
13037
+ const active = scope ? await registry.activeRules(scope) : await registry.activeRules();
13038
+ for (const rule of active) {
13039
+ if (seen.has(rule.id)) continue;
13040
+ seen.add(rule.id);
13041
+ rules.push({
13042
+ id: rule.id,
13043
+ text: rule.statement,
13044
+ tier: rule.ruleClass === "IMMUTABLE" || rule.ruleClass === "OWNER_CONTROLLED" ? "hard-precondition" : "precondition",
13045
+ source: "hard",
13046
+ appliesWhen: rule.scope,
13047
+ hasCheck: false
13048
+ });
13049
+ }
13050
+ } catch {
13051
+ }
13052
+ return rules;
13053
+ }, "resolveApplicableRules");
13054
+ }
13055
+ });
13056
+
13057
+ // core/knowledge/index.ts
13058
+ var init_knowledge = __esm({
13059
+ "core/knowledge/index.ts"() {
13060
+ init_acquisition_boundary();
13061
+ init_acquisition_limits();
13062
+ init_applicability();
13063
+ init_behavioral_invariants();
13064
+ init_bootstrap();
13065
+ init_built_in_context();
13066
+ init_built_in_context_rules();
13067
+ init_canonical_hash();
13068
+ init_canonical_reconstruction();
13069
+ init_canonical_schema();
13070
+ init_context_budget();
13071
+ init_contract();
13072
+ init_correction();
13073
+ init_currentness();
13074
+ init_detection_events();
13075
+ init_detection_journal();
13076
+ init_discover();
13077
+ init_solvers();
13078
+ init_signatures();
13079
+ init_probe();
13080
+ init_semantic_provider();
13081
+ init_effective_contract();
13082
+ init_exemplars();
13083
+ init_explain();
13084
+ init_feedback();
13085
+ init_fingerprint();
13086
+ init_identity_governance();
13087
+ init_identity_resolution();
13088
+ init_incidents();
13089
+ init_inspect_report();
13090
+ init_language_detect();
13091
+ init_loops();
13092
+ init_mem_package();
13093
+ init_personality_anchor();
13094
+ init_policy();
13095
+ init_policy_namespace_lock();
13096
+ init_policy_store();
13097
+ init_project();
13098
+ init_project_anchor();
13099
+ init_read_only();
13100
+ init_renderer();
13101
+ init_repository();
13102
+ init_rule_checker();
13103
+ init_rules_loader();
13104
+ init_runtime();
13105
+ init_scope_eligibility();
13106
+ init_select();
13107
+ init_session();
13108
+ init_staging();
13109
+ init_state();
13110
+ init_storage_location();
13111
+ init_storage_settings();
13112
+ init_tool_guard();
13113
+ init_user_identity();
13114
+ init_user_language();
13115
+ init_user_paths();
13116
+ init_vault();
13117
+ init_verification();
13118
+ init_verify();
13119
+ init_violations();
13120
+ init_claim_identity();
13121
+ init_store_registry();
13122
+ init_migration_audit();
13123
+ init_session_metrics();
13124
+ init_session_metrics();
13125
+ init_session_metrics();
13126
+ init_session_metrics();
13127
+ init_rule_enforcement();
13128
+ }
13129
+ });
13130
+
13131
+ // core/logic/helpers.ts
13132
+ var normalizeClaimIds2, revisionFromAcquire;
13133
+ var init_helpers = __esm({
13134
+ "core/logic/helpers.ts"() {
13135
+ normalizeClaimIds2 = /* @__PURE__ */ __name((value) => {
13136
+ if (!value) return [];
13137
+ return Array.isArray(value) ? value : [value];
13138
+ }, "normalizeClaimIds");
13139
+ revisionFromAcquire = /* @__PURE__ */ __name((opts) => {
13140
+ const refines = normalizeClaimIds2(opts.refines);
13141
+ const supersedes = normalizeClaimIds2(opts.supersedes);
13142
+ const retracts = normalizeClaimIds2(opts.retracts);
13143
+ if ([refines, supersedes, retracts].filter((ids) => ids.length > 0).length > 1) {
13144
+ throw new Error("Acquired knowledge can refine, supersede, or retract prior knowledge, not more than one");
13145
+ }
13146
+ if (refines.length > 0) return { kind: "refines", claimIds: refines, ...opts.reason ? { reason: opts.reason } : {} };
13147
+ if (supersedes.length > 0) return { kind: "supersedes", claimIds: supersedes, ...opts.reason ? { reason: opts.reason } : {} };
13148
+ if (retracts.length > 0) return { kind: "retracts", claimIds: retracts, ...opts.reason ? { reason: opts.reason } : {} };
13149
+ return void 0;
13150
+ }, "revisionFromAcquire");
13151
+ }
13152
+ });
13153
+
13154
+ // core/logic/index.ts
13155
+ var logic_exports = {};
13156
+ __export(logic_exports, {
13157
+ LogicEngine: () => LogicEngine,
13158
+ default: () => logic_default,
13159
+ getLogicRuntime: () => getLogicRuntime,
13160
+ logic: () => logic
13161
+ });
12433
13162
  var LOGIC_MEM_FILE, nodeCwd2, cachedRuntime, resetLogicRuntime, getLogicRuntime, LogicEngine, _inferConfidence, logic, logic_default;
12434
13163
  var init_logic = __esm({
12435
13164
  "core/logic/index.ts"() {
@@ -12728,21 +13457,6 @@ __export(encryption_exports, {
12728
13457
  decryptPayload: () => decryptPayload,
12729
13458
  encryptPayload: () => encryptPayload
12730
13459
  });
12731
- function getHybridKeys() {
12732
- const dir = `${resolveUserDotMemPath()}/keys`;
12733
- try {
12734
- fs__default.default.mkdirSync(dir, { recursive: true });
12735
- } catch {
12736
- }
12737
- try {
12738
- const raw = JSON.parse(fs__default.default.readFileSync(hybridKeyFile(), "utf8"));
12739
- return { publicKey: Buffer.from(raw.publicKey, "hex"), secretKey: Buffer.from(raw.secretKey, "hex") };
12740
- } catch {
12741
- }
12742
- const keys = hybrid_js.ml_kem768_x25519.keygen();
12743
- fs__default.default.writeFileSync(hybridKeyFile(), JSON.stringify({ publicKey: Buffer.from(keys.publicKey).toString("hex"), secretKey: Buffer.from(keys.secretKey).toString("hex") }), { mode: 384 });
12744
- return { publicKey: keys.publicKey, secretKey: keys.secretKey };
12745
- }
12746
13460
  function encryptPayload(plaintext) {
12747
13461
  const keys = getHybridKeys();
12748
13462
  const { sharedSecret, cipherText: kemCt } = hybrid_js.ml_kem768_x25519.encapsulate(keys.publicKey);
@@ -12758,7 +13472,7 @@ function decryptPayload(envelope) {
12758
13472
  try {
12759
13473
  if (!envelope.startsWith("{")) {
12760
13474
  const keyFile = `${resolveUserDotMemPath()}/keys/local.key`;
12761
- const hex = fs__default.default.readFileSync(keyFile, "utf8").trim();
13475
+ const hex = fs6__default.default.readFileSync(keyFile, "utf8").trim();
12762
13476
  const key2 = Buffer.from(hex, "hex");
12763
13477
  const [ivB64, tagB64, ctB64] = envelope.split(":");
12764
13478
  const iv2 = Buffer.from(ivB64, "base64");
@@ -12785,12 +13499,26 @@ function decryptPayload(envelope) {
12785
13499
  return null;
12786
13500
  }
12787
13501
  }
12788
- var hybridKeyFile;
13502
+ var hybridKeyFile, getHybridKeys;
12789
13503
  var init_encryption = __esm({
12790
13504
  "core/knowledge/encryption.ts"() {
12791
13505
  init_user_paths();
12792
13506
  hybridKeyFile = /* @__PURE__ */ __name(() => `${resolveUserDotMemPath()}/keys/hybrid.key`, "hybridKeyFile");
12793
- __name(getHybridKeys, "getHybridKeys");
13507
+ getHybridKeys = /* @__PURE__ */ __name(() => {
13508
+ const dir = `${resolveUserDotMemPath()}/keys`;
13509
+ try {
13510
+ fs6__default.default.mkdirSync(dir, { recursive: true });
13511
+ } catch {
13512
+ }
13513
+ try {
13514
+ const raw = JSON.parse(fs6__default.default.readFileSync(hybridKeyFile(), "utf8"));
13515
+ return { publicKey: Buffer.from(raw.publicKey, "hex"), secretKey: Buffer.from(raw.secretKey, "hex") };
13516
+ } catch {
13517
+ }
13518
+ const keys = hybrid_js.ml_kem768_x25519.keygen();
13519
+ fs6__default.default.writeFileSync(hybridKeyFile(), JSON.stringify({ publicKey: Buffer.from(keys.publicKey).toString("hex"), secretKey: Buffer.from(keys.secretKey).toString("hex") }), { mode: 384 });
13520
+ return { publicKey: keys.publicKey, secretKey: keys.secretKey };
13521
+ }, "getHybridKeys");
12794
13522
  __name(encryptPayload, "encryptPayload");
12795
13523
  __name(decryptPayload, "decryptPayload");
12796
13524
  }
@@ -12841,13 +13569,13 @@ var init_brain = __esm({
12841
13569
  }, "brainSave");
12842
13570
  cachedBrainPath = null;
12843
13571
  getBrainDocument = /* @__PURE__ */ __name(async () => {
12844
- const path10 = getBrainPath();
12845
- cachedBrainPath = path10;
12846
- return brainLoad(path10);
13572
+ const path11 = getBrainPath();
13573
+ cachedBrainPath = path11;
13574
+ return brainLoad(path11);
12847
13575
  }, "getBrainDocument");
12848
13576
  saveBrainDocument = /* @__PURE__ */ __name(async (document) => {
12849
- const path10 = cachedBrainPath || getBrainPath();
12850
- await brainSave(path10, document);
13577
+ const path11 = cachedBrainPath || getBrainPath();
13578
+ await brainSave(path11, document);
12851
13579
  }, "saveBrainDocument");
12852
13580
  resetBrainPathCache = /* @__PURE__ */ __name(() => {
12853
13581
  cachedBrainPath = null;
@@ -14392,7 +15120,7 @@ ${content}`);
14392
15120
  for (const file2 of files) {
14393
15121
  if (!file2.endsWith(".arch.mem")) continue;
14394
15122
  try {
14395
- const bytes = await fs14__default.default.readFile(path8__default.default.join(dir, file2));
15123
+ const bytes = await fs14__default.default.readFile(path5__default.default.join(dir, file2));
14396
15124
  const { metadata } = readZip(bytes);
14397
15125
  entries2.push(metadata);
14398
15126
  } catch {
@@ -14654,7 +15382,7 @@ var init_acquire = __esm({
14654
15382
  const { findClaimLocations: findClaimLocations2 } = await Promise.resolve().then(() => (init_claim_identity(), claim_identity_exports));
14655
15383
  const locations = await findClaimLocations2(targetId);
14656
15384
  if (locations.length === 0) {
14657
- throw new Error(`Claim ${claimId} references unknown prior claim ${targetId}. Searched all stores.`);
15385
+ throw new Error(`Claim ${claimId} references any prior claim ${targetId}. Searched all stores.`);
14658
15386
  }
14659
15387
  if (locations.length > 1) {
14660
15388
  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(", "));
@@ -15049,11 +15777,11 @@ var init_durable_store = __esm({
15049
15777
  writeFile: writeFile4,
15050
15778
  rename,
15051
15779
  copyFile,
15052
- rm: /* @__PURE__ */ __name((path10, opts) => rm(path10, opts), "rm"),
15780
+ rm: /* @__PURE__ */ __name((path11, opts) => rm(path11, opts), "rm"),
15053
15781
  mkdir,
15054
- open: /* @__PURE__ */ __name(async (path10, flags) => {
15782
+ open: /* @__PURE__ */ __name(async (path11, flags) => {
15055
15783
  if (!Deno.open) throw new Error("Deno.open is unavailable");
15056
- const file2 = await Deno.open(path10, flags);
15784
+ const file2 = await Deno.open(path11, flags);
15057
15785
  return {
15058
15786
  writeFile: /* @__PURE__ */ __name(async (data) => {
15059
15787
  const written = await file2.write(data);
@@ -15368,9 +16096,9 @@ var init_entries = __esm({
15368
16096
  };
15369
16097
  return recencyScore * confidenceScore * accessScore * typeBoost[entry.type] * scopeBoost[entry.scope];
15370
16098
  }, "computeRelevance");
15371
- getNestedPath = /* @__PURE__ */ __name((obj, path10) => {
15372
- if (!path10 || typeof path10 !== "string") return void 0;
15373
- const parts = path10.replace(/^state\./, "").split(".");
16099
+ getNestedPath = /* @__PURE__ */ __name((obj, path11) => {
16100
+ if (!path11 || typeof path11 !== "string") return void 0;
16101
+ const parts = path11.replace(/^state\./, "").split(".");
15374
16102
  let current = obj;
15375
16103
  for (const part of parts) {
15376
16104
  if (current === null || current === void 0) return void 0;
@@ -15378,9 +16106,9 @@ var init_entries = __esm({
15378
16106
  }
15379
16107
  return current;
15380
16108
  }, "getNestedPath");
15381
- setNestedPath = /* @__PURE__ */ __name((obj, path10, value) => {
15382
- if (!path10 || typeof path10 !== "string") return;
15383
- const parts = path10.replace(/^state\./, "").split(".");
16109
+ setNestedPath = /* @__PURE__ */ __name((obj, path11, value) => {
16110
+ if (!path11 || typeof path11 !== "string") return;
16111
+ const parts = path11.replace(/^state\./, "").split(".");
15384
16112
  let current = obj;
15385
16113
  for (let i3 = 0; i3 < parts.length - 1; i3++) {
15386
16114
  const part = parts[i3];
@@ -15391,9 +16119,9 @@ var init_entries = __esm({
15391
16119
  }
15392
16120
  current[parts[parts.length - 1]] = value;
15393
16121
  }, "setNestedPath");
15394
- deleteNestedPath = /* @__PURE__ */ __name((obj, path10) => {
15395
- if (!path10 || typeof path10 !== "string") return;
15396
- const parts = path10.replace(/^state\./, "").split(".");
16122
+ deleteNestedPath = /* @__PURE__ */ __name((obj, path11) => {
16123
+ if (!path11 || typeof path11 !== "string") return;
16124
+ const parts = path11.replace(/^state\./, "").split(".");
15397
16125
  let current = obj;
15398
16126
  for (let i3 = 0; i3 < parts.length - 1; i3++) {
15399
16127
  const part = parts[i3];
@@ -15867,14 +16595,14 @@ var init_store2 = __esm({
15867
16595
  const fs16 = getSyncFs();
15868
16596
  if (!fs16) return;
15869
16597
  const validated = validateConversationalState(state3);
15870
- const path10 = resolveConversationalStatePath(validated.scope, validated.subject, validated.conversationId, tenantId);
16598
+ const path11 = resolveConversationalStatePath(validated.scope, validated.subject, validated.conversationId, tenantId);
15871
16599
  const fsPromises = await import('fs/promises');
15872
16600
  await fsPromises.mkdir(resolveConversationalStateDir(tenantId), { recursive: true });
15873
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
16601
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
15874
16602
  try {
15875
16603
  await fsPromises.writeFile(temporary, `${JSON.stringify(validated, null, 2)}
15876
16604
  `, "utf8");
15877
- await fsPromises.rename(temporary, path10);
16605
+ await fsPromises.rename(temporary, path11);
15878
16606
  } catch (error) {
15879
16607
  await fsPromises.rm(temporary, { force: true }).catch(() => void 0);
15880
16608
  throw error;
@@ -16022,7 +16750,7 @@ var init_conversational_state = __esm({
16022
16750
  });
16023
16751
 
16024
16752
  // core/memory/capture-persistence.ts
16025
- var CAPTURE_STORE_KEY, CAPTURE_KEY_PREFIX, sessionRecordKey, nowIso, CapturePersistence, defaultPersistence, getCapturePersistence;
16753
+ var CAPTURE_STORE_KEY, CAPTURE_KEY_PREFIX, sessionRecordKey, nowIso2, CapturePersistence, defaultPersistence, getCapturePersistence;
16026
16754
  var init_capture_persistence = __esm({
16027
16755
  "core/memory/capture-persistence.ts"() {
16028
16756
  init_durable_store();
@@ -16030,7 +16758,7 @@ var init_capture_persistence = __esm({
16030
16758
  CAPTURE_STORE_KEY = "capture-items";
16031
16759
  CAPTURE_KEY_PREFIX = "capture:";
16032
16760
  sessionRecordKey = /* @__PURE__ */ __name((conversationId) => `${CAPTURE_KEY_PREFIX}${conversationId}`, "sessionRecordKey");
16033
- nowIso = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
16761
+ nowIso2 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
16034
16762
  CapturePersistence = class {
16035
16763
  static {
16036
16764
  __name(this, "CapturePersistence");
@@ -16045,7 +16773,7 @@ var init_capture_persistence = __esm({
16045
16773
  conversationId,
16046
16774
  items,
16047
16775
  explicitInstructions,
16048
- updatedAt: nowIso()
16776
+ updatedAt: nowIso2()
16049
16777
  };
16050
16778
  await this.store.set({
16051
16779
  id: sessionRecordKey(conversationId),
@@ -16105,7 +16833,7 @@ var init_capture_persistence = __esm({
16105
16833
  }, "getCapturePersistence");
16106
16834
  }
16107
16835
  });
16108
- 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;
16836
+ 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;
16109
16837
  var init_capture_engine = __esm({
16110
16838
  "core/memory/capture-engine.ts"() {
16111
16839
  init_exemplars();
@@ -16141,7 +16869,7 @@ var init_capture_engine = __esm({
16141
16869
  generateId = /* @__PURE__ */ __name(() => {
16142
16870
  return `capture-${memorio.hlc.serialize(memorio.hlc.tick())}-${Math.random().toString(36).slice(2, 10)}`;
16143
16871
  }, "generateId");
16144
- nowIso2 = /* @__PURE__ */ __name(() => {
16872
+ nowIso3 = /* @__PURE__ */ __name(() => {
16145
16873
  return (/* @__PURE__ */ new Date()).toISOString();
16146
16874
  }, "nowIso");
16147
16875
  normalizeText = /* @__PURE__ */ __name((text) => {
@@ -16174,7 +16902,7 @@ var init_capture_engine = __esm({
16174
16902
  type: "remember",
16175
16903
  content: text,
16176
16904
  source,
16177
- timestamp: nowIso2()
16905
+ timestamp: nowIso3()
16178
16906
  });
16179
16907
  break;
16180
16908
  }
@@ -16185,7 +16913,7 @@ var init_capture_engine = __esm({
16185
16913
  type: "do-not-remember",
16186
16914
  content: text,
16187
16915
  source,
16188
- timestamp: nowIso2()
16916
+ timestamp: nowIso3()
16189
16917
  });
16190
16918
  break;
16191
16919
  }
@@ -16538,7 +17266,7 @@ var init_capture_engine = __esm({
16538
17266
  const source = {
16539
17267
  conversationId: options.conversationId,
16540
17268
  messageIds: options.messageIds ?? [],
16541
- timestamp: nowIso2(),
17269
+ timestamp: nowIso3(),
16542
17270
  turnIndex: 0
16543
17271
  };
16544
17272
  const instructions = detectExplicitInstructions(text, source);
@@ -16558,7 +17286,7 @@ var init_capture_engine = __esm({
16558
17286
  classification: "temporary_context",
16559
17287
  confidence: "low",
16560
17288
  epistemicType: "observed",
16561
- capturedAt: nowIso2(),
17289
+ capturedAt: nowIso3(),
16562
17290
  method: "automatic"
16563
17291
  },
16564
17292
  confidence: "low",
@@ -16578,7 +17306,7 @@ var init_capture_engine = __esm({
16578
17306
  classification: category,
16579
17307
  confidence,
16580
17308
  epistemicType,
16581
- capturedAt: nowIso2(),
17309
+ capturedAt: nowIso3(),
16582
17310
  method: hasExplicitRemember ? "explicit" : "automatic"
16583
17311
  };
16584
17312
  const item = {
@@ -16640,7 +17368,7 @@ var init_capture_engine = __esm({
16640
17368
  const source = {
16641
17369
  conversationId: options.conversationId,
16642
17370
  messageIds: [msg.id ?? `msg-${index}`],
16643
- timestamp: msg.timestamp ?? nowIso2(),
17371
+ timestamp: msg.timestamp ?? nowIso3(),
16644
17372
  turnIndex: index
16645
17373
  };
16646
17374
  const instructions = detectExplicitInstructions(msg.content, source);
@@ -16660,7 +17388,7 @@ var init_capture_engine = __esm({
16660
17388
  classification: "temporary_context",
16661
17389
  confidence: "low",
16662
17390
  epistemicType: "observed",
16663
- capturedAt: nowIso2(),
17391
+ capturedAt: nowIso3(),
16664
17392
  method: "automatic"
16665
17393
  },
16666
17394
  confidence: "low",
@@ -16680,7 +17408,7 @@ var init_capture_engine = __esm({
16680
17408
  classification: category,
16681
17409
  confidence,
16682
17410
  epistemicType,
16683
- capturedAt: nowIso2(),
17411
+ capturedAt: nowIso3(),
16684
17412
  method: hasExplicitRemember ? "explicit" : "automatic"
16685
17413
  };
16686
17414
  const item = {
@@ -16837,7 +17565,7 @@ var init_capture_engine = __esm({
16837
17565
  if (this.clearedConversations.has(conversationId)) {
16838
17566
  ctx = {
16839
17567
  conversationId,
16840
- startedAt: nowIso2(),
17568
+ startedAt: nowIso3(),
16841
17569
  items: [],
16842
17570
  explicitInstructions: []
16843
17571
  };
@@ -16857,7 +17585,7 @@ var init_capture_engine = __esm({
16857
17585
  }
16858
17586
  ctx = {
16859
17587
  conversationId,
16860
- startedAt: nowIso2(),
17588
+ startedAt: nowIso3(),
16861
17589
  items: [],
16862
17590
  explicitInstructions: []
16863
17591
  };
@@ -17029,7 +17757,7 @@ var init_note = __esm({
17029
17757
  init_storage_coordinator();
17030
17758
  init_claim_identity();
17031
17759
  TOMBSTONE_FILE = "deleted-notes.tombstones.json";
17032
- tombstonePath = /* @__PURE__ */ __name(() => path8__default.default.join(resolveUserDotMemPath(), TOMBSTONE_FILE), "tombstonePath");
17760
+ tombstonePath = /* @__PURE__ */ __name(() => path5__default.default.join(resolveUserDotMemPath(), TOMBSTONE_FILE), "tombstonePath");
17033
17761
  loadNoteTombstones = /* @__PURE__ */ __name(async () => {
17034
17762
  try {
17035
17763
  const raw = await fs14__default.default.readFile(tombstonePath(), "utf8");
@@ -17045,7 +17773,7 @@ var init_note = __esm({
17045
17773
  if (!existing.some((t) => t.id === id)) {
17046
17774
  existing.push({ id, deletedAt: (/* @__PURE__ */ new Date()).toISOString() });
17047
17775
  }
17048
- await fs14__default.default.mkdir(path8__default.default.dirname(tombstonePath()), { recursive: true });
17776
+ await fs14__default.default.mkdir(path5__default.default.dirname(tombstonePath()), { recursive: true });
17049
17777
  await fs14__default.default.writeFile(tombstonePath(), JSON.stringify({ deletedNotes: existing }, null, 2), "utf8");
17050
17778
  const g2 = globalThis.__dotmemDeletedNotes || /* @__PURE__ */ new Set();
17051
17779
  g2.add(id);
@@ -17072,7 +17800,7 @@ var init_note = __esm({
17072
17800
  if (referencing.length === 0) continue;
17073
17801
  const newClaims = artifact.state.claims.filter((claim) => !(claim.revision?.claimIds ?? []).includes(noteId));
17074
17802
  const newState = { version: artifact.state.version + 1, claims: newClaims };
17075
- await withStorageLock(path8__default.default.dirname(filePath), async () => {
17803
+ await withStorageLock(path5__default.default.dirname(filePath), async () => {
17076
17804
  const currentBytes = await fs14__default.default.readFile(filePath);
17077
17805
  const currentArtifact = await decodeMemArtifact(currentBytes);
17078
17806
  if (!currentArtifact.state || currentArtifact.state.version !== artifact.state.version) {
@@ -17080,7 +17808,7 @@ var init_note = __esm({
17080
17808
  }
17081
17809
  const tmp = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
17082
17810
  try {
17083
- await fs14__default.default.mkdir(path8__default.default.dirname(filePath), { recursive: true });
17811
+ await fs14__default.default.mkdir(path5__default.default.dirname(filePath), { recursive: true });
17084
17812
  const { quarantineClaimRecord: quarantineClaimRecord2 } = await Promise.resolve().then(() => (init_quarantine(), quarantine_exports));
17085
17813
  for (const claim of referencing) {
17086
17814
  await quarantineClaimRecord2({
@@ -17213,7 +17941,7 @@ var init_note = __esm({
17213
17941
  return { deleted: 0, byStore: {}, allDeleted: finalOccurrences2.length === 0, remaining: finalOccurrences2 };
17214
17942
  }
17215
17943
  for (const [filePath, occs] of byFile) {
17216
- const storeId = occs[0]?.store ?? "unknown";
17944
+ const storeId = occs[0]?.store ?? "any";
17217
17945
  try {
17218
17946
  const bytes = await fs14__default.default.readFile(filePath);
17219
17947
  const artifact = await decodeMemArtifact(bytes);
@@ -17229,7 +17957,7 @@ var init_note = __esm({
17229
17957
  }
17230
17958
  const newClaims = artifact.state.claims.filter((c) => !(c.id === id && c.kind === "note"));
17231
17959
  const newState = { version: artifact.state.version + 1, claims: newClaims };
17232
- await withStorageLock(path8__default.default.dirname(filePath), async () => {
17960
+ await withStorageLock(path5__default.default.dirname(filePath), async () => {
17233
17961
  const currentBytes = await fs14__default.default.readFile(filePath);
17234
17962
  const currentArtifact = await decodeMemArtifact(currentBytes);
17235
17963
  if (!currentArtifact.state || currentArtifact.state.version !== artifact.state.version) {
@@ -17237,7 +17965,7 @@ var init_note = __esm({
17237
17965
  }
17238
17966
  const tmp = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
17239
17967
  try {
17240
- await fs14__default.default.mkdir(path8__default.default.dirname(filePath), { recursive: true });
17968
+ await fs14__default.default.mkdir(path5__default.default.dirname(filePath), { recursive: true });
17241
17969
  const encoded = await encodeMemPackage(newState, currentArtifact.preserved, currentArtifact.package);
17242
17970
  await fs14__default.default.writeFile(tmp, encoded);
17243
17971
  await decodeMemArtifact(await fs14__default.default.readFile(tmp));
@@ -17331,9 +18059,9 @@ var init_note = __esm({
17331
18059
  };
17332
18060
  }, "noteDeleteAll");
17333
18061
  try {
17334
- const tp = path8__default.default.join(resolveUserDotMemPath(), TOMBSTONE_FILE);
17335
- if (fs__default.default.existsSync(tp)) {
17336
- const raw = fs__default.default.readFileSync(tp, "utf8");
18062
+ const tp = path5__default.default.join(resolveUserDotMemPath(), TOMBSTONE_FILE);
18063
+ if (fs6__default.default.existsSync(tp)) {
18064
+ const raw = fs6__default.default.readFileSync(tp, "utf8");
17337
18065
  const parsed = JSON.parse(raw);
17338
18066
  const arr = Array.isArray(parsed) ? parsed : parsed.deletedNotes ?? [];
17339
18067
  const g2 = globalThis.__dotmemDeletedNotes || /* @__PURE__ */ new Set();
@@ -17666,8 +18394,8 @@ var init_ontology = __esm({
17666
18394
  errors.push("relation must be object");
17667
18395
  continue;
17668
18396
  }
17669
- if (!ids.has(r.from)) errors.push(`relation.from unknown: ${r.from}`);
17670
- if (!ids.has(r.to)) errors.push(`relation.to unknown: ${r.to}`);
18397
+ if (!ids.has(r.from)) errors.push(`relation.from any: ${r.from}`);
18398
+ if (!ids.has(r.to)) errors.push(`relation.to any: ${r.to}`);
17671
18399
  if (!RELATION_TYPES.includes(r.type)) errors.push(`relation.type invalid: ${r.type}`);
17672
18400
  }
17673
18401
  return { valid: errors.length === 0, errors };
@@ -17684,7 +18412,7 @@ var init_ontology = __esm({
17684
18412
  ),
17685
18413
  byPos: graph.concepts.reduce(
17686
18414
  (acc, c) => {
17687
- const k = c.pos || "unknown";
18415
+ const k = c.pos || "any";
17688
18416
  acc[k] = (acc[k] || 0) + 1;
17689
18417
  return acc;
17690
18418
  },
@@ -17744,7 +18472,7 @@ var init_anthology = __esm({
17744
18472
  errors.push("provenance must be an object");
17745
18473
  return { valid: false, errors };
17746
18474
  }
17747
- const kinds = ["user-statement", "system-observation", "imported-document", "external-source", "agent-inference", "model-summary", "human-correction", "system-event", "unknown"];
18475
+ const kinds = ["user-statement", "system-observation", "imported-document", "external-source", "agent-inference", "model-summary", "human-correction", "system-event", "any"];
17748
18476
  if (!kinds.includes(p.kind)) errors.push("invalid provenance kind");
17749
18477
  if (p.observedAt !== void 0 && (typeof p.observedAt !== "string" || isNaN(Date.parse(p.observedAt)))) {
17750
18478
  errors.push("observedAt must be valid ISO timestamp if provided");
@@ -17798,681 +18526,908 @@ var init_anthology = __esm({
17798
18526
  schemaVersion: 0,
17799
18527
  category: "legacy",
17800
18528
  payload: item,
17801
- scope: item?.scope ?? "unknown",
17802
- provenance: { kind: "unknown" },
18529
+ scope: item?.scope ?? "any",
18530
+ provenance: { kind: "any" },
17803
18531
  epistemicStatus: "unassessed",
17804
- sensitivity: "unknown",
18532
+ sensitivity: "any",
17805
18533
  temporal: { recordedAt: item?.createdAt ? new Date(item.createdAt).toISOString() : (/* @__PURE__ */ new Date(0)).toISOString() },
17806
18534
  revision: { revision: 0 }
17807
18535
  };
17808
18536
  }, "normalizeLegacyRecord");
17809
- MEMORY_CATEGORIES = ["observation", "claim", "fact-candidate", "hypothesis", "decision", "preference", "instruction", "experience", "goal", "relationship", "derived-summary", "unknown-disputed", "legacy"];
18537
+ MEMORY_CATEGORIES = ["observation", "claim", "fact-candidate", "hypothesis", "decision", "preference", "instruction", "experience", "goal", "relationship", "derived-summary", "any-disputed", "legacy"];
17810
18538
  EPISTEMIC_STATUSES = ["unassessed", "asserted", "corroborated", "reviewed", "disputed", "refuted", "superseded"];
17811
18539
  }
17812
18540
  });
17813
- function stripCode(content) {
17814
- let out = "";
17815
- let i3 = 0;
17816
- const n = content.length;
17817
- while (i3 < n) {
17818
- const c = content[i3];
17819
- const next = content[i3 + 1];
17820
- if (c === "/" && next === "/") {
17821
- const nl = content.indexOf("\n", i3);
17822
- if (nl === -1) break;
17823
- out += "\n";
17824
- i3 = nl + 1;
17825
- continue;
17826
- }
17827
- if (c === "/" && next === "*") {
17828
- const end = content.indexOf("*/", i3 + 2);
17829
- if (end === -1) break;
17830
- const seg = content.slice(i3, end + 2);
17831
- out += seg.replace(/[^\n]/g, " ");
17832
- i3 = end + 2;
17833
- continue;
18541
+ function audit(options = {}) {
18542
+ const projectPath = options.projectPath ?? process.cwd();
18543
+ const allFindings = scanDir(projectPath, projectPath);
18544
+ allFindings.push(...runNpmAudit(projectPath));
18545
+ const quality = allFindings.filter((f) => f.category === "quality");
18546
+ const security2 = allFindings.filter((f) => f.category === "security");
18547
+ const performance = allFindings.filter((f) => f.category === "performance");
18548
+ const errorCount = allFindings.filter((f) => f.severity === "critical" || f.severity === "high").length;
18549
+ const totalFindings = allFindings.length;
18550
+ const score = Math.max(0, 100 - errorCount * 10 - (totalFindings - errorCount) * 2);
18551
+ const grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : score >= 60 ? "D" : "F";
18552
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
18553
+ const result = {
18554
+ projectPath,
18555
+ timestamp,
18556
+ quality,
18557
+ security: security2,
18558
+ performance,
18559
+ score,
18560
+ grade,
18561
+ summary: `Audit complete: ${totalFindings} findings (${errorCount} critical/high). Score: ${score}/100 (Grade: ${grade}).`,
18562
+ report: ""
18563
+ };
18564
+ result.report = generateReport({ quality, security: security2, performance, score, grade, projectPath, timestamp });
18565
+ if (options.onFinding) {
18566
+ for (const f of allFindings) {
18567
+ options.onFinding(f);
17834
18568
  }
17835
- if (c === '"' || c === "'" || c === "`") {
17836
- const quote = c;
17837
- let j = i3 + 1;
17838
- while (j < n) {
17839
- if (content[j] === "\\") {
17840
- j += 2;
18569
+ }
18570
+ return {
18571
+ name: "audit",
18572
+ version: "0.3.0",
18573
+ description: "Professional IT audit: quality, security, performance, npm vulnerabilities.",
18574
+ hooks: {
18575
+ onAudit(_result) {
18576
+ }
18577
+ },
18578
+ run: /* @__PURE__ */ __name(() => result, "run"),
18579
+ report: /* @__PURE__ */ __name(() => result.report, "report")
18580
+ };
18581
+ }
18582
+ var stripCode, hasEval, isInNonCode, collectDangerousNames, hasProcessExec, scanFile, scanDir, runNpmAudit, generateReport;
18583
+ var init_audit = __esm({
18584
+ "plugins/audit/index.ts"() {
18585
+ stripCode = /* @__PURE__ */ __name((content) => {
18586
+ let out = "";
18587
+ let i3 = 0;
18588
+ const n = content.length;
18589
+ while (i3 < n) {
18590
+ const c = content[i3];
18591
+ const next = content[i3 + 1];
18592
+ if (c === "/" && next === "/") {
18593
+ const nl = content.indexOf("\n", i3);
18594
+ if (nl === -1) break;
18595
+ out += "\n";
18596
+ i3 = nl + 1;
17841
18597
  continue;
17842
18598
  }
17843
- if (content[j] === quote) {
17844
- j++;
17845
- break;
18599
+ if (c === "/" && next === "*") {
18600
+ const end = content.indexOf("*/", i3 + 2);
18601
+ if (end === -1) break;
18602
+ const seg = content.slice(i3, end + 2);
18603
+ out += seg.replace(/[^\n]/g, " ");
18604
+ i3 = end + 2;
18605
+ continue;
18606
+ }
18607
+ if (c === '"' || c === "'" || c === "`") {
18608
+ const quote = c;
18609
+ let j = i3 + 1;
18610
+ while (j < n) {
18611
+ if (content[j] === "\\") {
18612
+ j += 2;
18613
+ continue;
18614
+ }
18615
+ if (content[j] === quote) {
18616
+ j++;
18617
+ break;
18618
+ }
18619
+ if (content[j] === "\n") break;
18620
+ j++;
18621
+ }
18622
+ const seg = content.slice(i3, j);
18623
+ out += seg.replace(/[^\n]/g, " ");
18624
+ i3 = j;
18625
+ continue;
18626
+ }
18627
+ if (c === "/") {
18628
+ let k = out.length - 1;
18629
+ while (k >= 0 && /\s/.test(out[k])) k--;
18630
+ const prev = k >= 0 ? out[k] : "";
18631
+ const regexStartChars = "(,=:[!&|?{;+-*/%^~";
18632
+ if (regexStartChars.includes(prev) || prev === "") {
18633
+ let j = i3 + 1;
18634
+ let inClass = false;
18635
+ while (j < n) {
18636
+ if (content[j] === "\\") {
18637
+ j += 2;
18638
+ continue;
18639
+ }
18640
+ if (content[j] === "[") {
18641
+ inClass = true;
18642
+ j++;
18643
+ continue;
18644
+ }
18645
+ if (content[j] === "]") {
18646
+ inClass = false;
18647
+ j++;
18648
+ continue;
18649
+ }
18650
+ if (content[j] === "/" && !inClass) {
18651
+ j++;
18652
+ break;
18653
+ }
18654
+ if (content[j] === "\n") break;
18655
+ j++;
18656
+ }
18657
+ const seg = content.slice(i3, j);
18658
+ out += seg.replace(/[^\n]/g, " ");
18659
+ i3 = j;
18660
+ continue;
18661
+ }
17846
18662
  }
17847
- if (content[j] === "\n") break;
17848
- j++;
18663
+ out += c;
18664
+ i3++;
17849
18665
  }
17850
- const seg = content.slice(i3, j);
17851
- out += seg.replace(/[^\n]/g, " ");
17852
- i3 = j;
17853
- continue;
17854
- }
17855
- if (c === "/") {
17856
- let k = out.length - 1;
17857
- while (k >= 0 && /\s/.test(out[k])) k--;
17858
- const prev = k >= 0 ? out[k] : "";
17859
- const regexStartChars = "(,=:[!&|?{;+-*/%^~";
17860
- if (regexStartChars.includes(prev) || prev === "") {
17861
- let j = i3 + 1;
17862
- let inClass = false;
17863
- while (j < n) {
17864
- if (content[j] === "\\") {
17865
- j += 2;
18666
+ return out;
18667
+ }, "stripCode");
18668
+ hasEval = /* @__PURE__ */ __name((content) => {
18669
+ const code = stripCode(content);
18670
+ if (/\b(?:globalThis|global|window|self)\s*\.\s*eval\s*\(/.test(code)) return true;
18671
+ if (/\beval\s*\(/.test(code)) return true;
18672
+ return false;
18673
+ }, "hasEval");
18674
+ isInNonCode = /* @__PURE__ */ __name((content, index) => {
18675
+ let i3 = 0;
18676
+ let inLineComment = false;
18677
+ let inBlockComment = false;
18678
+ let inString = null;
18679
+ while (i3 < index) {
18680
+ const c = content[i3];
18681
+ const next = content[i3 + 1];
18682
+ if (inLineComment) {
18683
+ if (c === "\n") inLineComment = false;
18684
+ i3++;
18685
+ continue;
18686
+ }
18687
+ if (inBlockComment) {
18688
+ if (c === "*" && next === "/") {
18689
+ inBlockComment = false;
18690
+ i3 += 2;
17866
18691
  continue;
17867
18692
  }
17868
- if (content[j] === "[") {
17869
- inClass = true;
17870
- j++;
18693
+ i3++;
18694
+ continue;
18695
+ }
18696
+ if (inString) {
18697
+ if (c === "\\") {
18698
+ i3 += 2;
17871
18699
  continue;
17872
18700
  }
17873
- if (content[j] === "]") {
17874
- inClass = false;
17875
- j++;
18701
+ if (c === inString) inString = null;
18702
+ i3++;
18703
+ continue;
18704
+ }
18705
+ if (c === "/" && next === "/") {
18706
+ inLineComment = true;
18707
+ i3 += 2;
18708
+ continue;
18709
+ }
18710
+ if (c === "/" && next === "*") {
18711
+ inBlockComment = true;
18712
+ i3 += 2;
18713
+ continue;
18714
+ }
18715
+ if (c === '"' || c === "'" || c === "`") {
18716
+ inString = c;
18717
+ i3++;
18718
+ continue;
18719
+ }
18720
+ i3++;
18721
+ }
18722
+ return inLineComment || inBlockComment || inString !== null;
18723
+ }, "isInNonCode");
18724
+ collectDangerousNames = /* @__PURE__ */ __name((content) => {
18725
+ const names = /* @__PURE__ */ new Set();
18726
+ const namespaces = /* @__PURE__ */ new Set();
18727
+ const addName = /* @__PURE__ */ __name((name, local) => {
18728
+ if (["exec", "execSync", "spawn", "spawnSync"].includes(name)) {
18729
+ names.add(local);
18730
+ }
18731
+ }, "addName");
18732
+ let m;
18733
+ const esImport = /import\s*\{([^}]+)\}\s*from\s*['"](?:node:)?child_process['"]/g;
18734
+ while ((m = esImport.exec(content)) !== null) {
18735
+ if (isInNonCode(content, m.index)) continue;
18736
+ for (const part of m[1].split(",")) {
18737
+ const p = part.trim();
18738
+ if (!p) continue;
18739
+ const alias = p.match(/^(\w+)\s+as\s+(\w+)$/);
18740
+ if (alias) addName(alias[1], alias[2]);
18741
+ else addName(p, p);
18742
+ }
18743
+ }
18744
+ const esNs = /import\s*\*\s*as\s+(\w+)\s*from\s*['"](?:node:)?child_process['"]/g;
18745
+ while ((m = esNs.exec(content)) !== null) {
18746
+ if (isInNonCode(content, m.index)) continue;
18747
+ namespaces.add(m[1]);
18748
+ }
18749
+ const cjsDestruct = /(?:const|let|var)\s*\{([^}]+)\}\s*=\s*require\(\s*['"](?:node:)?child_process['"]\s*\)/g;
18750
+ while ((m = cjsDestruct.exec(content)) !== null) {
18751
+ if (isInNonCode(content, m.index)) continue;
18752
+ for (const part of m[1].split(",")) {
18753
+ const p = part.trim();
18754
+ if (!p) continue;
18755
+ const colon = p.match(/^(\w+)\s*:\s*(\w+)$/);
18756
+ if (colon) {
18757
+ addName(colon[1], colon[2]);
17876
18758
  continue;
17877
18759
  }
17878
- if (content[j] === "/" && !inClass) {
17879
- j++;
17880
- break;
18760
+ const alias = p.match(/^(\w+)\s+as\s+(\w+)$/);
18761
+ if (alias) addName(alias[1], alias[2]);
18762
+ else addName(p, p);
18763
+ }
18764
+ }
18765
+ const cjsNs = /(?:const|let|var)\s+(\w+)\s*=\s*require\(\s*['"](?:node:)?child_process['"]\s*\)/g;
18766
+ while ((m = cjsNs.exec(content)) !== null) {
18767
+ if (isInNonCode(content, m.index)) continue;
18768
+ namespaces.add(m[1]);
18769
+ }
18770
+ const cjsProp = /(?:const|let|var)\s+(\w+)\s*=\s*require\(\s*['"](?:node:)?child_process['"]\s*\)\s*\.\s*(exec|execSync|spawn|spawnSync)\b/g;
18771
+ while ((m = cjsProp.exec(content)) !== null) {
18772
+ if (isInNonCode(content, m.index)) continue;
18773
+ names.add(m[1]);
18774
+ }
18775
+ return { names, namespaces };
18776
+ }, "collectDangerousNames");
18777
+ hasProcessExec = /* @__PURE__ */ __name((content) => {
18778
+ const code = stripCode(content);
18779
+ const { names, namespaces } = collectDangerousNames(content);
18780
+ for (const ns of namespaces) {
18781
+ const re = new RegExp("\\b" + ns + "\\s*\\.\\s*(exec|execSync|spawn|spawnSync)\\s*\\(");
18782
+ if (re.test(code)) return true;
18783
+ }
18784
+ for (const name of names) {
18785
+ const re = new RegExp("\\b" + name + "\\s*\\(");
18786
+ if (re.test(code)) return true;
18787
+ }
18788
+ if (/\b(?:child_process|childProcess)\s*\.\s*(exec|execSync|spawn|spawnSync)\s*\(/.test(code)) return true;
18789
+ if (/require\(\s*['"](?:node:)?child_process['"]\s*\)\s*\.\s*(exec|execSync|spawn|spawnSync)\s*\(/.test(code)) return true;
18790
+ return false;
18791
+ }, "hasProcessExec");
18792
+ scanFile = /* @__PURE__ */ __name((filePath, content, projectPath) => {
18793
+ const findings = [];
18794
+ const lines = content.split("\n");
18795
+ const relPath = path5.relative(projectPath, filePath);
18796
+ const ext = path5.extname(filePath);
18797
+ if (/password\s*=\s*['"]/i.test(content)) {
18798
+ 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)" });
18799
+ }
18800
+ if (/api[_-]?key\s*=\s*['"]/i.test(content)) {
18801
+ 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)" });
18802
+ }
18803
+ if (/secret\s*=\s*['"]/i.test(content)) {
18804
+ 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)" });
18805
+ }
18806
+ if (hasEval(content)) {
18807
+ 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)" });
18808
+ }
18809
+ if (/innerHTML\s*=/.test(content)) {
18810
+ 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)" });
18811
+ }
18812
+ if (/document\.write\s*\(/.test(content)) {
18813
+ 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" });
18814
+ }
18815
+ if (hasProcessExec(content)) {
18816
+ 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)" });
18817
+ }
18818
+ if (/cors\s*\(\s*\{\s*origin:\s*['"]\*['"]/.test(content)) {
18819
+ 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)" });
18820
+ }
18821
+ if (/debug\s*:\s*true/.test(content)) {
18822
+ 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)" });
18823
+ }
18824
+ const consoleCount = (content.match(/console\.log/g) || []).length;
18825
+ if (consoleCount > 5 && !filePath.includes("test")) {
18826
+ 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)" });
18827
+ }
18828
+ if (ext === ".c" || ext === ".cpp" || ext === ".rs") {
18829
+ if (/strcpy|strcat|sprintf|gets\s*\(/.test(content)) {
18830
+ 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)" });
18831
+ }
18832
+ }
18833
+ if (lines.length > 500) {
18834
+ 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)" });
18835
+ }
18836
+ const todoCount = (content.match(/TODO|FIXME|HACK|XXX/gi) || []).length;
18837
+ if (todoCount > 3) {
18838
+ 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" });
18839
+ }
18840
+ if (!content.includes("test") && (ext === ".ts" || ext === ".js") && !filePath.includes("test") && !filePath.includes("spec")) {
18841
+ 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" });
18842
+ }
18843
+ if (/await\s+\w+\(/.test(content) && !content.includes("try") && !content.includes("catch")) {
18844
+ 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" });
18845
+ }
18846
+ const nestedLoops = content.match(/for\s*\(.*\)\s*\{[^}]*for\s*\(/g);
18847
+ if (nestedLoops && nestedLoops.length > 0) {
18848
+ 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" });
18849
+ }
18850
+ if (/JSON\.parse\(.*JSON\.stringify/.test(content)) {
18851
+ 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" });
18852
+ }
18853
+ const syncReads = (content.match(/readFileSync/g) || []).length;
18854
+ if (syncReads > 3) {
18855
+ 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" });
18856
+ }
18857
+ return findings;
18858
+ }, "scanFile");
18859
+ scanDir = /* @__PURE__ */ __name((dir, projectPath) => {
18860
+ const allFindings = [];
18861
+ try {
18862
+ const entries2 = fs6.readdirSync(dir, { withFileTypes: true });
18863
+ for (const entry of entries2) {
18864
+ if (["node_modules", ".git", "dist", ".cache", "coverage", ".private", ".project", ".dev"].includes(entry.name)) continue;
18865
+ const fullPath = path5.join(dir, entry.name);
18866
+ if (entry.isDirectory()) {
18867
+ allFindings.push(...scanDir(fullPath, projectPath));
18868
+ } else if (entry.isFile() && /\.(ts|js|tsx|jsx|py|go|rs|c|cpp|java)$/.test(entry.name)) {
18869
+ try {
18870
+ const content = fs6.readFileSync(fullPath, "utf-8");
18871
+ allFindings.push(...scanFile(fullPath, content, projectPath));
18872
+ } catch {
18873
+ }
17881
18874
  }
17882
- if (content[j] === "\n") break;
17883
- j++;
17884
18875
  }
17885
- const seg = content.slice(i3, j);
17886
- out += seg.replace(/[^\n]/g, " ");
17887
- i3 = j;
17888
- continue;
18876
+ } catch {
17889
18877
  }
17890
- }
17891
- out += c;
17892
- i3++;
17893
- }
17894
- return out;
17895
- }
17896
- function hasEval(content) {
17897
- const code = stripCode(content);
17898
- if (/\b(?:globalThis|global|window|self)\s*\.\s*eval\s*\(/.test(code)) return true;
17899
- if (/\beval\s*\(/.test(code)) return true;
17900
- return false;
17901
- }
17902
- function isInNonCode(content, index) {
17903
- let i3 = 0;
17904
- let inLineComment = false;
17905
- let inBlockComment = false;
17906
- let inString = null;
17907
- while (i3 < index) {
17908
- const c = content[i3];
17909
- const next = content[i3 + 1];
17910
- if (inLineComment) {
17911
- if (c === "\n") inLineComment = false;
17912
- i3++;
17913
- continue;
17914
- }
17915
- if (inBlockComment) {
17916
- if (c === "*" && next === "/") {
17917
- inBlockComment = false;
17918
- i3 += 2;
17919
- continue;
17920
- }
17921
- i3++;
17922
- continue;
17923
- }
17924
- if (inString) {
17925
- if (c === "\\") {
17926
- i3 += 2;
17927
- continue;
17928
- }
17929
- if (c === inString) inString = null;
17930
- i3++;
17931
- continue;
17932
- }
17933
- if (c === "/" && next === "/") {
17934
- inLineComment = true;
17935
- i3 += 2;
17936
- continue;
17937
- }
17938
- if (c === "/" && next === "*") {
17939
- inBlockComment = true;
17940
- i3 += 2;
17941
- continue;
17942
- }
17943
- if (c === '"' || c === "'" || c === "`") {
17944
- inString = c;
17945
- i3++;
17946
- continue;
17947
- }
17948
- i3++;
17949
- }
17950
- return inLineComment || inBlockComment || inString !== null;
17951
- }
17952
- function collectDangerousNames(content) {
17953
- const names = /* @__PURE__ */ new Set();
17954
- const namespaces = /* @__PURE__ */ new Set();
17955
- const addName = /* @__PURE__ */ __name((name, local) => {
17956
- if (["exec", "execSync", "spawn", "spawnSync"].includes(name)) {
17957
- names.add(local);
17958
- }
17959
- }, "addName");
17960
- let m;
17961
- const esImport = /import\s*\{([^}]+)\}\s*from\s*['"](?:node:)?child_process['"]/g;
17962
- while ((m = esImport.exec(content)) !== null) {
17963
- if (isInNonCode(content, m.index)) continue;
17964
- for (const part of m[1].split(",")) {
17965
- const p = part.trim();
17966
- if (!p) continue;
17967
- const alias = p.match(/^(\w+)\s+as\s+(\w+)$/);
17968
- if (alias) addName(alias[1], alias[2]);
17969
- else addName(p, p);
17970
- }
17971
- }
17972
- const esNs = /import\s*\*\s*as\s+(\w+)\s*from\s*['"](?:node:)?child_process['"]/g;
17973
- while ((m = esNs.exec(content)) !== null) {
17974
- if (isInNonCode(content, m.index)) continue;
17975
- namespaces.add(m[1]);
17976
- }
17977
- const cjsDestruct = /(?:const|let|var)\s*\{([^}]+)\}\s*=\s*require\(\s*['"](?:node:)?child_process['"]\s*\)/g;
17978
- while ((m = cjsDestruct.exec(content)) !== null) {
17979
- if (isInNonCode(content, m.index)) continue;
17980
- for (const part of m[1].split(",")) {
17981
- const p = part.trim();
17982
- if (!p) continue;
17983
- const colon = p.match(/^(\w+)\s*:\s*(\w+)$/);
17984
- if (colon) {
17985
- addName(colon[1], colon[2]);
17986
- continue;
17987
- }
17988
- const alias = p.match(/^(\w+)\s+as\s+(\w+)$/);
17989
- if (alias) addName(alias[1], alias[2]);
17990
- else addName(p, p);
17991
- }
17992
- }
17993
- const cjsNs = /(?:const|let|var)\s+(\w+)\s*=\s*require\(\s*['"](?:node:)?child_process['"]\s*\)/g;
17994
- while ((m = cjsNs.exec(content)) !== null) {
17995
- if (isInNonCode(content, m.index)) continue;
17996
- namespaces.add(m[1]);
17997
- }
17998
- const cjsProp = /(?:const|let|var)\s+(\w+)\s*=\s*require\(\s*['"](?:node:)?child_process['"]\s*\)\s*\.\s*(exec|execSync|spawn|spawnSync)\b/g;
17999
- while ((m = cjsProp.exec(content)) !== null) {
18000
- if (isInNonCode(content, m.index)) continue;
18001
- names.add(m[1]);
18002
- }
18003
- return { names, namespaces };
18004
- }
18005
- function hasProcessExec(content) {
18006
- const code = stripCode(content);
18007
- const { names, namespaces } = collectDangerousNames(content);
18008
- for (const ns of namespaces) {
18009
- const re = new RegExp("\\b" + ns + "\\s*\\.\\s*(exec|execSync|spawn|spawnSync)\\s*\\(");
18010
- if (re.test(code)) return true;
18011
- }
18012
- for (const name of names) {
18013
- const re = new RegExp("\\b" + name + "\\s*\\(");
18014
- if (re.test(code)) return true;
18015
- }
18016
- if (/\b(?:child_process|childProcess)\s*\.\s*(exec|execSync|spawn|spawnSync)\s*\(/.test(code)) return true;
18017
- if (/require\(\s*['"](?:node:)?child_process['"]\s*\)\s*\.\s*(exec|execSync|spawn|spawnSync)\s*\(/.test(code)) return true;
18018
- return false;
18019
- }
18020
- function scanFile(filePath, content, projectPath) {
18021
- const findings = [];
18022
- const lines = content.split("\n");
18023
- const relPath = path8.relative(projectPath, filePath);
18024
- const ext = path8.extname(filePath);
18025
- if (/password\s*=\s*['"]/i.test(content)) {
18026
- 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)" });
18027
- }
18028
- if (/api[_-]?key\s*=\s*['"]/i.test(content)) {
18029
- 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)" });
18030
- }
18031
- if (/secret\s*=\s*['"]/i.test(content)) {
18032
- 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)" });
18033
- }
18034
- if (hasEval(content)) {
18035
- 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)" });
18036
- }
18037
- if (/innerHTML\s*=/.test(content)) {
18038
- 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)" });
18039
- }
18040
- if (/document\.write\s*\(/.test(content)) {
18041
- 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" });
18042
- }
18043
- if (hasProcessExec(content)) {
18044
- 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)" });
18045
- }
18046
- if (/cors\s*\(\s*\{\s*origin:\s*['"]\*['"]/.test(content)) {
18047
- 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)" });
18048
- }
18049
- if (/debug\s*:\s*true/.test(content)) {
18050
- 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)" });
18051
- }
18052
- const consoleCount = (content.match(/console\.log/g) || []).length;
18053
- if (consoleCount > 5 && !filePath.includes("test")) {
18054
- 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)" });
18055
- }
18056
- if (ext === ".c" || ext === ".cpp" || ext === ".rs") {
18057
- if (/strcpy|strcat|sprintf|gets\s*\(/.test(content)) {
18058
- 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)" });
18059
- }
18060
- }
18061
- if (lines.length > 500) {
18062
- 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)" });
18063
- }
18064
- const todoCount = (content.match(/TODO|FIXME|HACK|XXX/gi) || []).length;
18065
- if (todoCount > 3) {
18066
- 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" });
18067
- }
18068
- if (!content.includes("test") && (ext === ".ts" || ext === ".js") && !filePath.includes("test") && !filePath.includes("spec")) {
18069
- 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" });
18070
- }
18071
- if (/await\s+\w+\(/.test(content) && !content.includes("try") && !content.includes("catch")) {
18072
- 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" });
18073
- }
18074
- const nestedLoops = content.match(/for\s*\(.*\)\s*\{[^}]*for\s*\(/g);
18075
- if (nestedLoops && nestedLoops.length > 0) {
18076
- 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" });
18077
- }
18078
- if (/JSON\.parse\(.*JSON\.stringify/.test(content)) {
18079
- 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" });
18080
- }
18081
- const syncReads = (content.match(/readFileSync/g) || []).length;
18082
- if (syncReads > 3) {
18083
- 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" });
18084
- }
18085
- return findings;
18086
- }
18087
- function scanDir(dir, projectPath) {
18088
- const allFindings = [];
18089
- try {
18090
- const entries2 = fs.readdirSync(dir, { withFileTypes: true });
18091
- for (const entry of entries2) {
18092
- if (["node_modules", ".git", "dist", ".cache", "coverage", ".private", ".project", ".dev"].includes(entry.name)) continue;
18093
- const fullPath = path8.join(dir, entry.name);
18094
- if (entry.isDirectory()) {
18095
- allFindings.push(...scanDir(fullPath, projectPath));
18096
- } else if (entry.isFile() && /\.(ts|js|tsx|jsx|py|go|rs|c|cpp|java)$/.test(entry.name)) {
18878
+ return allFindings;
18879
+ }, "scanDir");
18880
+ runNpmAudit = /* @__PURE__ */ __name((projectPath) => {
18881
+ const findings = [];
18882
+ try {
18883
+ let output = "";
18097
18884
  try {
18098
- const content = fs.readFileSync(fullPath, "utf-8");
18099
- allFindings.push(...scanFile(fullPath, content, projectPath));
18100
- } catch {
18885
+ output = child_process.execFileSync("npm", ["audit", "--json"], { cwd: projectPath, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
18886
+ } catch (e) {
18887
+ output = e.stdout || "";
18888
+ }
18889
+ if (!output) return findings;
18890
+ const data = JSON.parse(output);
18891
+ const vulns = data.vulnerabilities ?? {};
18892
+ let idCounter = 1;
18893
+ for (const [name, info] of Object.entries(vulns)) {
18894
+ const severity = (info.severity ?? "low").toLowerCase();
18895
+ const mappedSeverity = severity === "critical" ? "critical" : severity === "high" ? "high" : severity === "moderate" ? "medium" : "low";
18896
+ const via = Array.isArray(info.via) ? info.via.filter((v) => typeof v === "object").map((v) => v.title || v.name).join(", ") : "";
18897
+ findings.push({
18898
+ id: `NPM-${String(idCounter++).padStart(3, "0")}`,
18899
+ category: "security",
18900
+ severity: mappedSeverity,
18901
+ framework: "npm audit",
18902
+ control: "OWASP A06",
18903
+ message: `${name}: ${via || info.name || "vulnerability"} (${severity})`,
18904
+ file: "package.json",
18905
+ remediation: `Run "npm audit fix" or update ${name} to a patched version`
18906
+ });
18101
18907
  }
18908
+ const meta = data.metadata?.vulnerabilities;
18909
+ if (meta && meta.total > 0) {
18910
+ findings.push({
18911
+ id: "NPM-SUM",
18912
+ category: "security",
18913
+ severity: meta.critical > 0 ? "critical" : meta.high > 0 ? "high" : meta.moderate > 0 ? "medium" : "low",
18914
+ framework: "npm audit",
18915
+ control: "OWASP A06",
18916
+ message: `npm audit: ${meta.total} vulnerabilities (${meta.critical} critical, ${meta.high} high, ${meta.moderate} moderate, ${meta.low} low)`,
18917
+ file: "package.json",
18918
+ remediation: 'Run "npm audit fix" to resolve. Review breaking changes before applying.'
18919
+ });
18920
+ }
18921
+ } catch {
18102
18922
  }
18103
- }
18104
- } catch {
18105
- }
18106
- return allFindings;
18107
- }
18108
- function runNpmAudit(projectPath) {
18109
- const findings = [];
18110
- try {
18111
- let output = "";
18112
- try {
18113
- output = child_process.execFileSync("npm", ["audit", "--json"], { cwd: projectPath, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
18114
- } catch (e) {
18115
- output = e.stdout || "";
18116
- }
18117
- if (!output) return findings;
18118
- const data = JSON.parse(output);
18119
- const vulns = data.vulnerabilities ?? {};
18120
- let idCounter = 1;
18121
- for (const [name, info] of Object.entries(vulns)) {
18122
- const severity = (info.severity ?? "low").toLowerCase();
18123
- const mappedSeverity = severity === "critical" ? "critical" : severity === "high" ? "high" : severity === "moderate" ? "medium" : "low";
18124
- const via = Array.isArray(info.via) ? info.via.filter((v) => typeof v === "object").map((v) => v.title || v.name).join(", ") : "";
18125
- findings.push({
18126
- id: `NPM-${String(idCounter++).padStart(3, "0")}`,
18127
- category: "security",
18128
- severity: mappedSeverity,
18129
- framework: "npm audit",
18130
- control: "OWASP A06",
18131
- message: `${name}: ${via || info.name || "vulnerability"} (${severity})`,
18132
- file: "package.json",
18133
- remediation: `Run "npm audit fix" or update ${name} to a patched version`
18134
- });
18135
- }
18136
- const meta = data.metadata?.vulnerabilities;
18137
- if (meta && meta.total > 0) {
18138
- findings.push({
18139
- id: "NPM-SUM",
18140
- category: "security",
18141
- severity: meta.critical > 0 ? "critical" : meta.high > 0 ? "high" : meta.moderate > 0 ? "medium" : "low",
18142
- framework: "npm audit",
18143
- control: "OWASP A06",
18144
- message: `npm audit: ${meta.total} vulnerabilities (${meta.critical} critical, ${meta.high} high, ${meta.moderate} moderate, ${meta.low} low)`,
18145
- file: "package.json",
18146
- remediation: 'Run "npm audit fix" to resolve. Review breaking changes before applying.'
18147
- });
18148
- }
18149
- } catch {
18150
- }
18151
- return findings;
18152
- }
18153
- function generateReport(result) {
18154
- const { quality, security: security2, performance, score, grade, projectPath, timestamp } = result;
18155
- const all = [...quality, ...security2, ...performance];
18156
- const critical = all.filter((f) => f.severity === "critical").length;
18157
- const high = all.filter((f) => f.severity === "high").length;
18158
- const medium = all.filter((f) => f.severity === "medium").length;
18159
- const low = all.filter((f) => f.severity === "low" || f.severity === "info").length;
18160
- let report = "";
18161
- 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";
18162
- report += " PROFESSIONAL IT AUDIT REPORT\n";
18163
- 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";
18164
- report += `Project: ${projectPath}
18923
+ return findings;
18924
+ }, "runNpmAudit");
18925
+ generateReport = /* @__PURE__ */ __name((result) => {
18926
+ const { quality, security: security2, performance, score, grade, projectPath, timestamp } = result;
18927
+ const all = [...quality, ...security2, ...performance];
18928
+ const critical = all.filter((f) => f.severity === "critical").length;
18929
+ const high = all.filter((f) => f.severity === "high").length;
18930
+ const medium = all.filter((f) => f.severity === "medium").length;
18931
+ const low = all.filter((f) => f.severity === "low" || f.severity === "info").length;
18932
+ let report = "";
18933
+ 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";
18934
+ report += " PROFESSIONAL IT AUDIT REPORT\n";
18935
+ 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";
18936
+ report += `Project: ${projectPath}
18165
18937
  `;
18166
- report += `Date: ${timestamp}
18938
+ report += `Date: ${timestamp}
18167
18939
  `;
18168
- report += `Auditor: dotmem audit plugin
18940
+ report += `Auditor: dotmem audit plugin
18169
18941
  `;
18170
- report += `Frameworks: OWASP Top 10, NIST SP 800-53, NSA/CISA Guidelines, ISO 25010, npm audit
18942
+ report += `Frameworks: OWASP Top 10, NIST SP 800-53, NSA/CISA Guidelines, ISO 25010, npm audit
18171
18943
  `;
18172
- report += `OSI Layers: L7 (Application) analyzed
18944
+ report += `OSI Layers: L7 (Application) analyzed
18173
18945
 
18174
18946
  `;
18175
- 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";
18176
- report += " EXECUTIVE SUMMARY\n";
18177
- 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";
18178
- report += `Overall Score: ${score}/100 (Grade: ${grade})
18947
+ 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";
18948
+ report += " EXECUTIVE SUMMARY\n";
18949
+ 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";
18950
+ report += `Overall Score: ${score}/100 (Grade: ${grade})
18179
18951
  `;
18180
- report += `Total Findings: ${all.length}
18952
+ report += `Total Findings: ${all.length}
18181
18953
  `;
18182
- report += ` Critical: ${critical} High: ${high} Medium: ${medium} Low/Info: ${low}
18954
+ report += ` Critical: ${critical} High: ${high} Medium: ${medium} Low/Info: ${low}
18183
18955
 
18184
18956
  `;
18185
- report += ` Quality: ${quality.length} findings
18957
+ report += ` Quality: ${quality.length} findings
18186
18958
  `;
18187
- report += ` Security: ${security2.length} findings (incl. npm vulnerabilities)
18959
+ report += ` Security: ${security2.length} findings (incl. npm vulnerabilities)
18188
18960
  `;
18189
- report += ` Performance: ${performance.length} findings
18961
+ report += ` Performance: ${performance.length} findings
18190
18962
 
18191
18963
  `;
18192
- 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";
18193
- report += " 1. SECURITY ASSESSMENT\n";
18194
- 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";
18195
- report += "Frameworks: OWASP Top 10 (2021), NIST SP 800-53 Rev.5, NSA Secure Coding, npm audit\n\n";
18196
- if (security2.length === 0) {
18197
- report += "No security findings. All checks passed.\n\n";
18198
- } else {
18199
- for (const f of security2) {
18200
- report += `[${f.severity.toUpperCase()}] ${f.id}: ${f.message}
18964
+ 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";
18965
+ report += " 1. SECURITY ASSESSMENT\n";
18966
+ 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";
18967
+ report += "Frameworks: OWASP Top 10 (2021), NIST SP 800-53 Rev.5, NSA Secure Coding, npm audit\n\n";
18968
+ if (security2.length === 0) {
18969
+ report += "No security findings. All checks passed.\n\n";
18970
+ } else {
18971
+ for (const f of security2) {
18972
+ report += `[${f.severity.toUpperCase()}] ${f.id}: ${f.message}
18201
18973
  `;
18202
- report += ` Framework: ${f.framework} ${f.control}
18974
+ report += ` Framework: ${f.framework} ${f.control}
18203
18975
  `;
18204
- if (f.file) report += ` File: ${f.file}
18976
+ if (f.file) report += ` File: ${f.file}
18205
18977
  `;
18206
- report += ` Remediation: ${f.remediation}
18978
+ report += ` Remediation: ${f.remediation}
18207
18979
 
18208
18980
  `;
18209
- }
18210
- }
18211
- 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";
18212
- report += " 2. QUALITY ASSESSMENT\n";
18213
- 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";
18214
- report += "Framework: ISO/IEC 25010 Software Quality Model\n\n";
18215
- if (quality.length === 0) {
18216
- report += "No quality findings. All checks passed.\n\n";
18217
- } else {
18218
- for (const f of quality) {
18219
- report += `[${f.severity.toUpperCase()}] ${f.id}: ${f.message}
18981
+ }
18982
+ }
18983
+ 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";
18984
+ report += " 2. QUALITY ASSESSMENT\n";
18985
+ 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";
18986
+ report += "Framework: ISO/IEC 25010 Software Quality Model\n\n";
18987
+ if (quality.length === 0) {
18988
+ report += "No quality findings. All checks passed.\n\n";
18989
+ } else {
18990
+ for (const f of quality) {
18991
+ report += `[${f.severity.toUpperCase()}] ${f.id}: ${f.message}
18220
18992
  `;
18221
- report += ` Framework: ${f.framework} - ${f.control}
18993
+ report += ` Framework: ${f.framework} - ${f.control}
18222
18994
  `;
18223
- if (f.file) report += ` File: ${f.file}
18995
+ if (f.file) report += ` File: ${f.file}
18224
18996
  `;
18225
- report += ` Remediation: ${f.remediation}
18997
+ report += ` Remediation: ${f.remediation}
18226
18998
 
18227
18999
  `;
18228
- }
18229
- }
18230
- 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";
18231
- report += " 3. PERFORMANCE ASSESSMENT\n";
18232
- 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";
18233
- report += "Framework: OSI Model Layer 7 (Application) Analysis\n\n";
18234
- if (performance.length === 0) {
18235
- report += "No performance findings. All checks passed.\n\n";
18236
- } else {
18237
- for (const f of performance) {
18238
- report += `[${f.severity.toUpperCase()}] ${f.id}: ${f.message}
19000
+ }
19001
+ }
19002
+ 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";
19003
+ report += " 3. PERFORMANCE ASSESSMENT\n";
19004
+ 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";
19005
+ report += "Framework: OSI Model Layer 7 (Application) Analysis\n\n";
19006
+ if (performance.length === 0) {
19007
+ report += "No performance findings. All checks passed.\n\n";
19008
+ } else {
19009
+ for (const f of performance) {
19010
+ report += `[${f.severity.toUpperCase()}] ${f.id}: ${f.message}
18239
19011
  `;
18240
- report += ` Framework: ${f.framework} - ${f.control}
19012
+ report += ` Framework: ${f.framework} - ${f.control}
18241
19013
  `;
18242
- if (f.file) report += ` File: ${f.file}
19014
+ if (f.file) report += ` File: ${f.file}
18243
19015
  `;
18244
- report += ` Remediation: ${f.remediation}
19016
+ report += ` Remediation: ${f.remediation}
18245
19017
 
18246
19018
  `;
18247
- }
18248
- }
18249
- 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";
18250
- report += " 4. RECOMMENDATIONS\n";
18251
- 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";
18252
- const criticalFindings = all.filter((f) => f.severity === "critical" || f.severity === "high");
18253
- if (criticalFindings.length === 0) {
18254
- report += "No critical or high-severity findings. Project meets baseline security standards.\n\n";
18255
- } else {
18256
- report += "Priority actions (critical/high severity):\n";
18257
- for (const f of criticalFindings) {
18258
- report += ` - ${f.id}: ${f.message} (${f.file ?? "N/A"})
18259
- `;
18260
- }
18261
- report += "\n";
18262
- }
18263
- 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";
18264
- report += " 5. FRAMEWORK COMPLIANCE MATRIX\n";
18265
- 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";
18266
- report += "OWASP Top 10 (2021):\n";
18267
- const owaspIds = ["A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08", "A09", "A10"];
18268
- const owaspNames = ["Broken Access Control", "Cryptographic Failures", "Injection", "Insecure Design", "Security Misconfiguration", "Vulnerable Components", "Auth Failures", "Integrity Failures", "Logging Failures", "SSRF"];
18269
- for (let i3 = 0; i3 < owaspIds.length; i3++) {
18270
- const found = security2.some((f) => f.control === owaspIds[i3]);
18271
- report += ` ${owaspIds[i3]} ${owaspNames[i3]}: ${found ? "FINDINGS" : "PASS"}
18272
- `;
18273
- }
18274
- report += "\nnpm audit:\n";
18275
- const npmFindings = security2.filter((f) => f.framework === "npm audit");
18276
- report += ` Total vulnerabilities: ${npmFindings.filter((f) => f.id !== "NPM-SUM").length}
18277
- `;
18278
- report += ` Status: ${npmFindings.length > 0 ? "FINDINGS" : "PASS"}
18279
- `;
18280
- 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";
18281
- report += " END OF REPORT\n";
18282
- 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";
18283
- return report;
18284
- }
18285
- function audit(options = {}) {
18286
- const projectPath = options.projectPath ?? process.cwd();
18287
- const allFindings = scanDir(projectPath, projectPath);
18288
- allFindings.push(...runNpmAudit(projectPath));
18289
- const quality = allFindings.filter((f) => f.category === "quality");
18290
- const security2 = allFindings.filter((f) => f.category === "security");
18291
- const performance = allFindings.filter((f) => f.category === "performance");
18292
- const errorCount = allFindings.filter((f) => f.severity === "critical" || f.severity === "high").length;
18293
- const totalFindings = allFindings.length;
18294
- const score = Math.max(0, 100 - errorCount * 10 - (totalFindings - errorCount) * 2);
18295
- const grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : score >= 60 ? "D" : "F";
18296
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
18297
- const result = {
18298
- projectPath,
18299
- timestamp,
18300
- quality,
18301
- security: security2,
18302
- performance,
18303
- score,
18304
- grade,
18305
- summary: `Audit complete: ${totalFindings} findings (${errorCount} critical/high). Score: ${score}/100 (Grade: ${grade}).`,
18306
- report: ""
18307
- };
18308
- result.report = generateReport({ quality, security: security2, performance, score, grade, projectPath, timestamp });
18309
- if (options.onFinding) {
18310
- for (const f of allFindings) {
18311
- options.onFinding(f);
18312
- }
18313
- }
18314
- return {
18315
- name: "audit",
18316
- version: "0.3.0",
18317
- description: "Professional IT audit: quality, security, performance, npm vulnerabilities.",
18318
- hooks: {
18319
- onAudit(_result) {
19019
+ }
18320
19020
  }
18321
- },
18322
- run: /* @__PURE__ */ __name(() => result, "run"),
18323
- report: /* @__PURE__ */ __name(() => result.report, "report")
18324
- };
18325
- }
18326
- var init_audit = __esm({
18327
- "plugins/audit/index.ts"() {
18328
- __name(stripCode, "stripCode");
18329
- __name(hasEval, "hasEval");
18330
- __name(isInNonCode, "isInNonCode");
18331
- __name(collectDangerousNames, "collectDangerousNames");
18332
- __name(hasProcessExec, "hasProcessExec");
18333
- __name(scanFile, "scanFile");
18334
- __name(scanDir, "scanDir");
18335
- __name(runNpmAudit, "runNpmAudit");
18336
- __name(generateReport, "generateReport");
19021
+ 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";
19022
+ report += " 4. RECOMMENDATIONS\n";
19023
+ 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";
19024
+ const criticalFindings = all.filter((f) => f.severity === "critical" || f.severity === "high");
19025
+ if (criticalFindings.length === 0) {
19026
+ report += "No critical or high-severity findings. Project meets baseline security standards.\n\n";
19027
+ } else {
19028
+ report += "Priority actions (critical/high severity):\n";
19029
+ for (const f of criticalFindings) {
19030
+ report += ` - ${f.id}: ${f.message} (${f.file ?? "N/A"})
19031
+ `;
19032
+ }
19033
+ report += "\n";
19034
+ }
19035
+ 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";
19036
+ report += " 5. FRAMEWORK COMPLIANCE MATRIX\n";
19037
+ 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";
19038
+ report += "OWASP Top 10 (2021):\n";
19039
+ const owaspIds = ["A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08", "A09", "A10"];
19040
+ const owaspNames = ["Broken Access Control", "Cryptographic Failures", "Injection", "Insecure Design", "Security Misconfiguration", "Vulnerable Components", "Auth Failures", "Integrity Failures", "Logging Failures", "SSRF"];
19041
+ for (let i3 = 0; i3 < owaspIds.length; i3++) {
19042
+ const found = security2.some((f) => f.control === owaspIds[i3]);
19043
+ report += ` ${owaspIds[i3]} ${owaspNames[i3]}: ${found ? "FINDINGS" : "PASS"}
19044
+ `;
19045
+ }
19046
+ report += "\nnpm audit:\n";
19047
+ const npmFindings = security2.filter((f) => f.framework === "npm audit");
19048
+ report += ` Total vulnerabilities: ${npmFindings.filter((f) => f.id !== "NPM-SUM").length}
19049
+ `;
19050
+ report += ` Status: ${npmFindings.length > 0 ? "FINDINGS" : "PASS"}
19051
+ `;
19052
+ 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";
19053
+ report += " END OF REPORT\n";
19054
+ 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";
19055
+ return report;
19056
+ }, "generateReport");
18337
19057
  __name(audit, "audit");
18338
19058
  }
18339
19059
  });
18340
- function resolveDbPath(override) {
18341
- if (override) return override;
18342
- const root = resolveDotMemStorageRoot();
18343
- const dir = path8__default.default.join(root, "neurocore");
18344
- if (!fs__default.default.existsSync(dir)) fs__default.default.mkdirSync(dir, { recursive: true });
18345
- return path8__default.default.join(dir, "neurocore.db");
18346
- }
18347
- var DatabaseSync, SCHEMA_VERSION, NeuroCoreSqliteStore, createSqliteStore;
19060
+ var SCHEMA_VERSION, SchemaVersion, Episode, Assessment, Pattern, Proposal, Adaptation, Verification, resolveDbPath, ENTITIES, NeuroCoreSqliteStore, createSqliteStore;
18348
19061
  var init_sqlite = __esm({
18349
19062
  "plugins/neurocore/storage/sqlite.ts"() {
18350
19063
  init_storage_location();
18351
- ({ DatabaseSync } = globalThis.process?.getBuiltinModule?.("node:sqlite") ?? __require("sqlite"));
18352
19064
  SCHEMA_VERSION = 1;
18353
- __name(resolveDbPath, "resolveDbPath");
19065
+ SchemaVersion = class {
19066
+ version;
19067
+ };
19068
+ __name(SchemaVersion, "SchemaVersion");
19069
+ __decorateClass([
19070
+ typeorm.PrimaryColumn("integer")
19071
+ ], SchemaVersion.prototype, "version", 2);
19072
+ SchemaVersion = __decorateClass([
19073
+ typeorm.Entity("schema_version")
19074
+ ], SchemaVersion);
19075
+ Episode = class {
19076
+ id;
19077
+ scope;
19078
+ context;
19079
+ objective;
19080
+ observation;
19081
+ outcome;
19082
+ provenance;
19083
+ createdAt;
19084
+ memoryRefs;
19085
+ evidence;
19086
+ };
19087
+ __name(Episode, "Episode");
19088
+ __decorateClass([
19089
+ typeorm.PrimaryColumn("text")
19090
+ ], Episode.prototype, "id", 2);
19091
+ __decorateClass([
19092
+ typeorm.Column("text")
19093
+ ], Episode.prototype, "scope", 2);
19094
+ __decorateClass([
19095
+ typeorm.Column("text")
19096
+ ], Episode.prototype, "context", 2);
19097
+ __decorateClass([
19098
+ typeorm.Column("text")
19099
+ ], Episode.prototype, "objective", 2);
19100
+ __decorateClass([
19101
+ typeorm.Column("text")
19102
+ ], Episode.prototype, "observation", 2);
19103
+ __decorateClass([
19104
+ typeorm.Column("text")
19105
+ ], Episode.prototype, "outcome", 2);
19106
+ __decorateClass([
19107
+ typeorm.Column("text")
19108
+ ], Episode.prototype, "provenance", 2);
19109
+ __decorateClass([
19110
+ typeorm.Column({ name: "created_at", type: "text" })
19111
+ ], Episode.prototype, "createdAt", 2);
19112
+ __decorateClass([
19113
+ typeorm.Column({ name: "memory_refs", type: "text", nullable: true })
19114
+ ], Episode.prototype, "memoryRefs", 2);
19115
+ __decorateClass([
19116
+ typeorm.Column({ name: "evidence", type: "text", nullable: true })
19117
+ ], Episode.prototype, "evidence", 2);
19118
+ Episode = __decorateClass([
19119
+ typeorm.Entity("episodes")
19120
+ ], Episode);
19121
+ Assessment = class {
19122
+ id;
19123
+ episodeId;
19124
+ assessmentType;
19125
+ findings;
19126
+ evidence;
19127
+ structuredEvidence;
19128
+ confidence;
19129
+ limitations;
19130
+ assessedAt;
19131
+ assessor;
19132
+ };
19133
+ __name(Assessment, "Assessment");
19134
+ __decorateClass([
19135
+ typeorm.PrimaryColumn("text")
19136
+ ], Assessment.prototype, "id", 2);
19137
+ __decorateClass([
19138
+ typeorm.Column({ name: "episode_id", type: "text" })
19139
+ ], Assessment.prototype, "episodeId", 2);
19140
+ __decorateClass([
19141
+ typeorm.Column({ name: "assessment_type", type: "text" })
19142
+ ], Assessment.prototype, "assessmentType", 2);
19143
+ __decorateClass([
19144
+ typeorm.Column("text")
19145
+ ], Assessment.prototype, "findings", 2);
19146
+ __decorateClass([
19147
+ typeorm.Column("text")
19148
+ ], Assessment.prototype, "evidence", 2);
19149
+ __decorateClass([
19150
+ typeorm.Column({ name: "structured_evidence", type: "text", nullable: true })
19151
+ ], Assessment.prototype, "structuredEvidence", 2);
19152
+ __decorateClass([
19153
+ typeorm.Column("real")
19154
+ ], Assessment.prototype, "confidence", 2);
19155
+ __decorateClass([
19156
+ typeorm.Column("text")
19157
+ ], Assessment.prototype, "limitations", 2);
19158
+ __decorateClass([
19159
+ typeorm.Column({ name: "assessed_at", type: "text" })
19160
+ ], Assessment.prototype, "assessedAt", 2);
19161
+ __decorateClass([
19162
+ typeorm.Column("text")
19163
+ ], Assessment.prototype, "assessor", 2);
19164
+ Assessment = __decorateClass([
19165
+ typeorm.Entity("assessments")
19166
+ ], Assessment);
19167
+ Pattern = class {
19168
+ id;
19169
+ scope;
19170
+ description;
19171
+ episodeIds;
19172
+ supportingEvidence;
19173
+ contradictingEvidence;
19174
+ confidence;
19175
+ status;
19176
+ revision;
19177
+ firstObserved;
19178
+ lastObserved;
19179
+ };
19180
+ __name(Pattern, "Pattern");
19181
+ __decorateClass([
19182
+ typeorm.PrimaryColumn("text")
19183
+ ], Pattern.prototype, "id", 2);
19184
+ __decorateClass([
19185
+ typeorm.Column("text")
19186
+ ], Pattern.prototype, "scope", 2);
19187
+ __decorateClass([
19188
+ typeorm.Column("text")
19189
+ ], Pattern.prototype, "description", 2);
19190
+ __decorateClass([
19191
+ typeorm.Column({ name: "episode_ids", type: "text" })
19192
+ ], Pattern.prototype, "episodeIds", 2);
19193
+ __decorateClass([
19194
+ typeorm.Column({ name: "supporting_evidence", type: "text" })
19195
+ ], Pattern.prototype, "supportingEvidence", 2);
19196
+ __decorateClass([
19197
+ typeorm.Column({ name: "contradicting_evidence", type: "text" })
19198
+ ], Pattern.prototype, "contradictingEvidence", 2);
19199
+ __decorateClass([
19200
+ typeorm.Column("real")
19201
+ ], Pattern.prototype, "confidence", 2);
19202
+ __decorateClass([
19203
+ typeorm.Column("text")
19204
+ ], Pattern.prototype, "status", 2);
19205
+ __decorateClass([
19206
+ typeorm.Column("integer")
19207
+ ], Pattern.prototype, "revision", 2);
19208
+ __decorateClass([
19209
+ typeorm.Column({ name: "first_observed", type: "text", nullable: true })
19210
+ ], Pattern.prototype, "firstObserved", 2);
19211
+ __decorateClass([
19212
+ typeorm.Column({ name: "last_observed", type: "text", nullable: true })
19213
+ ], Pattern.prototype, "lastObserved", 2);
19214
+ Pattern = __decorateClass([
19215
+ typeorm.Entity("patterns")
19216
+ ], Pattern);
19217
+ Proposal = class {
19218
+ id;
19219
+ patternId;
19220
+ problem;
19221
+ proposedStrategy;
19222
+ applicableContext;
19223
+ expectedOutcome;
19224
+ verificationCriteria;
19225
+ evidence;
19226
+ status;
19227
+ revision;
19228
+ createdAt;
19229
+ };
19230
+ __name(Proposal, "Proposal");
19231
+ __decorateClass([
19232
+ typeorm.PrimaryColumn("text")
19233
+ ], Proposal.prototype, "id", 2);
19234
+ __decorateClass([
19235
+ typeorm.Column({ name: "pattern_id", type: "text", nullable: true })
19236
+ ], Proposal.prototype, "patternId", 2);
19237
+ __decorateClass([
19238
+ typeorm.Column("text")
19239
+ ], Proposal.prototype, "problem", 2);
19240
+ __decorateClass([
19241
+ typeorm.Column({ name: "proposed_strategy", type: "text" })
19242
+ ], Proposal.prototype, "proposedStrategy", 2);
19243
+ __decorateClass([
19244
+ typeorm.Column({ name: "applicable_context", type: "text" })
19245
+ ], Proposal.prototype, "applicableContext", 2);
19246
+ __decorateClass([
19247
+ typeorm.Column({ name: "expected_outcome", type: "text" })
19248
+ ], Proposal.prototype, "expectedOutcome", 2);
19249
+ __decorateClass([
19250
+ typeorm.Column({ name: "verification_criteria", type: "text" })
19251
+ ], Proposal.prototype, "verificationCriteria", 2);
19252
+ __decorateClass([
19253
+ typeorm.Column("text")
19254
+ ], Proposal.prototype, "evidence", 2);
19255
+ __decorateClass([
19256
+ typeorm.Column("text")
19257
+ ], Proposal.prototype, "status", 2);
19258
+ __decorateClass([
19259
+ typeorm.Column("integer")
19260
+ ], Proposal.prototype, "revision", 2);
19261
+ __decorateClass([
19262
+ typeorm.Column({ name: "created_at", type: "text" })
19263
+ ], Proposal.prototype, "createdAt", 2);
19264
+ Proposal = __decorateClass([
19265
+ typeorm.Entity("proposals")
19266
+ ], Proposal);
19267
+ Adaptation = class {
19268
+ id;
19269
+ proposalId;
19270
+ strategyVersion;
19271
+ activationScope;
19272
+ status;
19273
+ approvedBy;
19274
+ activatedAt;
19275
+ deactivatedAt;
19276
+ };
19277
+ __name(Adaptation, "Adaptation");
19278
+ __decorateClass([
19279
+ typeorm.PrimaryColumn("text")
19280
+ ], Adaptation.prototype, "id", 2);
19281
+ __decorateClass([
19282
+ typeorm.Column({ name: "proposal_id", type: "text" })
19283
+ ], Adaptation.prototype, "proposalId", 2);
19284
+ __decorateClass([
19285
+ typeorm.Column({ name: "strategy_version", type: "integer" })
19286
+ ], Adaptation.prototype, "strategyVersion", 2);
19287
+ __decorateClass([
19288
+ typeorm.Column({ name: "activation_scope", type: "text" })
19289
+ ], Adaptation.prototype, "activationScope", 2);
19290
+ __decorateClass([
19291
+ typeorm.Column("text")
19292
+ ], Adaptation.prototype, "status", 2);
19293
+ __decorateClass([
19294
+ typeorm.Column({ name: "approved_by", type: "text", nullable: true })
19295
+ ], Adaptation.prototype, "approvedBy", 2);
19296
+ __decorateClass([
19297
+ typeorm.Column({ name: "activated_at", type: "text" })
19298
+ ], Adaptation.prototype, "activatedAt", 2);
19299
+ __decorateClass([
19300
+ typeorm.Column({ name: "deactivated_at", type: "text", nullable: true })
19301
+ ], Adaptation.prototype, "deactivatedAt", 2);
19302
+ Adaptation = __decorateClass([
19303
+ typeorm.Entity("adaptations")
19304
+ ], Adaptation);
19305
+ Verification = class {
19306
+ id;
19307
+ adaptationId;
19308
+ measurement;
19309
+ baseline;
19310
+ observedOutcome;
19311
+ comparisonContext;
19312
+ conclusion;
19313
+ limitations;
19314
+ verifiedAt;
19315
+ };
19316
+ __name(Verification, "Verification");
19317
+ __decorateClass([
19318
+ typeorm.PrimaryColumn("text")
19319
+ ], Verification.prototype, "id", 2);
19320
+ __decorateClass([
19321
+ typeorm.Column({ name: "adaptation_id", type: "text" })
19322
+ ], Verification.prototype, "adaptationId", 2);
19323
+ __decorateClass([
19324
+ typeorm.Column("text")
19325
+ ], Verification.prototype, "measurement", 2);
19326
+ __decorateClass([
19327
+ typeorm.Column("text")
19328
+ ], Verification.prototype, "baseline", 2);
19329
+ __decorateClass([
19330
+ typeorm.Column({ name: "observed_outcome", type: "text" })
19331
+ ], Verification.prototype, "observedOutcome", 2);
19332
+ __decorateClass([
19333
+ typeorm.Column({ name: "comparison_context", type: "text" })
19334
+ ], Verification.prototype, "comparisonContext", 2);
19335
+ __decorateClass([
19336
+ typeorm.Column("text")
19337
+ ], Verification.prototype, "conclusion", 2);
19338
+ __decorateClass([
19339
+ typeorm.Column("text")
19340
+ ], Verification.prototype, "limitations", 2);
19341
+ __decorateClass([
19342
+ typeorm.Column({ name: "verified_at", type: "text" })
19343
+ ], Verification.prototype, "verifiedAt", 2);
19344
+ Verification = __decorateClass([
19345
+ typeorm.Entity("verifications")
19346
+ ], Verification);
19347
+ resolveDbPath = /* @__PURE__ */ __name((override) => {
19348
+ if (override) return override;
19349
+ const root = resolveDotMemStorageRoot();
19350
+ const dir = path5__default.default.join(root, "neurocore");
19351
+ if (!fs6__default.default.existsSync(dir)) fs6__default.default.mkdirSync(dir, { recursive: true });
19352
+ return path5__default.default.join(dir, "neurocore.db");
19353
+ }, "resolveDbPath");
19354
+ ENTITIES = [
19355
+ SchemaVersion,
19356
+ Episode,
19357
+ Assessment,
19358
+ Pattern,
19359
+ Proposal,
19360
+ Adaptation,
19361
+ Verification
19362
+ ];
18354
19363
  NeuroCoreSqliteStore = class {
18355
19364
  static {
18356
19365
  __name(this, "NeuroCoreSqliteStore");
18357
19366
  }
18358
- db;
19367
+ ds = null;
18359
19368
  dbPath;
19369
+ initialized = false;
18360
19370
  constructor(dbPath) {
18361
19371
  this.dbPath = resolveDbPath(dbPath);
18362
- const dir = path8__default.default.dirname(this.dbPath);
18363
- if (!fs__default.default.existsSync(dir)) fs__default.default.mkdirSync(dir, { recursive: true });
18364
- this.db = new DatabaseSync(this.dbPath);
18365
- this.db.exec("PRAGMA journal_mode = WAL;");
18366
- this.db.exec("PRAGMA busy_timeout = 5000;");
18367
- this.migrate();
18368
- }
18369
- migrate() {
18370
- this.db.exec(`CREATE TABLE IF NOT EXISTS schema_version (version INTEGER PRIMARY KEY);`);
18371
- const row = this.db.prepare("SELECT version FROM schema_version LIMIT 1").get();
19372
+ const dir = path5__default.default.dirname(this.dbPath);
19373
+ if (!fs6__default.default.existsSync(dir)) fs6__default.default.mkdirSync(dir, { recursive: true });
19374
+ }
19375
+ async init() {
19376
+ if (this.initialized) return;
19377
+ this.ds = new typeorm.DataSource({
19378
+ type: "better-sqlite3",
19379
+ database: this.dbPath,
19380
+ entities: ENTITIES,
19381
+ synchronize: true,
19382
+ logging: false
19383
+ });
19384
+ await this.ds.initialize();
19385
+ await this.migrate();
19386
+ this.initialized = true;
19387
+ }
19388
+ async migrate() {
19389
+ if (!this.ds) throw new Error("DataSource not initialized");
19390
+ const svRepo = this.ds.getRepository(SchemaVersion);
19391
+ const row = await svRepo.findOne({ where: {} });
18372
19392
  const current = row ? row.version : 0;
18373
- if (current === 0) {
18374
- this.db.exec(`
18375
- CREATE TABLE episodes (
18376
- id TEXT PRIMARY KEY,
18377
- scope TEXT NOT NULL,
18378
- context TEXT NOT NULL,
18379
- objective TEXT NOT NULL,
18380
- observation TEXT NOT NULL,
18381
- outcome TEXT NOT NULL,
18382
- provenance TEXT NOT NULL,
18383
- created_at TEXT NOT NULL,
18384
- memory_refs TEXT,
18385
- evidence TEXT
18386
- );
18387
- CREATE TABLE assessments (
18388
- id TEXT PRIMARY KEY,
18389
- episode_id TEXT NOT NULL,
18390
- assessment_type TEXT NOT NULL,
18391
- findings TEXT NOT NULL,
18392
- evidence TEXT NOT NULL,
18393
- structured_evidence TEXT,
18394
- confidence REAL NOT NULL,
18395
- limitations TEXT NOT NULL,
18396
- assessed_at TEXT NOT NULL,
18397
- assessor TEXT NOT NULL,
18398
- FOREIGN KEY (episode_id) REFERENCES episodes(id)
18399
- );
18400
- CREATE TABLE patterns (
18401
- id TEXT PRIMARY KEY,
18402
- scope TEXT NOT NULL,
18403
- description TEXT NOT NULL,
18404
- episode_ids TEXT NOT NULL,
18405
- supporting_evidence TEXT NOT NULL,
18406
- contradicting_evidence TEXT NOT NULL,
18407
- confidence REAL NOT NULL,
18408
- status TEXT NOT NULL,
18409
- revision INTEGER NOT NULL,
18410
- first_observed TEXT,
18411
- last_observed TEXT
18412
- );
18413
- CREATE TABLE proposals (
18414
- id TEXT PRIMARY KEY,
18415
- pattern_id TEXT,
18416
- problem TEXT NOT NULL,
18417
- proposed_strategy TEXT NOT NULL,
18418
- applicable_context TEXT NOT NULL,
18419
- expected_outcome TEXT NOT NULL,
18420
- verification_criteria TEXT NOT NULL,
18421
- evidence TEXT NOT NULL,
18422
- status TEXT NOT NULL,
18423
- revision INTEGER NOT NULL,
18424
- created_at TEXT NOT NULL
18425
- );
18426
- CREATE TABLE adaptations (
18427
- id TEXT PRIMARY KEY,
18428
- proposal_id TEXT NOT NULL,
18429
- strategy_version INTEGER NOT NULL,
18430
- activation_scope TEXT NOT NULL,
18431
- status TEXT NOT NULL,
18432
- approved_by TEXT,
18433
- activated_at TEXT NOT NULL,
18434
- deactivated_at TEXT
18435
- );
18436
- CREATE TABLE verifications (
18437
- id TEXT PRIMARY KEY,
18438
- adaptation_id TEXT NOT NULL,
18439
- measurement TEXT NOT NULL,
18440
- baseline TEXT NOT NULL,
18441
- observed_outcome TEXT NOT NULL,
18442
- comparison_context TEXT NOT NULL,
18443
- conclusion TEXT NOT NULL,
18444
- limitations TEXT NOT NULL,
18445
- verified_at TEXT NOT NULL
18446
- );
18447
- INSERT INTO schema_version (version) VALUES (${SCHEMA_VERSION});
18448
- `);
18449
- } else if (current !== SCHEMA_VERSION) {
18450
- throw new Error(`Unsupported NeuroCore schema version: ${current}`);
19393
+ if (current !== SCHEMA_VERSION) {
19394
+ if (current === 0) {
19395
+ await svRepo.insert({ version: SCHEMA_VERSION });
19396
+ } else {
19397
+ throw new Error(`Unsupported NeuroCore schema version: ${current}`);
19398
+ }
19399
+ }
19400
+ }
19401
+ ensureInit() {
19402
+ if (!this.initialized || !this.ds) {
19403
+ throw new Error("Store not initialized. Call init() before using the store.");
18451
19404
  }
18452
19405
  }
18453
- // NeuroCoreStore implementation
18454
- saveEpisode(episode) {
18455
- const stmt = this.db.prepare(`INSERT INTO episodes (id, scope, context, objective, observation, outcome, provenance, created_at, memory_refs, evidence) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
19406
+ async saveEpisode(episode) {
19407
+ this.ensureInit();
19408
+ const repo = this.ds.getRepository(Episode);
18456
19409
  try {
18457
- stmt.run(
18458
- episode.id,
18459
- episode.scope,
18460
- episode.context,
18461
- episode.objective,
18462
- episode.observation,
18463
- episode.outcome,
18464
- episode.provenance,
18465
- episode.createdAt,
18466
- JSON.stringify(episode.memoryRefs ?? []),
18467
- JSON.stringify(episode.evidence ?? null)
18468
- );
19410
+ await repo.insert({
19411
+ id: episode.id,
19412
+ scope: episode.scope,
19413
+ context: episode.context,
19414
+ objective: episode.objective,
19415
+ observation: episode.observation,
19416
+ outcome: episode.outcome,
19417
+ provenance: episode.provenance,
19418
+ createdAt: episode.createdAt,
19419
+ memoryRefs: JSON.stringify(episode.memoryRefs ?? []),
19420
+ evidence: episode.evidence != null ? JSON.stringify(episode.evidence) : null
19421
+ });
18469
19422
  } catch (e) {
18470
19423
  if (String(e).includes("UNIQUE") || String(e).includes("PRIMARY KEY")) throw new Error(`duplicate episode id: ${episode.id}`);
18471
19424
  throw e;
18472
19425
  }
18473
19426
  }
18474
- getEpisode(id) {
18475
- const row = this.db.prepare("SELECT * FROM episodes WHERE id = ?").get(id);
19427
+ async getEpisode(id) {
19428
+ this.ensureInit();
19429
+ const repo = this.ds.getRepository(Episode);
19430
+ const row = await repo.findOne({ where: { id } });
18476
19431
  if (!row) return void 0;
18477
19432
  return {
18478
19433
  id: row.id,
@@ -18482,24 +19437,17 @@ var init_sqlite = __esm({
18482
19437
  observation: row.observation,
18483
19438
  outcome: row.outcome,
18484
19439
  provenance: row.provenance,
18485
- createdAt: row.created_at,
18486
- memoryRefs: JSON.parse(row.memory_refs || "[]"),
19440
+ createdAt: row.createdAt,
19441
+ memoryRefs: JSON.parse(row.memoryRefs ?? "[]"),
18487
19442
  evidence: row.evidence ? JSON.parse(row.evidence) : void 0
18488
19443
  };
18489
19444
  }
18490
- listEpisodes(options) {
18491
- let sql = "SELECT * FROM episodes";
18492
- const params = [];
18493
- if (options?.scope) {
18494
- sql += " WHERE scope = ?";
18495
- params.push(options.scope);
18496
- }
18497
- sql += " ORDER BY created_at ASC";
18498
- if (options?.limit && options.limit > 0) {
18499
- sql += " LIMIT ?";
18500
- params.push(options.limit);
18501
- }
18502
- const rows = this.db.prepare(sql).all(...params);
19445
+ async listEpisodes(options) {
19446
+ this.ensureInit();
19447
+ const repo = this.ds.getRepository(Episode);
19448
+ const where = {};
19449
+ if (options?.scope) where.scope = options.scope;
19450
+ const rows = await repo.find({ where, order: { createdAt: "ASC" }, take: options?.limit });
18503
19451
  return rows.map((row) => ({
18504
19452
  id: row.id,
18505
19453
  scope: row.scope,
@@ -18508,226 +19456,256 @@ var init_sqlite = __esm({
18508
19456
  observation: row.observation,
18509
19457
  outcome: row.outcome,
18510
19458
  provenance: row.provenance,
18511
- createdAt: row.created_at,
18512
- memoryRefs: JSON.parse(row.memory_refs || "[]"),
19459
+ createdAt: row.createdAt,
19460
+ memoryRefs: JSON.parse(row.memoryRefs ?? "[]"),
18513
19461
  evidence: row.evidence ? JSON.parse(row.evidence) : void 0
18514
19462
  }));
18515
19463
  }
18516
- saveAssessment(a) {
18517
- const stmt = this.db.prepare(`INSERT INTO assessments (id, episode_id, assessment_type, findings, evidence, structured_evidence, confidence, limitations, assessed_at, assessor) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
19464
+ async saveAssessment(a) {
19465
+ this.ensureInit();
19466
+ const repo = this.ds.getRepository(Assessment);
18518
19467
  try {
18519
- stmt.run(
18520
- a.id,
18521
- a.episodeId,
18522
- a.assessmentType,
18523
- JSON.stringify(a.findings ?? []),
18524
- JSON.stringify(a.evidence ?? []),
18525
- a.structuredEvidence ? JSON.stringify(a.structuredEvidence) : null,
18526
- a.confidence,
18527
- JSON.stringify(a.limitations ?? []),
18528
- a.assessedAt,
18529
- a.assessor
18530
- );
19468
+ await repo.insert({
19469
+ id: a.id,
19470
+ episodeId: a.episodeId,
19471
+ assessmentType: a.assessmentType,
19472
+ findings: JSON.stringify(a.findings ?? []),
19473
+ evidence: JSON.stringify(a.evidence ?? []),
19474
+ structuredEvidence: a.structuredEvidence != null ? JSON.stringify(a.structuredEvidence) : null,
19475
+ confidence: a.confidence,
19476
+ limitations: JSON.stringify(a.limitations ?? []),
19477
+ assessedAt: a.assessedAt,
19478
+ assessor: a.assessor
19479
+ });
18531
19480
  } catch (e) {
18532
19481
  if (String(e).includes("UNIQUE") || String(e).includes("PRIMARY KEY")) throw new Error(`duplicate assessment id: ${a.id}`);
18533
19482
  throw e;
18534
19483
  }
18535
19484
  }
18536
- getAssessment(id) {
18537
- const row = this.db.prepare("SELECT * FROM assessments WHERE id = ?").get(id);
19485
+ async getAssessment(id) {
19486
+ this.ensureInit();
19487
+ const repo = this.ds.getRepository(Assessment);
19488
+ const row = await repo.findOne({ where: { id } });
18538
19489
  if (!row) return void 0;
18539
19490
  return {
18540
19491
  id: row.id,
18541
- episodeId: row.episode_id,
18542
- assessmentType: row.assessment_type,
19492
+ episodeId: row.episodeId,
19493
+ assessmentType: row.assessmentType,
18543
19494
  findings: JSON.parse(row.findings),
18544
19495
  evidence: JSON.parse(row.evidence),
18545
- structuredEvidence: row.structured_evidence ? JSON.parse(row.structured_evidence) : void 0,
19496
+ structuredEvidence: row.structuredEvidence ? JSON.parse(row.structuredEvidence) : void 0,
18546
19497
  confidence: row.confidence,
18547
19498
  limitations: JSON.parse(row.limitations),
18548
- assessedAt: row.assessed_at,
19499
+ assessedAt: row.assessedAt,
18549
19500
  assessor: row.assessor
18550
19501
  };
18551
19502
  }
18552
- listAssessmentsByEpisode(episodeId) {
18553
- const rows = this.db.prepare("SELECT * FROM assessments WHERE episode_id = ? ORDER BY assessed_at ASC").all(episodeId);
19503
+ async listAssessmentsByEpisode(episodeId) {
19504
+ this.ensureInit();
19505
+ const repo = this.ds.getRepository(Assessment);
19506
+ const rows = await repo.find({ where: { episodeId }, order: { assessedAt: "ASC" } });
18554
19507
  return rows.map((row) => ({
18555
19508
  id: row.id,
18556
- episodeId: row.episode_id,
18557
- assessmentType: row.assessment_type,
19509
+ episodeId: row.episodeId,
19510
+ assessmentType: row.assessmentType,
18558
19511
  findings: JSON.parse(row.findings),
18559
19512
  evidence: JSON.parse(row.evidence),
18560
- structuredEvidence: row.structured_evidence ? JSON.parse(row.structured_evidence) : void 0,
19513
+ structuredEvidence: row.structuredEvidence ? JSON.parse(row.structuredEvidence) : void 0,
18561
19514
  confidence: row.confidence,
18562
19515
  limitations: JSON.parse(row.limitations),
18563
- assessedAt: row.assessed_at,
19516
+ assessedAt: row.assessedAt,
18564
19517
  assessor: row.assessor
18565
19518
  }));
18566
19519
  }
18567
- // Patterns
18568
- savePattern(p) {
18569
- 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
19520
+ async savePattern(p) {
19521
+ this.ensureInit();
19522
+ const repo = this.ds.getRepository(Pattern);
18570
19523
  try {
18571
- stmt.run(
18572
- p.id,
18573
- p.scope,
18574
- p.description,
18575
- JSON.stringify(p.episodeIds ?? []),
18576
- JSON.stringify(p.supportingEvidence ?? []),
18577
- JSON.stringify(p.contradictingEvidence ?? []),
18578
- p.confidence,
18579
- p.status,
18580
- p.revision,
18581
- p.firstObserved ?? null,
18582
- p.lastObserved ?? null
18583
- );
19524
+ await repo.insert({
19525
+ id: p.id,
19526
+ scope: p.scope,
19527
+ description: p.description,
19528
+ episodeIds: JSON.stringify(p.episodeIds ?? []),
19529
+ supportingEvidence: JSON.stringify(p.supportingEvidence ?? []),
19530
+ contradictingEvidence: JSON.stringify(p.contradictingEvidence ?? []),
19531
+ confidence: p.confidence,
19532
+ status: p.status,
19533
+ revision: p.revision,
19534
+ firstObserved: p.firstObserved ?? null,
19535
+ lastObserved: p.lastObserved ?? null
19536
+ });
18584
19537
  } catch (e) {
18585
19538
  if (String(e).includes("UNIQUE") || String(e).includes("PRIMARY KEY")) throw new Error(`duplicate pattern id: ${p.id}`);
18586
19539
  throw e;
18587
19540
  }
18588
19541
  }
18589
- getPattern(id) {
18590
- const row = this.db.prepare("SELECT * FROM patterns WHERE id = ?").get(id);
19542
+ async getPattern(id) {
19543
+ this.ensureInit();
19544
+ const repo = this.ds.getRepository(Pattern);
19545
+ const row = await repo.findOne({ where: { id } });
18591
19546
  if (!row) return void 0;
18592
19547
  return {
18593
19548
  id: row.id,
18594
19549
  scope: row.scope,
18595
19550
  description: row.description,
18596
- episodeIds: JSON.parse(row.episode_ids),
18597
- supportingEvidence: JSON.parse(row.supporting_evidence),
18598
- contradictingEvidence: JSON.parse(row.contradicting_evidence),
19551
+ episodeIds: JSON.parse(row.episodeIds),
19552
+ supportingEvidence: JSON.parse(row.supportingEvidence),
19553
+ contradictingEvidence: JSON.parse(row.contradictingEvidence),
18599
19554
  confidence: row.confidence,
18600
19555
  status: row.status,
18601
19556
  revision: row.revision,
18602
- firstObserved: row.first_observed,
18603
- lastObserved: row.last_observed
19557
+ firstObserved: row.firstObserved,
19558
+ lastObserved: row.lastObserved
18604
19559
  };
18605
19560
  }
18606
- listPatterns() {
18607
- const rows = this.db.prepare("SELECT * FROM patterns").all();
19561
+ async listPatterns() {
19562
+ this.ensureInit();
19563
+ const repo = this.ds.getRepository(Pattern);
19564
+ const rows = await repo.find();
18608
19565
  return rows.map((row) => ({
18609
19566
  id: row.id,
18610
19567
  scope: row.scope,
18611
19568
  description: row.description,
18612
- episodeIds: JSON.parse(row.episode_ids),
18613
- supportingEvidence: JSON.parse(row.supporting_evidence),
18614
- contradictingEvidence: JSON.parse(row.contradicting_evidence),
19569
+ episodeIds: JSON.parse(row.episodeIds),
19570
+ supportingEvidence: JSON.parse(row.supportingEvidence),
19571
+ contradictingEvidence: JSON.parse(row.contradictingEvidence),
18615
19572
  confidence: row.confidence,
18616
19573
  status: row.status,
18617
19574
  revision: row.revision,
18618
- firstObserved: row.first_observed,
18619
- lastObserved: row.last_observed
19575
+ firstObserved: row.firstObserved,
19576
+ lastObserved: row.lastObserved
18620
19577
  }));
18621
19578
  }
18622
- // Proposals
18623
- saveProposal(p) {
18624
- 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
19579
+ async saveProposal(p) {
19580
+ this.ensureInit();
19581
+ const repo = this.ds.getRepository(Proposal);
18625
19582
  try {
18626
- stmt.run(
18627
- p.id,
18628
- p.patternId ?? null,
18629
- p.problem,
18630
- p.proposedStrategy,
18631
- p.applicableContext,
18632
- p.expectedOutcome,
18633
- p.verificationCriteria,
18634
- JSON.stringify(p.evidence ?? []),
18635
- p.status,
18636
- p.revision,
18637
- p.createdAt
18638
- );
19583
+ await repo.insert({
19584
+ id: p.id,
19585
+ patternId: p.patternId ?? null,
19586
+ problem: p.problem,
19587
+ proposedStrategy: p.proposedStrategy,
19588
+ applicableContext: p.applicableContext,
19589
+ expectedOutcome: p.expectedOutcome,
19590
+ verificationCriteria: p.verificationCriteria,
19591
+ evidence: JSON.stringify(p.evidence ?? []),
19592
+ status: p.status,
19593
+ revision: p.revision,
19594
+ createdAt: p.createdAt
19595
+ });
18639
19596
  } catch (e) {
18640
19597
  if (String(e).includes("UNIQUE") || String(e).includes("PRIMARY KEY")) throw new Error(`duplicate proposal id: ${p.id}`);
18641
19598
  throw e;
18642
19599
  }
18643
19600
  }
18644
- getProposal(id) {
18645
- const row = this.db.prepare("SELECT * FROM proposals WHERE id = ?").get(id);
19601
+ async getProposal(id) {
19602
+ this.ensureInit();
19603
+ const repo = this.ds.getRepository(Proposal);
19604
+ const row = await repo.findOne({ where: { id } });
18646
19605
  if (!row) return void 0;
18647
19606
  return {
18648
19607
  id: row.id,
18649
- patternId: row.pattern_id,
19608
+ patternId: row.patternId,
18650
19609
  problem: row.problem,
18651
- proposedStrategy: row.proposed_strategy,
18652
- applicableContext: row.applicable_context,
18653
- expectedOutcome: row.expected_outcome,
18654
- verificationCriteria: row.verification_criteria,
19610
+ proposedStrategy: row.proposedStrategy,
19611
+ applicableContext: row.applicableContext,
19612
+ expectedOutcome: row.expectedOutcome,
19613
+ verificationCriteria: row.verificationCriteria,
18655
19614
  evidence: JSON.parse(row.evidence),
18656
19615
  status: row.status,
18657
19616
  revision: row.revision,
18658
- createdAt: row.created_at
19617
+ createdAt: row.createdAt
18659
19618
  };
18660
19619
  }
18661
- // Adaptations
18662
- saveAdaptation(a) {
18663
- const stmt = this.db.prepare(`INSERT INTO adaptations (id, proposal_id, strategy_version, activation_scope, status, approved_by, activated_at, deactivated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);
19620
+ async saveAdaptation(a) {
19621
+ this.ensureInit();
19622
+ const repo = this.ds.getRepository(Adaptation);
18664
19623
  try {
18665
- stmt.run(a.id, a.proposalId, a.strategyVersion, a.activationScope, a.status, a.approvedBy ?? null, a.activatedAt, a.deactivatedAt ?? null);
19624
+ await repo.insert({
19625
+ id: a.id,
19626
+ proposalId: a.proposalId,
19627
+ strategyVersion: a.strategyVersion,
19628
+ activationScope: a.activationScope,
19629
+ status: a.status,
19630
+ approvedBy: a.approvedBy ?? null,
19631
+ activatedAt: a.activatedAt,
19632
+ deactivatedAt: a.deactivatedAt ?? null
19633
+ });
18666
19634
  } catch (e) {
18667
19635
  if (String(e).includes("UNIQUE") || String(e).includes("PRIMARY KEY")) throw new Error(`duplicate adaptation id: ${a.id}`);
18668
19636
  throw e;
18669
19637
  }
18670
19638
  }
18671
- getAdaptation(id) {
18672
- const row = this.db.prepare("SELECT * FROM adaptations WHERE id = ?").get(id);
19639
+ async getAdaptation(id) {
19640
+ this.ensureInit();
19641
+ const repo = this.ds.getRepository(Adaptation);
19642
+ const row = await repo.findOne({ where: { id } });
18673
19643
  if (!row) return void 0;
18674
19644
  return {
18675
19645
  id: row.id,
18676
- proposalId: row.proposal_id,
18677
- strategyVersion: row.strategy_version,
18678
- activationScope: row.activation_scope,
19646
+ proposalId: row.proposalId,
19647
+ strategyVersion: row.strategyVersion,
19648
+ activationScope: row.activationScope,
18679
19649
  status: row.status,
18680
- approvedBy: row.approved_by,
18681
- activatedAt: row.activated_at,
18682
- deactivatedAt: row.deactivated_at
19650
+ approvedBy: row.approvedBy,
19651
+ activatedAt: row.activatedAt,
19652
+ deactivatedAt: row.deactivatedAt
18683
19653
  };
18684
19654
  }
18685
- // Verifications
18686
- saveVerification(v) {
18687
- const stmt = this.db.prepare(`INSERT INTO verifications (id, adaptation_id, measurement, baseline, observed_outcome, comparison_context, conclusion, limitations, verified_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`);
19655
+ async saveVerification(v) {
19656
+ this.ensureInit();
19657
+ const repo = this.ds.getRepository(Verification);
18688
19658
  try {
18689
- stmt.run(
18690
- v.id,
18691
- v.adaptationId,
18692
- v.measurement,
18693
- v.baseline,
18694
- v.observedOutcome,
18695
- v.comparisonContext,
18696
- v.conclusion,
18697
- JSON.stringify(v.limitations ?? []),
18698
- v.verifiedAt
18699
- );
19659
+ await repo.insert({
19660
+ id: v.id,
19661
+ adaptationId: v.adaptationId,
19662
+ measurement: v.measurement,
19663
+ baseline: v.baseline,
19664
+ observedOutcome: v.observedOutcome,
19665
+ comparisonContext: v.comparisonContext,
19666
+ conclusion: v.conclusion,
19667
+ limitations: JSON.stringify(v.limitations ?? []),
19668
+ verifiedAt: v.verifiedAt
19669
+ });
18700
19670
  } catch (e) {
18701
19671
  if (String(e).includes("UNIQUE") || String(e).includes("PRIMARY KEY")) throw new Error(`duplicate verification id: ${v.id}`);
18702
19672
  throw e;
18703
19673
  }
18704
19674
  }
18705
- getVerification(id) {
18706
- const row = this.db.prepare("SELECT * FROM verifications WHERE id = ?").get(id);
19675
+ async getVerification(id) {
19676
+ this.ensureInit();
19677
+ const repo = this.ds.getRepository(Verification);
19678
+ const row = await repo.findOne({ where: { id } });
18707
19679
  if (!row) return void 0;
18708
19680
  return {
18709
19681
  id: row.id,
18710
- adaptationId: row.adaptation_id,
19682
+ adaptationId: row.adaptationId,
18711
19683
  measurement: row.measurement,
18712
19684
  baseline: row.baseline,
18713
- observedOutcome: row.observed_outcome,
18714
- comparisonContext: row.comparison_context,
19685
+ observedOutcome: row.observedOutcome,
19686
+ comparisonContext: row.comparisonContext,
18715
19687
  conclusion: row.conclusion,
18716
19688
  limitations: JSON.parse(row.limitations),
18717
- verifiedAt: row.verified_at
19689
+ verifiedAt: row.verifiedAt
18718
19690
  };
18719
19691
  }
18720
- close() {
19692
+ async close() {
18721
19693
  try {
18722
- this.db.close();
19694
+ await this.ds?.destroy();
18723
19695
  } catch {
18724
19696
  }
19697
+ this.ds = null;
19698
+ this.initialized = false;
18725
19699
  }
18726
19700
  getPath() {
18727
19701
  return this.dbPath;
18728
19702
  }
18729
19703
  };
18730
- createSqliteStore = /* @__PURE__ */ __name((dbPath) => new NeuroCoreSqliteStore(dbPath), "createSqliteStore");
19704
+ createSqliteStore = /* @__PURE__ */ __name(async (dbPath) => {
19705
+ const store7 = new NeuroCoreSqliteStore(dbPath);
19706
+ await store7.init();
19707
+ return store7;
19708
+ }, "createSqliteStore");
18731
19709
  }
18732
19710
  });
18733
19711
 
@@ -19200,7 +20178,7 @@ var init_handshake = __esm({
19200
20178
  const binding = candidate.authorityBinding;
19201
20179
  if (!binding || typeof binding !== "object") return null;
19202
20180
  if (binding.format !== "dotmem.authority-binding") return null;
19203
- if (binding.currentSpeakerBinding !== "trusted-hi" && binding.currentSpeakerBinding !== "unknown" && binding.currentSpeakerBinding !== "untrusted") return null;
20181
+ if (binding.currentSpeakerBinding !== "trusted-hi" && binding.currentSpeakerBinding !== "any" && binding.currentSpeakerBinding !== "untrusted") return null;
19204
20182
  if (binding.currentAuthorityBinding !== "BOUND" && binding.currentAuthorityBinding !== "UNBOUND") return null;
19205
20183
  if (typeof binding.requestedOperationalRole !== "string" || !binding.requestedOperationalRole) return null;
19206
20184
  return candidate;
@@ -19344,7 +20322,7 @@ __export(session_registry_exports, {
19344
20322
  sessionRegistry: () => sessionRegistry,
19345
20323
  updateSessionScope: () => updateSessionScope
19346
20324
  });
19347
- var SESSIONS_FILE, LEASE_MS, readAll3, writeAll3, nowIso3, parentDir2, registerSession, heartbeatSession, updateSessionScope, getSession, listActiveSessions, acknowledgeCursor, closeSession, reapExpiredSessions, sessionRegistry, session_registry_default;
20325
+ var SESSIONS_FILE, LEASE_MS, readAll3, writeAll3, nowIso4, parentDir2, registerSession, heartbeatSession, updateSessionScope, getSession, listActiveSessions, acknowledgeCursor, closeSession, reapExpiredSessions, sessionRegistry, session_registry_default;
19348
20326
  var init_session_registry = __esm({
19349
20327
  "core/memory/session-registry.ts"() {
19350
20328
  init_user_paths();
@@ -19373,29 +20351,29 @@ var init_session_registry = __esm({
19373
20351
  writeAll3 = /* @__PURE__ */ __name((items) => {
19374
20352
  const fs16 = getSyncFs();
19375
20353
  if (!fs16) return;
19376
- const path10 = SESSIONS_FILE();
19377
- const parent = path10.substring(0, Math.max(path10.lastIndexOf("/"), path10.lastIndexOf("\\")));
20354
+ const path11 = SESSIONS_FILE();
20355
+ const parent = path11.substring(0, Math.max(path11.lastIndexOf("/"), path11.lastIndexOf("\\")));
19378
20356
  try {
19379
20357
  fs16.mkdirSync(parent, { recursive: true });
19380
20358
  } catch {
19381
20359
  }
19382
- const tmp = `${path10}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
20360
+ const tmp = `${path11}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
19383
20361
  fs16.writeFileSync(tmp, JSON.stringify(items, null, 2));
19384
20362
  try {
19385
- if (fs16.existsSync(path10)) fs16.copyFileSync(path10, `${path10}.bak`);
20363
+ if (fs16.existsSync(path11)) fs16.copyFileSync(path11, `${path11}.bak`);
19386
20364
  } catch {
19387
20365
  }
19388
20366
  try {
19389
- fs16.renameSync(tmp, path10);
20367
+ fs16.renameSync(tmp, path11);
19390
20368
  } catch {
19391
- fs16.copyFileSync(tmp, path10);
20369
+ fs16.copyFileSync(tmp, path11);
19392
20370
  try {
19393
20371
  fs16.unlinkSync(tmp);
19394
20372
  } catch {
19395
20373
  }
19396
20374
  }
19397
20375
  }, "writeAll");
19398
- nowIso3 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
20376
+ nowIso4 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
19399
20377
  parentDir2 = /* @__PURE__ */ __name((p) => p.substring(0, Math.max(p.lastIndexOf("/"), p.lastIndexOf("\\"))), "parentDir");
19400
20378
  registerSession = /* @__PURE__ */ __name(async (input) => {
19401
20379
  const run = /* @__PURE__ */ __name(async () => {
@@ -19412,10 +20390,10 @@ var init_session_registry = __esm({
19412
20390
  projectId: input.projectId ?? null,
19413
20391
  dayKey: input.dayKey,
19414
20392
  status: "active",
19415
- startedAt: idx >= 0 ? items[idx].startedAt : input.startedAt ?? nowIso3(),
19416
- lastSeenAt: nowIso3(),
20393
+ startedAt: idx >= 0 ? items[idx].startedAt : input.startedAt ?? nowIso4(),
20394
+ lastSeenAt: nowIso4(),
19417
20395
  cursor: idx >= 0 ? items[idx].cursor : input.cursor ?? input.lastCursor ?? 0,
19418
- metadata: { ...idx >= 0 ? items[idx].metadata : {}, ...input.metadata ?? {} }
20396
+ metadata: { ...idx >= 0 ? items[idx].metadata : {}, ...input.metadata }
19419
20397
  };
19420
20398
  if (idx >= 0) items[idx] = rec;
19421
20399
  else items.push(rec);
@@ -19433,9 +20411,9 @@ var init_session_registry = __esm({
19433
20411
  const items = readAll3();
19434
20412
  const idx = items.findIndex((s) => s.sessionId === sessionId);
19435
20413
  if (idx < 0) return;
19436
- items[idx].lastSeenAt = nowIso3();
20414
+ items[idx].lastSeenAt = nowIso4();
19437
20415
  items[idx].status = "active";
19438
- if (metadata) items[idx].metadata = { ...items[idx].metadata ?? {}, ...metadata };
20416
+ if (metadata) items[idx].metadata = { ...items[idx].metadata, ...metadata };
19439
20417
  writeAll3(items);
19440
20418
  }, "run");
19441
20419
  try {
@@ -19456,7 +20434,7 @@ var init_session_registry = __esm({
19456
20434
  if (scope?.conversationId !== void 0) items[idx].conversationId = scope.conversationId;
19457
20435
  if (scope?.agentId !== void 0) items[idx].agentId = scope.agentId;
19458
20436
  if (scope?.dayKey !== void 0) items[idx].dayKey = scope.dayKey;
19459
- items[idx].lastSeenAt = nowIso3();
20437
+ items[idx].lastSeenAt = nowIso4();
19460
20438
  writeAll3(items);
19461
20439
  }, "run");
19462
20440
  try {
@@ -19491,7 +20469,7 @@ var init_session_registry = __esm({
19491
20469
  return;
19492
20470
  }
19493
20471
  items[idx].cursor = cursor;
19494
- items[idx].lastSeenAt = nowIso3();
20472
+ items[idx].lastSeenAt = nowIso4();
19495
20473
  writeAll3(items);
19496
20474
  }, "run");
19497
20475
  try {
@@ -19506,8 +20484,8 @@ var init_session_registry = __esm({
19506
20484
  const idx = items.findIndex((s) => s.sessionId === sessionId);
19507
20485
  if (idx < 0) return;
19508
20486
  items[idx].status = "closed";
19509
- items[idx].lastSeenAt = nowIso3();
19510
- if (reason) items[idx].metadata = { ...items[idx].metadata ?? {}, closeReason: reason };
20487
+ items[idx].lastSeenAt = nowIso4();
20488
+ if (reason) items[idx].metadata = { ...items[idx].metadata, closeReason: reason };
19511
20489
  writeAll3(items);
19512
20490
  }, "run");
19513
20491
  try {
@@ -19561,7 +20539,7 @@ __export(cross_chat_propagation_exports, {
19561
20539
  readCrossChatPropagationState: () => readCrossChatPropagationState,
19562
20540
  writeCrossChatPropagationState: () => writeCrossChatPropagationState
19563
20541
  });
19564
- var CROSS_CHAT_PROPAGATION_FILE_NAME, CROSS_CHAT_PROPAGATION_FORMAT_VERSION, emptyState, joinPath7, resolveFilePath, readRaw, writeRaw, validateState, readCrossChatPropagationState, writeCrossChatPropagationState, getCrossChatPropagationStatus, isCrossChatPropagationEnabled, getCrossChatPropagationChangeMarker;
20542
+ var CROSS_CHAT_PROPAGATION_FILE_NAME, CROSS_CHAT_PROPAGATION_FORMAT_VERSION, emptyState, joinPath8, resolveFilePath, readRaw, writeRaw, validateState, readCrossChatPropagationState, writeCrossChatPropagationState, getCrossChatPropagationStatus, isCrossChatPropagationEnabled, getCrossChatPropagationChangeMarker;
19565
20543
  var init_cross_chat_propagation = __esm({
19566
20544
  "core/continuity/cross-chat-propagation.ts"() {
19567
20545
  init_user_paths();
@@ -19573,12 +20551,12 @@ var init_cross_chat_propagation = __esm({
19573
20551
  configured: false,
19574
20552
  changeMarker: 0
19575
20553
  }), "emptyState");
19576
- joinPath7 = /* @__PURE__ */ __name((base, child) => {
20554
+ joinPath8 = /* @__PURE__ */ __name((base, child) => {
19577
20555
  const separator3 = process.platform === "win32" ? "\\" : "/";
19578
20556
  return `${base.replace(/[\\/]+/g, separator3)}${separator3}${child}`;
19579
20557
  }, "joinPath");
19580
20558
  resolveFilePath = /* @__PURE__ */ __name(() => {
19581
- return joinPath7(resolveUserDotMemPath(), CROSS_CHAT_PROPAGATION_FILE_NAME);
20559
+ return joinPath8(resolveUserDotMemPath(), CROSS_CHAT_PROPAGATION_FILE_NAME);
19582
20560
  }, "resolveFilePath");
19583
20561
  readRaw = /* @__PURE__ */ __name(async () => {
19584
20562
  const fs16 = await import('fs/promises');
@@ -19592,16 +20570,16 @@ var init_cross_chat_propagation = __esm({
19592
20570
  }, "readRaw");
19593
20571
  writeRaw = /* @__PURE__ */ __name(async (content) => {
19594
20572
  const fs16 = await import('fs/promises');
19595
- const path10 = resolveFilePath();
19596
- const dir = path10.replace(/[\\/][^\\/]+$/, "");
20573
+ const path11 = resolveFilePath();
20574
+ const dir = path11.replace(/[\\/][^\\/]+$/, "");
19597
20575
  await fs16.mkdir(dir, { recursive: true });
19598
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
20576
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
19599
20577
  try {
19600
20578
  await fs16.writeFile(temporary, content, "utf8");
19601
- await fs16.rename(temporary, path10);
20579
+ await fs16.rename(temporary, path11);
19602
20580
  } catch {
19603
20581
  await fs16.rm(temporary, { force: true }).catch(() => void 0);
19604
- throw new Error(`Failed to write cross-chat propagation config at ${path10}`);
20582
+ throw new Error(`Failed to write cross-chat propagation config at ${path11}`);
19605
20583
  }
19606
20584
  }, "writeRaw");
19607
20585
  validateState = /* @__PURE__ */ __name((value) => {
@@ -19676,213 +20654,6 @@ var init_cross_chat_propagation = __esm({
19676
20654
  }
19677
20655
  });
19678
20656
 
19679
- // core/context-compiler/index.ts
19680
- var CHARS_PER_TOKEN, estimateTokens, DEFAULT_BUDGETS, dedupe, ContextCompiler, compileContext;
19681
- var init_context_compiler = __esm({
19682
- "core/context-compiler/index.ts"() {
19683
- CHARS_PER_TOKEN = 4;
19684
- estimateTokens = /* @__PURE__ */ __name((text) => Math.ceil((text || "").length / CHARS_PER_TOKEN), "estimateTokens");
19685
- DEFAULT_BUDGETS = {
19686
- identity: 0.1,
19687
- rules: 0.15,
19688
- conversationalState: 0.3,
19689
- retrievedKnowledge: 0.45
19690
- };
19691
- dedupe = /* @__PURE__ */ __name((items) => {
19692
- const seen = /* @__PURE__ */ new Set();
19693
- const result = [];
19694
- for (const item of items) {
19695
- const key = item.trim().toLowerCase();
19696
- if (seen.has(key)) continue;
19697
- seen.add(key);
19698
- result.push(item);
19699
- }
19700
- return result;
19701
- }, "dedupe");
19702
- ContextCompiler = class {
19703
- static {
19704
- __name(this, "ContextCompiler");
19705
- }
19706
- compile(input) {
19707
- const totalBudget = input.tokenBudget ?? 4096;
19708
- const totalChars = totalBudget * CHARS_PER_TOKEN;
19709
- const budgets = {
19710
- identity: Math.floor(totalChars * (input.categoryBudgets?.identity ?? DEFAULT_BUDGETS.identity)),
19711
- rules: Math.floor(totalChars * (input.categoryBudgets?.rules ?? DEFAULT_BUDGETS.rules)),
19712
- conversationalState: Math.floor(totalChars * (input.categoryBudgets?.conversationalState ?? DEFAULT_BUDGETS.conversationalState)),
19713
- retrievedKnowledge: Math.floor(totalChars * (input.categoryBudgets?.retrievedKnowledge ?? DEFAULT_BUDGETS.retrievedKnowledge))
19714
- };
19715
- const omissions = [];
19716
- const identityText = (input.identity ?? "").trim();
19717
- let identityUsed = 0;
19718
- const mandatoryParts = [];
19719
- if (identityText) {
19720
- if (identityText.length <= budgets.identity) {
19721
- mandatoryParts.push(identityText);
19722
- identityUsed = identityText.length;
19723
- } else {
19724
- omissions.push({
19725
- category: "identity",
19726
- whatWasOmitted: identityText,
19727
- whyOmitted: "token budget exceeded",
19728
- wouldBreakContinuity: true
19729
- });
19730
- }
19731
- }
19732
- const rules = input.rules ?? [];
19733
- const activeRules = [];
19734
- let rulesUsed = 0;
19735
- for (const rule of rules) {
19736
- if (rulesUsed + rule.length <= budgets.rules) {
19737
- activeRules.push(rule);
19738
- rulesUsed += rule.length;
19739
- } else {
19740
- omissions.push({
19741
- category: "rules",
19742
- whatWasOmitted: rule,
19743
- whyOmitted: "token budget exceeded",
19744
- wouldBreakContinuity: false
19745
- });
19746
- }
19747
- }
19748
- const state3 = input.conversationalState ?? null;
19749
- const mandatoryStateParts = [];
19750
- if (state3) {
19751
- if (state3.objective) mandatoryStateParts.push(`Objective: ${state3.objective}`);
19752
- if (state3.currentWorkingPosition) mandatoryStateParts.push(`Working position: ${state3.currentWorkingPosition}`);
19753
- if (state3.openLoops.length > 0) {
19754
- mandatoryStateParts.push(`Open loops: ${state3.openLoops.map((l) => l.description).join("; ")}`);
19755
- }
19756
- if (state3.rejectedApproaches.length > 0) {
19757
- mandatoryStateParts.push(`Rejected approaches: ${state3.rejectedApproaches.map((r) => `${r.approach} (${r.reason})`).join("; ")}`);
19758
- }
19759
- }
19760
- const activeParts = [];
19761
- if (state3) {
19762
- if (state3.currentProblem) activeParts.push(`Current problem: ${state3.currentProblem}`);
19763
- if (state3.establishedUnderstanding) activeParts.push(`Established understanding: ${state3.establishedUnderstanding}`);
19764
- if (state3.decisionsMade.length > 0) {
19765
- activeParts.push(`Decisions: ${state3.decisionsMade.map((d) => `${d.decision} (rationale: ${d.rationale})`).join("; ")}`);
19766
- }
19767
- if (state3.pendingDecisions.length > 0) {
19768
- activeParts.push(`Pending decisions: ${state3.pendingDecisions.map((d) => `${d.decision} [${d.options.join(", ")}]`).join("; ")}`);
19769
- }
19770
- if (state3.unresolvedQuestions.length > 0) {
19771
- activeParts.push(`Unresolved questions: ${state3.unresolvedQuestions.map((q) => q.question).join("; ")}`);
19772
- }
19773
- if (state3.reasoningTrajectory.length > 0) {
19774
- activeParts.push(`Reasoning trajectory: ${state3.reasoningTrajectory.map((r) => r.conclusion).join(" -> ")}`);
19775
- }
19776
- if (state3.nextConversationalStep) {
19777
- activeParts.push(`Next step: ${state3.nextConversationalStep}`);
19778
- }
19779
- if (state3.lastCompletedAction) {
19780
- activeParts.push(`Last completed action: ${state3.lastCompletedAction}`);
19781
- }
19782
- }
19783
- const dedupedActive = dedupe(activeParts.filter((part) => !mandatoryStateParts.includes(part)));
19784
- let stateUsed = 0;
19785
- const admittedMandatoryState = [];
19786
- const admittedActive = [];
19787
- for (const part of mandatoryStateParts) {
19788
- if (stateUsed + part.length <= budgets.conversationalState) {
19789
- admittedMandatoryState.push(part);
19790
- stateUsed += part.length;
19791
- } else {
19792
- omissions.push({
19793
- category: "conversationalState",
19794
- whatWasOmitted: part,
19795
- whyOmitted: "token budget exceeded",
19796
- wouldBreakContinuity: true
19797
- });
19798
- }
19799
- }
19800
- for (const part of dedupedActive) {
19801
- if (stateUsed + part.length <= budgets.conversationalState) {
19802
- admittedActive.push(part);
19803
- stateUsed += part.length;
19804
- } else {
19805
- omissions.push({
19806
- category: "conversationalState",
19807
- whatWasOmitted: part,
19808
- whyOmitted: "token budget exceeded",
19809
- wouldBreakContinuity: false
19810
- });
19811
- }
19812
- }
19813
- const refs = [...input.knowledgeReferences ?? []].sort((a, b) => b.relevance - a.relevance);
19814
- const retrievedParts = [];
19815
- let retrievedUsed = 0;
19816
- for (const ref of refs) {
19817
- const text2 = ref.summary ? `${ref.kind}:${ref.identifier} - ${ref.summary}` : `${ref.kind}:${ref.identifier}`;
19818
- if (retrievedUsed + text2.length <= budgets.retrievedKnowledge) {
19819
- retrievedParts.push(text2);
19820
- retrievedUsed += text2.length;
19821
- } else {
19822
- omissions.push({
19823
- category: "retrievedKnowledge",
19824
- whatWasOmitted: text2,
19825
- whyOmitted: "token budget exceeded",
19826
- wouldBreakContinuity: false
19827
- });
19828
- }
19829
- }
19830
- const optionalParts = [];
19831
- let optionalUsed = 0;
19832
- const remainingBudget = totalChars - (identityUsed + rulesUsed + stateUsed + retrievedUsed);
19833
- for (const item of input.historicalContext ?? []) {
19834
- if (optionalUsed + item.length <= remainingBudget) {
19835
- optionalParts.push(item);
19836
- optionalUsed += item.length;
19837
- } else {
19838
- omissions.push({
19839
- category: "historical",
19840
- whatWasOmitted: item,
19841
- whyOmitted: "token budget exceeded",
19842
- wouldBreakContinuity: false
19843
- });
19844
- }
19845
- }
19846
- const admittedSet = new Set([...mandatoryParts, ...admittedMandatoryState, ...admittedActive].map((s) => s.trim().toLowerCase()));
19847
- const isDuplicate = /* @__PURE__ */ __name((item) => {
19848
- const normalized = item.trim().toLowerCase();
19849
- for (const existing of admittedSet) {
19850
- if (existing.includes(normalized) || normalized.includes(existing)) return true;
19851
- }
19852
- return false;
19853
- }, "isDuplicate");
19854
- const finalRetrieved = dedupe(retrievedParts.filter((p) => !isDuplicate(p)));
19855
- const finalOptional = dedupe(optionalParts.filter((p) => !isDuplicate(p) && !finalRetrieved.includes(p)));
19856
- const mandatory = [...mandatoryParts, ...admittedMandatoryState].join("\n");
19857
- const active = [...admittedActive];
19858
- const retrieved = finalRetrieved;
19859
- const optional = finalOptional;
19860
- const text = [mandatory ? `## MANDATORY
19861
- ${mandatory}` : "", active.length ? `## ACTIVE
19862
- ${active.join("\n")}` : "", retrieved.length ? `## RETRIEVED
19863
- ${retrieved.join("\n")}` : "", optional.length ? `## OPTIONAL
19864
- ${optional.join("\n")}` : "", rules.length ? `## RULES
19865
- ${activeRules.join("\n")}` : ""].filter(Boolean).join("\n\n");
19866
- const budgetUsed = estimateTokens(text);
19867
- return {
19868
- mandatory,
19869
- active,
19870
- retrieved,
19871
- optional,
19872
- omissions,
19873
- budgetUsed,
19874
- budgetAvailable: totalBudget,
19875
- text
19876
- };
19877
- }
19878
- };
19879
- compileContext = /* @__PURE__ */ __name((input) => {
19880
- const compiler = new ContextCompiler();
19881
- return compiler.compile(input);
19882
- }, "compileContext");
19883
- }
19884
- });
19885
-
19886
20657
  // core/recovery-service/index.ts
19887
20658
  var RecoveryService;
19888
20659
  var init_recovery_service = __esm({
@@ -19975,7 +20746,7 @@ __export(consolidation_engine_exports, {
19975
20746
  consolidationEngine: () => consolidationEngine,
19976
20747
  getConsolidationEngine: () => getConsolidationEngine
19977
20748
  });
19978
- var DEFAULT_CONFIG3, nowIso4, generateId2, normalizeText2, tokenize3, jaccardSimilarity2, detectOutcome, detectConditions, isDoNotRemember, CONSOLIDATION_STORE_KEY, ConsolidationPersistence, ConsolidationEngine, defaultEngine, getConsolidationEngine, consolidationEngine;
20749
+ var DEFAULT_CONFIG3, nowIso5, generateId2, normalizeText2, tokenize3, jaccardSimilarity2, detectOutcome, detectConditions, isDoNotRemember, CONSOLIDATION_STORE_KEY, ConsolidationPersistence, ConsolidationEngine, defaultEngine, getConsolidationEngine, consolidationEngine;
19979
20750
  var init_consolidation_engine = __esm({
19980
20751
  "core/memory/consolidation-engine.ts"() {
19981
20752
  init_durable_store();
@@ -19986,7 +20757,7 @@ var init_consolidation_engine = __esm({
19986
20757
  similarityThreshold: 0.5,
19987
20758
  minConfidenceForConsolidated: 0.7
19988
20759
  };
19989
- nowIso4 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
20760
+ nowIso5 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
19990
20761
  generateId2 = /* @__PURE__ */ __name(() => `cons-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`, "generateId");
19991
20762
  normalizeText2 = /* @__PURE__ */ __name((text) => {
19992
20763
  return text.normalize("NFKC").toLocaleLowerCase("en-US").replace(/[^\w\s]/g, " ").replace(/\s+/g, " ").trim();
@@ -20011,7 +20782,7 @@ var init_consolidation_engine = __esm({
20011
20782
  if (/if |when |only when|provided that|as long as/i.test(lower)) return "conditional";
20012
20783
  if (/succ(eed|ess)|works|passed|completed|resolved|fixed/i.test(lower)) return "success";
20013
20784
  if (category === "decision") return "success";
20014
- return "unknown";
20785
+ return "any";
20015
20786
  }, "detectOutcome");
20016
20787
  detectConditions = /* @__PURE__ */ __name((statement) => {
20017
20788
  const conditions = [];
@@ -20088,7 +20859,7 @@ var init_consolidation_engine = __esm({
20088
20859
  new DurableMemoryStore({
20089
20860
  filePath: `${resolveUserDotMemPath()}/consolidation-records.kv`,
20090
20861
  storeKey: CONSOLIDATION_STORE_KEY,
20091
- tenantId: this.tenantId
20862
+ tenantId: this.tenantId ?? void 0
20092
20863
  })
20093
20864
  );
20094
20865
  }
@@ -20205,7 +20976,7 @@ var init_consolidation_engine = __esm({
20205
20976
  }
20206
20977
  /** Create a new consolidation record from a group of experiences. */
20207
20978
  async createRecordFromGroup(group) {
20208
- const now3 = nowIso4();
20979
+ const now3 = nowIso5();
20209
20980
  const evidence = group.experiences.map((e) => ({
20210
20981
  experienceId: e.id,
20211
20982
  statement: e.statement,
@@ -20223,7 +20994,7 @@ var init_consolidation_engine = __esm({
20223
20994
  const outcomes = uniqueEvidence.map((e) => e.outcome);
20224
20995
  const hasFailure = outcomes.includes("failure");
20225
20996
  const hasSuccess = outcomes.includes("success");
20226
- const hasUnknown = outcomes.includes("unknown");
20997
+ const hasUnknown = outcomes.includes("any");
20227
20998
  const hasConditional = outcomes.includes("conditional");
20228
20999
  let lifecycleState = "pending";
20229
21000
  if (uniqueEvidence.length < this.config.minExperiencesForAcquired) {
@@ -20239,7 +21010,7 @@ var init_consolidation_engine = __esm({
20239
21010
  applicability["conditions"] = conditions.join("; ");
20240
21011
  }
20241
21012
  const limitations = [];
20242
- if (hasUnknown) limitations.push("Outcome unknown for some experiences");
21013
+ if (hasUnknown) limitations.push("Outcome any for some experiences");
20243
21014
  if (hasConditional) limitations.push("Success is conditional on specific circumstances");
20244
21015
  if (uniqueEvidence.length < this.config.minExperiencesForConsolidated) {
20245
21016
  limitations.push(`Only ${uniqueEvidence.length} supporting experience(s); ${this.config.minExperiencesForConsolidated} required for consolidation`);
@@ -20282,7 +21053,7 @@ var init_consolidation_engine = __esm({
20282
21053
  async updateRecordWithEvidence(record, newExperiences) {
20283
21054
  const newExpIds = newExperiences.map((e) => e.id).filter((id) => !record.supportingExperiences.includes(id));
20284
21055
  if (newExpIds.length === 0) return null;
20285
- const now3 = nowIso4();
21056
+ const now3 = nowIso5();
20286
21057
  const newEvidence = newExperiences.filter((e) => !record.supportingExperiences.includes(e.id)).map((e) => ({
20287
21058
  experienceId: e.id,
20288
21059
  statement: e.statement,
@@ -20340,7 +21111,7 @@ var init_consolidation_engine = __esm({
20340
21111
  if (record.doNotRemember) return false;
20341
21112
  const uniqueEvidence = this.deduplicateEvidence([...record.supportingEvidence, ...record.contradictingEvidence]);
20342
21113
  if (record.lifecycleState === "acquired" && uniqueEvidence.length >= this.config.minExperiencesForConsolidated && record.confidence >= this.config.minConfidenceForConsolidated && record.contradictingEvidence.length === 0) {
20343
- const now3 = nowIso4();
21114
+ const now3 = nowIso5();
20344
21115
  const promoted = {
20345
21116
  ...record,
20346
21117
  lifecycleState: "consolidated",
@@ -20362,7 +21133,7 @@ var init_consolidation_engine = __esm({
20362
21133
  return true;
20363
21134
  }
20364
21135
  if (record.lifecycleState === "insufficient_evidence" && uniqueEvidence.length >= this.config.minExperiencesForAcquired) {
20365
- const now3 = nowIso4();
21136
+ const now3 = nowIso5();
20366
21137
  const promoted = {
20367
21138
  ...record,
20368
21139
  lifecycleState: "acquired",
@@ -20402,7 +21173,7 @@ var init_consolidation_engine = __esm({
20402
21173
  a.history.push({
20403
21174
  from: a.lifecycleState,
20404
21175
  to: "conflicting",
20405
- at: nowIso4(),
21176
+ at: nowIso5(),
20406
21177
  reason: `Contradiction detected with record ${b.id}`
20407
21178
  });
20408
21179
  await this.persistence.saveRecord(a);
@@ -20430,11 +21201,11 @@ var init_consolidation_engine = __esm({
20430
21201
  if (evidence.length === 0) return 0;
20431
21202
  const successes = evidence.filter((e) => e.outcome === "success").length;
20432
21203
  const failures = evidence.filter((e) => e.outcome === "failure").length;
20433
- const unknowns = evidence.filter((e) => e.outcome === "unknown").length;
21204
+ const anys = evidence.filter((e) => e.outcome === "any").length;
20434
21205
  const conditionals = evidence.filter((e) => e.outcome === "conditional").length;
20435
21206
  let confidence = evidence.length > 0 ? successes / evidence.length : 0;
20436
- if (unknowns > 0) {
20437
- confidence *= 1 - unknowns / (evidence.length * 2);
21207
+ if (anys > 0) {
21208
+ confidence *= 1 - anys / (evidence.length * 2);
20438
21209
  }
20439
21210
  if (conditionals > 0) {
20440
21211
  confidence *= 0.9;
@@ -20450,14 +21221,14 @@ var init_consolidation_engine = __esm({
20450
21221
  buildConfidenceJustification(evidence, confidence) {
20451
21222
  const successes = evidence.filter((e) => e.outcome === "success").length;
20452
21223
  const failures = evidence.filter((e) => e.outcome === "failure").length;
20453
- const unknowns = evidence.filter((e) => e.outcome === "unknown").length;
20454
- return `Based on ${evidence.length} unique experience(s): ${successes} success, ${failures} failure, ${unknowns} unknown. Confidence: ${confidence}`;
21224
+ const anys = evidence.filter((e) => e.outcome === "any").length;
21225
+ return `Based on ${evidence.length} unique experience(s): ${successes} success, ${failures} failure, ${anys} any. Confidence: ${confidence}`;
20455
21226
  }
20456
21227
  /** Build limitations list. */
20457
21228
  buildLimitations(evidence, confidence) {
20458
21229
  const limitations = [];
20459
- const unknowns = evidence.filter((e) => e.outcome === "unknown").length;
20460
- if (unknowns > 0) limitations.push(`${unknowns} experience(s) with unknown outcome`);
21230
+ const anys = evidence.filter((e) => e.outcome === "any").length;
21231
+ if (anys > 0) limitations.push(`${anys} experience(s) with any outcome`);
20461
21232
  const conditionals = evidence.filter((e) => e.outcome === "conditional").length;
20462
21233
  if (conditionals > 0) limitations.push(`${conditionals} experience(s) with conditional success`);
20463
21234
  if (confidence < 0.5) limitations.push("Low confidence due to insufficient or conflicting evidence");
@@ -20472,7 +21243,7 @@ var init_consolidation_engine = __esm({
20472
21243
  const record = this.records.get(id);
20473
21244
  if (!record) throw new Error(`Record not found: ${id}`);
20474
21245
  if (record.doNotRemember) throw new Error(`Cannot promote do-not-remember record: ${id}`);
20475
- const now3 = nowIso4();
21246
+ const now3 = nowIso5();
20476
21247
  const promoted = {
20477
21248
  ...record,
20478
21249
  lifecycleState: "consolidated",
@@ -20498,7 +21269,7 @@ var init_consolidation_engine = __esm({
20498
21269
  await this.load();
20499
21270
  const record = this.records.get(id);
20500
21271
  if (!record) throw new Error(`Record not found: ${id}`);
20501
- const now3 = nowIso4();
21272
+ const now3 = nowIso5();
20502
21273
  const superseded = {
20503
21274
  ...record,
20504
21275
  lifecycleState: "superseded",
@@ -20523,7 +21294,7 @@ var init_consolidation_engine = __esm({
20523
21294
  await this.load();
20524
21295
  const record = this.records.get(id);
20525
21296
  if (!record) throw new Error(`Record not found: ${id}`);
20526
- const now3 = nowIso4();
21297
+ const now3 = nowIso5();
20527
21298
  const invalidated = {
20528
21299
  ...record,
20529
21300
  lifecycleState: "invalidated",
@@ -20548,7 +21319,7 @@ var init_consolidation_engine = __esm({
20548
21319
  await this.load();
20549
21320
  const record = this.records.get(id);
20550
21321
  if (!record) throw new Error(`Record not found: ${id}`);
20551
- const now3 = nowIso4();
21322
+ const now3 = nowIso5();
20552
21323
  const reassessed = {
20553
21324
  ...record,
20554
21325
  lifecycleState: "reassessment_required",
@@ -20621,20 +21392,20 @@ __export(session_bootstrap_exports, {
20621
21392
  bootstrapSession: () => bootstrapSession,
20622
21393
  createSessionBootstrap: () => createSessionBootstrap
20623
21394
  });
20624
- var nowIso5, defaultSubject, bootstrapSession, createSessionBootstrap;
21395
+ var nowIso6, defaultSubject, bootstrapSession, createSessionBootstrap;
20625
21396
  var init_session_bootstrap = __esm({
20626
21397
  "core/memory/session-bootstrap.ts"() {
20627
21398
  init_discover();
20628
21399
  init_project();
20629
- init_rules_loader();
21400
+ init_rule_enforcement();
20630
21401
  init_context_constants();
20631
21402
  init_context_compiler();
20632
21403
  init_conversational_state();
20633
21404
  init_recovery_service();
20634
- nowIso5 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
21405
+ nowIso6 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
20635
21406
  defaultSubject = "__default__";
20636
21407
  bootstrapSession = /* @__PURE__ */ __name(async (options = {}) => {
20637
- 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;
21408
+ 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;
20638
21409
  const scopes = {
20639
21410
  userId,
20640
21411
  projectId,
@@ -20692,6 +21463,7 @@ var init_session_bootstrap = __esm({
20692
21463
  let rulesCount = 0;
20693
21464
  let rulesSignature = "";
20694
21465
  let consolidatedKnowledge = [];
21466
+ let enforcementRules = [];
20695
21467
  try {
20696
21468
  const dynamicMemory = await Promise.resolve().then(() => (init_memory(), memory_exports));
20697
21469
  const state3 = await dynamicMemory.loadCombinedKnowledgeState();
@@ -20709,9 +21481,12 @@ var init_session_bootstrap = __esm({
20709
21481
  relevance: 1
20710
21482
  });
20711
21483
  }
20712
- const rules = loadIronRules(state3).rules;
20713
- rulesCount = rules.length;
20714
- rulesSignature = ruleSetSignature(rules);
21484
+ try {
21485
+ enforcementRules = await resolveApplicableRules(situation ?? "", scope);
21486
+ rulesCount = enforcementRules.length;
21487
+ rulesSignature = enforcementRules.map((r) => `${r.id}\0${r.text}`).join("");
21488
+ } catch {
21489
+ }
20715
21490
  try {
20716
21491
  const { consolidationEngine: consolidationEngine2 } = await Promise.resolve().then(() => (init_consolidation_engine(), consolidation_engine_exports));
20717
21492
  await consolidationEngine2.load();
@@ -20741,7 +21516,7 @@ var init_session_bootstrap = __esm({
20741
21516
  }
20742
21517
  const context2 = compileContext({
20743
21518
  conversationalState: recovery?.context?.conversationalState,
20744
- rules: inputRules,
21519
+ rules: enforcementRules.map((r) => `[${r.source.toUpperCase()}] ${r.text}` + (r.appliesWhen ? ` (quando: ${r.appliesWhen})` : "")),
20745
21520
  knowledgeReferences: knowledgeReferences.map((r) => ({
20746
21521
  id: r.id,
20747
21522
  kind: r.kind,
@@ -21119,11 +21894,11 @@ var init_memory = __esm({
21119
21894
  const byTrust = {};
21120
21895
  const byArea = {};
21121
21896
  for (const claim of state3.claims ?? []) {
21122
- const scope = claim.scope ?? "unknown";
21897
+ const scope = claim.scope ?? "any";
21123
21898
  byScope[scope] = (byScope[scope] || 0) + 1;
21124
- const trust = claim.trustBasis ?? "unknown";
21899
+ const trust = claim.trustBasis ?? "any";
21125
21900
  byTrust[trust] = (byTrust[trust] || 0) + 1;
21126
- const area = claim.applicability?.area ?? "unknown";
21901
+ const area = claim.applicability?.area ?? "any";
21127
21902
  byArea[area] = (byArea[area] || 0) + 1;
21128
21903
  }
21129
21904
  return { total: (state3.claims ?? []).length, byScope, byTrust, byArea };
@@ -21233,7 +22008,7 @@ var init_memory = __esm({
21233
22008
  const ids = [];
21234
22009
  for (const stmt of statements) {
21235
22010
  const id = await acquire.acquire({
21236
- knowledge: { hypothesis: stmt, situation: context2?.situation },
22011
+ knowledge: { hypothesis: stmt, ...context2?.situation !== void 0 ? { situation: context2.situation } : {} },
21237
22012
  applicability: context2?.applicability ?? { area: "hypothesis" },
21238
22013
  evidence: [{ id: `hyp-${Date.now()}`, source: "tree-of-thoughts", observedAt: (/* @__PURE__ */ new Date()).toISOString() }],
21239
22014
  epistemicType: "inferred",
@@ -21279,7 +22054,7 @@ var init_memory = __esm({
21279
22054
  },
21280
22055
  async learnFromFailure(claimId, failure, correction) {
21281
22056
  return acquire.acquire({
21282
- knowledge: { failedClaim: claimId, failure, correction },
22057
+ knowledge: { failedClaim: claimId, failure, ...correction !== void 0 ? { correction } : {} },
21283
22058
  applicability: { area: "continual-learning", kind: "correction" },
21284
22059
  evidence: [{ id: `fail-${Date.now()}`, source: "experience", observedAt: (/* @__PURE__ */ new Date()).toISOString() }],
21285
22060
  epistemicType: "observed",
@@ -21294,7 +22069,7 @@ var init_memory = __esm({
21294
22069
  const state3 = await loadCombinedKnowledgeState();
21295
22070
  const groups = {};
21296
22071
  for (const c of state3.claims ?? []) {
21297
- const area = c.applicability?.area ?? "unknown";
22072
+ const area = c.applicability?.area ?? "any";
21298
22073
  if (!groups[area]) groups[area] = [];
21299
22074
  groups[area].push(c.id);
21300
22075
  }
@@ -21364,7 +22139,7 @@ var init_memory = __esm({
21364
22139
  });
21365
22140
  const lines = ["Autobiography:"];
21366
22141
  for (const c of claims) {
21367
- const area = c.applicability?.area ?? "unknown";
22142
+ const area = c.applicability?.area ?? "any";
21368
22143
  lines.push(`- [${c.acquiredAt ?? "?"}] (${area}) ${JSON.stringify(c.knowledge).slice(0, 120)}`);
21369
22144
  }
21370
22145
  return lines.join("\n");