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.js CHANGED
@@ -1,25 +1,22 @@
1
1
  import { store, state, session, hlc, dispatch, temporal } from 'memorio';
2
2
  import crypto5 from 'crypto';
3
- import fs, { readFileSync, readdirSync } from 'fs';
4
- import path8, { relative, extname, join } from 'path';
3
+ import fs6, { readFileSync, readdirSync } from 'fs';
4
+ import path5, { join, relative, extname } from 'path';
5
5
  import { fileURLToPath } from 'url';
6
6
  import fs14 from 'fs/promises';
7
- import { execFileSync, spawnSync } from 'child_process';
7
+ import { spawnSync, execFileSync } from 'child_process';
8
+ import { tmpdir } from 'os';
8
9
  import '@noble/post-quantum/ml-dsa.js';
9
10
  import { ml_kem768_x25519 } from '@noble/post-quantum/hybrid.js';
10
11
  import { createRequire } from 'module';
12
+ import 'reflect-metadata';
13
+ import { PrimaryColumn, Entity, Column, DataSource } from 'typeorm';
11
14
 
12
15
  var __defProp = Object.defineProperty;
13
16
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
14
17
  var __getOwnPropNames = Object.getOwnPropertyNames;
15
18
  var __hasOwnProp = Object.prototype.hasOwnProperty;
16
19
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
17
- var __require = /* @__PURE__ */ ((x3) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x3, {
18
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
19
- }) : x3)(function(x3) {
20
- if (typeof require !== "undefined") return require.apply(this, arguments);
21
- throw Error('Dynamic require of "' + x3 + '" is not supported');
22
- });
23
20
  var __esm = (fn, res, err3) => function __init() {
24
21
  if (err3) throw err3[0];
25
22
  try {
@@ -41,6 +38,14 @@ var __copyProps = (to, from, except, desc) => {
41
38
  return to;
42
39
  };
43
40
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
41
+ var __decorateClass = (decorators, target, key, kind) => {
42
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
43
+ for (var i3 = decorators.length - 1, decorator; i3 >= 0; i3--)
44
+ if (decorator = decorators[i3])
45
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
46
+ if (kind && result) __defProp(target, key, result);
47
+ return result;
48
+ };
44
49
 
45
50
  // core/suppress-idb-warn.ts
46
51
  var origWarn;
@@ -854,18 +859,18 @@ var init_storage_settings = __esm({
854
859
  throw invalidSettings(file2, "must contain a JSON object");
855
860
  }
856
861
  const document = parsed;
857
- const unknownFields = Object.keys(document).filter((key) => key !== "storage");
858
- if (unknownFields.length > 0) {
859
- throw invalidSettings(file2, `contains unsupported top-level fields (${unknownFields.join(", ")})`);
862
+ const anyFields = Object.keys(document).filter((key) => key !== "storage");
863
+ if (anyFields.length > 0) {
864
+ throw invalidSettings(file2, `contains unsupported top-level fields (${anyFields.join(", ")})`);
860
865
  }
861
866
  const storage = document.storage;
862
867
  if (storage === void 0) return {};
863
868
  if (!storage || typeof storage !== "object" || Array.isArray(storage)) {
864
869
  throw invalidSettings(file2, "has a storage field that is not an object");
865
870
  }
866
- const unknownStorageFields = Object.keys(storage).filter((key) => key !== "root" && key !== "mode");
867
- if (unknownStorageFields.length > 0) {
868
- throw invalidSettings(file2, `storage contains unsupported fields (${unknownStorageFields.join(", ")})`);
871
+ const anyStorageFields = Object.keys(storage).filter((key) => key !== "root" && key !== "mode");
872
+ if (anyStorageFields.length > 0) {
873
+ throw invalidSettings(file2, `storage contains unsupported fields (${anyStorageFields.join(", ")})`);
869
874
  }
870
875
  if (storage.mode !== void 0 && (typeof storage.mode !== "string" || !SETTINGS_MODES.includes(storage.mode))) {
871
876
  throw invalidSettings(file2, `storage.mode must be one of ${SETTINGS_MODES.join(", ")} (received ${JSON.stringify(storage.mode)})`);
@@ -913,7 +918,7 @@ var init_storage_settings = __esm({
913
918
  if (code === "EACCES" || code === "EPERM") {
914
919
  throw invalidSettings(file2, `cannot be read (${code})`);
915
920
  }
916
- throw invalidSettings(file2, `cannot be read (${code ?? "unknown error"})`);
921
+ throw invalidSettings(file2, `cannot be read (${code ?? "any error"})`);
917
922
  }
918
923
  return raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw;
919
924
  }, "readTextFile");
@@ -962,7 +967,7 @@ var init_text_encoding = __esm({
962
967
  decodeText = /* @__PURE__ */ __name((bytes, options = {}) => {
963
968
  const bom = detectBom(bytes);
964
969
  if (bom === "utf-16le" || bom === "utf-16be") {
965
- throw new UnsupportedEncodingError(`UTF-16 encoded content detected in ${options.source ?? "unknown"}; dotmem persists UTF-8 only. Re-save the file as UTF-8 without BOM.`);
970
+ throw new UnsupportedEncodingError(`UTF-16 encoded content detected in ${options.source ?? "any"}; dotmem persists UTF-8 only. Re-save the file as UTF-8 without BOM.`);
966
971
  }
967
972
  let content = bytes;
968
973
  if (bom === "utf-8") {
@@ -1045,7 +1050,7 @@ var init_storage_location = __esm({
1045
1050
  if (code === "ENOENT") return "the directory does not exist";
1046
1051
  if (code === "EACCES" || code === "EPERM") return `the directory is not accessible (${code})`;
1047
1052
  if (code === "ENOTDIR") return "the path is not a directory";
1048
- return `the directory cannot be accessed (${code ?? "unknown error"})`;
1053
+ return `the directory cannot be accessed (${code ?? "any error"})`;
1049
1054
  }, "describeAccessFailure");
1050
1055
  validateConfiguredStorageRoot = /* @__PURE__ */ __name((value, source) => {
1051
1056
  if (typeof value !== "string" || !value.trim()) {
@@ -1096,9 +1101,9 @@ var init_storage_location = __esm({
1096
1101
  throw new DotMemStorageLocationError(`dotmem storage location cannot be resolved: the user locator file at ${locatorFile} must contain a JSON object.`);
1097
1102
  }
1098
1103
  const locator = parsed;
1099
- const unknownFields = Object.keys(locator).filter((key) => key !== "version" && key !== "storageRoot");
1100
- if (unknownFields.length > 0) {
1101
- throw new DotMemStorageLocationError(`dotmem storage location cannot be resolved: the user locator file at ${locatorFile} contains unsupported fields (${unknownFields.join(", ")}). The locator holds location metadata only.`);
1104
+ const anyFields = Object.keys(locator).filter((key) => key !== "version" && key !== "storageRoot");
1105
+ if (anyFields.length > 0) {
1106
+ throw new DotMemStorageLocationError(`dotmem storage location cannot be resolved: the user locator file at ${locatorFile} contains unsupported fields (${anyFields.join(", ")}). The locator holds location metadata only.`);
1102
1107
  }
1103
1108
  if (locator.version !== DOTMEM_STORAGE_LOCATOR_VERSION) {
1104
1109
  throw new DotMemStorageLocationError(`dotmem storage location cannot be resolved: the user locator file at ${locatorFile} has unsupported version ${JSON.stringify(locator.version)}; expected ${DOTMEM_STORAGE_LOCATOR_VERSION}.`);
@@ -1446,22 +1451,22 @@ var init_conversation_events = __esm({
1446
1451
  const fs16 = fsSync();
1447
1452
  if (fs16) {
1448
1453
  try {
1449
- const path10 = EVENTS_FILE();
1450
- const parent = path10.substring(0, Math.max(path10.lastIndexOf("/"), path10.lastIndexOf("\\")));
1454
+ const path11 = EVENTS_FILE();
1455
+ const parent = path11.substring(0, Math.max(path11.lastIndexOf("/"), path11.lastIndexOf("\\")));
1451
1456
  try {
1452
1457
  fs16.mkdirSync(parent, { recursive: true });
1453
1458
  } catch {
1454
1459
  }
1455
- const tmp = `${path10}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
1460
+ const tmp = `${path11}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
1456
1461
  fs16.writeFileSync(tmp, JSON.stringify(events));
1457
1462
  try {
1458
- if (fs16.existsSync(path10)) fs16.copyFileSync(path10, `${path10}.bak`);
1463
+ if (fs16.existsSync(path11)) fs16.copyFileSync(path11, `${path11}.bak`);
1459
1464
  } catch {
1460
1465
  }
1461
1466
  try {
1462
- fs16.renameSync(tmp, path10);
1467
+ fs16.renameSync(tmp, path11);
1463
1468
  } catch {
1464
- fs16.copyFileSync(tmp, path10);
1469
+ fs16.copyFileSync(tmp, path11);
1465
1470
  try {
1466
1471
  fs16.unlinkSync(tmp);
1467
1472
  } catch {
@@ -1602,8 +1607,8 @@ var init_conversation_events = __esm({
1602
1607
  try {
1603
1608
  const fs16 = fsSync();
1604
1609
  if (fs16) {
1605
- const path10 = EVENTS_FILE();
1606
- const parent = path10.substring(0, Math.max(path10.lastIndexOf("/"), path10.lastIndexOf("\\")));
1610
+ const path11 = EVENTS_FILE();
1611
+ const parent = path11.substring(0, Math.max(path11.lastIndexOf("/"), path11.lastIndexOf("\\")));
1607
1612
  return await withStorageLock(parent, run);
1608
1613
  }
1609
1614
  } catch {
@@ -1824,7 +1829,7 @@ var init_freshness = __esm({
1824
1829
  evaluateRef = /* @__PURE__ */ __name((ref, current) => {
1825
1830
  if (ref.version !== void 0 && current.version !== void 0 && ref.version !== current.version) return "changed";
1826
1831
  if (ref.digest !== void 0 && current.digest !== void 0 && ref.digest !== current.digest) return "changed";
1827
- if (ref.version === void 0 && current.version === void 0 && ref.digest === void 0 && current.digest === void 0) return "unknown";
1832
+ if (ref.version === void 0 && current.version === void 0 && ref.digest === void 0 && current.digest === void 0) return "any";
1828
1833
  return "same";
1829
1834
  }, "evaluateRef");
1830
1835
  evaluateFreshness = /* @__PURE__ */ __name((input) => {
@@ -1832,10 +1837,10 @@ var init_freshness = __esm({
1832
1837
  return { state: "stale", reason: "explicit invalidation", checkedAt: input.checkedAt };
1833
1838
  }
1834
1839
  if (input.sourceRefs.length === 0) {
1835
- return { state: "unknown", reason: "no source references recorded", checkedAt: input.checkedAt };
1840
+ return { state: "any", reason: "no source references recorded", checkedAt: input.checkedAt };
1836
1841
  }
1837
1842
  const staleReasons = [];
1838
- let unknown = false;
1843
+ let any = false;
1839
1844
  for (const ref of input.sourceRefs) {
1840
1845
  const current = input.currentSources.find((candidate) => candidate.kind === ref.kind && candidate.id === ref.id);
1841
1846
  if (!current) {
@@ -1847,15 +1852,15 @@ var init_freshness = __esm({
1847
1852
  staleReasons.push(`${ref.kind}:${ref.id} version ${ref.version ?? "?"} -> ${current.version ?? "?"}, digest ${ref.digest ?? "?"} -> ${current.digest ?? "?"}`);
1848
1853
  continue;
1849
1854
  }
1850
- if (comparison === "unknown") {
1851
- unknown = true;
1855
+ if (comparison === "any") {
1856
+ any = true;
1852
1857
  }
1853
1858
  }
1854
1859
  if (staleReasons.length > 0) {
1855
1860
  return { state: "stale", reason: staleReasons.join("; "), checkedAt: input.checkedAt };
1856
1861
  }
1857
- if (unknown) {
1858
- return { state: "unknown", reason: "sources without comparable identity", checkedAt: input.checkedAt };
1862
+ if (any) {
1863
+ return { state: "any", reason: "sources without comparable identity", checkedAt: input.checkedAt };
1859
1864
  }
1860
1865
  return { state: "fresh", checkedAt: input.checkedAt };
1861
1866
  }, "evaluateFreshness");
@@ -1978,31 +1983,31 @@ var init_store = __esm({
1978
1983
  snapshots: document.snapshots
1979
1984
  };
1980
1985
  }, "validateContinuityDocument");
1981
- deleteContinuityArtifact = /* @__PURE__ */ __name(async (path10) => {
1986
+ deleteContinuityArtifact = /* @__PURE__ */ __name(async (path11) => {
1982
1987
  const fs16 = getSyncFs();
1983
1988
  if (!fs16) return;
1984
- await fs16.promises.rm(path10, { force: true });
1989
+ await fs16.promises.rm(path11, { force: true });
1985
1990
  }, "deleteContinuityArtifact");
1986
- loadContinuityDocument = /* @__PURE__ */ __name(async (path10) => {
1991
+ loadContinuityDocument = /* @__PURE__ */ __name(async (path11) => {
1987
1992
  const fs16 = getSyncFs();
1988
1993
  if (!fs16) return emptyContinuityDocument();
1989
1994
  try {
1990
- const raw = await fs16.promises.readFile(path10, "utf8");
1995
+ const raw = await fs16.promises.readFile(path11, "utf8");
1991
1996
  return validateContinuityDocument(JSON.parse(raw));
1992
1997
  } catch {
1993
1998
  return emptyContinuityDocument();
1994
1999
  }
1995
2000
  }, "loadContinuityDocument");
1996
- saveContinuityDocument = /* @__PURE__ */ __name(async (path10, document) => {
2001
+ saveContinuityDocument = /* @__PURE__ */ __name(async (path11, document) => {
1997
2002
  const fs16 = getSyncFs();
1998
2003
  if (!fs16) return;
1999
2004
  const validated = validateContinuityDocument(document);
2000
2005
  await fs16.promises.mkdir(resolveUserContinuityDir(), { recursive: true });
2001
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
2006
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
2002
2007
  try {
2003
2008
  await fs16.promises.writeFile(temporary, `${JSON.stringify(validated, null, 2)}
2004
2009
  `, "utf8");
2005
- await fs16.promises.rename(temporary, path10);
2010
+ await fs16.promises.rename(temporary, path11);
2006
2011
  } catch (error) {
2007
2012
  await fs16.promises.rm(temporary, { force: true }).catch(() => void 0);
2008
2013
  throw error;
@@ -2048,9 +2053,9 @@ var init_policy_namespace_lock = __esm({
2048
2053
  currentHost = /* @__PURE__ */ __name(async () => {
2049
2054
  try {
2050
2055
  const os = await import('os');
2051
- return typeof os.hostname === "function" && os.hostname() ? os.hostname() : "unknown";
2056
+ return typeof os.hostname === "function" && os.hostname() ? os.hostname() : "any";
2052
2057
  } catch {
2053
- return "unknown";
2058
+ return "any";
2054
2059
  }
2055
2060
  }, "currentHost");
2056
2061
  delay = /* @__PURE__ */ __name(async (milliseconds) => {
@@ -2069,7 +2074,7 @@ var init_policy_namespace_lock = __esm({
2069
2074
  if (!parsed || typeof parsed !== "object") return null;
2070
2075
  return {
2071
2076
  pid: typeof parsed.pid === "number" ? parsed.pid : 0,
2072
- host: typeof parsed.host === "string" ? parsed.host : "unknown",
2077
+ host: typeof parsed.host === "string" ? parsed.host : "any",
2073
2078
  acquiredAt: typeof parsed.acquiredAt === "string" ? parsed.acquiredAt : "",
2074
2079
  token: typeof parsed.token === "string" ? parsed.token : ""
2075
2080
  };
@@ -2092,7 +2097,7 @@ var init_policy_namespace_lock = __esm({
2092
2097
  const acquiredAt = held ? Date.parse(held.acquiredAt) : Number.NaN;
2093
2098
  const age = Number.isFinite(acquiredAt) ? Date.now() - acquiredAt : Number.POSITIVE_INFINITY;
2094
2099
  if (age > POLICY_LOCK_TTL_MS) {
2095
- const stale = held ?? { pid: 0, host: "unknown", acquiredAt: "", token: "" };
2100
+ const stale = held ?? { pid: 0, host: "any", acquiredAt: "", token: "" };
2096
2101
  const outcome = await breakStalePolicyLock(fs16, lockPath, stale);
2097
2102
  if (outcome === "broken") {
2098
2103
  brokenOwner = stale;
@@ -2109,7 +2114,7 @@ var init_policy_namespace_lock = __esm({
2109
2114
  throw new PolicyNamespaceLockError(`Policy namespace lock could not be acquired after ${POLICY_LOCK_RETRY_ATTEMPTS} bounded retries; policy mutation fails closed`);
2110
2115
  }, "acquireLock");
2111
2116
  breakStalePolicyLock = /* @__PURE__ */ __name(async (fs16, lockPath, staleOwner) => {
2112
- const candidate = `${lockPath}.breaking-${staleOwner.token || "unknown"}`;
2117
+ const candidate = `${lockPath}.breaking-${staleOwner.token || "any"}`;
2113
2118
  try {
2114
2119
  await fs16.rename(lockPath, candidate);
2115
2120
  } catch (error) {
@@ -2331,11 +2336,11 @@ var init_state = __esm({
2331
2336
  if (evidence.length === 0) return;
2332
2337
  for (let index = 0; index < evidence.length; index++) {
2333
2338
  const entry = evidence[index];
2334
- const path10 = `evidence[${index}]`;
2339
+ const path11 = `evidence[${index}]`;
2335
2340
  if (Array.isArray(entry)) {
2336
2341
  throw canonicalEvidenceError({
2337
2342
  claimId: claim.id,
2338
- path: path10,
2343
+ path: path11,
2339
2344
  problem: CANONICAL_EVIDENCE_PROBLEMS.tupleEntry,
2340
2345
  received: entry,
2341
2346
  fix: CANONICAL_EVIDENCE_FIX.tupleEntry
@@ -2344,7 +2349,7 @@ var init_state = __esm({
2344
2349
  if (!entry || typeof entry !== "object") {
2345
2350
  throw canonicalEvidenceError({
2346
2351
  claimId: claim.id,
2347
- path: path10,
2352
+ path: path11,
2348
2353
  problem: CANONICAL_EVIDENCE_PROBLEMS.nonObjectEntry,
2349
2354
  received: entry,
2350
2355
  fix: CANONICAL_EVIDENCE_FIX.nonObjectEntry
@@ -2353,7 +2358,7 @@ var init_state = __esm({
2353
2358
  if (!requiredText(entry.id)) {
2354
2359
  throw canonicalEvidenceError({
2355
2360
  claimId: claim.id,
2356
- path: `${path10}.id`,
2361
+ path: `${path11}.id`,
2357
2362
  problem: CANONICAL_EVIDENCE_PROBLEMS.missingId,
2358
2363
  received: entry,
2359
2364
  fix: CANONICAL_EVIDENCE_FIX.missingId
@@ -2364,7 +2369,7 @@ var init_state = __esm({
2364
2369
  if (fieldValue !== void 0 && !requiredText(fieldValue)) {
2365
2370
  throw canonicalEvidenceError({
2366
2371
  claimId: claim.id,
2367
- path: `${path10}.${field}`,
2372
+ path: `${path11}.${field}`,
2368
2373
  problem: CANONICAL_EVIDENCE_PROBLEMS.invalidOptionalField(field),
2369
2374
  received: fieldValue,
2370
2375
  fix: CANONICAL_EVIDENCE_FIX.invalidOptionalField(field)
@@ -2427,7 +2432,7 @@ var init_state = __esm({
2427
2432
  if (options?.allowUnresolvedRevisions !== true) {
2428
2433
  for (const claim of state3.claims) {
2429
2434
  for (const relatedId of claim.revision?.claimIds || []) {
2430
- if (!ids.has(relatedId)) throw new Error(`Claim ${claim.id} references unknown claim ${relatedId}`);
2435
+ if (!ids.has(relatedId)) throw new Error(`Claim ${claim.id} references any claim ${relatedId}`);
2431
2436
  }
2432
2437
  }
2433
2438
  }
@@ -2451,7 +2456,7 @@ var init_state = __esm({
2451
2456
  }
2452
2457
  for (const claim of update.claims) {
2453
2458
  for (const relatedId of claim.revision?.claimIds || []) {
2454
- if (!known.has(relatedId)) throw new Error(`Claim ${claim.id} references unknown prior claim ${relatedId}`);
2459
+ if (!known.has(relatedId)) throw new Error(`Claim ${claim.id} references any prior claim ${relatedId}`);
2455
2460
  }
2456
2461
  }
2457
2462
  return structuredClone({ version: state3.version + 1, claims: [...state3.claims, ...update.claims] });
@@ -3184,7 +3189,7 @@ var init_policy_store = __esm({
3184
3189
  authority: { kind: "system", source: "policy-namespace-lock" },
3185
3190
  target: resolvePolicyNamespaceLockPath(directory),
3186
3191
  outcome: "applied",
3187
- detail: `stale policy namespace lock broken; previous owner pid ${lockBreak.brokenOwner.pid} host ${lockBreak.brokenOwner.host} acquiredAt ${lockBreak.brokenOwner.acquiredAt || "unknown"}`
3192
+ detail: `stale policy namespace lock broken; previous owner pid ${lockBreak.brokenOwner.pid} host ${lockBreak.brokenOwner.host} acquiredAt ${lockBreak.brokenOwner.acquiredAt || "any"}`
3188
3193
  })
3189
3194
  );
3190
3195
  next = { ...next, audit: boundedAudit([...next.audit, ...breakEntries], next.overrides) };
@@ -3504,7 +3509,7 @@ var init_policy_store = __esm({
3504
3509
  });
3505
3510
 
3506
3511
  // core/knowledge/sanitizer.ts
3507
- var SECRET_KEY_INDICATORS, isSecretKey, looksLikeSecretValue, looksLikeMojibake, collectMojibake, semanticizeSecret, sanitizeObject, sanitizeArray, sanitizeKnowledge;
3512
+ var SECRET_KEY_INDICATORS, isSecretKey, looksLikeSecretValue, looksLikeMojibake, collectMojibake, semanticizeSecret, sanitizeObject, sanitizeArray, sanitizeKnowledge, createSanitizedEnv;
3508
3513
  var init_sanitizer = __esm({
3509
3514
  "core/knowledge/sanitizer.ts"() {
3510
3515
  SECRET_KEY_INDICATORS = ["password", "passwd", "pwd", "secret", "apikey", "api_key", "token", "accesstoken", "refreshtoken", "privatekey", "private_key", "clientsecret", "authorization", "bearer", "credential", "credentials", "recoverycode", "sessionsecret", "jwtsecret"];
@@ -3629,6 +3634,15 @@ var init_sanitizer = __esm({
3629
3634
  disposition: "persist"
3630
3635
  };
3631
3636
  }, "sanitizeKnowledge");
3637
+ createSanitizedEnv = /* @__PURE__ */ __name(() => {
3638
+ const env = {};
3639
+ for (const [key, value] of Object.entries(process.env)) {
3640
+ if (isSecretKey(key)) continue;
3641
+ if (value === void 0 || value === null) continue;
3642
+ env[key] = value;
3643
+ }
3644
+ return env;
3645
+ }, "createSanitizedEnv");
3632
3646
  }
3633
3647
  });
3634
3648
 
@@ -3780,7 +3794,7 @@ var init_built_in_context = __esm({
3780
3794
  return __dirname;
3781
3795
  }
3782
3796
  try {
3783
- return path8.dirname(fileURLToPath(import.meta.url));
3797
+ return path5.dirname(fileURLToPath(import.meta.url));
3784
3798
  } catch {
3785
3799
  return process.cwd();
3786
3800
  }
@@ -3788,7 +3802,7 @@ var init_built_in_context = __esm({
3788
3802
  candidatePaths = /* @__PURE__ */ __name(() => {
3789
3803
  const paths = [];
3790
3804
  try {
3791
- paths.push(path8.join(pkgDirname(), "built-in-context.json"));
3805
+ paths.push(path5.join(pkgDirname(), "built-in-context.json"));
3792
3806
  } catch {
3793
3807
  }
3794
3808
  return paths;
@@ -3857,11 +3871,11 @@ var init_built_in_context = __esm({
3857
3871
  let lastError = "Built-in context artifact not found";
3858
3872
  const candidates = _artifactPathOverride ? [_artifactPathOverride] : candidatePaths();
3859
3873
  for (const candidate of candidates) {
3860
- if (!fs.existsSync(candidate)) continue;
3874
+ if (!fs6.existsSync(candidate)) continue;
3861
3875
  let readAttempts = 0;
3862
3876
  while (readAttempts < 60) {
3863
3877
  try {
3864
- const raw = fs.readFileSync(candidate);
3878
+ const raw = fs6.readFileSync(candidate);
3865
3879
  const parsed = JSON.parse(decodeText(raw, { source: candidate }));
3866
3880
  const artifact = validateArtifact(parsed);
3867
3881
  cached = artifact;
@@ -3898,15 +3912,15 @@ var init_built_in_context = __esm({
3898
3912
  }
3899
3913
  let attemptedPath = "";
3900
3914
  try {
3901
- attemptedPath = path8.join(pkgDirname(), "built-in-context.json");
3915
+ attemptedPath = path5.join(pkgDirname(), "built-in-context.json");
3902
3916
  } catch {
3903
3917
  }
3904
- let packageVersion = "unknown";
3918
+ let packageVersion = "any";
3905
3919
  try {
3906
- const pkgPath = path8.join(pkgDirname(), "package.json");
3907
- if (fs.existsSync(pkgPath)) {
3908
- const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
3909
- packageVersion = typeof pkg.version === "string" ? pkg.version : "unknown";
3920
+ const pkgPath = path5.join(pkgDirname(), "package.json");
3921
+ if (fs6.existsSync(pkgPath)) {
3922
+ const pkg = JSON.parse(fs6.readFileSync(pkgPath, "utf8"));
3923
+ packageVersion = typeof pkg.version === "string" ? pkg.version : "any";
3910
3924
  }
3911
3925
  } catch {
3912
3926
  }
@@ -5507,14 +5521,14 @@ var init_mem_package = __esm({
5507
5521
  const digest = await globalThis.crypto.subtle.digest("SHA-256", data);
5508
5522
  return `sha256:${[...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
5509
5523
  }, "sha256");
5510
- parseJson = /* @__PURE__ */ __name((bytes, path10) => {
5524
+ parseJson = /* @__PURE__ */ __name((bytes, path11) => {
5511
5525
  try {
5512
5526
  return JSON.parse(decodeText(bytes));
5513
5527
  } catch (error) {
5514
- throw new MemArtifactError("invalid", `Invalid UTF-8 JSON in ${path10}: ${error.message}`);
5528
+ throw new MemArtifactError("invalid", `Invalid UTF-8 JSON in ${path11}: ${error.message}`);
5515
5529
  }
5516
5530
  }, "parseJson");
5517
- 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");
5531
+ 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");
5518
5532
  concatenate = /* @__PURE__ */ __name((chunks, size) => {
5519
5533
  const result = new Uint8Array(size);
5520
5534
  let offset = 0;
@@ -5590,24 +5604,24 @@ var init_mem_package = __esm({
5590
5604
  [DATA_PATH]: jsonBytes(memory2.data),
5591
5605
  ...structuredClone(preservedPackage?.extensions ?? {})
5592
5606
  };
5593
- for (const path10 of Object.keys(protectedParts)) {
5594
- if (!requiredParts.includes(path10) && !path10.startsWith("extensions/")) {
5595
- throw new MemArtifactError("invalid", `Unsupported preserved package part: ${path10}`);
5607
+ for (const path11 of Object.keys(protectedParts)) {
5608
+ if (!requiredParts.includes(path11) && !path11.startsWith("extensions/")) {
5609
+ throw new MemArtifactError("invalid", `Unsupported preserved package part: ${path11}`);
5596
5610
  }
5597
- if (!validEntryPath(path10)) throw new MemArtifactError("invalid", `Unsafe MEM package path: ${path10}`);
5611
+ if (!validEntryPath(path11)) throw new MemArtifactError("invalid", `Unsafe MEM package path: ${path11}`);
5598
5612
  }
5599
- for (const path10 of Object.keys(signatures)) {
5600
- if (!/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path10)) {
5601
- throw new MemArtifactError("invalid", `Invalid MEM signature path: ${path10}`);
5613
+ for (const path11 of Object.keys(signatures)) {
5614
+ if (!/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path11)) {
5615
+ throw new MemArtifactError("invalid", `Invalid MEM signature path: ${path11}`);
5602
5616
  }
5603
5617
  }
5604
5618
  const files = {};
5605
- for (const path10 of Object.keys(protectedParts).sort()) files[path10] = await sha2562(protectedParts[path10]);
5619
+ for (const path11 of Object.keys(protectedParts).sort()) files[path11] = await sha2562(protectedParts[path11]);
5606
5620
  const integrity = { algorithm: "sha256", files, contentId: await digestTableIdentity(files) };
5607
5621
  const parts = { ...protectedParts, [INTEGRITY_PATH]: jsonBytes(integrity), ...signatures };
5608
- for (const [path10, bytes] of Object.entries(parts)) {
5622
+ for (const [path11, bytes] of Object.entries(parts)) {
5609
5623
  if (bytes.length > MEM_PACKAGE_WRITE_LIMITS.maximumEntryBytes) {
5610
- throw new MemArtifactError("invalid", `MEM package entry exceeds the write limit: ${path10}`);
5624
+ throw new MemArtifactError("invalid", `MEM package entry exceeds the write limit: ${path11}`);
5611
5625
  }
5612
5626
  }
5613
5627
  const uncompressedBytes = Object.values(parts).reduce((total, bytes) => total + bytes.length, 0);
@@ -5615,10 +5629,10 @@ var init_mem_package = __esm({
5615
5629
  throw new MemArtifactError("invalid", "MEM package exceeds the write limit for uncompressed content");
5616
5630
  }
5617
5631
  const zippable = Object.fromEntries(
5618
- Object.keys(parts).sort().map((path10) => [
5619
- path10,
5632
+ Object.keys(parts).sort().map((path11) => [
5633
+ path11,
5620
5634
  [
5621
- parts[path10],
5635
+ parts[path11],
5622
5636
  {
5623
5637
  level: 6,
5624
5638
  mtime: /* @__PURE__ */ new Date("1980-01-02T00:00:00.000Z")
@@ -5638,8 +5652,8 @@ var init_mem_package = __esm({
5638
5652
  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");
5639
5653
  decodePackage = /* @__PURE__ */ __name(async (bytes) => {
5640
5654
  const parts = readZipParts(bytes);
5641
- for (const path10 of [...requiredParts, INTEGRITY_PATH]) {
5642
- if (!parts[path10]) throw new MemArtifactError("invalid", `Missing MEM package part: ${path10}`);
5655
+ for (const path11 of [...requiredParts, INTEGRITY_PATH]) {
5656
+ if (!parts[path11]) throw new MemArtifactError("invalid", `Missing MEM package part: ${path11}`);
5643
5657
  }
5644
5658
  const manifest = parseJson(parts[MANIFEST_PATH], MANIFEST_PATH);
5645
5659
  if (manifest.format !== MEM_PACKAGE_FORMAT && manifest.format !== MEM_PACKAGE_FORMAT_LEGACY || manifest.version !== MEM_PACKAGE_VERSION) {
@@ -5650,8 +5664,8 @@ var init_mem_package = __esm({
5650
5664
  }
5651
5665
  const integrity = parseJson(parts[INTEGRITY_PATH], INTEGRITY_PATH);
5652
5666
  if (integrity.algorithm !== "sha256") throw new MemArtifactError("unsupported", "Unsupported MEM package integrity algorithm");
5653
- const signaturePaths = Object.keys(parts).filter((path10) => path10.startsWith("security/signatures/")).sort();
5654
- if (signaturePaths.some((path10) => !/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path10))) {
5667
+ const signaturePaths = Object.keys(parts).filter((path11) => path11.startsWith("security/signatures/")).sort();
5668
+ if (signaturePaths.some((path11) => !/^security\/signatures\/[a-f0-9]{64}\.json$/.test(path11))) {
5655
5669
  throw new MemArtifactError("invalid", "Invalid MEM signature entry path");
5656
5670
  }
5657
5671
  if (manifest.authenticity !== void 0 && manifest.authenticity.signed !== true) {
@@ -5660,14 +5674,14 @@ var init_mem_package = __esm({
5660
5674
  if (manifest.authenticity?.signed === true !== signaturePaths.length > 0) {
5661
5675
  throw new MemArtifactError("invalid", "Declared MEM signatures do not match package entries");
5662
5676
  }
5663
- const archivePaths = Object.keys(parts).filter((path10) => path10 !== INTEGRITY_PATH && !path10.startsWith("security/signatures/")).sort();
5677
+ const archivePaths = Object.keys(parts).filter((path11) => path11 !== INTEGRITY_PATH && !path11.startsWith("security/signatures/")).sort();
5664
5678
  const protectedPaths = Object.keys(integrity.files ?? {}).sort();
5665
5679
  if (JSON.stringify(archivePaths) !== JSON.stringify(protectedPaths)) {
5666
5680
  throw new MemArtifactError("invalid", "MEM package protected-parts table does not match archive contents");
5667
5681
  }
5668
- for (const path10 of protectedPaths) {
5669
- const actual = await sha2562(parts[path10]);
5670
- if (integrity.files[path10] !== actual) throw new MemArtifactError("checksum_mismatch", `Checksum mismatch for ${path10}`);
5682
+ for (const path11 of protectedPaths) {
5683
+ const actual = await sha2562(parts[path11]);
5684
+ if (integrity.files[path11] !== actual) throw new MemArtifactError("checksum_mismatch", `Checksum mismatch for ${path11}`);
5671
5685
  }
5672
5686
  if (integrity.contentId !== await digestTableIdentity(integrity.files)) {
5673
5687
  throw new MemArtifactError("checksum_mismatch", "MEM package content identity mismatch");
@@ -5680,8 +5694,8 @@ var init_mem_package = __esm({
5680
5694
  } catch (error) {
5681
5695
  throw new MemArtifactError("invalid", `Invalid packaged MEM semantics: ${error.message}`);
5682
5696
  }
5683
- const extensions = Object.fromEntries(Object.entries(parts).filter(([path10]) => path10.startsWith("extensions/")));
5684
- const signatures = Object.fromEntries(signaturePaths.map((path10) => [path10, parts[path10]]));
5697
+ const extensions = Object.fromEntries(Object.entries(parts).filter(([path11]) => path11.startsWith("extensions/")));
5698
+ const signatures = Object.fromEntries(signaturePaths.map((path11) => [path11, parts[path11]]));
5685
5699
  return { ...decoded, representation: "package-v1", package: { manifest, extensions, signatures }, parts, integrity };
5686
5700
  }, "decodePackage");
5687
5701
  decodeMemArtifact = /* @__PURE__ */ __name(async (input) => {
@@ -5720,13 +5734,13 @@ var init_quarantine = __esm({
5720
5734
  quarantineClaimRecord = /* @__PURE__ */ __name(async (record) => {
5721
5735
  if (!record.filePath) return null;
5722
5736
  try {
5723
- const dir = path8.dirname(record.filePath);
5724
- const quarantineDir = path8.join(dir, "quarantine");
5737
+ const dir = path5.dirname(record.filePath);
5738
+ const quarantineDir = path5.join(dir, "quarantine");
5725
5739
  await fs14.mkdir(quarantineDir, { recursive: true });
5726
- const safeId = String(record.claimId ?? "unknown").replace(/[^a-zA-Z0-9._-]/g, "-");
5740
+ const safeId = String(record.claimId ?? "any").replace(/[^a-zA-Z0-9._-]/g, "-");
5727
5741
  const timestamp = record.timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
5728
5742
  const fileName = `${safeId}-${Date.now()}.json`;
5729
- const fullPath = path8.join(quarantineDir, fileName);
5743
+ const fullPath = path5.join(quarantineDir, fileName);
5730
5744
  const payload = {
5731
5745
  claimId: record.claimId,
5732
5746
  store: record.store,
@@ -5767,7 +5781,7 @@ var init_store_registry = __esm({
5767
5781
  }
5768
5782
  for (const dirent of dirents) {
5769
5783
  if (!dirent.isFile()) continue;
5770
- const filePath = path8.join(directory, dirent.name);
5784
+ const filePath = path5.join(directory, dirent.name);
5771
5785
  if (isMemFile(dirent.name)) {
5772
5786
  entries2.push({ id: dirent.name, path: filePath, kind: "active", active: true, reason: "active .mem store" });
5773
5787
  continue;
@@ -5930,7 +5944,7 @@ var init_claim_delete = __esm({
5930
5944
  }
5931
5945
  let deleted = false;
5932
5946
  for (const location of selected) {
5933
- await withStorageLock(path8.dirname(location.filePath), async () => {
5947
+ await withStorageLock(path5.dirname(location.filePath), async () => {
5934
5948
  const bytes = await fs14.readFile(location.filePath);
5935
5949
  const artifact = await decodeMemArtifact(bytes);
5936
5950
  if (!artifact.state) throw new Error(`Unable to read store ${location.filePath}`);
@@ -6411,31 +6425,6 @@ var init_mem_repository = __esm({
6411
6425
  };
6412
6426
  }
6413
6427
  });
6414
- function parseProbe(probe) {
6415
- if (!probe) return null;
6416
- if (typeof probe === "string") {
6417
- const parts = probe.trim().split(/\s+/);
6418
- return { type: parts[0], args: parts.slice(1) };
6419
- }
6420
- if (typeof probe === "object") {
6421
- const type = String(probe.type ?? probe.kind ?? probe.name ?? "");
6422
- if (type === "file-exists") return { type, args: [String(probe.path ?? probe.file ?? probe.target ?? "")] };
6423
- if (type === "file-contains") return { type, args: [String(probe.path ?? probe.file ?? ""), String(probe.literal ?? probe.contains ?? probe.value ?? "")] };
6424
- if (type === "json-path") return { type, args: [String(probe.file ?? probe.path ?? ""), String(probe.path ?? probe.jsonPath ?? ""), String(probe.expected ?? probe.value ?? "")] };
6425
- 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) };
6426
- return { type, args: [] };
6427
- }
6428
- return null;
6429
- }
6430
- function allowlist() {
6431
- try {
6432
- const raw = fs.readFileSync(`${resolveUserDotMemPath()}/probe-allowlist.json`, "utf8");
6433
- const parsed = JSON.parse(raw);
6434
- if (Array.isArray(parsed)) return parsed.map(String);
6435
- } catch {
6436
- }
6437
- return ["node", "git", "bun"];
6438
- }
6439
6428
  function runProbe(probe) {
6440
6429
  const spec = parseProbe(probe);
6441
6430
  if (!spec) return true;
@@ -6445,23 +6434,54 @@ function runProbe(probe) {
6445
6434
  let ok = false;
6446
6435
  try {
6447
6436
  if (spec.type === "file-exists") {
6448
- ok = fs.existsSync(spec.args[0]);
6437
+ const target = spec.args[0];
6438
+ if (!isAuthorizedPath(target)) {
6439
+ cache.set(key, { at: Date.now(), ok: false });
6440
+ return false;
6441
+ }
6442
+ ok = fs6.existsSync(target);
6449
6443
  } else if (spec.type === "file-contains") {
6450
- const content = fs.readFileSync(spec.args[0], "utf8");
6444
+ const target = spec.args[0];
6445
+ if (!isAuthorizedPath(target)) {
6446
+ cache.set(key, { at: Date.now(), ok: false });
6447
+ return false;
6448
+ }
6449
+ const stat = fs6.statSync(target);
6450
+ if (stat.size > MAX_PROBE_FILE_BYTES) {
6451
+ cache.set(key, { at: Date.now(), ok: false });
6452
+ return false;
6453
+ }
6454
+ const content = fs6.readFileSync(target, "utf8");
6451
6455
  ok = content.includes(spec.args[1]);
6452
6456
  } else if (spec.type === "json-path") {
6453
- const obj = JSON.parse(fs.readFileSync(spec.args[0], "utf8"));
6457
+ const target = spec.args[0];
6458
+ if (!isAuthorizedPath(target)) {
6459
+ cache.set(key, { at: Date.now(), ok: false });
6460
+ return false;
6461
+ }
6462
+ const stat = fs6.statSync(target);
6463
+ if (stat.size > MAX_PROBE_FILE_BYTES) {
6464
+ cache.set(key, { at: Date.now(), ok: false });
6465
+ return false;
6466
+ }
6467
+ const obj = JSON.parse(fs6.readFileSync(target, "utf8"));
6454
6468
  const pathParts = spec.args[1].split(".");
6455
6469
  let cur = obj;
6456
6470
  for (const p of pathParts) cur = cur?.[p];
6457
6471
  ok = String(cur) === spec.args[2];
6458
6472
  } else if (spec.type === "command") {
6459
6473
  const cmd = spec.args[0];
6460
- if (!allowlist().includes(cmd)) {
6474
+ const args = spec.args.slice(1);
6475
+ if (args.some((a) => DANGEROUS_FLAGS.has(a))) {
6461
6476
  cache.set(key, { at: Date.now(), ok: false });
6462
6477
  return false;
6463
6478
  }
6464
- const res = spawnSync(cmd, spec.args.slice(1), { timeout: 5e3, encoding: "utf8", shell: false, maxBuffer: 64 * 1024 });
6479
+ const handler = isTrustedCommand(cmd, args);
6480
+ if (!handler) {
6481
+ cache.set(key, { at: Date.now(), ok: false });
6482
+ return false;
6483
+ }
6484
+ const res = spawnSync(handler.cmd, handler.args, { timeout: 5e3, encoding: "utf8", shell: false, maxBuffer: 64 * 1024, env: createSanitizedEnv() });
6465
6485
  ok = res.status === 0;
6466
6486
  } else {
6467
6487
  ok = false;
@@ -6472,12 +6492,91 @@ function runProbe(probe) {
6472
6492
  cache.set(key, { at: Date.now(), ok });
6473
6493
  return ok;
6474
6494
  }
6475
- var cache, CACHE_MS;
6495
+ var TRUSTED_PROBES, DANGEROUS_FLAGS, MAX_PROBE_FILE_BYTES, AUTHORIZED_ROOTS, isAuthorizedPath, isTrustedCommand, parseProbe, cache, CACHE_MS;
6476
6496
  var init_probe = __esm({
6477
6497
  "core/knowledge/probe.ts"() {
6478
- init_user_paths();
6479
- __name(parseProbe, "parseProbe");
6480
- __name(allowlist, "allowlist");
6498
+ init_sanitizer();
6499
+ TRUSTED_PROBES = [
6500
+ { id: "node-version", cmd: "node", args: ["--version"] },
6501
+ { id: "git-version", cmd: "git", args: ["--version"] }
6502
+ ];
6503
+ DANGEROUS_FLAGS = /* @__PURE__ */ new Set(["-e", "--eval", "-p", "--print", "-r", "--require", "--loader", "--input-type", "--experimental-vm-modules", "--experimental-loader"]);
6504
+ MAX_PROBE_FILE_BYTES = 10 * 1024 * 1024;
6505
+ AUTHORIZED_ROOTS = Array.from(/* @__PURE__ */ new Set([
6506
+ path5.resolve(process.cwd()),
6507
+ path5.resolve(tmpdir())
6508
+ ]));
6509
+ isAuthorizedPath = /* @__PURE__ */ __name((candidate) => {
6510
+ if (typeof candidate !== "string" || candidate.length === 0) return false;
6511
+ if (candidate.includes("\0")) return false;
6512
+ if (candidate.startsWith("\\\\") || candidate.startsWith("//")) return false;
6513
+ const resolved = path5.resolve(candidate);
6514
+ const lexicallyAllowed = AUTHORIZED_ROOTS.some((root) => {
6515
+ const rel = path5.relative(root, resolved);
6516
+ return rel === "" || !rel.startsWith("..") && !path5.isAbsolute(rel);
6517
+ });
6518
+ if (!lexicallyAllowed) return false;
6519
+ try {
6520
+ if (fs6.existsSync(resolved)) {
6521
+ const real = fs6.realpathSync(resolved);
6522
+ const reallyAllowed = AUTHORIZED_ROOTS.some((root) => {
6523
+ let realRoot = root;
6524
+ try {
6525
+ realRoot = fs6.realpathSync(root);
6526
+ } catch {
6527
+ }
6528
+ const rel = path5.relative(realRoot, real);
6529
+ return rel === "" || !rel.startsWith("..") && !path5.isAbsolute(rel);
6530
+ });
6531
+ if (!reallyAllowed) return false;
6532
+ }
6533
+ } catch {
6534
+ return false;
6535
+ }
6536
+ return true;
6537
+ }, "isAuthorizedPath");
6538
+ isTrustedCommand = /* @__PURE__ */ __name((cmd, args) => {
6539
+ return TRUSTED_PROBES.find((p) => p.cmd === cmd && JSON.stringify(p.args) === JSON.stringify(args)) ?? null;
6540
+ }, "isTrustedCommand");
6541
+ parseProbe = /* @__PURE__ */ __name((probe) => {
6542
+ if (!probe) return null;
6543
+ if (typeof probe === "string") {
6544
+ const parts = probe.trim().split(/\s+/);
6545
+ return { type: parts[0], args: parts.slice(1) };
6546
+ }
6547
+ if (typeof probe === "object") {
6548
+ const type = String(probe.type ?? probe.kind ?? probe.name ?? "");
6549
+ if (type === "file-exists") return { type, args: [String(probe.path ?? probe.file ?? probe.target ?? "")] };
6550
+ if (type === "file-contains") return { type, args: [String(probe.path ?? probe.file ?? ""), String(probe.literal ?? probe.contains ?? probe.value ?? "")] };
6551
+ if (type === "json-path") return { type, args: [String(probe.file ?? probe.path ?? ""), String(probe.path ?? probe.jsonPath ?? ""), String(probe.expected ?? probe.value ?? "")] };
6552
+ if (type === "command" || type === "probe") {
6553
+ if (typeof probe.id === "string") {
6554
+ const found = TRUSTED_PROBES.find((p) => p.id === probe.id);
6555
+ if (found) return { type: "command", args: [found.cmd, ...found.args] };
6556
+ return { type: "command", args: [] };
6557
+ }
6558
+ let cmd;
6559
+ let args = [];
6560
+ if (Array.isArray(probe.args) && probe.args.length > 0) {
6561
+ cmd = String(probe.args[0]);
6562
+ args = probe.args.slice(1).map(String);
6563
+ } else if (Array.isArray(probe.command)) {
6564
+ cmd = String(probe.command[0]);
6565
+ args = probe.command.slice(1).map(String);
6566
+ } else if (typeof probe.command === "string") {
6567
+ const parts = probe.command.trim().split(/\s+/);
6568
+ cmd = parts[0];
6569
+ args = parts.slice(1);
6570
+ }
6571
+ if (cmd) {
6572
+ return { type: "command", args: [cmd, ...args] };
6573
+ }
6574
+ return { type: "command", args: [] };
6575
+ }
6576
+ return { type, args: [] };
6577
+ }
6578
+ return null;
6579
+ }, "parseProbe");
6481
6580
  cache = /* @__PURE__ */ new Map();
6482
6581
  CACHE_MS = 6e4;
6483
6582
  __name(runProbe, "runProbe");
@@ -6492,19 +6591,6 @@ __export(telemetry_exports, {
6492
6591
  recordProjection: () => recordProjection,
6493
6592
  recordRetraction: () => recordRetraction
6494
6593
  });
6495
- function load() {
6496
- try {
6497
- return JSON.parse(fs.readFileSync(file(), "utf8"));
6498
- } catch {
6499
- return {};
6500
- }
6501
- }
6502
- function save(store7) {
6503
- try {
6504
- fs.writeFileSync(file(), JSON.stringify(store7, null, 2), "utf8");
6505
- } catch {
6506
- }
6507
- }
6508
6594
  function recordProjection(ids) {
6509
6595
  const store7 = load();
6510
6596
  const now3 = (/* @__PURE__ */ new Date()).toISOString();
@@ -6533,13 +6619,24 @@ function recordRetraction(id) {
6533
6619
  function readTelemetry() {
6534
6620
  return load();
6535
6621
  }
6536
- var file;
6622
+ var file, load, save;
6537
6623
  var init_telemetry = __esm({
6538
6624
  "core/knowledge/telemetry.ts"() {
6539
6625
  init_user_paths();
6540
6626
  file = /* @__PURE__ */ __name(() => `${resolveUserDotMemPath()}/telemetry.json`, "file");
6541
- __name(load, "load");
6542
- __name(save, "save");
6627
+ load = /* @__PURE__ */ __name(() => {
6628
+ try {
6629
+ return JSON.parse(fs6.readFileSync(file(), "utf8"));
6630
+ } catch {
6631
+ return {};
6632
+ }
6633
+ }, "load");
6634
+ save = /* @__PURE__ */ __name((store7) => {
6635
+ try {
6636
+ fs6.writeFileSync(file(), JSON.stringify(store7, null, 2), "utf8");
6637
+ } catch {
6638
+ }
6639
+ }, "save");
6543
6640
  __name(recordProjection, "recordProjection");
6544
6641
  __name(recordFeedback, "recordFeedback");
6545
6642
  __name(recordRetraction, "recordRetraction");
@@ -6586,7 +6683,7 @@ var init_currentness = __esm({
6586
6683
  const verifiedAt = verifiedAtOf(claim);
6587
6684
  if (verifiedAt !== void 0) return "verified";
6588
6685
  if (claim.epistemicType === "verified") return "unverified";
6589
- return "unknown-currentness";
6686
+ return "any-currentness";
6590
6687
  }, "deriveCurrentness");
6591
6688
  }
6592
6689
  });
@@ -7430,7 +7527,7 @@ var init_staging = __esm({
7430
7527
  throw new Error("Stage file must contain a claim object");
7431
7528
  }
7432
7529
  const claimValidation = buildClaimRecord({
7433
- id: s.claim.id,
7530
+ id: typeof s.claim.id === "string" ? s.claim.id : "",
7434
7531
  knowledge: s.claim.knowledge,
7435
7532
  applicability: s.claim.applicability,
7436
7533
  evidence: s.claim.evidence,
@@ -7847,7 +7944,7 @@ var init_violations = __esm({
7847
7944
  VIOLATION_FILE_NAME = "violations.json";
7848
7945
  }
7849
7946
  });
7850
- var isRuleClaim, isIronRule, extractIronRules, readViolationCounts, sortRulesByViolationFrequency, loadIronRules, ruleSetSignature;
7947
+ var isRuleClaim, isIronRule, extractIronRules, readViolationCounts, sortRulesByViolationFrequency, loadIronRules;
7851
7948
  var init_rules_loader = __esm({
7852
7949
  "core/knowledge/rules-loader.ts"() {
7853
7950
  init_state();
@@ -7913,15 +8010,6 @@ var init_rules_loader = __esm({
7913
8010
  sortedBy: "violation-frequency"
7914
8011
  };
7915
8012
  }, "loadIronRules");
7916
- ruleSetSignature = /* @__PURE__ */ __name((rules) => {
7917
- const material = rules.map((rule) => `${rule.id}\0${rule.text}`).join("");
7918
- let hash = 2166136261;
7919
- for (let index = 0; index < material.length; index += 1) {
7920
- hash ^= material.charCodeAt(index);
7921
- hash = Math.imul(hash, 16777619) >>> 0;
7922
- }
7923
- return hash.toString(16).padStart(8, "0");
7924
- }, "ruleSetSignature");
7925
8013
  }
7926
8014
  });
7927
8015
 
@@ -8105,25 +8193,25 @@ var init_exemplars = __esm({
8105
8193
  resolveExemplarsPath = /* @__PURE__ */ __name(() => {
8106
8194
  return joinPath3(resolveUserDotMemPath(), EXEMPLARS_FILE_NAME);
8107
8195
  }, "resolveExemplarsPath");
8108
- readFile = /* @__PURE__ */ __name(async (path10) => {
8196
+ readFile = /* @__PURE__ */ __name(async (path11) => {
8109
8197
  try {
8110
8198
  const fs16 = await import('fs/promises');
8111
- return await fs16.readFile(path10, "utf8");
8199
+ return await fs16.readFile(path11, "utf8");
8112
8200
  } catch {
8113
8201
  return null;
8114
8202
  }
8115
8203
  }, "readFile");
8116
- writeFile = /* @__PURE__ */ __name(async (path10, content) => {
8204
+ writeFile = /* @__PURE__ */ __name(async (path11, content) => {
8117
8205
  const fs16 = await import('fs/promises');
8118
- const dir = path10.replace(/[\\/][^\\/]+$/, "");
8206
+ const dir = path11.replace(/[\\/][^\\/]+$/, "");
8119
8207
  await fs16.mkdir(dir, { recursive: true });
8120
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
8208
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
8121
8209
  try {
8122
8210
  await fs16.writeFile(temporary, content, "utf8");
8123
- await fs16.rename(temporary, path10);
8211
+ await fs16.rename(temporary, path11);
8124
8212
  } catch {
8125
8213
  await fs16.rm(temporary, { force: true }).catch(() => void 0);
8126
- throw new Error(`Failed to write exemplars file at ${path10}`);
8214
+ throw new Error(`Failed to write exemplars file at ${path11}`);
8127
8215
  }
8128
8216
  }, "writeFile");
8129
8217
  emptyStore = /* @__PURE__ */ __name(() => {
@@ -11661,25 +11749,25 @@ var init_loops = __esm({
11661
11749
  release();
11662
11750
  }
11663
11751
  }, "withLoopLock");
11664
- readFile2 = /* @__PURE__ */ __name(async (path10) => {
11752
+ readFile2 = /* @__PURE__ */ __name(async (path11) => {
11665
11753
  try {
11666
11754
  const fs16 = await import('fs/promises');
11667
- return await fs16.readFile(path10, "utf8");
11755
+ return await fs16.readFile(path11, "utf8");
11668
11756
  } catch {
11669
11757
  return null;
11670
11758
  }
11671
11759
  }, "readFile");
11672
- writeFile2 = /* @__PURE__ */ __name(async (path10, content) => {
11760
+ writeFile2 = /* @__PURE__ */ __name(async (path11, content) => {
11673
11761
  const fs16 = await import('fs/promises');
11674
- const dir = path10.replace(/[\\/][^\\/]+$/, "");
11762
+ const dir = path11.replace(/[\\/][^\\/]+$/, "");
11675
11763
  await fs16.mkdir(dir, { recursive: true });
11676
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
11764
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
11677
11765
  try {
11678
11766
  await fs16.writeFile(temporary, content, "utf8");
11679
- await fs16.rename(temporary, path10);
11767
+ await fs16.rename(temporary, path11);
11680
11768
  } catch {
11681
11769
  await fs16.rm(temporary, { force: true }).catch(() => void 0);
11682
- throw new Error(`Failed to write loops file at ${path10}`);
11770
+ throw new Error(`Failed to write loops file at ${path11}`);
11683
11771
  }
11684
11772
  }, "writeFile");
11685
11773
  emptyDocument = /* @__PURE__ */ __name(() => {
@@ -11763,7 +11851,7 @@ var init_loops = __esm({
11763
11851
  text: input.text,
11764
11852
  waitor: input.waitor,
11765
11853
  openedAt: input.openedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
11766
- authorAgent: input.authorAgent ?? "unknown",
11854
+ authorAgent: input.authorAgent ?? "any",
11767
11855
  targetRole: input.targetRole ?? "any",
11768
11856
  status: input.status ?? "open",
11769
11857
  projectId: input.projectId,
@@ -11829,25 +11917,25 @@ var init_personality_anchor = __esm({
11829
11917
  resolvePersonalityAnchorPath = /* @__PURE__ */ __name(() => {
11830
11918
  return joinPath5(resolveUserDotMemPath(), PERSONALITY_ANCHOR_FILE_NAME);
11831
11919
  }, "resolvePersonalityAnchorPath");
11832
- readFile3 = /* @__PURE__ */ __name(async (path10) => {
11920
+ readFile3 = /* @__PURE__ */ __name(async (path11) => {
11833
11921
  try {
11834
11922
  const fs16 = await import('fs/promises');
11835
- return await fs16.readFile(path10, "utf8");
11923
+ return await fs16.readFile(path11, "utf8");
11836
11924
  } catch {
11837
11925
  return null;
11838
11926
  }
11839
11927
  }, "readFile");
11840
- writeFile3 = /* @__PURE__ */ __name(async (path10, content) => {
11928
+ writeFile3 = /* @__PURE__ */ __name(async (path11, content) => {
11841
11929
  const fs16 = await import('fs/promises');
11842
- const dir = path10.replace(/[\\/][^\\/]+$/, "");
11930
+ const dir = path11.replace(/[\\/][^\\/]+$/, "");
11843
11931
  await fs16.mkdir(dir, { recursive: true });
11844
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
11932
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
11845
11933
  try {
11846
11934
  await fs16.writeFile(temporary, content, "utf8");
11847
- await fs16.rename(temporary, path10);
11935
+ await fs16.rename(temporary, path11);
11848
11936
  } catch {
11849
11937
  await fs16.rm(temporary, { force: true }).catch(() => void 0);
11850
- throw new Error(`Failed to write personality anchor at ${path10}`);
11938
+ throw new Error(`Failed to write personality anchor at ${path11}`);
11851
11939
  }
11852
11940
  }, "writeFile");
11853
11941
  emptyAnchor = /* @__PURE__ */ __name(() => {
@@ -12056,6 +12144,7 @@ var init_repository = __esm({
12056
12144
  var init_rule_checker = __esm({
12057
12145
  "core/knowledge/rule-checker.ts"() {
12058
12146
  init_state();
12147
+ init_sanitizer();
12059
12148
  }
12060
12149
  });
12061
12150
 
@@ -12146,12 +12235,12 @@ var init_user_language = __esm({
12146
12235
  resolveLanguagePreferencePath = /* @__PURE__ */ __name(() => {
12147
12236
  return resolveUserLanguagePath();
12148
12237
  }, "resolveLanguagePreferencePath");
12149
- readJsonFile = /* @__PURE__ */ __name((path10) => {
12238
+ readJsonFile = /* @__PURE__ */ __name((path11) => {
12150
12239
  const fs16 = getSyncFs();
12151
12240
  if (!fs16) return null;
12152
12241
  let raw;
12153
12242
  try {
12154
- raw = decodeText(fs16.readFileSync(path10), { source: path10 });
12243
+ raw = decodeText(fs16.readFileSync(path11), { source: path11 });
12155
12244
  } catch {
12156
12245
  return null;
12157
12246
  }
@@ -12248,14 +12337,14 @@ var init_user_language = __esm({
12248
12337
  }, "getResponseLanguage");
12249
12338
  setUserLanguage = /* @__PURE__ */ __name(async (language2) => {
12250
12339
  const fsMod = await import('fs/promises');
12251
- const path10 = resolveUserLanguagePath();
12252
- const dir = parentStoragePath(path10);
12340
+ const path11 = resolveUserLanguagePath();
12341
+ const dir = parentStoragePath(path11);
12253
12342
  await fsMod.mkdir(dir, { recursive: true });
12254
12343
  const payload = { format: "dotmem.language", version: 1, language: String(language2).trim() };
12255
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
12344
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
12256
12345
  await fsMod.writeFile(temporary, `${JSON.stringify(payload, null, 2)}
12257
12346
  `, "utf8");
12258
- await fsMod.rename(temporary, path10);
12347
+ await fsMod.rename(temporary, path11);
12259
12348
  return payload.language;
12260
12349
  }, "setUserLanguage");
12261
12350
  saveUserLanguage = /* @__PURE__ */ __name(async (language2) => {
@@ -12309,117 +12398,757 @@ var init_session_metrics = __esm({
12309
12398
  }
12310
12399
  });
12311
12400
 
12312
- // core/knowledge/loading-policy.ts
12313
- var init_loading_policy = __esm({
12314
- "core/knowledge/loading-policy.ts"() {
12315
- }
12316
- });
12317
-
12318
- // core/knowledge/index.ts
12319
- var init_knowledge = __esm({
12320
- "core/knowledge/index.ts"() {
12321
- init_acquisition_boundary();
12322
- init_acquisition_limits();
12323
- init_applicability();
12324
- init_behavioral_invariants();
12325
- init_bootstrap();
12326
- init_built_in_context();
12327
- init_built_in_context_rules();
12328
- init_canonical_hash();
12329
- init_canonical_reconstruction();
12330
- init_canonical_schema();
12331
- init_context_budget();
12332
- init_contract();
12333
- init_correction();
12334
- init_currentness();
12401
+ // core/knowledge/hard-rules-registry.ts
12402
+ 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;
12403
+ var init_hard_rules_registry = __esm({
12404
+ "core/knowledge/hard-rules-registry.ts"() {
12335
12405
  init_detection_events();
12336
- init_detection_journal();
12337
- init_discover();
12338
- init_solvers();
12339
- init_signatures();
12340
- init_probe();
12341
- init_semantic_provider();
12342
- init_effective_contract();
12343
- init_exemplars();
12344
- init_explain();
12345
- init_feedback();
12346
- init_fingerprint();
12347
- init_identity_governance();
12348
- init_identity_resolution();
12349
- init_incidents();
12350
- init_inspect_report();
12351
- init_language_detect();
12352
- init_loops();
12353
- init_mem_package();
12354
- init_personality_anchor();
12355
12406
  init_policy();
12356
12407
  init_policy_namespace_lock();
12357
- init_policy_store();
12358
- init_project();
12359
- init_project_anchor();
12360
- init_read_only();
12361
- init_renderer();
12362
- init_repository();
12363
- init_rule_checker();
12364
- init_rules_loader();
12365
- init_runtime();
12366
- init_scope_eligibility();
12367
- init_select();
12368
- init_session();
12369
- init_staging();
12370
- init_state();
12371
- init_storage_location();
12372
- init_storage_settings();
12373
- init_tool_guard();
12374
- init_user_identity();
12375
- init_user_language();
12376
12408
  init_user_paths();
12377
- init_vault();
12378
- init_verification();
12379
- init_verify();
12380
- init_violations();
12381
- init_claim_identity();
12382
- init_store_registry();
12383
- init_migration_audit();
12384
- init_session_metrics();
12385
- init_loading_policy();
12386
- init_session_metrics();
12387
- init_session_metrics();
12388
- init_session_metrics();
12389
- }
12390
- });
12391
-
12392
- // core/logic/helpers.ts
12393
- var normalizeClaimIds2, revisionFromAcquire;
12394
- var init_helpers = __esm({
12395
- "core/logic/helpers.ts"() {
12396
- normalizeClaimIds2 = /* @__PURE__ */ __name((value) => {
12397
- if (!value) return [];
12398
- return Array.isArray(value) ? value : [value];
12399
- }, "normalizeClaimIds");
12400
- revisionFromAcquire = /* @__PURE__ */ __name((opts) => {
12401
- const refines = normalizeClaimIds2(opts.refines);
12402
- const supersedes = normalizeClaimIds2(opts.supersedes);
12403
- const retracts = normalizeClaimIds2(opts.retracts);
12404
- if ([refines, supersedes, retracts].filter((ids) => ids.length > 0).length > 1) {
12405
- throw new Error("Acquired knowledge can refine, supersede, or retract prior knowledge, not more than one");
12409
+ HARD_RULES_REGISTRY_FORMAT = "dotmem.hard-rules";
12410
+ HARD_RULES_REGISTRY_VERSION = 1;
12411
+ HARD_RULES_REGISTRY_AUDIT_RETENTION = 200;
12412
+ HARD_RULES_REGISTRY_FILE_NAME = "hard-rules.registry.json";
12413
+ HardRulesRegistryError = class extends Error {
12414
+ static {
12415
+ __name(this, "HardRulesRegistryError");
12406
12416
  }
12407
- if (refines.length > 0) return { kind: "refines", claimIds: refines, ...opts.reason ? { reason: opts.reason } : {} };
12408
- if (supersedes.length > 0) return { kind: "supersedes", claimIds: supersedes, ...opts.reason ? { reason: opts.reason } : {} };
12409
- if (retracts.length > 0) return { kind: "retracts", claimIds: retracts, ...opts.reason ? { reason: opts.reason } : {} };
12410
- return void 0;
12411
- }, "revisionFromAcquire");
12417
+ constructor(message) {
12418
+ super(message);
12419
+ this.name = "HardRulesRegistryError";
12420
+ }
12421
+ };
12422
+ requiredText3 = /* @__PURE__ */ __name((v) => typeof v === "string" && v.trim().length > 0, "requiredText");
12423
+ nowIso = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
12424
+ joinPath7 = /* @__PURE__ */ __name((base, child) => {
12425
+ const sep = process.platform === "win32" ? "\\" : "/";
12426
+ return `${base.replace(/[\\/]+/g, sep)}${sep}${child}`;
12427
+ }, "joinPath");
12428
+ resolveRegistryDir = /* @__PURE__ */ __name((directory) => directory ?? joinPath7(resolveUserDotMemPath(), "policy"), "resolveRegistryDir");
12429
+ resolveRegistryFilePath = /* @__PURE__ */ __name((directory) => joinPath7(resolveRegistryDir(directory), HARD_RULES_REGISTRY_FILE_NAME), "resolveRegistryFilePath");
12430
+ validateHardRuleAuthority = /* @__PURE__ */ __name((value) => {
12431
+ try {
12432
+ return validatePolicyAuthority(value);
12433
+ } catch (err3) {
12434
+ void detectAuthorityEscalationAttempt({ claimed: "invalid hard-rule authority", channel: "hard-rules" }).catch(() => void 0);
12435
+ throw err3 instanceof HardRulesRegistryError ? err3 : new HardRulesRegistryError(err3.message);
12436
+ }
12437
+ }, "validateHardRuleAuthority");
12438
+ canonicalFingerprint = /* @__PURE__ */ __name((rule) => {
12439
+ const payload = {
12440
+ id: rule.id,
12441
+ version: rule.version,
12442
+ ruleClass: rule.ruleClass,
12443
+ status: rule.status,
12444
+ scope: rule.scope,
12445
+ statement: rule.statement,
12446
+ applicability: rule.applicability ?? null,
12447
+ authority: rule.authority
12448
+ };
12449
+ return `hr.${rule.id}@v${rule.version}.${Buffer.from(JSON.stringify(payload)).toString("base64").slice(0, 16)}`;
12450
+ }, "canonicalFingerprint");
12451
+ validateRule = /* @__PURE__ */ __name((value) => {
12452
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new HardRulesRegistryError("Hard rule must be an object");
12453
+ const r = value;
12454
+ if (!requiredText3(r.id)) throw new HardRulesRegistryError("id is required");
12455
+ if (typeof r.version !== "number" || !Number.isInteger(r.version) || r.version < 1) throw new HardRulesRegistryError("version must be a positive integer");
12456
+ if (typeof r.revision !== "number" || !Number.isInteger(r.revision) || r.revision < 0) throw new HardRulesRegistryError("revision must be a non-negative integer");
12457
+ if (typeof r.ruleClass !== "string" || !["IMMUTABLE", "OWNER_CONTROLLED", "USER_OVERRIDEABLE", "SESSION"].includes(r.ruleClass)) throw new HardRulesRegistryError("invalid ruleClass");
12458
+ if (typeof r.status !== "string" || !["proposed", "under_review", "approved", "active", "suspended", "retired", "rejected"].includes(r.status)) throw new HardRulesRegistryError("invalid status");
12459
+ if (!requiredText3(r.scope)) throw new HardRulesRegistryError("scope is required");
12460
+ if (!requiredText3(r.statement)) throw new HardRulesRegistryError("statement is required");
12461
+ if (!requiredText3(r.grantedAt)) throw new HardRulesRegistryError("grantedAt is required");
12462
+ if (!requiredText3(r.createdAt)) throw new HardRulesRegistryError("createdAt is required");
12463
+ const authority = validateHardRuleAuthority(r.authority);
12464
+ const validated = {
12465
+ id: r.id,
12466
+ version: r.version,
12467
+ revision: r.revision,
12468
+ ruleClass: r.ruleClass,
12469
+ status: r.status,
12470
+ scope: r.scope,
12471
+ statement: r.statement,
12472
+ ...r.applicability && typeof r.applicability === "object" ? { applicability: r.applicability } : {},
12473
+ authority,
12474
+ grantedAt: r.grantedAt,
12475
+ createdAt: r.createdAt,
12476
+ ...requiredText3(r.updatedAt) ? { updatedAt: r.updatedAt } : {},
12477
+ fingerprint: ""
12478
+ };
12479
+ const fp = canonicalFingerprint(validated);
12480
+ if (requiredText3(r.fingerprint) && r.fingerprint !== fp) {
12481
+ throw new HardRulesRegistryError(`Hard rule fingerprint mismatch for ${validated.id}`);
12482
+ }
12483
+ validated.fingerprint = fp;
12484
+ if (requiredText3(r.provenance) === false && r.provenance !== void 0) ;
12485
+ if (r.provenance && typeof r.provenance === "object") validated.provenance = r.provenance;
12486
+ if (requiredText3(r.auditRef)) validated.auditRef = r.auditRef;
12487
+ return validated;
12488
+ }, "validateRule");
12489
+ validateDocument2 = /* @__PURE__ */ __name((value) => {
12490
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new HardRulesRegistryError("document must be an object");
12491
+ const d = value;
12492
+ if (d.format !== HARD_RULES_REGISTRY_FORMAT) throw new HardRulesRegistryError("invalid format");
12493
+ if (d.version !== HARD_RULES_REGISTRY_VERSION) throw new HardRulesRegistryError("invalid version");
12494
+ if (typeof d.revision !== "number" || !Number.isInteger(d.revision) || d.revision < 0) throw new HardRulesRegistryError("invalid revision");
12495
+ if (!Array.isArray(d.rules)) throw new HardRulesRegistryError("rules must be an array");
12496
+ if (!Array.isArray(d.audit)) throw new HardRulesRegistryError("audit must be an array");
12497
+ const ids = /* @__PURE__ */ new Set();
12498
+ const rules = d.rules.map(validateRule);
12499
+ for (const rule of rules) {
12500
+ if (ids.has(rule.id + "@" + rule.version)) throw new HardRulesRegistryError(`Duplicate hard rule ${rule.id} v${rule.version}`);
12501
+ ids.add(rule.id + "@" + rule.version);
12502
+ }
12503
+ const audit2 = d.audit.map((e) => {
12504
+ if (!e || typeof e !== "object" || Array.isArray(e)) throw new HardRulesRegistryError("audit entry must be an object");
12505
+ const r = e;
12506
+ if (!requiredText3(r.id)) throw new HardRulesRegistryError("audit id required");
12507
+ if (!requiredText3(r.action)) throw new HardRulesRegistryError("audit action required");
12508
+ if (!requiredText3(r.at)) throw new HardRulesRegistryError("audit at required");
12509
+ if (r.outcome !== "applied" && r.outcome !== "rejected") throw new HardRulesRegistryError("audit outcome invalid");
12510
+ return r;
12511
+ });
12512
+ return { format: HARD_RULES_REGISTRY_FORMAT, version: HARD_RULES_REGISTRY_VERSION, revision: d.revision, rules, audit: audit2 };
12513
+ }, "validateDocument");
12514
+ emptyDocument2 = /* @__PURE__ */ __name(() => ({
12515
+ format: HARD_RULES_REGISTRY_FORMAT,
12516
+ version: HARD_RULES_REGISTRY_VERSION,
12517
+ revision: 0,
12518
+ rules: [],
12519
+ audit: []
12520
+ }), "emptyDocument");
12521
+ boundedAudit2 = /* @__PURE__ */ __name((entries2) => {
12522
+ if (entries2.length <= HARD_RULES_REGISTRY_AUDIT_RETENTION) return [...entries2];
12523
+ const kept = [];
12524
+ let budget = HARD_RULES_REGISTRY_AUDIT_RETENTION;
12525
+ for (let i3 = entries2.length - 1; i3 >= 0; i3--) {
12526
+ const e = entries2[i3];
12527
+ if (e.mandatory === true || budget > 0) {
12528
+ kept.unshift(e);
12529
+ if (e.mandatory !== true) budget--;
12530
+ }
12531
+ }
12532
+ return kept;
12533
+ }, "boundedAudit");
12534
+ buildAudit = /* @__PURE__ */ __name((entry) => ({
12535
+ id: entry.id ?? `hr-audit.${entry.action}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}`,
12536
+ action: entry.action,
12537
+ at: entry.at,
12538
+ ...entry.actorPrincipal !== void 0 ? { actorPrincipal: entry.actorPrincipal } : {},
12539
+ ...entry.targetRuleId !== void 0 ? { targetRuleId: entry.targetRuleId } : {},
12540
+ ...entry.targetVersion !== void 0 ? { targetVersion: entry.targetVersion } : {},
12541
+ ...entry.scope !== void 0 ? { scope: entry.scope } : {},
12542
+ outcome: entry.outcome,
12543
+ ...entry.reason !== void 0 ? { reason: entry.reason } : {},
12544
+ ...entry.detail !== void 0 ? { detail: entry.detail } : {},
12545
+ ...entry.mandatory !== void 0 ? { mandatory: entry.mandatory } : {}
12546
+ }), "buildAudit");
12547
+ HardRulesRegistry = class {
12548
+ constructor(directory) {
12549
+ this.directory = directory;
12550
+ }
12551
+ directory;
12552
+ static {
12553
+ __name(this, "HardRulesRegistry");
12554
+ }
12555
+ dir() {
12556
+ return resolveRegistryDir(this.directory);
12557
+ }
12558
+ filePath() {
12559
+ return resolveRegistryFilePath(this.directory);
12560
+ }
12561
+ async load() {
12562
+ const fs16 = await import('fs/promises');
12563
+ try {
12564
+ const raw = await fs16.readFile(this.filePath(), "utf8");
12565
+ return validateDocument2(JSON.parse(raw));
12566
+ } catch (err3) {
12567
+ if (err3.code === "ENOENT") return emptyDocument2();
12568
+ throw err3;
12569
+ }
12570
+ }
12571
+ async readDoc(fs16) {
12572
+ try {
12573
+ const raw = await fs16.readFile(this.filePath(), "utf8");
12574
+ return validateDocument2(JSON.parse(raw));
12575
+ } catch (err3) {
12576
+ if (err3.code === "ENOENT") return emptyDocument2();
12577
+ throw err3;
12578
+ }
12579
+ }
12580
+ async writeDoc(fs16, doc) {
12581
+ await fs16.mkdir(this.dir(), { recursive: true });
12582
+ const fp = this.filePath();
12583
+ const tmp = `${fp}.${process.pid}.${Date.now().toString(36)}.tmp`;
12584
+ try {
12585
+ await fs16.writeFile(tmp, `${JSON.stringify(doc, null, 2)}
12586
+ `, "utf8");
12587
+ const handle = await fs16.open(tmp, "r+");
12588
+ try {
12589
+ await handle.sync();
12590
+ } finally {
12591
+ await handle.close();
12592
+ }
12593
+ await fs16.rename(tmp, fp);
12594
+ } catch (err3) {
12595
+ await fs16.rm(tmp, { force: true }).catch(() => void 0);
12596
+ throw err3;
12597
+ }
12598
+ }
12599
+ async mutate(operation, options = {}) {
12600
+ const directory = this.dir();
12601
+ return withPolicyNamespaceLock(
12602
+ async (session3) => {
12603
+ const fs16 = await import('fs/promises');
12604
+ const doc = await this.readDoc(fs16);
12605
+ if (options.basedOnRevision !== void 0 && options.basedOnRevision !== doc.revision) {
12606
+ throw new HardRulesRegistryError(`Stale hard-rules revision: expected ${options.basedOnRevision}, current ${doc.revision}`);
12607
+ }
12608
+ const outcome = operation(doc);
12609
+ let next = outcome.document;
12610
+ validateDocument2(next);
12611
+ await session3.assertOwnership();
12612
+ await this.writeDoc(fs16, next);
12613
+ return outcome.result;
12614
+ },
12615
+ { directory }
12616
+ );
12617
+ }
12618
+ async listRules() {
12619
+ const doc = await this.load();
12620
+ return [...doc.rules].sort((a, b) => a.id.localeCompare(b.id) || a.version - b.version);
12621
+ }
12622
+ async activeRules(scope) {
12623
+ const doc = await this.load();
12624
+ return doc.rules.filter((r) => r.status === "active" && (!scope || r.scope === "*" || r.scope === scope || scope.startsWith(r.scope.endsWith("/") ? r.scope : r.scope + "/")));
12625
+ }
12626
+ async failClosedResolve(scope) {
12627
+ const actives = await this.activeRules(scope);
12628
+ if (actives.length === 0) return { outcome: "none", rule: null, reason: "no applicable hard rule" };
12629
+ if (actives.length > 1) return { outcome: "conflicting", rule: null, reason: "conflicting active hard rules" };
12630
+ const r = actives[0];
12631
+ if (r.ruleClass === "IMMUTABLE" || r.ruleClass === "OWNER_CONTROLLED") {
12632
+ if (r.authority.kind !== "HI" && r.authority.kind !== "operator") {
12633
+ return { outcome: "unresolved-authority", rule: null, reason: "unresolved authority" };
12634
+ }
12635
+ }
12636
+ return { outcome: "applicable", rule: r, reason: "applicable" };
12637
+ }
12638
+ async assign(input, basedOnRevision) {
12639
+ const authority = validateHardRuleAuthority(input.authority);
12640
+ if (!requiredText3(input.scope)) throw new HardRulesRegistryError("scope is required");
12641
+ if (!requiredText3(input.statement)) throw new HardRulesRegistryError("statement is required");
12642
+ if (!["IMMUTABLE", "OWNER_CONTROLLED", "USER_OVERRIDEABLE", "SESSION"].includes(input.ruleClass)) throw new HardRulesRegistryError("invalid ruleClass");
12643
+ const doc0 = await this.load();
12644
+ const ruleId = input.id ?? `hr.${Date.now()}.${Math.random().toString(36).slice(2, 8)}`;
12645
+ const existing = doc0.rules.filter((r) => r.id === ruleId);
12646
+ const version = input.version ?? (existing.length > 0 ? Math.max(...existing.map((r) => r.version)) + 1 : 1);
12647
+ const priorActive = existing.find((r) => r.status === "active" && r.ruleClass === "IMMUTABLE");
12648
+ if (priorActive && input.ruleClass !== "IMMUTABLE") {
12649
+ throw new HardRulesRegistryError("cannot weaken immutable rule");
12650
+ }
12651
+ if (priorActive && authority.kind !== "HI") {
12652
+ throw new HardRulesRegistryError("immutable rule requires HI authority to amend");
12653
+ }
12654
+ const createdAt = nowIso();
12655
+ const grantedAt = input.grantedAt ?? createdAt;
12656
+ const rule = {
12657
+ id: ruleId,
12658
+ version,
12659
+ revision: 0,
12660
+ ruleClass: input.ruleClass,
12661
+ status: "proposed",
12662
+ scope: input.scope,
12663
+ statement: input.statement,
12664
+ ...input.applicability ? { applicability: input.applicability } : {},
12665
+ authority,
12666
+ grantedAt,
12667
+ createdAt,
12668
+ fingerprint: ""
12669
+ };
12670
+ rule.fingerprint = canonicalFingerprint({ ...rule, fingerprint: "" });
12671
+ return this.mutate(
12672
+ (doc) => {
12673
+ const revision = doc.revision + 1;
12674
+ const stored = { ...rule, revision, fingerprint: canonicalFingerprint({ ...rule, revision, fingerprint: "" }) };
12675
+ const rules = doc.rules.map((r) => {
12676
+ if (r.id === stored.id && r.version !== stored.version && r.status === "active") {
12677
+ return { ...r, status: "retired", updatedAt: nowIso() };
12678
+ }
12679
+ return r;
12680
+ });
12681
+ rules.push(stored);
12682
+ const audit2 = boundedAudit2([
12683
+ ...doc.audit,
12684
+ buildAudit({
12685
+ action: "rule.assigned",
12686
+ at: stored.grantedAt,
12687
+ actorPrincipal: authority.kind,
12688
+ targetRuleId: stored.id,
12689
+ targetVersion: stored.version,
12690
+ scope: stored.scope,
12691
+ outcome: "applied",
12692
+ detail: `hard rule ${stored.id} v${stored.version} assigned (${stored.ruleClass})`,
12693
+ mandatory: true
12694
+ })
12695
+ ]);
12696
+ return { document: { ...doc, revision, rules, audit: audit2 }, result: stored };
12697
+ },
12698
+ { basedOnRevision }
12699
+ );
12700
+ }
12701
+ async activate(input, basedOnRevision) {
12702
+ const doc0 = await this.load();
12703
+ const rule = doc0.rules.find((r) => r.id === input.id && r.version === input.version);
12704
+ if (!rule) throw new HardRulesRegistryError("rule not found");
12705
+ if (rule.status !== "approved" && rule.status !== "proposed") ;
12706
+ const authority = input.authority ? validateHardRuleAuthority(input.authority) : rule.authority;
12707
+ if ((rule.ruleClass === "IMMUTABLE" || rule.ruleClass === "OWNER_CONTROLLED") && authority.kind !== "HI" && authority.kind !== "operator") {
12708
+ throw new HardRulesRegistryError("activation requires HI or operator authority");
12709
+ }
12710
+ const actives = doc0.rules.filter((r) => r.status === "active" && r.scope === rule.scope && r.id !== rule.id);
12711
+ if (actives.length > 0 && (rule.ruleClass === "IMMUTABLE" || rule.ruleClass === "OWNER_CONTROLLED")) {
12712
+ throw new HardRulesRegistryError("conflicting active mandatory rules");
12713
+ }
12714
+ return this.mutate(
12715
+ (doc) => {
12716
+ const idx = doc.rules.findIndex((r) => r.id === input.id && r.version === input.version);
12717
+ if (idx < 0) throw new HardRulesRegistryError("rule not found");
12718
+ const current = doc.rules[idx];
12719
+ const rules = doc.rules.map((r) => {
12720
+ if (r.id === current.id && r.version !== current.version && r.status === "active") {
12721
+ return { ...r, status: "retired", updatedAt: nowIso() };
12722
+ }
12723
+ return r;
12724
+ });
12725
+ const now3 = nowIso();
12726
+ rules[idx >= rules.length ? rules.length - 1 : idx] = { ...current, status: "active", updatedAt: now3 };
12727
+ const targetIndex = rules.findIndex((r) => r.id === current.id && r.version === current.version);
12728
+ if (targetIndex >= 0) rules[targetIndex] = { ...current, status: "active", updatedAt: now3 };
12729
+ const updated = rules.find((r) => r.id === current.id && r.version === current.version);
12730
+ const revision = doc.revision + 1;
12731
+ const audit2 = boundedAudit2([
12732
+ ...doc.audit,
12733
+ buildAudit({
12734
+ action: "rule.activated",
12735
+ at: now3,
12736
+ actorPrincipal: input.actorPrincipal ?? authority.kind,
12737
+ targetRuleId: updated.id,
12738
+ targetVersion: updated.version,
12739
+ scope: updated.scope,
12740
+ outcome: "applied",
12741
+ mandatory: true
12742
+ })
12743
+ ]);
12744
+ return { document: { ...doc, revision, rules, audit: audit2 }, result: updated };
12745
+ },
12746
+ { basedOnRevision }
12747
+ );
12748
+ }
12749
+ async remove(id, authority, basedOnRevision) {
12750
+ const auth = validateHardRuleAuthority(authority);
12751
+ const doc0 = await this.load();
12752
+ const rule = doc0.rules.find((r) => r.id === id && r.status === "active");
12753
+ if (rule) {
12754
+ if (rule.ruleClass === "IMMUTABLE") throw new HardRulesRegistryError("cannot remove immutable rule");
12755
+ if (rule.ruleClass === "OWNER_CONTROLLED" && auth.kind !== "HI" && auth.kind !== "operator") throw new HardRulesRegistryError("unauthenticated cannot remove owner-controlled rule");
12756
+ }
12757
+ await this.mutate(
12758
+ (doc) => {
12759
+ const rules = doc.rules.filter((r) => r.id !== id);
12760
+ if (rules.length === doc.rules.length) return { document: doc, result: void 0 };
12761
+ const revision = doc.revision + 1;
12762
+ const audit2 = boundedAudit2([
12763
+ ...doc.audit,
12764
+ buildAudit({
12765
+ action: "rule.removed",
12766
+ at: nowIso(),
12767
+ actorPrincipal: auth.kind,
12768
+ targetRuleId: id,
12769
+ scope: rule?.scope,
12770
+ outcome: "applied",
12771
+ mandatory: true
12772
+ })
12773
+ ]);
12774
+ return { document: { ...doc, revision, rules, audit: audit2 }, result: void 0 };
12775
+ },
12776
+ { basedOnRevision }
12777
+ );
12778
+ }
12779
+ async auditTrail() {
12780
+ const doc = await this.load();
12781
+ return [...doc.audit];
12782
+ }
12783
+ async revision() {
12784
+ const doc = await this.load();
12785
+ return doc.revision;
12786
+ }
12787
+ };
12412
12788
  }
12413
12789
  });
12414
12790
 
12415
- // core/logic/index.ts
12416
- var logic_exports = {};
12417
- __export(logic_exports, {
12418
- LogicEngine: () => LogicEngine,
12419
- default: () => logic_default,
12420
- getLogicRuntime: () => getLogicRuntime,
12421
- logic: () => logic
12422
- });
12791
+ // core/context-compiler/index.ts
12792
+ var CHARS_PER_TOKEN, estimateTokens, DEFAULT_BUDGETS, dedupe, ContextCompiler, compileContext;
12793
+ var init_context_compiler = __esm({
12794
+ "core/context-compiler/index.ts"() {
12795
+ CHARS_PER_TOKEN = 4;
12796
+ estimateTokens = /* @__PURE__ */ __name((text) => Math.ceil((text || "").length / CHARS_PER_TOKEN), "estimateTokens");
12797
+ DEFAULT_BUDGETS = {
12798
+ identity: 0.1,
12799
+ rules: 0.15,
12800
+ conversationalState: 0.3,
12801
+ retrievedKnowledge: 0.45
12802
+ };
12803
+ dedupe = /* @__PURE__ */ __name((items) => {
12804
+ const seen = /* @__PURE__ */ new Set();
12805
+ const result = [];
12806
+ for (const item of items) {
12807
+ const key = item.trim().toLowerCase();
12808
+ if (seen.has(key)) continue;
12809
+ seen.add(key);
12810
+ result.push(item);
12811
+ }
12812
+ return result;
12813
+ }, "dedupe");
12814
+ ContextCompiler = class {
12815
+ static {
12816
+ __name(this, "ContextCompiler");
12817
+ }
12818
+ compile(input) {
12819
+ const totalBudget = input.tokenBudget ?? 4096;
12820
+ const totalChars = totalBudget * CHARS_PER_TOKEN;
12821
+ const budgets = {
12822
+ identity: Math.floor(totalChars * (input.categoryBudgets?.identity ?? DEFAULT_BUDGETS.identity)),
12823
+ rules: Math.floor(totalChars * (input.categoryBudgets?.rules ?? DEFAULT_BUDGETS.rules)),
12824
+ conversationalState: Math.floor(totalChars * (input.categoryBudgets?.conversationalState ?? DEFAULT_BUDGETS.conversationalState)),
12825
+ retrievedKnowledge: Math.floor(totalChars * (input.categoryBudgets?.retrievedKnowledge ?? DEFAULT_BUDGETS.retrievedKnowledge))
12826
+ };
12827
+ const omissions = [];
12828
+ const identityText = (input.identity ?? "").trim();
12829
+ let identityUsed = 0;
12830
+ const mandatoryParts = [];
12831
+ if (identityText) {
12832
+ if (identityText.length <= budgets.identity) {
12833
+ mandatoryParts.push(identityText);
12834
+ identityUsed = identityText.length;
12835
+ } else {
12836
+ omissions.push({
12837
+ category: "identity",
12838
+ whatWasOmitted: identityText,
12839
+ whyOmitted: "token budget exceeded",
12840
+ wouldBreakContinuity: true
12841
+ });
12842
+ }
12843
+ }
12844
+ const rules = input.rules ?? [];
12845
+ const activeRules = [];
12846
+ let rulesUsed = 0;
12847
+ for (const rule of rules) {
12848
+ if (rulesUsed + rule.length <= budgets.rules) {
12849
+ activeRules.push(rule);
12850
+ rulesUsed += rule.length;
12851
+ } else {
12852
+ omissions.push({
12853
+ category: "rules",
12854
+ whatWasOmitted: rule,
12855
+ whyOmitted: "token budget exceeded",
12856
+ wouldBreakContinuity: false
12857
+ });
12858
+ }
12859
+ }
12860
+ const state3 = input.conversationalState ?? null;
12861
+ const mandatoryStateParts = [];
12862
+ if (state3) {
12863
+ if (state3.objective) mandatoryStateParts.push(`Objective: ${state3.objective}`);
12864
+ if (state3.currentWorkingPosition) mandatoryStateParts.push(`Working position: ${state3.currentWorkingPosition}`);
12865
+ if (state3.openLoops.length > 0) {
12866
+ mandatoryStateParts.push(`Open loops: ${state3.openLoops.map((l) => l.description).join("; ")}`);
12867
+ }
12868
+ if (state3.rejectedApproaches.length > 0) {
12869
+ mandatoryStateParts.push(`Rejected approaches: ${state3.rejectedApproaches.map((r) => `${r.approach} (${r.reason})`).join("; ")}`);
12870
+ }
12871
+ }
12872
+ const activeParts = [];
12873
+ if (state3) {
12874
+ if (state3.currentProblem) activeParts.push(`Current problem: ${state3.currentProblem}`);
12875
+ if (state3.establishedUnderstanding) activeParts.push(`Established understanding: ${state3.establishedUnderstanding}`);
12876
+ if (state3.decisionsMade.length > 0) {
12877
+ activeParts.push(`Decisions: ${state3.decisionsMade.map((d) => `${d.decision} (rationale: ${d.rationale})`).join("; ")}`);
12878
+ }
12879
+ if (state3.pendingDecisions.length > 0) {
12880
+ activeParts.push(`Pending decisions: ${state3.pendingDecisions.map((d) => `${d.decision} [${d.options.join(", ")}]`).join("; ")}`);
12881
+ }
12882
+ if (state3.unresolvedQuestions.length > 0) {
12883
+ activeParts.push(`Unresolved questions: ${state3.unresolvedQuestions.map((q) => q.question).join("; ")}`);
12884
+ }
12885
+ if (state3.reasoningTrajectory.length > 0) {
12886
+ activeParts.push(`Reasoning trajectory: ${state3.reasoningTrajectory.map((r) => r.conclusion).join(" -> ")}`);
12887
+ }
12888
+ if (state3.nextConversationalStep) {
12889
+ activeParts.push(`Next step: ${state3.nextConversationalStep}`);
12890
+ }
12891
+ if (state3.lastCompletedAction) {
12892
+ activeParts.push(`Last completed action: ${state3.lastCompletedAction}`);
12893
+ }
12894
+ }
12895
+ const dedupedActive = dedupe(activeParts.filter((part) => !mandatoryStateParts.includes(part)));
12896
+ let stateUsed = 0;
12897
+ const admittedMandatoryState = [];
12898
+ const admittedActive = [];
12899
+ for (const part of mandatoryStateParts) {
12900
+ if (stateUsed + part.length <= budgets.conversationalState) {
12901
+ admittedMandatoryState.push(part);
12902
+ stateUsed += part.length;
12903
+ } else {
12904
+ omissions.push({
12905
+ category: "conversationalState",
12906
+ whatWasOmitted: part,
12907
+ whyOmitted: "token budget exceeded",
12908
+ wouldBreakContinuity: true
12909
+ });
12910
+ }
12911
+ }
12912
+ for (const part of dedupedActive) {
12913
+ if (stateUsed + part.length <= budgets.conversationalState) {
12914
+ admittedActive.push(part);
12915
+ stateUsed += part.length;
12916
+ } else {
12917
+ omissions.push({
12918
+ category: "conversationalState",
12919
+ whatWasOmitted: part,
12920
+ whyOmitted: "token budget exceeded",
12921
+ wouldBreakContinuity: false
12922
+ });
12923
+ }
12924
+ }
12925
+ const refs = [...input.knowledgeReferences ?? []].sort((a, b) => b.relevance - a.relevance);
12926
+ const retrievedParts = [];
12927
+ let retrievedUsed = 0;
12928
+ for (const ref of refs) {
12929
+ const text2 = ref.summary ? `${ref.kind}:${ref.identifier} - ${ref.summary}` : `${ref.kind}:${ref.identifier}`;
12930
+ if (retrievedUsed + text2.length <= budgets.retrievedKnowledge) {
12931
+ retrievedParts.push(text2);
12932
+ retrievedUsed += text2.length;
12933
+ } else {
12934
+ omissions.push({
12935
+ category: "retrievedKnowledge",
12936
+ whatWasOmitted: text2,
12937
+ whyOmitted: "token budget exceeded",
12938
+ wouldBreakContinuity: false
12939
+ });
12940
+ }
12941
+ }
12942
+ const optionalParts = [];
12943
+ let optionalUsed = 0;
12944
+ const remainingBudget = totalChars - (identityUsed + rulesUsed + stateUsed + retrievedUsed);
12945
+ for (const item of input.historicalContext ?? []) {
12946
+ if (optionalUsed + item.length <= remainingBudget) {
12947
+ optionalParts.push(item);
12948
+ optionalUsed += item.length;
12949
+ } else {
12950
+ omissions.push({
12951
+ category: "historical",
12952
+ whatWasOmitted: item,
12953
+ whyOmitted: "token budget exceeded",
12954
+ wouldBreakContinuity: false
12955
+ });
12956
+ }
12957
+ }
12958
+ const admittedSet = new Set([...mandatoryParts, ...admittedMandatoryState, ...admittedActive].map((s) => s.trim().toLowerCase()));
12959
+ const isDuplicate = /* @__PURE__ */ __name((item) => {
12960
+ const normalized = item.trim().toLowerCase();
12961
+ for (const existing of admittedSet) {
12962
+ if (existing.includes(normalized) || normalized.includes(existing)) return true;
12963
+ }
12964
+ return false;
12965
+ }, "isDuplicate");
12966
+ const finalRetrieved = dedupe(retrievedParts.filter((p) => !isDuplicate(p)));
12967
+ const finalOptional = dedupe(optionalParts.filter((p) => !isDuplicate(p) && !finalRetrieved.includes(p)));
12968
+ const mandatory = [...mandatoryParts, ...admittedMandatoryState].join("\n");
12969
+ const active = [...admittedActive];
12970
+ const retrieved = finalRetrieved;
12971
+ const optional = finalOptional;
12972
+ const text = [mandatory ? `## MANDATORY
12973
+ ${mandatory}` : "", active.length ? `## ACTIVE
12974
+ ${active.join("\n")}` : "", retrieved.length ? `## RETRIEVED
12975
+ ${retrieved.join("\n")}` : "", optional.length ? `## OPTIONAL
12976
+ ${optional.join("\n")}` : "", rules.length ? `## RULES
12977
+ ${activeRules.join("\n")}` : ""].filter(Boolean).join("\n\n");
12978
+ const budgetUsed = estimateTokens(text);
12979
+ return {
12980
+ mandatory,
12981
+ active,
12982
+ retrieved,
12983
+ optional,
12984
+ omissions,
12985
+ budgetUsed,
12986
+ budgetAvailable: totalBudget,
12987
+ text
12988
+ };
12989
+ }
12990
+ };
12991
+ compileContext = /* @__PURE__ */ __name((input) => {
12992
+ const compiler = new ContextCompiler();
12993
+ return compiler.compile(input);
12994
+ }, "compileContext");
12995
+ }
12996
+ });
12997
+
12998
+ // core/knowledge/rule-enforcement.ts
12999
+ var resolveApplicableRules;
13000
+ var init_rule_enforcement = __esm({
13001
+ "core/knowledge/rule-enforcement.ts"() {
13002
+ init_rules_loader();
13003
+ init_violations();
13004
+ init_hard_rules_registry();
13005
+ init_memory();
13006
+ init_context_compiler();
13007
+ resolveApplicableRules = /* @__PURE__ */ __name(async (situation, scope) => {
13008
+ const state3 = await loadCombinedKnowledgeState();
13009
+ const rules = [];
13010
+ const seen = /* @__PURE__ */ new Set();
13011
+ const ironReport = loadIronRules(state3);
13012
+ for (const rule of ironReport.rules) {
13013
+ if (seen.has(rule.id)) continue;
13014
+ seen.add(rule.id);
13015
+ const claim = state3.claims.find((c) => c.id === rule.id);
13016
+ rules.push({
13017
+ id: rule.id,
13018
+ text: rule.text,
13019
+ tier: "context",
13020
+ source: "iron",
13021
+ appliesWhen: rule.appliesWhen || void 0,
13022
+ hasCheck: !!claim?.check
13023
+ });
13024
+ }
13025
+ try {
13026
+ const registry = new HardRulesRegistry();
13027
+ const active = scope ? await registry.activeRules(scope) : await registry.activeRules();
13028
+ for (const rule of active) {
13029
+ if (seen.has(rule.id)) continue;
13030
+ seen.add(rule.id);
13031
+ rules.push({
13032
+ id: rule.id,
13033
+ text: rule.statement,
13034
+ tier: rule.ruleClass === "IMMUTABLE" || rule.ruleClass === "OWNER_CONTROLLED" ? "hard-precondition" : "precondition",
13035
+ source: "hard",
13036
+ appliesWhen: rule.scope,
13037
+ hasCheck: false
13038
+ });
13039
+ }
13040
+ } catch {
13041
+ }
13042
+ return rules;
13043
+ }, "resolveApplicableRules");
13044
+ }
13045
+ });
13046
+
13047
+ // core/knowledge/index.ts
13048
+ var init_knowledge = __esm({
13049
+ "core/knowledge/index.ts"() {
13050
+ init_acquisition_boundary();
13051
+ init_acquisition_limits();
13052
+ init_applicability();
13053
+ init_behavioral_invariants();
13054
+ init_bootstrap();
13055
+ init_built_in_context();
13056
+ init_built_in_context_rules();
13057
+ init_canonical_hash();
13058
+ init_canonical_reconstruction();
13059
+ init_canonical_schema();
13060
+ init_context_budget();
13061
+ init_contract();
13062
+ init_correction();
13063
+ init_currentness();
13064
+ init_detection_events();
13065
+ init_detection_journal();
13066
+ init_discover();
13067
+ init_solvers();
13068
+ init_signatures();
13069
+ init_probe();
13070
+ init_semantic_provider();
13071
+ init_effective_contract();
13072
+ init_exemplars();
13073
+ init_explain();
13074
+ init_feedback();
13075
+ init_fingerprint();
13076
+ init_identity_governance();
13077
+ init_identity_resolution();
13078
+ init_incidents();
13079
+ init_inspect_report();
13080
+ init_language_detect();
13081
+ init_loops();
13082
+ init_mem_package();
13083
+ init_personality_anchor();
13084
+ init_policy();
13085
+ init_policy_namespace_lock();
13086
+ init_policy_store();
13087
+ init_project();
13088
+ init_project_anchor();
13089
+ init_read_only();
13090
+ init_renderer();
13091
+ init_repository();
13092
+ init_rule_checker();
13093
+ init_rules_loader();
13094
+ init_runtime();
13095
+ init_scope_eligibility();
13096
+ init_select();
13097
+ init_session();
13098
+ init_staging();
13099
+ init_state();
13100
+ init_storage_location();
13101
+ init_storage_settings();
13102
+ init_tool_guard();
13103
+ init_user_identity();
13104
+ init_user_language();
13105
+ init_user_paths();
13106
+ init_vault();
13107
+ init_verification();
13108
+ init_verify();
13109
+ init_violations();
13110
+ init_claim_identity();
13111
+ init_store_registry();
13112
+ init_migration_audit();
13113
+ init_session_metrics();
13114
+ init_session_metrics();
13115
+ init_session_metrics();
13116
+ init_session_metrics();
13117
+ init_rule_enforcement();
13118
+ }
13119
+ });
13120
+
13121
+ // core/logic/helpers.ts
13122
+ var normalizeClaimIds2, revisionFromAcquire;
13123
+ var init_helpers = __esm({
13124
+ "core/logic/helpers.ts"() {
13125
+ normalizeClaimIds2 = /* @__PURE__ */ __name((value) => {
13126
+ if (!value) return [];
13127
+ return Array.isArray(value) ? value : [value];
13128
+ }, "normalizeClaimIds");
13129
+ revisionFromAcquire = /* @__PURE__ */ __name((opts) => {
13130
+ const refines = normalizeClaimIds2(opts.refines);
13131
+ const supersedes = normalizeClaimIds2(opts.supersedes);
13132
+ const retracts = normalizeClaimIds2(opts.retracts);
13133
+ if ([refines, supersedes, retracts].filter((ids) => ids.length > 0).length > 1) {
13134
+ throw new Error("Acquired knowledge can refine, supersede, or retract prior knowledge, not more than one");
13135
+ }
13136
+ if (refines.length > 0) return { kind: "refines", claimIds: refines, ...opts.reason ? { reason: opts.reason } : {} };
13137
+ if (supersedes.length > 0) return { kind: "supersedes", claimIds: supersedes, ...opts.reason ? { reason: opts.reason } : {} };
13138
+ if (retracts.length > 0) return { kind: "retracts", claimIds: retracts, ...opts.reason ? { reason: opts.reason } : {} };
13139
+ return void 0;
13140
+ }, "revisionFromAcquire");
13141
+ }
13142
+ });
13143
+
13144
+ // core/logic/index.ts
13145
+ var logic_exports = {};
13146
+ __export(logic_exports, {
13147
+ LogicEngine: () => LogicEngine,
13148
+ default: () => logic_default,
13149
+ getLogicRuntime: () => getLogicRuntime,
13150
+ logic: () => logic
13151
+ });
12423
13152
  var LOGIC_MEM_FILE, nodeCwd2, cachedRuntime, resetLogicRuntime, getLogicRuntime, LogicEngine, _inferConfidence, logic, logic_default;
12424
13153
  var init_logic = __esm({
12425
13154
  "core/logic/index.ts"() {
@@ -12718,21 +13447,6 @@ __export(encryption_exports, {
12718
13447
  decryptPayload: () => decryptPayload,
12719
13448
  encryptPayload: () => encryptPayload
12720
13449
  });
12721
- function getHybridKeys() {
12722
- const dir = `${resolveUserDotMemPath()}/keys`;
12723
- try {
12724
- fs.mkdirSync(dir, { recursive: true });
12725
- } catch {
12726
- }
12727
- try {
12728
- const raw = JSON.parse(fs.readFileSync(hybridKeyFile(), "utf8"));
12729
- return { publicKey: Buffer.from(raw.publicKey, "hex"), secretKey: Buffer.from(raw.secretKey, "hex") };
12730
- } catch {
12731
- }
12732
- const keys = ml_kem768_x25519.keygen();
12733
- fs.writeFileSync(hybridKeyFile(), JSON.stringify({ publicKey: Buffer.from(keys.publicKey).toString("hex"), secretKey: Buffer.from(keys.secretKey).toString("hex") }), { mode: 384 });
12734
- return { publicKey: keys.publicKey, secretKey: keys.secretKey };
12735
- }
12736
13450
  function encryptPayload(plaintext) {
12737
13451
  const keys = getHybridKeys();
12738
13452
  const { sharedSecret, cipherText: kemCt } = ml_kem768_x25519.encapsulate(keys.publicKey);
@@ -12748,7 +13462,7 @@ function decryptPayload(envelope) {
12748
13462
  try {
12749
13463
  if (!envelope.startsWith("{")) {
12750
13464
  const keyFile = `${resolveUserDotMemPath()}/keys/local.key`;
12751
- const hex = fs.readFileSync(keyFile, "utf8").trim();
13465
+ const hex = fs6.readFileSync(keyFile, "utf8").trim();
12752
13466
  const key2 = Buffer.from(hex, "hex");
12753
13467
  const [ivB64, tagB64, ctB64] = envelope.split(":");
12754
13468
  const iv2 = Buffer.from(ivB64, "base64");
@@ -12775,12 +13489,26 @@ function decryptPayload(envelope) {
12775
13489
  return null;
12776
13490
  }
12777
13491
  }
12778
- var hybridKeyFile;
13492
+ var hybridKeyFile, getHybridKeys;
12779
13493
  var init_encryption = __esm({
12780
13494
  "core/knowledge/encryption.ts"() {
12781
13495
  init_user_paths();
12782
13496
  hybridKeyFile = /* @__PURE__ */ __name(() => `${resolveUserDotMemPath()}/keys/hybrid.key`, "hybridKeyFile");
12783
- __name(getHybridKeys, "getHybridKeys");
13497
+ getHybridKeys = /* @__PURE__ */ __name(() => {
13498
+ const dir = `${resolveUserDotMemPath()}/keys`;
13499
+ try {
13500
+ fs6.mkdirSync(dir, { recursive: true });
13501
+ } catch {
13502
+ }
13503
+ try {
13504
+ const raw = JSON.parse(fs6.readFileSync(hybridKeyFile(), "utf8"));
13505
+ return { publicKey: Buffer.from(raw.publicKey, "hex"), secretKey: Buffer.from(raw.secretKey, "hex") };
13506
+ } catch {
13507
+ }
13508
+ const keys = ml_kem768_x25519.keygen();
13509
+ fs6.writeFileSync(hybridKeyFile(), JSON.stringify({ publicKey: Buffer.from(keys.publicKey).toString("hex"), secretKey: Buffer.from(keys.secretKey).toString("hex") }), { mode: 384 });
13510
+ return { publicKey: keys.publicKey, secretKey: keys.secretKey };
13511
+ }, "getHybridKeys");
12784
13512
  __name(encryptPayload, "encryptPayload");
12785
13513
  __name(decryptPayload, "decryptPayload");
12786
13514
  }
@@ -12831,13 +13559,13 @@ var init_brain = __esm({
12831
13559
  }, "brainSave");
12832
13560
  cachedBrainPath = null;
12833
13561
  getBrainDocument = /* @__PURE__ */ __name(async () => {
12834
- const path10 = getBrainPath();
12835
- cachedBrainPath = path10;
12836
- return brainLoad(path10);
13562
+ const path11 = getBrainPath();
13563
+ cachedBrainPath = path11;
13564
+ return brainLoad(path11);
12837
13565
  }, "getBrainDocument");
12838
13566
  saveBrainDocument = /* @__PURE__ */ __name(async (document) => {
12839
- const path10 = cachedBrainPath || getBrainPath();
12840
- await brainSave(path10, document);
13567
+ const path11 = cachedBrainPath || getBrainPath();
13568
+ await brainSave(path11, document);
12841
13569
  }, "saveBrainDocument");
12842
13570
  resetBrainPathCache = /* @__PURE__ */ __name(() => {
12843
13571
  cachedBrainPath = null;
@@ -14382,7 +15110,7 @@ ${content}`);
14382
15110
  for (const file2 of files) {
14383
15111
  if (!file2.endsWith(".arch.mem")) continue;
14384
15112
  try {
14385
- const bytes = await fs14.readFile(path8.join(dir, file2));
15113
+ const bytes = await fs14.readFile(path5.join(dir, file2));
14386
15114
  const { metadata } = readZip(bytes);
14387
15115
  entries2.push(metadata);
14388
15116
  } catch {
@@ -14644,7 +15372,7 @@ var init_acquire = __esm({
14644
15372
  const { findClaimLocations: findClaimLocations2 } = await Promise.resolve().then(() => (init_claim_identity(), claim_identity_exports));
14645
15373
  const locations = await findClaimLocations2(targetId);
14646
15374
  if (locations.length === 0) {
14647
- throw new Error(`Claim ${claimId} references unknown prior claim ${targetId}. Searched all stores.`);
15375
+ throw new Error(`Claim ${claimId} references any prior claim ${targetId}. Searched all stores.`);
14648
15376
  }
14649
15377
  if (locations.length > 1) {
14650
15378
  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(", "));
@@ -15039,11 +15767,11 @@ var init_durable_store = __esm({
15039
15767
  writeFile: writeFile4,
15040
15768
  rename,
15041
15769
  copyFile,
15042
- rm: /* @__PURE__ */ __name((path10, opts) => rm(path10, opts), "rm"),
15770
+ rm: /* @__PURE__ */ __name((path11, opts) => rm(path11, opts), "rm"),
15043
15771
  mkdir,
15044
- open: /* @__PURE__ */ __name(async (path10, flags) => {
15772
+ open: /* @__PURE__ */ __name(async (path11, flags) => {
15045
15773
  if (!Deno.open) throw new Error("Deno.open is unavailable");
15046
- const file2 = await Deno.open(path10, flags);
15774
+ const file2 = await Deno.open(path11, flags);
15047
15775
  return {
15048
15776
  writeFile: /* @__PURE__ */ __name(async (data) => {
15049
15777
  const written = await file2.write(data);
@@ -15358,9 +16086,9 @@ var init_entries = __esm({
15358
16086
  };
15359
16087
  return recencyScore * confidenceScore * accessScore * typeBoost[entry.type] * scopeBoost[entry.scope];
15360
16088
  }, "computeRelevance");
15361
- getNestedPath = /* @__PURE__ */ __name((obj, path10) => {
15362
- if (!path10 || typeof path10 !== "string") return void 0;
15363
- const parts = path10.replace(/^state\./, "").split(".");
16089
+ getNestedPath = /* @__PURE__ */ __name((obj, path11) => {
16090
+ if (!path11 || typeof path11 !== "string") return void 0;
16091
+ const parts = path11.replace(/^state\./, "").split(".");
15364
16092
  let current = obj;
15365
16093
  for (const part of parts) {
15366
16094
  if (current === null || current === void 0) return void 0;
@@ -15368,9 +16096,9 @@ var init_entries = __esm({
15368
16096
  }
15369
16097
  return current;
15370
16098
  }, "getNestedPath");
15371
- setNestedPath = /* @__PURE__ */ __name((obj, path10, value) => {
15372
- if (!path10 || typeof path10 !== "string") return;
15373
- const parts = path10.replace(/^state\./, "").split(".");
16099
+ setNestedPath = /* @__PURE__ */ __name((obj, path11, value) => {
16100
+ if (!path11 || typeof path11 !== "string") return;
16101
+ const parts = path11.replace(/^state\./, "").split(".");
15374
16102
  let current = obj;
15375
16103
  for (let i3 = 0; i3 < parts.length - 1; i3++) {
15376
16104
  const part = parts[i3];
@@ -15381,9 +16109,9 @@ var init_entries = __esm({
15381
16109
  }
15382
16110
  current[parts[parts.length - 1]] = value;
15383
16111
  }, "setNestedPath");
15384
- deleteNestedPath = /* @__PURE__ */ __name((obj, path10) => {
15385
- if (!path10 || typeof path10 !== "string") return;
15386
- const parts = path10.replace(/^state\./, "").split(".");
16112
+ deleteNestedPath = /* @__PURE__ */ __name((obj, path11) => {
16113
+ if (!path11 || typeof path11 !== "string") return;
16114
+ const parts = path11.replace(/^state\./, "").split(".");
15387
16115
  let current = obj;
15388
16116
  for (let i3 = 0; i3 < parts.length - 1; i3++) {
15389
16117
  const part = parts[i3];
@@ -15857,14 +16585,14 @@ var init_store2 = __esm({
15857
16585
  const fs16 = getSyncFs();
15858
16586
  if (!fs16) return;
15859
16587
  const validated = validateConversationalState(state3);
15860
- const path10 = resolveConversationalStatePath(validated.scope, validated.subject, validated.conversationId, tenantId);
16588
+ const path11 = resolveConversationalStatePath(validated.scope, validated.subject, validated.conversationId, tenantId);
15861
16589
  const fsPromises = await import('fs/promises');
15862
16590
  await fsPromises.mkdir(resolveConversationalStateDir(tenantId), { recursive: true });
15863
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
16591
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
15864
16592
  try {
15865
16593
  await fsPromises.writeFile(temporary, `${JSON.stringify(validated, null, 2)}
15866
16594
  `, "utf8");
15867
- await fsPromises.rename(temporary, path10);
16595
+ await fsPromises.rename(temporary, path11);
15868
16596
  } catch (error) {
15869
16597
  await fsPromises.rm(temporary, { force: true }).catch(() => void 0);
15870
16598
  throw error;
@@ -16012,7 +16740,7 @@ var init_conversational_state = __esm({
16012
16740
  });
16013
16741
 
16014
16742
  // core/memory/capture-persistence.ts
16015
- var CAPTURE_STORE_KEY, CAPTURE_KEY_PREFIX, sessionRecordKey, nowIso, CapturePersistence, defaultPersistence, getCapturePersistence;
16743
+ var CAPTURE_STORE_KEY, CAPTURE_KEY_PREFIX, sessionRecordKey, nowIso2, CapturePersistence, defaultPersistence, getCapturePersistence;
16016
16744
  var init_capture_persistence = __esm({
16017
16745
  "core/memory/capture-persistence.ts"() {
16018
16746
  init_durable_store();
@@ -16020,7 +16748,7 @@ var init_capture_persistence = __esm({
16020
16748
  CAPTURE_STORE_KEY = "capture-items";
16021
16749
  CAPTURE_KEY_PREFIX = "capture:";
16022
16750
  sessionRecordKey = /* @__PURE__ */ __name((conversationId) => `${CAPTURE_KEY_PREFIX}${conversationId}`, "sessionRecordKey");
16023
- nowIso = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
16751
+ nowIso2 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
16024
16752
  CapturePersistence = class {
16025
16753
  static {
16026
16754
  __name(this, "CapturePersistence");
@@ -16035,7 +16763,7 @@ var init_capture_persistence = __esm({
16035
16763
  conversationId,
16036
16764
  items,
16037
16765
  explicitInstructions,
16038
- updatedAt: nowIso()
16766
+ updatedAt: nowIso2()
16039
16767
  };
16040
16768
  await this.store.set({
16041
16769
  id: sessionRecordKey(conversationId),
@@ -16095,7 +16823,7 @@ var init_capture_persistence = __esm({
16095
16823
  }, "getCapturePersistence");
16096
16824
  }
16097
16825
  });
16098
- 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;
16826
+ 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;
16099
16827
  var init_capture_engine = __esm({
16100
16828
  "core/memory/capture-engine.ts"() {
16101
16829
  init_exemplars();
@@ -16131,7 +16859,7 @@ var init_capture_engine = __esm({
16131
16859
  generateId = /* @__PURE__ */ __name(() => {
16132
16860
  return `capture-${hlc.serialize(hlc.tick())}-${Math.random().toString(36).slice(2, 10)}`;
16133
16861
  }, "generateId");
16134
- nowIso2 = /* @__PURE__ */ __name(() => {
16862
+ nowIso3 = /* @__PURE__ */ __name(() => {
16135
16863
  return (/* @__PURE__ */ new Date()).toISOString();
16136
16864
  }, "nowIso");
16137
16865
  normalizeText = /* @__PURE__ */ __name((text) => {
@@ -16164,7 +16892,7 @@ var init_capture_engine = __esm({
16164
16892
  type: "remember",
16165
16893
  content: text,
16166
16894
  source,
16167
- timestamp: nowIso2()
16895
+ timestamp: nowIso3()
16168
16896
  });
16169
16897
  break;
16170
16898
  }
@@ -16175,7 +16903,7 @@ var init_capture_engine = __esm({
16175
16903
  type: "do-not-remember",
16176
16904
  content: text,
16177
16905
  source,
16178
- timestamp: nowIso2()
16906
+ timestamp: nowIso3()
16179
16907
  });
16180
16908
  break;
16181
16909
  }
@@ -16528,7 +17256,7 @@ var init_capture_engine = __esm({
16528
17256
  const source = {
16529
17257
  conversationId: options.conversationId,
16530
17258
  messageIds: options.messageIds ?? [],
16531
- timestamp: nowIso2(),
17259
+ timestamp: nowIso3(),
16532
17260
  turnIndex: 0
16533
17261
  };
16534
17262
  const instructions = detectExplicitInstructions(text, source);
@@ -16548,7 +17276,7 @@ var init_capture_engine = __esm({
16548
17276
  classification: "temporary_context",
16549
17277
  confidence: "low",
16550
17278
  epistemicType: "observed",
16551
- capturedAt: nowIso2(),
17279
+ capturedAt: nowIso3(),
16552
17280
  method: "automatic"
16553
17281
  },
16554
17282
  confidence: "low",
@@ -16568,7 +17296,7 @@ var init_capture_engine = __esm({
16568
17296
  classification: category,
16569
17297
  confidence,
16570
17298
  epistemicType,
16571
- capturedAt: nowIso2(),
17299
+ capturedAt: nowIso3(),
16572
17300
  method: hasExplicitRemember ? "explicit" : "automatic"
16573
17301
  };
16574
17302
  const item = {
@@ -16630,7 +17358,7 @@ var init_capture_engine = __esm({
16630
17358
  const source = {
16631
17359
  conversationId: options.conversationId,
16632
17360
  messageIds: [msg.id ?? `msg-${index}`],
16633
- timestamp: msg.timestamp ?? nowIso2(),
17361
+ timestamp: msg.timestamp ?? nowIso3(),
16634
17362
  turnIndex: index
16635
17363
  };
16636
17364
  const instructions = detectExplicitInstructions(msg.content, source);
@@ -16650,7 +17378,7 @@ var init_capture_engine = __esm({
16650
17378
  classification: "temporary_context",
16651
17379
  confidence: "low",
16652
17380
  epistemicType: "observed",
16653
- capturedAt: nowIso2(),
17381
+ capturedAt: nowIso3(),
16654
17382
  method: "automatic"
16655
17383
  },
16656
17384
  confidence: "low",
@@ -16670,7 +17398,7 @@ var init_capture_engine = __esm({
16670
17398
  classification: category,
16671
17399
  confidence,
16672
17400
  epistemicType,
16673
- capturedAt: nowIso2(),
17401
+ capturedAt: nowIso3(),
16674
17402
  method: hasExplicitRemember ? "explicit" : "automatic"
16675
17403
  };
16676
17404
  const item = {
@@ -16827,7 +17555,7 @@ var init_capture_engine = __esm({
16827
17555
  if (this.clearedConversations.has(conversationId)) {
16828
17556
  ctx = {
16829
17557
  conversationId,
16830
- startedAt: nowIso2(),
17558
+ startedAt: nowIso3(),
16831
17559
  items: [],
16832
17560
  explicitInstructions: []
16833
17561
  };
@@ -16847,7 +17575,7 @@ var init_capture_engine = __esm({
16847
17575
  }
16848
17576
  ctx = {
16849
17577
  conversationId,
16850
- startedAt: nowIso2(),
17578
+ startedAt: nowIso3(),
16851
17579
  items: [],
16852
17580
  explicitInstructions: []
16853
17581
  };
@@ -17019,7 +17747,7 @@ var init_note = __esm({
17019
17747
  init_storage_coordinator();
17020
17748
  init_claim_identity();
17021
17749
  TOMBSTONE_FILE = "deleted-notes.tombstones.json";
17022
- tombstonePath = /* @__PURE__ */ __name(() => path8.join(resolveUserDotMemPath(), TOMBSTONE_FILE), "tombstonePath");
17750
+ tombstonePath = /* @__PURE__ */ __name(() => path5.join(resolveUserDotMemPath(), TOMBSTONE_FILE), "tombstonePath");
17023
17751
  loadNoteTombstones = /* @__PURE__ */ __name(async () => {
17024
17752
  try {
17025
17753
  const raw = await fs14.readFile(tombstonePath(), "utf8");
@@ -17035,7 +17763,7 @@ var init_note = __esm({
17035
17763
  if (!existing.some((t) => t.id === id)) {
17036
17764
  existing.push({ id, deletedAt: (/* @__PURE__ */ new Date()).toISOString() });
17037
17765
  }
17038
- await fs14.mkdir(path8.dirname(tombstonePath()), { recursive: true });
17766
+ await fs14.mkdir(path5.dirname(tombstonePath()), { recursive: true });
17039
17767
  await fs14.writeFile(tombstonePath(), JSON.stringify({ deletedNotes: existing }, null, 2), "utf8");
17040
17768
  const g2 = globalThis.__dotmemDeletedNotes || /* @__PURE__ */ new Set();
17041
17769
  g2.add(id);
@@ -17062,7 +17790,7 @@ var init_note = __esm({
17062
17790
  if (referencing.length === 0) continue;
17063
17791
  const newClaims = artifact.state.claims.filter((claim) => !(claim.revision?.claimIds ?? []).includes(noteId));
17064
17792
  const newState = { version: artifact.state.version + 1, claims: newClaims };
17065
- await withStorageLock(path8.dirname(filePath), async () => {
17793
+ await withStorageLock(path5.dirname(filePath), async () => {
17066
17794
  const currentBytes = await fs14.readFile(filePath);
17067
17795
  const currentArtifact = await decodeMemArtifact(currentBytes);
17068
17796
  if (!currentArtifact.state || currentArtifact.state.version !== artifact.state.version) {
@@ -17070,7 +17798,7 @@ var init_note = __esm({
17070
17798
  }
17071
17799
  const tmp = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
17072
17800
  try {
17073
- await fs14.mkdir(path8.dirname(filePath), { recursive: true });
17801
+ await fs14.mkdir(path5.dirname(filePath), { recursive: true });
17074
17802
  const { quarantineClaimRecord: quarantineClaimRecord2 } = await Promise.resolve().then(() => (init_quarantine(), quarantine_exports));
17075
17803
  for (const claim of referencing) {
17076
17804
  await quarantineClaimRecord2({
@@ -17203,7 +17931,7 @@ var init_note = __esm({
17203
17931
  return { deleted: 0, byStore: {}, allDeleted: finalOccurrences2.length === 0, remaining: finalOccurrences2 };
17204
17932
  }
17205
17933
  for (const [filePath, occs] of byFile) {
17206
- const storeId = occs[0]?.store ?? "unknown";
17934
+ const storeId = occs[0]?.store ?? "any";
17207
17935
  try {
17208
17936
  const bytes = await fs14.readFile(filePath);
17209
17937
  const artifact = await decodeMemArtifact(bytes);
@@ -17219,7 +17947,7 @@ var init_note = __esm({
17219
17947
  }
17220
17948
  const newClaims = artifact.state.claims.filter((c) => !(c.id === id && c.kind === "note"));
17221
17949
  const newState = { version: artifact.state.version + 1, claims: newClaims };
17222
- await withStorageLock(path8.dirname(filePath), async () => {
17950
+ await withStorageLock(path5.dirname(filePath), async () => {
17223
17951
  const currentBytes = await fs14.readFile(filePath);
17224
17952
  const currentArtifact = await decodeMemArtifact(currentBytes);
17225
17953
  if (!currentArtifact.state || currentArtifact.state.version !== artifact.state.version) {
@@ -17227,7 +17955,7 @@ var init_note = __esm({
17227
17955
  }
17228
17956
  const tmp = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
17229
17957
  try {
17230
- await fs14.mkdir(path8.dirname(filePath), { recursive: true });
17958
+ await fs14.mkdir(path5.dirname(filePath), { recursive: true });
17231
17959
  const encoded = await encodeMemPackage(newState, currentArtifact.preserved, currentArtifact.package);
17232
17960
  await fs14.writeFile(tmp, encoded);
17233
17961
  await decodeMemArtifact(await fs14.readFile(tmp));
@@ -17321,9 +18049,9 @@ var init_note = __esm({
17321
18049
  };
17322
18050
  }, "noteDeleteAll");
17323
18051
  try {
17324
- const tp = path8.join(resolveUserDotMemPath(), TOMBSTONE_FILE);
17325
- if (fs.existsSync(tp)) {
17326
- const raw = fs.readFileSync(tp, "utf8");
18052
+ const tp = path5.join(resolveUserDotMemPath(), TOMBSTONE_FILE);
18053
+ if (fs6.existsSync(tp)) {
18054
+ const raw = fs6.readFileSync(tp, "utf8");
17327
18055
  const parsed = JSON.parse(raw);
17328
18056
  const arr = Array.isArray(parsed) ? parsed : parsed.deletedNotes ?? [];
17329
18057
  const g2 = globalThis.__dotmemDeletedNotes || /* @__PURE__ */ new Set();
@@ -17656,8 +18384,8 @@ var init_ontology = __esm({
17656
18384
  errors.push("relation must be object");
17657
18385
  continue;
17658
18386
  }
17659
- if (!ids.has(r.from)) errors.push(`relation.from unknown: ${r.from}`);
17660
- if (!ids.has(r.to)) errors.push(`relation.to unknown: ${r.to}`);
18387
+ if (!ids.has(r.from)) errors.push(`relation.from any: ${r.from}`);
18388
+ if (!ids.has(r.to)) errors.push(`relation.to any: ${r.to}`);
17661
18389
  if (!RELATION_TYPES.includes(r.type)) errors.push(`relation.type invalid: ${r.type}`);
17662
18390
  }
17663
18391
  return { valid: errors.length === 0, errors };
@@ -17674,7 +18402,7 @@ var init_ontology = __esm({
17674
18402
  ),
17675
18403
  byPos: graph.concepts.reduce(
17676
18404
  (acc, c) => {
17677
- const k = c.pos || "unknown";
18405
+ const k = c.pos || "any";
17678
18406
  acc[k] = (acc[k] || 0) + 1;
17679
18407
  return acc;
17680
18408
  },
@@ -17734,7 +18462,7 @@ var init_anthology = __esm({
17734
18462
  errors.push("provenance must be an object");
17735
18463
  return { valid: false, errors };
17736
18464
  }
17737
- const kinds = ["user-statement", "system-observation", "imported-document", "external-source", "agent-inference", "model-summary", "human-correction", "system-event", "unknown"];
18465
+ const kinds = ["user-statement", "system-observation", "imported-document", "external-source", "agent-inference", "model-summary", "human-correction", "system-event", "any"];
17738
18466
  if (!kinds.includes(p.kind)) errors.push("invalid provenance kind");
17739
18467
  if (p.observedAt !== void 0 && (typeof p.observedAt !== "string" || isNaN(Date.parse(p.observedAt)))) {
17740
18468
  errors.push("observedAt must be valid ISO timestamp if provided");
@@ -17788,681 +18516,908 @@ var init_anthology = __esm({
17788
18516
  schemaVersion: 0,
17789
18517
  category: "legacy",
17790
18518
  payload: item,
17791
- scope: item?.scope ?? "unknown",
17792
- provenance: { kind: "unknown" },
18519
+ scope: item?.scope ?? "any",
18520
+ provenance: { kind: "any" },
17793
18521
  epistemicStatus: "unassessed",
17794
- sensitivity: "unknown",
18522
+ sensitivity: "any",
17795
18523
  temporal: { recordedAt: item?.createdAt ? new Date(item.createdAt).toISOString() : (/* @__PURE__ */ new Date(0)).toISOString() },
17796
18524
  revision: { revision: 0 }
17797
18525
  };
17798
18526
  }, "normalizeLegacyRecord");
17799
- MEMORY_CATEGORIES = ["observation", "claim", "fact-candidate", "hypothesis", "decision", "preference", "instruction", "experience", "goal", "relationship", "derived-summary", "unknown-disputed", "legacy"];
18527
+ MEMORY_CATEGORIES = ["observation", "claim", "fact-candidate", "hypothesis", "decision", "preference", "instruction", "experience", "goal", "relationship", "derived-summary", "any-disputed", "legacy"];
17800
18528
  EPISTEMIC_STATUSES = ["unassessed", "asserted", "corroborated", "reviewed", "disputed", "refuted", "superseded"];
17801
18529
  }
17802
18530
  });
17803
- function stripCode(content) {
17804
- let out = "";
17805
- let i3 = 0;
17806
- const n = content.length;
17807
- while (i3 < n) {
17808
- const c = content[i3];
17809
- const next = content[i3 + 1];
17810
- if (c === "/" && next === "/") {
17811
- const nl = content.indexOf("\n", i3);
17812
- if (nl === -1) break;
17813
- out += "\n";
17814
- i3 = nl + 1;
17815
- continue;
17816
- }
17817
- if (c === "/" && next === "*") {
17818
- const end = content.indexOf("*/", i3 + 2);
17819
- if (end === -1) break;
17820
- const seg = content.slice(i3, end + 2);
17821
- out += seg.replace(/[^\n]/g, " ");
17822
- i3 = end + 2;
17823
- continue;
18531
+ function audit(options = {}) {
18532
+ const projectPath = options.projectPath ?? process.cwd();
18533
+ const allFindings = scanDir(projectPath, projectPath);
18534
+ allFindings.push(...runNpmAudit(projectPath));
18535
+ const quality = allFindings.filter((f) => f.category === "quality");
18536
+ const security2 = allFindings.filter((f) => f.category === "security");
18537
+ const performance = allFindings.filter((f) => f.category === "performance");
18538
+ const errorCount = allFindings.filter((f) => f.severity === "critical" || f.severity === "high").length;
18539
+ const totalFindings = allFindings.length;
18540
+ const score = Math.max(0, 100 - errorCount * 10 - (totalFindings - errorCount) * 2);
18541
+ const grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : score >= 60 ? "D" : "F";
18542
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
18543
+ const result = {
18544
+ projectPath,
18545
+ timestamp,
18546
+ quality,
18547
+ security: security2,
18548
+ performance,
18549
+ score,
18550
+ grade,
18551
+ summary: `Audit complete: ${totalFindings} findings (${errorCount} critical/high). Score: ${score}/100 (Grade: ${grade}).`,
18552
+ report: ""
18553
+ };
18554
+ result.report = generateReport({ quality, security: security2, performance, score, grade, projectPath, timestamp });
18555
+ if (options.onFinding) {
18556
+ for (const f of allFindings) {
18557
+ options.onFinding(f);
17824
18558
  }
17825
- if (c === '"' || c === "'" || c === "`") {
17826
- const quote = c;
17827
- let j = i3 + 1;
17828
- while (j < n) {
17829
- if (content[j] === "\\") {
17830
- j += 2;
18559
+ }
18560
+ return {
18561
+ name: "audit",
18562
+ version: "0.3.0",
18563
+ description: "Professional IT audit: quality, security, performance, npm vulnerabilities.",
18564
+ hooks: {
18565
+ onAudit(_result) {
18566
+ }
18567
+ },
18568
+ run: /* @__PURE__ */ __name(() => result, "run"),
18569
+ report: /* @__PURE__ */ __name(() => result.report, "report")
18570
+ };
18571
+ }
18572
+ var stripCode, hasEval, isInNonCode, collectDangerousNames, hasProcessExec, scanFile, scanDir, runNpmAudit, generateReport;
18573
+ var init_audit = __esm({
18574
+ "plugins/audit/index.ts"() {
18575
+ stripCode = /* @__PURE__ */ __name((content) => {
18576
+ let out = "";
18577
+ let i3 = 0;
18578
+ const n = content.length;
18579
+ while (i3 < n) {
18580
+ const c = content[i3];
18581
+ const next = content[i3 + 1];
18582
+ if (c === "/" && next === "/") {
18583
+ const nl = content.indexOf("\n", i3);
18584
+ if (nl === -1) break;
18585
+ out += "\n";
18586
+ i3 = nl + 1;
17831
18587
  continue;
17832
18588
  }
17833
- if (content[j] === quote) {
17834
- j++;
17835
- break;
18589
+ if (c === "/" && next === "*") {
18590
+ const end = content.indexOf("*/", i3 + 2);
18591
+ if (end === -1) break;
18592
+ const seg = content.slice(i3, end + 2);
18593
+ out += seg.replace(/[^\n]/g, " ");
18594
+ i3 = end + 2;
18595
+ continue;
18596
+ }
18597
+ if (c === '"' || c === "'" || c === "`") {
18598
+ const quote = c;
18599
+ let j = i3 + 1;
18600
+ while (j < n) {
18601
+ if (content[j] === "\\") {
18602
+ j += 2;
18603
+ continue;
18604
+ }
18605
+ if (content[j] === quote) {
18606
+ j++;
18607
+ break;
18608
+ }
18609
+ if (content[j] === "\n") break;
18610
+ j++;
18611
+ }
18612
+ const seg = content.slice(i3, j);
18613
+ out += seg.replace(/[^\n]/g, " ");
18614
+ i3 = j;
18615
+ continue;
18616
+ }
18617
+ if (c === "/") {
18618
+ let k = out.length - 1;
18619
+ while (k >= 0 && /\s/.test(out[k])) k--;
18620
+ const prev = k >= 0 ? out[k] : "";
18621
+ const regexStartChars = "(,=:[!&|?{;+-*/%^~";
18622
+ if (regexStartChars.includes(prev) || prev === "") {
18623
+ let j = i3 + 1;
18624
+ let inClass = false;
18625
+ while (j < n) {
18626
+ if (content[j] === "\\") {
18627
+ j += 2;
18628
+ continue;
18629
+ }
18630
+ if (content[j] === "[") {
18631
+ inClass = true;
18632
+ j++;
18633
+ continue;
18634
+ }
18635
+ if (content[j] === "]") {
18636
+ inClass = false;
18637
+ j++;
18638
+ continue;
18639
+ }
18640
+ if (content[j] === "/" && !inClass) {
18641
+ j++;
18642
+ break;
18643
+ }
18644
+ if (content[j] === "\n") break;
18645
+ j++;
18646
+ }
18647
+ const seg = content.slice(i3, j);
18648
+ out += seg.replace(/[^\n]/g, " ");
18649
+ i3 = j;
18650
+ continue;
18651
+ }
17836
18652
  }
17837
- if (content[j] === "\n") break;
17838
- j++;
18653
+ out += c;
18654
+ i3++;
17839
18655
  }
17840
- const seg = content.slice(i3, j);
17841
- out += seg.replace(/[^\n]/g, " ");
17842
- i3 = j;
17843
- continue;
17844
- }
17845
- if (c === "/") {
17846
- let k = out.length - 1;
17847
- while (k >= 0 && /\s/.test(out[k])) k--;
17848
- const prev = k >= 0 ? out[k] : "";
17849
- const regexStartChars = "(,=:[!&|?{;+-*/%^~";
17850
- if (regexStartChars.includes(prev) || prev === "") {
17851
- let j = i3 + 1;
17852
- let inClass = false;
17853
- while (j < n) {
17854
- if (content[j] === "\\") {
17855
- j += 2;
18656
+ return out;
18657
+ }, "stripCode");
18658
+ hasEval = /* @__PURE__ */ __name((content) => {
18659
+ const code = stripCode(content);
18660
+ if (/\b(?:globalThis|global|window|self)\s*\.\s*eval\s*\(/.test(code)) return true;
18661
+ if (/\beval\s*\(/.test(code)) return true;
18662
+ return false;
18663
+ }, "hasEval");
18664
+ isInNonCode = /* @__PURE__ */ __name((content, index) => {
18665
+ let i3 = 0;
18666
+ let inLineComment = false;
18667
+ let inBlockComment = false;
18668
+ let inString = null;
18669
+ while (i3 < index) {
18670
+ const c = content[i3];
18671
+ const next = content[i3 + 1];
18672
+ if (inLineComment) {
18673
+ if (c === "\n") inLineComment = false;
18674
+ i3++;
18675
+ continue;
18676
+ }
18677
+ if (inBlockComment) {
18678
+ if (c === "*" && next === "/") {
18679
+ inBlockComment = false;
18680
+ i3 += 2;
17856
18681
  continue;
17857
18682
  }
17858
- if (content[j] === "[") {
17859
- inClass = true;
17860
- j++;
18683
+ i3++;
18684
+ continue;
18685
+ }
18686
+ if (inString) {
18687
+ if (c === "\\") {
18688
+ i3 += 2;
17861
18689
  continue;
17862
18690
  }
17863
- if (content[j] === "]") {
17864
- inClass = false;
17865
- j++;
18691
+ if (c === inString) inString = null;
18692
+ i3++;
18693
+ continue;
18694
+ }
18695
+ if (c === "/" && next === "/") {
18696
+ inLineComment = true;
18697
+ i3 += 2;
18698
+ continue;
18699
+ }
18700
+ if (c === "/" && next === "*") {
18701
+ inBlockComment = true;
18702
+ i3 += 2;
18703
+ continue;
18704
+ }
18705
+ if (c === '"' || c === "'" || c === "`") {
18706
+ inString = c;
18707
+ i3++;
18708
+ continue;
18709
+ }
18710
+ i3++;
18711
+ }
18712
+ return inLineComment || inBlockComment || inString !== null;
18713
+ }, "isInNonCode");
18714
+ collectDangerousNames = /* @__PURE__ */ __name((content) => {
18715
+ const names = /* @__PURE__ */ new Set();
18716
+ const namespaces = /* @__PURE__ */ new Set();
18717
+ const addName = /* @__PURE__ */ __name((name, local) => {
18718
+ if (["exec", "execSync", "spawn", "spawnSync"].includes(name)) {
18719
+ names.add(local);
18720
+ }
18721
+ }, "addName");
18722
+ let m;
18723
+ const esImport = /import\s*\{([^}]+)\}\s*from\s*['"](?:node:)?child_process['"]/g;
18724
+ while ((m = esImport.exec(content)) !== null) {
18725
+ if (isInNonCode(content, m.index)) continue;
18726
+ for (const part of m[1].split(",")) {
18727
+ const p = part.trim();
18728
+ if (!p) continue;
18729
+ const alias = p.match(/^(\w+)\s+as\s+(\w+)$/);
18730
+ if (alias) addName(alias[1], alias[2]);
18731
+ else addName(p, p);
18732
+ }
18733
+ }
18734
+ const esNs = /import\s*\*\s*as\s+(\w+)\s*from\s*['"](?:node:)?child_process['"]/g;
18735
+ while ((m = esNs.exec(content)) !== null) {
18736
+ if (isInNonCode(content, m.index)) continue;
18737
+ namespaces.add(m[1]);
18738
+ }
18739
+ const cjsDestruct = /(?:const|let|var)\s*\{([^}]+)\}\s*=\s*require\(\s*['"](?:node:)?child_process['"]\s*\)/g;
18740
+ while ((m = cjsDestruct.exec(content)) !== null) {
18741
+ if (isInNonCode(content, m.index)) continue;
18742
+ for (const part of m[1].split(",")) {
18743
+ const p = part.trim();
18744
+ if (!p) continue;
18745
+ const colon = p.match(/^(\w+)\s*:\s*(\w+)$/);
18746
+ if (colon) {
18747
+ addName(colon[1], colon[2]);
17866
18748
  continue;
17867
18749
  }
17868
- if (content[j] === "/" && !inClass) {
17869
- j++;
17870
- break;
18750
+ const alias = p.match(/^(\w+)\s+as\s+(\w+)$/);
18751
+ if (alias) addName(alias[1], alias[2]);
18752
+ else addName(p, p);
18753
+ }
18754
+ }
18755
+ const cjsNs = /(?:const|let|var)\s+(\w+)\s*=\s*require\(\s*['"](?:node:)?child_process['"]\s*\)/g;
18756
+ while ((m = cjsNs.exec(content)) !== null) {
18757
+ if (isInNonCode(content, m.index)) continue;
18758
+ namespaces.add(m[1]);
18759
+ }
18760
+ const cjsProp = /(?:const|let|var)\s+(\w+)\s*=\s*require\(\s*['"](?:node:)?child_process['"]\s*\)\s*\.\s*(exec|execSync|spawn|spawnSync)\b/g;
18761
+ while ((m = cjsProp.exec(content)) !== null) {
18762
+ if (isInNonCode(content, m.index)) continue;
18763
+ names.add(m[1]);
18764
+ }
18765
+ return { names, namespaces };
18766
+ }, "collectDangerousNames");
18767
+ hasProcessExec = /* @__PURE__ */ __name((content) => {
18768
+ const code = stripCode(content);
18769
+ const { names, namespaces } = collectDangerousNames(content);
18770
+ for (const ns of namespaces) {
18771
+ const re = new RegExp("\\b" + ns + "\\s*\\.\\s*(exec|execSync|spawn|spawnSync)\\s*\\(");
18772
+ if (re.test(code)) return true;
18773
+ }
18774
+ for (const name of names) {
18775
+ const re = new RegExp("\\b" + name + "\\s*\\(");
18776
+ if (re.test(code)) return true;
18777
+ }
18778
+ if (/\b(?:child_process|childProcess)\s*\.\s*(exec|execSync|spawn|spawnSync)\s*\(/.test(code)) return true;
18779
+ if (/require\(\s*['"](?:node:)?child_process['"]\s*\)\s*\.\s*(exec|execSync|spawn|spawnSync)\s*\(/.test(code)) return true;
18780
+ return false;
18781
+ }, "hasProcessExec");
18782
+ scanFile = /* @__PURE__ */ __name((filePath, content, projectPath) => {
18783
+ const findings = [];
18784
+ const lines = content.split("\n");
18785
+ const relPath = relative(projectPath, filePath);
18786
+ const ext = extname(filePath);
18787
+ if (/password\s*=\s*['"]/i.test(content)) {
18788
+ 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)" });
18789
+ }
18790
+ if (/api[_-]?key\s*=\s*['"]/i.test(content)) {
18791
+ 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)" });
18792
+ }
18793
+ if (/secret\s*=\s*['"]/i.test(content)) {
18794
+ 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)" });
18795
+ }
18796
+ if (hasEval(content)) {
18797
+ 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)" });
18798
+ }
18799
+ if (/innerHTML\s*=/.test(content)) {
18800
+ 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)" });
18801
+ }
18802
+ if (/document\.write\s*\(/.test(content)) {
18803
+ 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" });
18804
+ }
18805
+ if (hasProcessExec(content)) {
18806
+ 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)" });
18807
+ }
18808
+ if (/cors\s*\(\s*\{\s*origin:\s*['"]\*['"]/.test(content)) {
18809
+ 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)" });
18810
+ }
18811
+ if (/debug\s*:\s*true/.test(content)) {
18812
+ 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)" });
18813
+ }
18814
+ const consoleCount = (content.match(/console\.log/g) || []).length;
18815
+ if (consoleCount > 5 && !filePath.includes("test")) {
18816
+ 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)" });
18817
+ }
18818
+ if (ext === ".c" || ext === ".cpp" || ext === ".rs") {
18819
+ if (/strcpy|strcat|sprintf|gets\s*\(/.test(content)) {
18820
+ 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)" });
18821
+ }
18822
+ }
18823
+ if (lines.length > 500) {
18824
+ 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)" });
18825
+ }
18826
+ const todoCount = (content.match(/TODO|FIXME|HACK|XXX/gi) || []).length;
18827
+ if (todoCount > 3) {
18828
+ 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" });
18829
+ }
18830
+ if (!content.includes("test") && (ext === ".ts" || ext === ".js") && !filePath.includes("test") && !filePath.includes("spec")) {
18831
+ 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" });
18832
+ }
18833
+ if (/await\s+\w+\(/.test(content) && !content.includes("try") && !content.includes("catch")) {
18834
+ 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" });
18835
+ }
18836
+ const nestedLoops = content.match(/for\s*\(.*\)\s*\{[^}]*for\s*\(/g);
18837
+ if (nestedLoops && nestedLoops.length > 0) {
18838
+ 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" });
18839
+ }
18840
+ if (/JSON\.parse\(.*JSON\.stringify/.test(content)) {
18841
+ 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" });
18842
+ }
18843
+ const syncReads = (content.match(/readFileSync/g) || []).length;
18844
+ if (syncReads > 3) {
18845
+ 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" });
18846
+ }
18847
+ return findings;
18848
+ }, "scanFile");
18849
+ scanDir = /* @__PURE__ */ __name((dir, projectPath) => {
18850
+ const allFindings = [];
18851
+ try {
18852
+ const entries2 = readdirSync(dir, { withFileTypes: true });
18853
+ for (const entry of entries2) {
18854
+ if (["node_modules", ".git", "dist", ".cache", "coverage", ".private", ".project", ".dev"].includes(entry.name)) continue;
18855
+ const fullPath = join(dir, entry.name);
18856
+ if (entry.isDirectory()) {
18857
+ allFindings.push(...scanDir(fullPath, projectPath));
18858
+ } else if (entry.isFile() && /\.(ts|js|tsx|jsx|py|go|rs|c|cpp|java)$/.test(entry.name)) {
18859
+ try {
18860
+ const content = readFileSync(fullPath, "utf-8");
18861
+ allFindings.push(...scanFile(fullPath, content, projectPath));
18862
+ } catch {
18863
+ }
17871
18864
  }
17872
- if (content[j] === "\n") break;
17873
- j++;
17874
18865
  }
17875
- const seg = content.slice(i3, j);
17876
- out += seg.replace(/[^\n]/g, " ");
17877
- i3 = j;
17878
- continue;
18866
+ } catch {
17879
18867
  }
17880
- }
17881
- out += c;
17882
- i3++;
17883
- }
17884
- return out;
17885
- }
17886
- function hasEval(content) {
17887
- const code = stripCode(content);
17888
- if (/\b(?:globalThis|global|window|self)\s*\.\s*eval\s*\(/.test(code)) return true;
17889
- if (/\beval\s*\(/.test(code)) return true;
17890
- return false;
17891
- }
17892
- function isInNonCode(content, index) {
17893
- let i3 = 0;
17894
- let inLineComment = false;
17895
- let inBlockComment = false;
17896
- let inString = null;
17897
- while (i3 < index) {
17898
- const c = content[i3];
17899
- const next = content[i3 + 1];
17900
- if (inLineComment) {
17901
- if (c === "\n") inLineComment = false;
17902
- i3++;
17903
- continue;
17904
- }
17905
- if (inBlockComment) {
17906
- if (c === "*" && next === "/") {
17907
- inBlockComment = false;
17908
- i3 += 2;
17909
- continue;
17910
- }
17911
- i3++;
17912
- continue;
17913
- }
17914
- if (inString) {
17915
- if (c === "\\") {
17916
- i3 += 2;
17917
- continue;
17918
- }
17919
- if (c === inString) inString = null;
17920
- i3++;
17921
- continue;
17922
- }
17923
- if (c === "/" && next === "/") {
17924
- inLineComment = true;
17925
- i3 += 2;
17926
- continue;
17927
- }
17928
- if (c === "/" && next === "*") {
17929
- inBlockComment = true;
17930
- i3 += 2;
17931
- continue;
17932
- }
17933
- if (c === '"' || c === "'" || c === "`") {
17934
- inString = c;
17935
- i3++;
17936
- continue;
17937
- }
17938
- i3++;
17939
- }
17940
- return inLineComment || inBlockComment || inString !== null;
17941
- }
17942
- function collectDangerousNames(content) {
17943
- const names = /* @__PURE__ */ new Set();
17944
- const namespaces = /* @__PURE__ */ new Set();
17945
- const addName = /* @__PURE__ */ __name((name, local) => {
17946
- if (["exec", "execSync", "spawn", "spawnSync"].includes(name)) {
17947
- names.add(local);
17948
- }
17949
- }, "addName");
17950
- let m;
17951
- const esImport = /import\s*\{([^}]+)\}\s*from\s*['"](?:node:)?child_process['"]/g;
17952
- while ((m = esImport.exec(content)) !== null) {
17953
- if (isInNonCode(content, m.index)) continue;
17954
- for (const part of m[1].split(",")) {
17955
- const p = part.trim();
17956
- if (!p) continue;
17957
- const alias = p.match(/^(\w+)\s+as\s+(\w+)$/);
17958
- if (alias) addName(alias[1], alias[2]);
17959
- else addName(p, p);
17960
- }
17961
- }
17962
- const esNs = /import\s*\*\s*as\s+(\w+)\s*from\s*['"](?:node:)?child_process['"]/g;
17963
- while ((m = esNs.exec(content)) !== null) {
17964
- if (isInNonCode(content, m.index)) continue;
17965
- namespaces.add(m[1]);
17966
- }
17967
- const cjsDestruct = /(?:const|let|var)\s*\{([^}]+)\}\s*=\s*require\(\s*['"](?:node:)?child_process['"]\s*\)/g;
17968
- while ((m = cjsDestruct.exec(content)) !== null) {
17969
- if (isInNonCode(content, m.index)) continue;
17970
- for (const part of m[1].split(",")) {
17971
- const p = part.trim();
17972
- if (!p) continue;
17973
- const colon = p.match(/^(\w+)\s*:\s*(\w+)$/);
17974
- if (colon) {
17975
- addName(colon[1], colon[2]);
17976
- continue;
17977
- }
17978
- const alias = p.match(/^(\w+)\s+as\s+(\w+)$/);
17979
- if (alias) addName(alias[1], alias[2]);
17980
- else addName(p, p);
17981
- }
17982
- }
17983
- const cjsNs = /(?:const|let|var)\s+(\w+)\s*=\s*require\(\s*['"](?:node:)?child_process['"]\s*\)/g;
17984
- while ((m = cjsNs.exec(content)) !== null) {
17985
- if (isInNonCode(content, m.index)) continue;
17986
- namespaces.add(m[1]);
17987
- }
17988
- const cjsProp = /(?:const|let|var)\s+(\w+)\s*=\s*require\(\s*['"](?:node:)?child_process['"]\s*\)\s*\.\s*(exec|execSync|spawn|spawnSync)\b/g;
17989
- while ((m = cjsProp.exec(content)) !== null) {
17990
- if (isInNonCode(content, m.index)) continue;
17991
- names.add(m[1]);
17992
- }
17993
- return { names, namespaces };
17994
- }
17995
- function hasProcessExec(content) {
17996
- const code = stripCode(content);
17997
- const { names, namespaces } = collectDangerousNames(content);
17998
- for (const ns of namespaces) {
17999
- const re = new RegExp("\\b" + ns + "\\s*\\.\\s*(exec|execSync|spawn|spawnSync)\\s*\\(");
18000
- if (re.test(code)) return true;
18001
- }
18002
- for (const name of names) {
18003
- const re = new RegExp("\\b" + name + "\\s*\\(");
18004
- if (re.test(code)) return true;
18005
- }
18006
- if (/\b(?:child_process|childProcess)\s*\.\s*(exec|execSync|spawn|spawnSync)\s*\(/.test(code)) return true;
18007
- if (/require\(\s*['"](?:node:)?child_process['"]\s*\)\s*\.\s*(exec|execSync|spawn|spawnSync)\s*\(/.test(code)) return true;
18008
- return false;
18009
- }
18010
- function scanFile(filePath, content, projectPath) {
18011
- const findings = [];
18012
- const lines = content.split("\n");
18013
- const relPath = relative(projectPath, filePath);
18014
- const ext = extname(filePath);
18015
- if (/password\s*=\s*['"]/i.test(content)) {
18016
- 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)" });
18017
- }
18018
- if (/api[_-]?key\s*=\s*['"]/i.test(content)) {
18019
- 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)" });
18020
- }
18021
- if (/secret\s*=\s*['"]/i.test(content)) {
18022
- 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)" });
18023
- }
18024
- if (hasEval(content)) {
18025
- 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)" });
18026
- }
18027
- if (/innerHTML\s*=/.test(content)) {
18028
- 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)" });
18029
- }
18030
- if (/document\.write\s*\(/.test(content)) {
18031
- 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" });
18032
- }
18033
- if (hasProcessExec(content)) {
18034
- 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)" });
18035
- }
18036
- if (/cors\s*\(\s*\{\s*origin:\s*['"]\*['"]/.test(content)) {
18037
- 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)" });
18038
- }
18039
- if (/debug\s*:\s*true/.test(content)) {
18040
- 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)" });
18041
- }
18042
- const consoleCount = (content.match(/console\.log/g) || []).length;
18043
- if (consoleCount > 5 && !filePath.includes("test")) {
18044
- 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)" });
18045
- }
18046
- if (ext === ".c" || ext === ".cpp" || ext === ".rs") {
18047
- if (/strcpy|strcat|sprintf|gets\s*\(/.test(content)) {
18048
- 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)" });
18049
- }
18050
- }
18051
- if (lines.length > 500) {
18052
- 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)" });
18053
- }
18054
- const todoCount = (content.match(/TODO|FIXME|HACK|XXX/gi) || []).length;
18055
- if (todoCount > 3) {
18056
- 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" });
18057
- }
18058
- if (!content.includes("test") && (ext === ".ts" || ext === ".js") && !filePath.includes("test") && !filePath.includes("spec")) {
18059
- 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" });
18060
- }
18061
- if (/await\s+\w+\(/.test(content) && !content.includes("try") && !content.includes("catch")) {
18062
- 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" });
18063
- }
18064
- const nestedLoops = content.match(/for\s*\(.*\)\s*\{[^}]*for\s*\(/g);
18065
- if (nestedLoops && nestedLoops.length > 0) {
18066
- 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" });
18067
- }
18068
- if (/JSON\.parse\(.*JSON\.stringify/.test(content)) {
18069
- 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" });
18070
- }
18071
- const syncReads = (content.match(/readFileSync/g) || []).length;
18072
- if (syncReads > 3) {
18073
- 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" });
18074
- }
18075
- return findings;
18076
- }
18077
- function scanDir(dir, projectPath) {
18078
- const allFindings = [];
18079
- try {
18080
- const entries2 = readdirSync(dir, { withFileTypes: true });
18081
- for (const entry of entries2) {
18082
- if (["node_modules", ".git", "dist", ".cache", "coverage", ".private", ".project", ".dev"].includes(entry.name)) continue;
18083
- const fullPath = join(dir, entry.name);
18084
- if (entry.isDirectory()) {
18085
- allFindings.push(...scanDir(fullPath, projectPath));
18086
- } else if (entry.isFile() && /\.(ts|js|tsx|jsx|py|go|rs|c|cpp|java)$/.test(entry.name)) {
18868
+ return allFindings;
18869
+ }, "scanDir");
18870
+ runNpmAudit = /* @__PURE__ */ __name((projectPath) => {
18871
+ const findings = [];
18872
+ try {
18873
+ let output = "";
18087
18874
  try {
18088
- const content = readFileSync(fullPath, "utf-8");
18089
- allFindings.push(...scanFile(fullPath, content, projectPath));
18090
- } catch {
18875
+ output = execFileSync("npm", ["audit", "--json"], { cwd: projectPath, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
18876
+ } catch (e) {
18877
+ output = e.stdout || "";
18878
+ }
18879
+ if (!output) return findings;
18880
+ const data = JSON.parse(output);
18881
+ const vulns = data.vulnerabilities ?? {};
18882
+ let idCounter = 1;
18883
+ for (const [name, info] of Object.entries(vulns)) {
18884
+ const severity = (info.severity ?? "low").toLowerCase();
18885
+ const mappedSeverity = severity === "critical" ? "critical" : severity === "high" ? "high" : severity === "moderate" ? "medium" : "low";
18886
+ const via = Array.isArray(info.via) ? info.via.filter((v) => typeof v === "object").map((v) => v.title || v.name).join(", ") : "";
18887
+ findings.push({
18888
+ id: `NPM-${String(idCounter++).padStart(3, "0")}`,
18889
+ category: "security",
18890
+ severity: mappedSeverity,
18891
+ framework: "npm audit",
18892
+ control: "OWASP A06",
18893
+ message: `${name}: ${via || info.name || "vulnerability"} (${severity})`,
18894
+ file: "package.json",
18895
+ remediation: `Run "npm audit fix" or update ${name} to a patched version`
18896
+ });
18091
18897
  }
18898
+ const meta = data.metadata?.vulnerabilities;
18899
+ if (meta && meta.total > 0) {
18900
+ findings.push({
18901
+ id: "NPM-SUM",
18902
+ category: "security",
18903
+ severity: meta.critical > 0 ? "critical" : meta.high > 0 ? "high" : meta.moderate > 0 ? "medium" : "low",
18904
+ framework: "npm audit",
18905
+ control: "OWASP A06",
18906
+ message: `npm audit: ${meta.total} vulnerabilities (${meta.critical} critical, ${meta.high} high, ${meta.moderate} moderate, ${meta.low} low)`,
18907
+ file: "package.json",
18908
+ remediation: 'Run "npm audit fix" to resolve. Review breaking changes before applying.'
18909
+ });
18910
+ }
18911
+ } catch {
18092
18912
  }
18093
- }
18094
- } catch {
18095
- }
18096
- return allFindings;
18097
- }
18098
- function runNpmAudit(projectPath) {
18099
- const findings = [];
18100
- try {
18101
- let output = "";
18102
- try {
18103
- output = execFileSync("npm", ["audit", "--json"], { cwd: projectPath, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
18104
- } catch (e) {
18105
- output = e.stdout || "";
18106
- }
18107
- if (!output) return findings;
18108
- const data = JSON.parse(output);
18109
- const vulns = data.vulnerabilities ?? {};
18110
- let idCounter = 1;
18111
- for (const [name, info] of Object.entries(vulns)) {
18112
- const severity = (info.severity ?? "low").toLowerCase();
18113
- const mappedSeverity = severity === "critical" ? "critical" : severity === "high" ? "high" : severity === "moderate" ? "medium" : "low";
18114
- const via = Array.isArray(info.via) ? info.via.filter((v) => typeof v === "object").map((v) => v.title || v.name).join(", ") : "";
18115
- findings.push({
18116
- id: `NPM-${String(idCounter++).padStart(3, "0")}`,
18117
- category: "security",
18118
- severity: mappedSeverity,
18119
- framework: "npm audit",
18120
- control: "OWASP A06",
18121
- message: `${name}: ${via || info.name || "vulnerability"} (${severity})`,
18122
- file: "package.json",
18123
- remediation: `Run "npm audit fix" or update ${name} to a patched version`
18124
- });
18125
- }
18126
- const meta = data.metadata?.vulnerabilities;
18127
- if (meta && meta.total > 0) {
18128
- findings.push({
18129
- id: "NPM-SUM",
18130
- category: "security",
18131
- severity: meta.critical > 0 ? "critical" : meta.high > 0 ? "high" : meta.moderate > 0 ? "medium" : "low",
18132
- framework: "npm audit",
18133
- control: "OWASP A06",
18134
- message: `npm audit: ${meta.total} vulnerabilities (${meta.critical} critical, ${meta.high} high, ${meta.moderate} moderate, ${meta.low} low)`,
18135
- file: "package.json",
18136
- remediation: 'Run "npm audit fix" to resolve. Review breaking changes before applying.'
18137
- });
18138
- }
18139
- } catch {
18140
- }
18141
- return findings;
18142
- }
18143
- function generateReport(result) {
18144
- const { quality, security: security2, performance, score, grade, projectPath, timestamp } = result;
18145
- const all = [...quality, ...security2, ...performance];
18146
- const critical = all.filter((f) => f.severity === "critical").length;
18147
- const high = all.filter((f) => f.severity === "high").length;
18148
- const medium = all.filter((f) => f.severity === "medium").length;
18149
- const low = all.filter((f) => f.severity === "low" || f.severity === "info").length;
18150
- let report = "";
18151
- 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";
18152
- report += " PROFESSIONAL IT AUDIT REPORT\n";
18153
- 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";
18154
- report += `Project: ${projectPath}
18913
+ return findings;
18914
+ }, "runNpmAudit");
18915
+ generateReport = /* @__PURE__ */ __name((result) => {
18916
+ const { quality, security: security2, performance, score, grade, projectPath, timestamp } = result;
18917
+ const all = [...quality, ...security2, ...performance];
18918
+ const critical = all.filter((f) => f.severity === "critical").length;
18919
+ const high = all.filter((f) => f.severity === "high").length;
18920
+ const medium = all.filter((f) => f.severity === "medium").length;
18921
+ const low = all.filter((f) => f.severity === "low" || f.severity === "info").length;
18922
+ let report = "";
18923
+ 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";
18924
+ report += " PROFESSIONAL IT AUDIT REPORT\n";
18925
+ 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";
18926
+ report += `Project: ${projectPath}
18155
18927
  `;
18156
- report += `Date: ${timestamp}
18928
+ report += `Date: ${timestamp}
18157
18929
  `;
18158
- report += `Auditor: dotmem audit plugin
18930
+ report += `Auditor: dotmem audit plugin
18159
18931
  `;
18160
- report += `Frameworks: OWASP Top 10, NIST SP 800-53, NSA/CISA Guidelines, ISO 25010, npm audit
18932
+ report += `Frameworks: OWASP Top 10, NIST SP 800-53, NSA/CISA Guidelines, ISO 25010, npm audit
18161
18933
  `;
18162
- report += `OSI Layers: L7 (Application) analyzed
18934
+ report += `OSI Layers: L7 (Application) analyzed
18163
18935
 
18164
18936
  `;
18165
- 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";
18166
- report += " EXECUTIVE SUMMARY\n";
18167
- 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";
18168
- report += `Overall Score: ${score}/100 (Grade: ${grade})
18937
+ 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";
18938
+ report += " EXECUTIVE SUMMARY\n";
18939
+ 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";
18940
+ report += `Overall Score: ${score}/100 (Grade: ${grade})
18169
18941
  `;
18170
- report += `Total Findings: ${all.length}
18942
+ report += `Total Findings: ${all.length}
18171
18943
  `;
18172
- report += ` Critical: ${critical} High: ${high} Medium: ${medium} Low/Info: ${low}
18944
+ report += ` Critical: ${critical} High: ${high} Medium: ${medium} Low/Info: ${low}
18173
18945
 
18174
18946
  `;
18175
- report += ` Quality: ${quality.length} findings
18947
+ report += ` Quality: ${quality.length} findings
18176
18948
  `;
18177
- report += ` Security: ${security2.length} findings (incl. npm vulnerabilities)
18949
+ report += ` Security: ${security2.length} findings (incl. npm vulnerabilities)
18178
18950
  `;
18179
- report += ` Performance: ${performance.length} findings
18951
+ report += ` Performance: ${performance.length} findings
18180
18952
 
18181
18953
  `;
18182
- 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";
18183
- report += " 1. SECURITY ASSESSMENT\n";
18184
- 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";
18185
- report += "Frameworks: OWASP Top 10 (2021), NIST SP 800-53 Rev.5, NSA Secure Coding, npm audit\n\n";
18186
- if (security2.length === 0) {
18187
- report += "No security findings. All checks passed.\n\n";
18188
- } else {
18189
- for (const f of security2) {
18190
- report += `[${f.severity.toUpperCase()}] ${f.id}: ${f.message}
18954
+ 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";
18955
+ report += " 1. SECURITY ASSESSMENT\n";
18956
+ 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";
18957
+ report += "Frameworks: OWASP Top 10 (2021), NIST SP 800-53 Rev.5, NSA Secure Coding, npm audit\n\n";
18958
+ if (security2.length === 0) {
18959
+ report += "No security findings. All checks passed.\n\n";
18960
+ } else {
18961
+ for (const f of security2) {
18962
+ report += `[${f.severity.toUpperCase()}] ${f.id}: ${f.message}
18191
18963
  `;
18192
- report += ` Framework: ${f.framework} ${f.control}
18964
+ report += ` Framework: ${f.framework} ${f.control}
18193
18965
  `;
18194
- if (f.file) report += ` File: ${f.file}
18966
+ if (f.file) report += ` File: ${f.file}
18195
18967
  `;
18196
- report += ` Remediation: ${f.remediation}
18968
+ report += ` Remediation: ${f.remediation}
18197
18969
 
18198
18970
  `;
18199
- }
18200
- }
18201
- 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";
18202
- report += " 2. QUALITY ASSESSMENT\n";
18203
- 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";
18204
- report += "Framework: ISO/IEC 25010 Software Quality Model\n\n";
18205
- if (quality.length === 0) {
18206
- report += "No quality findings. All checks passed.\n\n";
18207
- } else {
18208
- for (const f of quality) {
18209
- report += `[${f.severity.toUpperCase()}] ${f.id}: ${f.message}
18971
+ }
18972
+ }
18973
+ 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";
18974
+ report += " 2. QUALITY ASSESSMENT\n";
18975
+ 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";
18976
+ report += "Framework: ISO/IEC 25010 Software Quality Model\n\n";
18977
+ if (quality.length === 0) {
18978
+ report += "No quality findings. All checks passed.\n\n";
18979
+ } else {
18980
+ for (const f of quality) {
18981
+ report += `[${f.severity.toUpperCase()}] ${f.id}: ${f.message}
18210
18982
  `;
18211
- report += ` Framework: ${f.framework} - ${f.control}
18983
+ report += ` Framework: ${f.framework} - ${f.control}
18212
18984
  `;
18213
- if (f.file) report += ` File: ${f.file}
18985
+ if (f.file) report += ` File: ${f.file}
18214
18986
  `;
18215
- report += ` Remediation: ${f.remediation}
18987
+ report += ` Remediation: ${f.remediation}
18216
18988
 
18217
18989
  `;
18218
- }
18219
- }
18220
- 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";
18221
- report += " 3. PERFORMANCE ASSESSMENT\n";
18222
- 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";
18223
- report += "Framework: OSI Model Layer 7 (Application) Analysis\n\n";
18224
- if (performance.length === 0) {
18225
- report += "No performance findings. All checks passed.\n\n";
18226
- } else {
18227
- for (const f of performance) {
18228
- report += `[${f.severity.toUpperCase()}] ${f.id}: ${f.message}
18990
+ }
18991
+ }
18992
+ 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";
18993
+ report += " 3. PERFORMANCE ASSESSMENT\n";
18994
+ 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";
18995
+ report += "Framework: OSI Model Layer 7 (Application) Analysis\n\n";
18996
+ if (performance.length === 0) {
18997
+ report += "No performance findings. All checks passed.\n\n";
18998
+ } else {
18999
+ for (const f of performance) {
19000
+ report += `[${f.severity.toUpperCase()}] ${f.id}: ${f.message}
18229
19001
  `;
18230
- report += ` Framework: ${f.framework} - ${f.control}
19002
+ report += ` Framework: ${f.framework} - ${f.control}
18231
19003
  `;
18232
- if (f.file) report += ` File: ${f.file}
19004
+ if (f.file) report += ` File: ${f.file}
18233
19005
  `;
18234
- report += ` Remediation: ${f.remediation}
19006
+ report += ` Remediation: ${f.remediation}
18235
19007
 
18236
19008
  `;
18237
- }
18238
- }
18239
- 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";
18240
- report += " 4. RECOMMENDATIONS\n";
18241
- 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";
18242
- const criticalFindings = all.filter((f) => f.severity === "critical" || f.severity === "high");
18243
- if (criticalFindings.length === 0) {
18244
- report += "No critical or high-severity findings. Project meets baseline security standards.\n\n";
18245
- } else {
18246
- report += "Priority actions (critical/high severity):\n";
18247
- for (const f of criticalFindings) {
18248
- report += ` - ${f.id}: ${f.message} (${f.file ?? "N/A"})
18249
- `;
18250
- }
18251
- report += "\n";
18252
- }
18253
- 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";
18254
- report += " 5. FRAMEWORK COMPLIANCE MATRIX\n";
18255
- 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";
18256
- report += "OWASP Top 10 (2021):\n";
18257
- const owaspIds = ["A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08", "A09", "A10"];
18258
- const owaspNames = ["Broken Access Control", "Cryptographic Failures", "Injection", "Insecure Design", "Security Misconfiguration", "Vulnerable Components", "Auth Failures", "Integrity Failures", "Logging Failures", "SSRF"];
18259
- for (let i3 = 0; i3 < owaspIds.length; i3++) {
18260
- const found = security2.some((f) => f.control === owaspIds[i3]);
18261
- report += ` ${owaspIds[i3]} ${owaspNames[i3]}: ${found ? "FINDINGS" : "PASS"}
18262
- `;
18263
- }
18264
- report += "\nnpm audit:\n";
18265
- const npmFindings = security2.filter((f) => f.framework === "npm audit");
18266
- report += ` Total vulnerabilities: ${npmFindings.filter((f) => f.id !== "NPM-SUM").length}
18267
- `;
18268
- report += ` Status: ${npmFindings.length > 0 ? "FINDINGS" : "PASS"}
18269
- `;
18270
- 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";
18271
- report += " END OF REPORT\n";
18272
- 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";
18273
- return report;
18274
- }
18275
- function audit(options = {}) {
18276
- const projectPath = options.projectPath ?? process.cwd();
18277
- const allFindings = scanDir(projectPath, projectPath);
18278
- allFindings.push(...runNpmAudit(projectPath));
18279
- const quality = allFindings.filter((f) => f.category === "quality");
18280
- const security2 = allFindings.filter((f) => f.category === "security");
18281
- const performance = allFindings.filter((f) => f.category === "performance");
18282
- const errorCount = allFindings.filter((f) => f.severity === "critical" || f.severity === "high").length;
18283
- const totalFindings = allFindings.length;
18284
- const score = Math.max(0, 100 - errorCount * 10 - (totalFindings - errorCount) * 2);
18285
- const grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : score >= 60 ? "D" : "F";
18286
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
18287
- const result = {
18288
- projectPath,
18289
- timestamp,
18290
- quality,
18291
- security: security2,
18292
- performance,
18293
- score,
18294
- grade,
18295
- summary: `Audit complete: ${totalFindings} findings (${errorCount} critical/high). Score: ${score}/100 (Grade: ${grade}).`,
18296
- report: ""
18297
- };
18298
- result.report = generateReport({ quality, security: security2, performance, score, grade, projectPath, timestamp });
18299
- if (options.onFinding) {
18300
- for (const f of allFindings) {
18301
- options.onFinding(f);
18302
- }
18303
- }
18304
- return {
18305
- name: "audit",
18306
- version: "0.3.0",
18307
- description: "Professional IT audit: quality, security, performance, npm vulnerabilities.",
18308
- hooks: {
18309
- onAudit(_result) {
19009
+ }
18310
19010
  }
18311
- },
18312
- run: /* @__PURE__ */ __name(() => result, "run"),
18313
- report: /* @__PURE__ */ __name(() => result.report, "report")
18314
- };
18315
- }
18316
- var init_audit = __esm({
18317
- "plugins/audit/index.ts"() {
18318
- __name(stripCode, "stripCode");
18319
- __name(hasEval, "hasEval");
18320
- __name(isInNonCode, "isInNonCode");
18321
- __name(collectDangerousNames, "collectDangerousNames");
18322
- __name(hasProcessExec, "hasProcessExec");
18323
- __name(scanFile, "scanFile");
18324
- __name(scanDir, "scanDir");
18325
- __name(runNpmAudit, "runNpmAudit");
18326
- __name(generateReport, "generateReport");
19011
+ 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";
19012
+ report += " 4. RECOMMENDATIONS\n";
19013
+ 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";
19014
+ const criticalFindings = all.filter((f) => f.severity === "critical" || f.severity === "high");
19015
+ if (criticalFindings.length === 0) {
19016
+ report += "No critical or high-severity findings. Project meets baseline security standards.\n\n";
19017
+ } else {
19018
+ report += "Priority actions (critical/high severity):\n";
19019
+ for (const f of criticalFindings) {
19020
+ report += ` - ${f.id}: ${f.message} (${f.file ?? "N/A"})
19021
+ `;
19022
+ }
19023
+ report += "\n";
19024
+ }
19025
+ 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";
19026
+ report += " 5. FRAMEWORK COMPLIANCE MATRIX\n";
19027
+ 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";
19028
+ report += "OWASP Top 10 (2021):\n";
19029
+ const owaspIds = ["A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08", "A09", "A10"];
19030
+ const owaspNames = ["Broken Access Control", "Cryptographic Failures", "Injection", "Insecure Design", "Security Misconfiguration", "Vulnerable Components", "Auth Failures", "Integrity Failures", "Logging Failures", "SSRF"];
19031
+ for (let i3 = 0; i3 < owaspIds.length; i3++) {
19032
+ const found = security2.some((f) => f.control === owaspIds[i3]);
19033
+ report += ` ${owaspIds[i3]} ${owaspNames[i3]}: ${found ? "FINDINGS" : "PASS"}
19034
+ `;
19035
+ }
19036
+ report += "\nnpm audit:\n";
19037
+ const npmFindings = security2.filter((f) => f.framework === "npm audit");
19038
+ report += ` Total vulnerabilities: ${npmFindings.filter((f) => f.id !== "NPM-SUM").length}
19039
+ `;
19040
+ report += ` Status: ${npmFindings.length > 0 ? "FINDINGS" : "PASS"}
19041
+ `;
19042
+ 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";
19043
+ report += " END OF REPORT\n";
19044
+ 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";
19045
+ return report;
19046
+ }, "generateReport");
18327
19047
  __name(audit, "audit");
18328
19048
  }
18329
19049
  });
18330
- function resolveDbPath(override) {
18331
- if (override) return override;
18332
- const root = resolveDotMemStorageRoot();
18333
- const dir = path8.join(root, "neurocore");
18334
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
18335
- return path8.join(dir, "neurocore.db");
18336
- }
18337
- var DatabaseSync, SCHEMA_VERSION, NeuroCoreSqliteStore, createSqliteStore;
19050
+ var SCHEMA_VERSION, SchemaVersion, Episode, Assessment, Pattern, Proposal, Adaptation, Verification, resolveDbPath, ENTITIES, NeuroCoreSqliteStore, createSqliteStore;
18338
19051
  var init_sqlite = __esm({
18339
19052
  "plugins/neurocore/storage/sqlite.ts"() {
18340
19053
  init_storage_location();
18341
- ({ DatabaseSync } = globalThis.process?.getBuiltinModule?.("node:sqlite") ?? __require("sqlite"));
18342
19054
  SCHEMA_VERSION = 1;
18343
- __name(resolveDbPath, "resolveDbPath");
19055
+ SchemaVersion = class {
19056
+ version;
19057
+ };
19058
+ __name(SchemaVersion, "SchemaVersion");
19059
+ __decorateClass([
19060
+ PrimaryColumn("integer")
19061
+ ], SchemaVersion.prototype, "version", 2);
19062
+ SchemaVersion = __decorateClass([
19063
+ Entity("schema_version")
19064
+ ], SchemaVersion);
19065
+ Episode = class {
19066
+ id;
19067
+ scope;
19068
+ context;
19069
+ objective;
19070
+ observation;
19071
+ outcome;
19072
+ provenance;
19073
+ createdAt;
19074
+ memoryRefs;
19075
+ evidence;
19076
+ };
19077
+ __name(Episode, "Episode");
19078
+ __decorateClass([
19079
+ PrimaryColumn("text")
19080
+ ], Episode.prototype, "id", 2);
19081
+ __decorateClass([
19082
+ Column("text")
19083
+ ], Episode.prototype, "scope", 2);
19084
+ __decorateClass([
19085
+ Column("text")
19086
+ ], Episode.prototype, "context", 2);
19087
+ __decorateClass([
19088
+ Column("text")
19089
+ ], Episode.prototype, "objective", 2);
19090
+ __decorateClass([
19091
+ Column("text")
19092
+ ], Episode.prototype, "observation", 2);
19093
+ __decorateClass([
19094
+ Column("text")
19095
+ ], Episode.prototype, "outcome", 2);
19096
+ __decorateClass([
19097
+ Column("text")
19098
+ ], Episode.prototype, "provenance", 2);
19099
+ __decorateClass([
19100
+ Column({ name: "created_at", type: "text" })
19101
+ ], Episode.prototype, "createdAt", 2);
19102
+ __decorateClass([
19103
+ Column({ name: "memory_refs", type: "text", nullable: true })
19104
+ ], Episode.prototype, "memoryRefs", 2);
19105
+ __decorateClass([
19106
+ Column({ name: "evidence", type: "text", nullable: true })
19107
+ ], Episode.prototype, "evidence", 2);
19108
+ Episode = __decorateClass([
19109
+ Entity("episodes")
19110
+ ], Episode);
19111
+ Assessment = class {
19112
+ id;
19113
+ episodeId;
19114
+ assessmentType;
19115
+ findings;
19116
+ evidence;
19117
+ structuredEvidence;
19118
+ confidence;
19119
+ limitations;
19120
+ assessedAt;
19121
+ assessor;
19122
+ };
19123
+ __name(Assessment, "Assessment");
19124
+ __decorateClass([
19125
+ PrimaryColumn("text")
19126
+ ], Assessment.prototype, "id", 2);
19127
+ __decorateClass([
19128
+ Column({ name: "episode_id", type: "text" })
19129
+ ], Assessment.prototype, "episodeId", 2);
19130
+ __decorateClass([
19131
+ Column({ name: "assessment_type", type: "text" })
19132
+ ], Assessment.prototype, "assessmentType", 2);
19133
+ __decorateClass([
19134
+ Column("text")
19135
+ ], Assessment.prototype, "findings", 2);
19136
+ __decorateClass([
19137
+ Column("text")
19138
+ ], Assessment.prototype, "evidence", 2);
19139
+ __decorateClass([
19140
+ Column({ name: "structured_evidence", type: "text", nullable: true })
19141
+ ], Assessment.prototype, "structuredEvidence", 2);
19142
+ __decorateClass([
19143
+ Column("real")
19144
+ ], Assessment.prototype, "confidence", 2);
19145
+ __decorateClass([
19146
+ Column("text")
19147
+ ], Assessment.prototype, "limitations", 2);
19148
+ __decorateClass([
19149
+ Column({ name: "assessed_at", type: "text" })
19150
+ ], Assessment.prototype, "assessedAt", 2);
19151
+ __decorateClass([
19152
+ Column("text")
19153
+ ], Assessment.prototype, "assessor", 2);
19154
+ Assessment = __decorateClass([
19155
+ Entity("assessments")
19156
+ ], Assessment);
19157
+ Pattern = class {
19158
+ id;
19159
+ scope;
19160
+ description;
19161
+ episodeIds;
19162
+ supportingEvidence;
19163
+ contradictingEvidence;
19164
+ confidence;
19165
+ status;
19166
+ revision;
19167
+ firstObserved;
19168
+ lastObserved;
19169
+ };
19170
+ __name(Pattern, "Pattern");
19171
+ __decorateClass([
19172
+ PrimaryColumn("text")
19173
+ ], Pattern.prototype, "id", 2);
19174
+ __decorateClass([
19175
+ Column("text")
19176
+ ], Pattern.prototype, "scope", 2);
19177
+ __decorateClass([
19178
+ Column("text")
19179
+ ], Pattern.prototype, "description", 2);
19180
+ __decorateClass([
19181
+ Column({ name: "episode_ids", type: "text" })
19182
+ ], Pattern.prototype, "episodeIds", 2);
19183
+ __decorateClass([
19184
+ Column({ name: "supporting_evidence", type: "text" })
19185
+ ], Pattern.prototype, "supportingEvidence", 2);
19186
+ __decorateClass([
19187
+ Column({ name: "contradicting_evidence", type: "text" })
19188
+ ], Pattern.prototype, "contradictingEvidence", 2);
19189
+ __decorateClass([
19190
+ Column("real")
19191
+ ], Pattern.prototype, "confidence", 2);
19192
+ __decorateClass([
19193
+ Column("text")
19194
+ ], Pattern.prototype, "status", 2);
19195
+ __decorateClass([
19196
+ Column("integer")
19197
+ ], Pattern.prototype, "revision", 2);
19198
+ __decorateClass([
19199
+ Column({ name: "first_observed", type: "text", nullable: true })
19200
+ ], Pattern.prototype, "firstObserved", 2);
19201
+ __decorateClass([
19202
+ Column({ name: "last_observed", type: "text", nullable: true })
19203
+ ], Pattern.prototype, "lastObserved", 2);
19204
+ Pattern = __decorateClass([
19205
+ Entity("patterns")
19206
+ ], Pattern);
19207
+ Proposal = class {
19208
+ id;
19209
+ patternId;
19210
+ problem;
19211
+ proposedStrategy;
19212
+ applicableContext;
19213
+ expectedOutcome;
19214
+ verificationCriteria;
19215
+ evidence;
19216
+ status;
19217
+ revision;
19218
+ createdAt;
19219
+ };
19220
+ __name(Proposal, "Proposal");
19221
+ __decorateClass([
19222
+ PrimaryColumn("text")
19223
+ ], Proposal.prototype, "id", 2);
19224
+ __decorateClass([
19225
+ Column({ name: "pattern_id", type: "text", nullable: true })
19226
+ ], Proposal.prototype, "patternId", 2);
19227
+ __decorateClass([
19228
+ Column("text")
19229
+ ], Proposal.prototype, "problem", 2);
19230
+ __decorateClass([
19231
+ Column({ name: "proposed_strategy", type: "text" })
19232
+ ], Proposal.prototype, "proposedStrategy", 2);
19233
+ __decorateClass([
19234
+ Column({ name: "applicable_context", type: "text" })
19235
+ ], Proposal.prototype, "applicableContext", 2);
19236
+ __decorateClass([
19237
+ Column({ name: "expected_outcome", type: "text" })
19238
+ ], Proposal.prototype, "expectedOutcome", 2);
19239
+ __decorateClass([
19240
+ Column({ name: "verification_criteria", type: "text" })
19241
+ ], Proposal.prototype, "verificationCriteria", 2);
19242
+ __decorateClass([
19243
+ Column("text")
19244
+ ], Proposal.prototype, "evidence", 2);
19245
+ __decorateClass([
19246
+ Column("text")
19247
+ ], Proposal.prototype, "status", 2);
19248
+ __decorateClass([
19249
+ Column("integer")
19250
+ ], Proposal.prototype, "revision", 2);
19251
+ __decorateClass([
19252
+ Column({ name: "created_at", type: "text" })
19253
+ ], Proposal.prototype, "createdAt", 2);
19254
+ Proposal = __decorateClass([
19255
+ Entity("proposals")
19256
+ ], Proposal);
19257
+ Adaptation = class {
19258
+ id;
19259
+ proposalId;
19260
+ strategyVersion;
19261
+ activationScope;
19262
+ status;
19263
+ approvedBy;
19264
+ activatedAt;
19265
+ deactivatedAt;
19266
+ };
19267
+ __name(Adaptation, "Adaptation");
19268
+ __decorateClass([
19269
+ PrimaryColumn("text")
19270
+ ], Adaptation.prototype, "id", 2);
19271
+ __decorateClass([
19272
+ Column({ name: "proposal_id", type: "text" })
19273
+ ], Adaptation.prototype, "proposalId", 2);
19274
+ __decorateClass([
19275
+ Column({ name: "strategy_version", type: "integer" })
19276
+ ], Adaptation.prototype, "strategyVersion", 2);
19277
+ __decorateClass([
19278
+ Column({ name: "activation_scope", type: "text" })
19279
+ ], Adaptation.prototype, "activationScope", 2);
19280
+ __decorateClass([
19281
+ Column("text")
19282
+ ], Adaptation.prototype, "status", 2);
19283
+ __decorateClass([
19284
+ Column({ name: "approved_by", type: "text", nullable: true })
19285
+ ], Adaptation.prototype, "approvedBy", 2);
19286
+ __decorateClass([
19287
+ Column({ name: "activated_at", type: "text" })
19288
+ ], Adaptation.prototype, "activatedAt", 2);
19289
+ __decorateClass([
19290
+ Column({ name: "deactivated_at", type: "text", nullable: true })
19291
+ ], Adaptation.prototype, "deactivatedAt", 2);
19292
+ Adaptation = __decorateClass([
19293
+ Entity("adaptations")
19294
+ ], Adaptation);
19295
+ Verification = class {
19296
+ id;
19297
+ adaptationId;
19298
+ measurement;
19299
+ baseline;
19300
+ observedOutcome;
19301
+ comparisonContext;
19302
+ conclusion;
19303
+ limitations;
19304
+ verifiedAt;
19305
+ };
19306
+ __name(Verification, "Verification");
19307
+ __decorateClass([
19308
+ PrimaryColumn("text")
19309
+ ], Verification.prototype, "id", 2);
19310
+ __decorateClass([
19311
+ Column({ name: "adaptation_id", type: "text" })
19312
+ ], Verification.prototype, "adaptationId", 2);
19313
+ __decorateClass([
19314
+ Column("text")
19315
+ ], Verification.prototype, "measurement", 2);
19316
+ __decorateClass([
19317
+ Column("text")
19318
+ ], Verification.prototype, "baseline", 2);
19319
+ __decorateClass([
19320
+ Column({ name: "observed_outcome", type: "text" })
19321
+ ], Verification.prototype, "observedOutcome", 2);
19322
+ __decorateClass([
19323
+ Column({ name: "comparison_context", type: "text" })
19324
+ ], Verification.prototype, "comparisonContext", 2);
19325
+ __decorateClass([
19326
+ Column("text")
19327
+ ], Verification.prototype, "conclusion", 2);
19328
+ __decorateClass([
19329
+ Column("text")
19330
+ ], Verification.prototype, "limitations", 2);
19331
+ __decorateClass([
19332
+ Column({ name: "verified_at", type: "text" })
19333
+ ], Verification.prototype, "verifiedAt", 2);
19334
+ Verification = __decorateClass([
19335
+ Entity("verifications")
19336
+ ], Verification);
19337
+ resolveDbPath = /* @__PURE__ */ __name((override) => {
19338
+ if (override) return override;
19339
+ const root = resolveDotMemStorageRoot();
19340
+ const dir = path5.join(root, "neurocore");
19341
+ if (!fs6.existsSync(dir)) fs6.mkdirSync(dir, { recursive: true });
19342
+ return path5.join(dir, "neurocore.db");
19343
+ }, "resolveDbPath");
19344
+ ENTITIES = [
19345
+ SchemaVersion,
19346
+ Episode,
19347
+ Assessment,
19348
+ Pattern,
19349
+ Proposal,
19350
+ Adaptation,
19351
+ Verification
19352
+ ];
18344
19353
  NeuroCoreSqliteStore = class {
18345
19354
  static {
18346
19355
  __name(this, "NeuroCoreSqliteStore");
18347
19356
  }
18348
- db;
19357
+ ds = null;
18349
19358
  dbPath;
19359
+ initialized = false;
18350
19360
  constructor(dbPath) {
18351
19361
  this.dbPath = resolveDbPath(dbPath);
18352
- const dir = path8.dirname(this.dbPath);
18353
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
18354
- this.db = new DatabaseSync(this.dbPath);
18355
- this.db.exec("PRAGMA journal_mode = WAL;");
18356
- this.db.exec("PRAGMA busy_timeout = 5000;");
18357
- this.migrate();
18358
- }
18359
- migrate() {
18360
- this.db.exec(`CREATE TABLE IF NOT EXISTS schema_version (version INTEGER PRIMARY KEY);`);
18361
- const row = this.db.prepare("SELECT version FROM schema_version LIMIT 1").get();
19362
+ const dir = path5.dirname(this.dbPath);
19363
+ if (!fs6.existsSync(dir)) fs6.mkdirSync(dir, { recursive: true });
19364
+ }
19365
+ async init() {
19366
+ if (this.initialized) return;
19367
+ this.ds = new DataSource({
19368
+ type: "better-sqlite3",
19369
+ database: this.dbPath,
19370
+ entities: ENTITIES,
19371
+ synchronize: true,
19372
+ logging: false
19373
+ });
19374
+ await this.ds.initialize();
19375
+ await this.migrate();
19376
+ this.initialized = true;
19377
+ }
19378
+ async migrate() {
19379
+ if (!this.ds) throw new Error("DataSource not initialized");
19380
+ const svRepo = this.ds.getRepository(SchemaVersion);
19381
+ const row = await svRepo.findOne({ where: {} });
18362
19382
  const current = row ? row.version : 0;
18363
- if (current === 0) {
18364
- this.db.exec(`
18365
- CREATE TABLE episodes (
18366
- id TEXT PRIMARY KEY,
18367
- scope TEXT NOT NULL,
18368
- context TEXT NOT NULL,
18369
- objective TEXT NOT NULL,
18370
- observation TEXT NOT NULL,
18371
- outcome TEXT NOT NULL,
18372
- provenance TEXT NOT NULL,
18373
- created_at TEXT NOT NULL,
18374
- memory_refs TEXT,
18375
- evidence TEXT
18376
- );
18377
- CREATE TABLE assessments (
18378
- id TEXT PRIMARY KEY,
18379
- episode_id TEXT NOT NULL,
18380
- assessment_type TEXT NOT NULL,
18381
- findings TEXT NOT NULL,
18382
- evidence TEXT NOT NULL,
18383
- structured_evidence TEXT,
18384
- confidence REAL NOT NULL,
18385
- limitations TEXT NOT NULL,
18386
- assessed_at TEXT NOT NULL,
18387
- assessor TEXT NOT NULL,
18388
- FOREIGN KEY (episode_id) REFERENCES episodes(id)
18389
- );
18390
- CREATE TABLE patterns (
18391
- id TEXT PRIMARY KEY,
18392
- scope TEXT NOT NULL,
18393
- description TEXT NOT NULL,
18394
- episode_ids TEXT NOT NULL,
18395
- supporting_evidence TEXT NOT NULL,
18396
- contradicting_evidence TEXT NOT NULL,
18397
- confidence REAL NOT NULL,
18398
- status TEXT NOT NULL,
18399
- revision INTEGER NOT NULL,
18400
- first_observed TEXT,
18401
- last_observed TEXT
18402
- );
18403
- CREATE TABLE proposals (
18404
- id TEXT PRIMARY KEY,
18405
- pattern_id TEXT,
18406
- problem TEXT NOT NULL,
18407
- proposed_strategy TEXT NOT NULL,
18408
- applicable_context TEXT NOT NULL,
18409
- expected_outcome TEXT NOT NULL,
18410
- verification_criteria TEXT NOT NULL,
18411
- evidence TEXT NOT NULL,
18412
- status TEXT NOT NULL,
18413
- revision INTEGER NOT NULL,
18414
- created_at TEXT NOT NULL
18415
- );
18416
- CREATE TABLE adaptations (
18417
- id TEXT PRIMARY KEY,
18418
- proposal_id TEXT NOT NULL,
18419
- strategy_version INTEGER NOT NULL,
18420
- activation_scope TEXT NOT NULL,
18421
- status TEXT NOT NULL,
18422
- approved_by TEXT,
18423
- activated_at TEXT NOT NULL,
18424
- deactivated_at TEXT
18425
- );
18426
- CREATE TABLE verifications (
18427
- id TEXT PRIMARY KEY,
18428
- adaptation_id TEXT NOT NULL,
18429
- measurement TEXT NOT NULL,
18430
- baseline TEXT NOT NULL,
18431
- observed_outcome TEXT NOT NULL,
18432
- comparison_context TEXT NOT NULL,
18433
- conclusion TEXT NOT NULL,
18434
- limitations TEXT NOT NULL,
18435
- verified_at TEXT NOT NULL
18436
- );
18437
- INSERT INTO schema_version (version) VALUES (${SCHEMA_VERSION});
18438
- `);
18439
- } else if (current !== SCHEMA_VERSION) {
18440
- throw new Error(`Unsupported NeuroCore schema version: ${current}`);
19383
+ if (current !== SCHEMA_VERSION) {
19384
+ if (current === 0) {
19385
+ await svRepo.insert({ version: SCHEMA_VERSION });
19386
+ } else {
19387
+ throw new Error(`Unsupported NeuroCore schema version: ${current}`);
19388
+ }
19389
+ }
19390
+ }
19391
+ ensureInit() {
19392
+ if (!this.initialized || !this.ds) {
19393
+ throw new Error("Store not initialized. Call init() before using the store.");
18441
19394
  }
18442
19395
  }
18443
- // NeuroCoreStore implementation
18444
- saveEpisode(episode) {
18445
- const stmt = this.db.prepare(`INSERT INTO episodes (id, scope, context, objective, observation, outcome, provenance, created_at, memory_refs, evidence) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
19396
+ async saveEpisode(episode) {
19397
+ this.ensureInit();
19398
+ const repo = this.ds.getRepository(Episode);
18446
19399
  try {
18447
- stmt.run(
18448
- episode.id,
18449
- episode.scope,
18450
- episode.context,
18451
- episode.objective,
18452
- episode.observation,
18453
- episode.outcome,
18454
- episode.provenance,
18455
- episode.createdAt,
18456
- JSON.stringify(episode.memoryRefs ?? []),
18457
- JSON.stringify(episode.evidence ?? null)
18458
- );
19400
+ await repo.insert({
19401
+ id: episode.id,
19402
+ scope: episode.scope,
19403
+ context: episode.context,
19404
+ objective: episode.objective,
19405
+ observation: episode.observation,
19406
+ outcome: episode.outcome,
19407
+ provenance: episode.provenance,
19408
+ createdAt: episode.createdAt,
19409
+ memoryRefs: JSON.stringify(episode.memoryRefs ?? []),
19410
+ evidence: episode.evidence != null ? JSON.stringify(episode.evidence) : null
19411
+ });
18459
19412
  } catch (e) {
18460
19413
  if (String(e).includes("UNIQUE") || String(e).includes("PRIMARY KEY")) throw new Error(`duplicate episode id: ${episode.id}`);
18461
19414
  throw e;
18462
19415
  }
18463
19416
  }
18464
- getEpisode(id) {
18465
- const row = this.db.prepare("SELECT * FROM episodes WHERE id = ?").get(id);
19417
+ async getEpisode(id) {
19418
+ this.ensureInit();
19419
+ const repo = this.ds.getRepository(Episode);
19420
+ const row = await repo.findOne({ where: { id } });
18466
19421
  if (!row) return void 0;
18467
19422
  return {
18468
19423
  id: row.id,
@@ -18472,24 +19427,17 @@ var init_sqlite = __esm({
18472
19427
  observation: row.observation,
18473
19428
  outcome: row.outcome,
18474
19429
  provenance: row.provenance,
18475
- createdAt: row.created_at,
18476
- memoryRefs: JSON.parse(row.memory_refs || "[]"),
19430
+ createdAt: row.createdAt,
19431
+ memoryRefs: JSON.parse(row.memoryRefs ?? "[]"),
18477
19432
  evidence: row.evidence ? JSON.parse(row.evidence) : void 0
18478
19433
  };
18479
19434
  }
18480
- listEpisodes(options) {
18481
- let sql = "SELECT * FROM episodes";
18482
- const params = [];
18483
- if (options?.scope) {
18484
- sql += " WHERE scope = ?";
18485
- params.push(options.scope);
18486
- }
18487
- sql += " ORDER BY created_at ASC";
18488
- if (options?.limit && options.limit > 0) {
18489
- sql += " LIMIT ?";
18490
- params.push(options.limit);
18491
- }
18492
- const rows = this.db.prepare(sql).all(...params);
19435
+ async listEpisodes(options) {
19436
+ this.ensureInit();
19437
+ const repo = this.ds.getRepository(Episode);
19438
+ const where = {};
19439
+ if (options?.scope) where.scope = options.scope;
19440
+ const rows = await repo.find({ where, order: { createdAt: "ASC" }, take: options?.limit });
18493
19441
  return rows.map((row) => ({
18494
19442
  id: row.id,
18495
19443
  scope: row.scope,
@@ -18498,226 +19446,256 @@ var init_sqlite = __esm({
18498
19446
  observation: row.observation,
18499
19447
  outcome: row.outcome,
18500
19448
  provenance: row.provenance,
18501
- createdAt: row.created_at,
18502
- memoryRefs: JSON.parse(row.memory_refs || "[]"),
19449
+ createdAt: row.createdAt,
19450
+ memoryRefs: JSON.parse(row.memoryRefs ?? "[]"),
18503
19451
  evidence: row.evidence ? JSON.parse(row.evidence) : void 0
18504
19452
  }));
18505
19453
  }
18506
- saveAssessment(a) {
18507
- const stmt = this.db.prepare(`INSERT INTO assessments (id, episode_id, assessment_type, findings, evidence, structured_evidence, confidence, limitations, assessed_at, assessor) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
19454
+ async saveAssessment(a) {
19455
+ this.ensureInit();
19456
+ const repo = this.ds.getRepository(Assessment);
18508
19457
  try {
18509
- stmt.run(
18510
- a.id,
18511
- a.episodeId,
18512
- a.assessmentType,
18513
- JSON.stringify(a.findings ?? []),
18514
- JSON.stringify(a.evidence ?? []),
18515
- a.structuredEvidence ? JSON.stringify(a.structuredEvidence) : null,
18516
- a.confidence,
18517
- JSON.stringify(a.limitations ?? []),
18518
- a.assessedAt,
18519
- a.assessor
18520
- );
19458
+ await repo.insert({
19459
+ id: a.id,
19460
+ episodeId: a.episodeId,
19461
+ assessmentType: a.assessmentType,
19462
+ findings: JSON.stringify(a.findings ?? []),
19463
+ evidence: JSON.stringify(a.evidence ?? []),
19464
+ structuredEvidence: a.structuredEvidence != null ? JSON.stringify(a.structuredEvidence) : null,
19465
+ confidence: a.confidence,
19466
+ limitations: JSON.stringify(a.limitations ?? []),
19467
+ assessedAt: a.assessedAt,
19468
+ assessor: a.assessor
19469
+ });
18521
19470
  } catch (e) {
18522
19471
  if (String(e).includes("UNIQUE") || String(e).includes("PRIMARY KEY")) throw new Error(`duplicate assessment id: ${a.id}`);
18523
19472
  throw e;
18524
19473
  }
18525
19474
  }
18526
- getAssessment(id) {
18527
- const row = this.db.prepare("SELECT * FROM assessments WHERE id = ?").get(id);
19475
+ async getAssessment(id) {
19476
+ this.ensureInit();
19477
+ const repo = this.ds.getRepository(Assessment);
19478
+ const row = await repo.findOne({ where: { id } });
18528
19479
  if (!row) return void 0;
18529
19480
  return {
18530
19481
  id: row.id,
18531
- episodeId: row.episode_id,
18532
- assessmentType: row.assessment_type,
19482
+ episodeId: row.episodeId,
19483
+ assessmentType: row.assessmentType,
18533
19484
  findings: JSON.parse(row.findings),
18534
19485
  evidence: JSON.parse(row.evidence),
18535
- structuredEvidence: row.structured_evidence ? JSON.parse(row.structured_evidence) : void 0,
19486
+ structuredEvidence: row.structuredEvidence ? JSON.parse(row.structuredEvidence) : void 0,
18536
19487
  confidence: row.confidence,
18537
19488
  limitations: JSON.parse(row.limitations),
18538
- assessedAt: row.assessed_at,
19489
+ assessedAt: row.assessedAt,
18539
19490
  assessor: row.assessor
18540
19491
  };
18541
19492
  }
18542
- listAssessmentsByEpisode(episodeId) {
18543
- const rows = this.db.prepare("SELECT * FROM assessments WHERE episode_id = ? ORDER BY assessed_at ASC").all(episodeId);
19493
+ async listAssessmentsByEpisode(episodeId) {
19494
+ this.ensureInit();
19495
+ const repo = this.ds.getRepository(Assessment);
19496
+ const rows = await repo.find({ where: { episodeId }, order: { assessedAt: "ASC" } });
18544
19497
  return rows.map((row) => ({
18545
19498
  id: row.id,
18546
- episodeId: row.episode_id,
18547
- assessmentType: row.assessment_type,
19499
+ episodeId: row.episodeId,
19500
+ assessmentType: row.assessmentType,
18548
19501
  findings: JSON.parse(row.findings),
18549
19502
  evidence: JSON.parse(row.evidence),
18550
- structuredEvidence: row.structured_evidence ? JSON.parse(row.structured_evidence) : void 0,
19503
+ structuredEvidence: row.structuredEvidence ? JSON.parse(row.structuredEvidence) : void 0,
18551
19504
  confidence: row.confidence,
18552
19505
  limitations: JSON.parse(row.limitations),
18553
- assessedAt: row.assessed_at,
19506
+ assessedAt: row.assessedAt,
18554
19507
  assessor: row.assessor
18555
19508
  }));
18556
19509
  }
18557
- // Patterns
18558
- savePattern(p) {
18559
- 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
19510
+ async savePattern(p) {
19511
+ this.ensureInit();
19512
+ const repo = this.ds.getRepository(Pattern);
18560
19513
  try {
18561
- stmt.run(
18562
- p.id,
18563
- p.scope,
18564
- p.description,
18565
- JSON.stringify(p.episodeIds ?? []),
18566
- JSON.stringify(p.supportingEvidence ?? []),
18567
- JSON.stringify(p.contradictingEvidence ?? []),
18568
- p.confidence,
18569
- p.status,
18570
- p.revision,
18571
- p.firstObserved ?? null,
18572
- p.lastObserved ?? null
18573
- );
19514
+ await repo.insert({
19515
+ id: p.id,
19516
+ scope: p.scope,
19517
+ description: p.description,
19518
+ episodeIds: JSON.stringify(p.episodeIds ?? []),
19519
+ supportingEvidence: JSON.stringify(p.supportingEvidence ?? []),
19520
+ contradictingEvidence: JSON.stringify(p.contradictingEvidence ?? []),
19521
+ confidence: p.confidence,
19522
+ status: p.status,
19523
+ revision: p.revision,
19524
+ firstObserved: p.firstObserved ?? null,
19525
+ lastObserved: p.lastObserved ?? null
19526
+ });
18574
19527
  } catch (e) {
18575
19528
  if (String(e).includes("UNIQUE") || String(e).includes("PRIMARY KEY")) throw new Error(`duplicate pattern id: ${p.id}`);
18576
19529
  throw e;
18577
19530
  }
18578
19531
  }
18579
- getPattern(id) {
18580
- const row = this.db.prepare("SELECT * FROM patterns WHERE id = ?").get(id);
19532
+ async getPattern(id) {
19533
+ this.ensureInit();
19534
+ const repo = this.ds.getRepository(Pattern);
19535
+ const row = await repo.findOne({ where: { id } });
18581
19536
  if (!row) return void 0;
18582
19537
  return {
18583
19538
  id: row.id,
18584
19539
  scope: row.scope,
18585
19540
  description: row.description,
18586
- episodeIds: JSON.parse(row.episode_ids),
18587
- supportingEvidence: JSON.parse(row.supporting_evidence),
18588
- contradictingEvidence: JSON.parse(row.contradicting_evidence),
19541
+ episodeIds: JSON.parse(row.episodeIds),
19542
+ supportingEvidence: JSON.parse(row.supportingEvidence),
19543
+ contradictingEvidence: JSON.parse(row.contradictingEvidence),
18589
19544
  confidence: row.confidence,
18590
19545
  status: row.status,
18591
19546
  revision: row.revision,
18592
- firstObserved: row.first_observed,
18593
- lastObserved: row.last_observed
19547
+ firstObserved: row.firstObserved,
19548
+ lastObserved: row.lastObserved
18594
19549
  };
18595
19550
  }
18596
- listPatterns() {
18597
- const rows = this.db.prepare("SELECT * FROM patterns").all();
19551
+ async listPatterns() {
19552
+ this.ensureInit();
19553
+ const repo = this.ds.getRepository(Pattern);
19554
+ const rows = await repo.find();
18598
19555
  return rows.map((row) => ({
18599
19556
  id: row.id,
18600
19557
  scope: row.scope,
18601
19558
  description: row.description,
18602
- episodeIds: JSON.parse(row.episode_ids),
18603
- supportingEvidence: JSON.parse(row.supporting_evidence),
18604
- contradictingEvidence: JSON.parse(row.contradicting_evidence),
19559
+ episodeIds: JSON.parse(row.episodeIds),
19560
+ supportingEvidence: JSON.parse(row.supportingEvidence),
19561
+ contradictingEvidence: JSON.parse(row.contradictingEvidence),
18605
19562
  confidence: row.confidence,
18606
19563
  status: row.status,
18607
19564
  revision: row.revision,
18608
- firstObserved: row.first_observed,
18609
- lastObserved: row.last_observed
19565
+ firstObserved: row.firstObserved,
19566
+ lastObserved: row.lastObserved
18610
19567
  }));
18611
19568
  }
18612
- // Proposals
18613
- saveProposal(p) {
18614
- 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
19569
+ async saveProposal(p) {
19570
+ this.ensureInit();
19571
+ const repo = this.ds.getRepository(Proposal);
18615
19572
  try {
18616
- stmt.run(
18617
- p.id,
18618
- p.patternId ?? null,
18619
- p.problem,
18620
- p.proposedStrategy,
18621
- p.applicableContext,
18622
- p.expectedOutcome,
18623
- p.verificationCriteria,
18624
- JSON.stringify(p.evidence ?? []),
18625
- p.status,
18626
- p.revision,
18627
- p.createdAt
18628
- );
19573
+ await repo.insert({
19574
+ id: p.id,
19575
+ patternId: p.patternId ?? null,
19576
+ problem: p.problem,
19577
+ proposedStrategy: p.proposedStrategy,
19578
+ applicableContext: p.applicableContext,
19579
+ expectedOutcome: p.expectedOutcome,
19580
+ verificationCriteria: p.verificationCriteria,
19581
+ evidence: JSON.stringify(p.evidence ?? []),
19582
+ status: p.status,
19583
+ revision: p.revision,
19584
+ createdAt: p.createdAt
19585
+ });
18629
19586
  } catch (e) {
18630
19587
  if (String(e).includes("UNIQUE") || String(e).includes("PRIMARY KEY")) throw new Error(`duplicate proposal id: ${p.id}`);
18631
19588
  throw e;
18632
19589
  }
18633
19590
  }
18634
- getProposal(id) {
18635
- const row = this.db.prepare("SELECT * FROM proposals WHERE id = ?").get(id);
19591
+ async getProposal(id) {
19592
+ this.ensureInit();
19593
+ const repo = this.ds.getRepository(Proposal);
19594
+ const row = await repo.findOne({ where: { id } });
18636
19595
  if (!row) return void 0;
18637
19596
  return {
18638
19597
  id: row.id,
18639
- patternId: row.pattern_id,
19598
+ patternId: row.patternId,
18640
19599
  problem: row.problem,
18641
- proposedStrategy: row.proposed_strategy,
18642
- applicableContext: row.applicable_context,
18643
- expectedOutcome: row.expected_outcome,
18644
- verificationCriteria: row.verification_criteria,
19600
+ proposedStrategy: row.proposedStrategy,
19601
+ applicableContext: row.applicableContext,
19602
+ expectedOutcome: row.expectedOutcome,
19603
+ verificationCriteria: row.verificationCriteria,
18645
19604
  evidence: JSON.parse(row.evidence),
18646
19605
  status: row.status,
18647
19606
  revision: row.revision,
18648
- createdAt: row.created_at
19607
+ createdAt: row.createdAt
18649
19608
  };
18650
19609
  }
18651
- // Adaptations
18652
- saveAdaptation(a) {
18653
- const stmt = this.db.prepare(`INSERT INTO adaptations (id, proposal_id, strategy_version, activation_scope, status, approved_by, activated_at, deactivated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);
19610
+ async saveAdaptation(a) {
19611
+ this.ensureInit();
19612
+ const repo = this.ds.getRepository(Adaptation);
18654
19613
  try {
18655
- stmt.run(a.id, a.proposalId, a.strategyVersion, a.activationScope, a.status, a.approvedBy ?? null, a.activatedAt, a.deactivatedAt ?? null);
19614
+ await repo.insert({
19615
+ id: a.id,
19616
+ proposalId: a.proposalId,
19617
+ strategyVersion: a.strategyVersion,
19618
+ activationScope: a.activationScope,
19619
+ status: a.status,
19620
+ approvedBy: a.approvedBy ?? null,
19621
+ activatedAt: a.activatedAt,
19622
+ deactivatedAt: a.deactivatedAt ?? null
19623
+ });
18656
19624
  } catch (e) {
18657
19625
  if (String(e).includes("UNIQUE") || String(e).includes("PRIMARY KEY")) throw new Error(`duplicate adaptation id: ${a.id}`);
18658
19626
  throw e;
18659
19627
  }
18660
19628
  }
18661
- getAdaptation(id) {
18662
- const row = this.db.prepare("SELECT * FROM adaptations WHERE id = ?").get(id);
19629
+ async getAdaptation(id) {
19630
+ this.ensureInit();
19631
+ const repo = this.ds.getRepository(Adaptation);
19632
+ const row = await repo.findOne({ where: { id } });
18663
19633
  if (!row) return void 0;
18664
19634
  return {
18665
19635
  id: row.id,
18666
- proposalId: row.proposal_id,
18667
- strategyVersion: row.strategy_version,
18668
- activationScope: row.activation_scope,
19636
+ proposalId: row.proposalId,
19637
+ strategyVersion: row.strategyVersion,
19638
+ activationScope: row.activationScope,
18669
19639
  status: row.status,
18670
- approvedBy: row.approved_by,
18671
- activatedAt: row.activated_at,
18672
- deactivatedAt: row.deactivated_at
19640
+ approvedBy: row.approvedBy,
19641
+ activatedAt: row.activatedAt,
19642
+ deactivatedAt: row.deactivatedAt
18673
19643
  };
18674
19644
  }
18675
- // Verifications
18676
- saveVerification(v) {
18677
- const stmt = this.db.prepare(`INSERT INTO verifications (id, adaptation_id, measurement, baseline, observed_outcome, comparison_context, conclusion, limitations, verified_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`);
19645
+ async saveVerification(v) {
19646
+ this.ensureInit();
19647
+ const repo = this.ds.getRepository(Verification);
18678
19648
  try {
18679
- stmt.run(
18680
- v.id,
18681
- v.adaptationId,
18682
- v.measurement,
18683
- v.baseline,
18684
- v.observedOutcome,
18685
- v.comparisonContext,
18686
- v.conclusion,
18687
- JSON.stringify(v.limitations ?? []),
18688
- v.verifiedAt
18689
- );
19649
+ await repo.insert({
19650
+ id: v.id,
19651
+ adaptationId: v.adaptationId,
19652
+ measurement: v.measurement,
19653
+ baseline: v.baseline,
19654
+ observedOutcome: v.observedOutcome,
19655
+ comparisonContext: v.comparisonContext,
19656
+ conclusion: v.conclusion,
19657
+ limitations: JSON.stringify(v.limitations ?? []),
19658
+ verifiedAt: v.verifiedAt
19659
+ });
18690
19660
  } catch (e) {
18691
19661
  if (String(e).includes("UNIQUE") || String(e).includes("PRIMARY KEY")) throw new Error(`duplicate verification id: ${v.id}`);
18692
19662
  throw e;
18693
19663
  }
18694
19664
  }
18695
- getVerification(id) {
18696
- const row = this.db.prepare("SELECT * FROM verifications WHERE id = ?").get(id);
19665
+ async getVerification(id) {
19666
+ this.ensureInit();
19667
+ const repo = this.ds.getRepository(Verification);
19668
+ const row = await repo.findOne({ where: { id } });
18697
19669
  if (!row) return void 0;
18698
19670
  return {
18699
19671
  id: row.id,
18700
- adaptationId: row.adaptation_id,
19672
+ adaptationId: row.adaptationId,
18701
19673
  measurement: row.measurement,
18702
19674
  baseline: row.baseline,
18703
- observedOutcome: row.observed_outcome,
18704
- comparisonContext: row.comparison_context,
19675
+ observedOutcome: row.observedOutcome,
19676
+ comparisonContext: row.comparisonContext,
18705
19677
  conclusion: row.conclusion,
18706
19678
  limitations: JSON.parse(row.limitations),
18707
- verifiedAt: row.verified_at
19679
+ verifiedAt: row.verifiedAt
18708
19680
  };
18709
19681
  }
18710
- close() {
19682
+ async close() {
18711
19683
  try {
18712
- this.db.close();
19684
+ await this.ds?.destroy();
18713
19685
  } catch {
18714
19686
  }
19687
+ this.ds = null;
19688
+ this.initialized = false;
18715
19689
  }
18716
19690
  getPath() {
18717
19691
  return this.dbPath;
18718
19692
  }
18719
19693
  };
18720
- createSqliteStore = /* @__PURE__ */ __name((dbPath) => new NeuroCoreSqliteStore(dbPath), "createSqliteStore");
19694
+ createSqliteStore = /* @__PURE__ */ __name(async (dbPath) => {
19695
+ const store7 = new NeuroCoreSqliteStore(dbPath);
19696
+ await store7.init();
19697
+ return store7;
19698
+ }, "createSqliteStore");
18721
19699
  }
18722
19700
  });
18723
19701
 
@@ -19190,7 +20168,7 @@ var init_handshake = __esm({
19190
20168
  const binding = candidate.authorityBinding;
19191
20169
  if (!binding || typeof binding !== "object") return null;
19192
20170
  if (binding.format !== "dotmem.authority-binding") return null;
19193
- if (binding.currentSpeakerBinding !== "trusted-hi" && binding.currentSpeakerBinding !== "unknown" && binding.currentSpeakerBinding !== "untrusted") return null;
20171
+ if (binding.currentSpeakerBinding !== "trusted-hi" && binding.currentSpeakerBinding !== "any" && binding.currentSpeakerBinding !== "untrusted") return null;
19194
20172
  if (binding.currentAuthorityBinding !== "BOUND" && binding.currentAuthorityBinding !== "UNBOUND") return null;
19195
20173
  if (typeof binding.requestedOperationalRole !== "string" || !binding.requestedOperationalRole) return null;
19196
20174
  return candidate;
@@ -19334,7 +20312,7 @@ __export(session_registry_exports, {
19334
20312
  sessionRegistry: () => sessionRegistry,
19335
20313
  updateSessionScope: () => updateSessionScope
19336
20314
  });
19337
- var SESSIONS_FILE, LEASE_MS, readAll3, writeAll3, nowIso3, parentDir2, registerSession, heartbeatSession, updateSessionScope, getSession, listActiveSessions, acknowledgeCursor, closeSession, reapExpiredSessions, sessionRegistry, session_registry_default;
20315
+ var SESSIONS_FILE, LEASE_MS, readAll3, writeAll3, nowIso4, parentDir2, registerSession, heartbeatSession, updateSessionScope, getSession, listActiveSessions, acknowledgeCursor, closeSession, reapExpiredSessions, sessionRegistry, session_registry_default;
19338
20316
  var init_session_registry = __esm({
19339
20317
  "core/memory/session-registry.ts"() {
19340
20318
  init_user_paths();
@@ -19363,29 +20341,29 @@ var init_session_registry = __esm({
19363
20341
  writeAll3 = /* @__PURE__ */ __name((items) => {
19364
20342
  const fs16 = getSyncFs();
19365
20343
  if (!fs16) return;
19366
- const path10 = SESSIONS_FILE();
19367
- const parent = path10.substring(0, Math.max(path10.lastIndexOf("/"), path10.lastIndexOf("\\")));
20344
+ const path11 = SESSIONS_FILE();
20345
+ const parent = path11.substring(0, Math.max(path11.lastIndexOf("/"), path11.lastIndexOf("\\")));
19368
20346
  try {
19369
20347
  fs16.mkdirSync(parent, { recursive: true });
19370
20348
  } catch {
19371
20349
  }
19372
- const tmp = `${path10}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
20350
+ const tmp = `${path11}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
19373
20351
  fs16.writeFileSync(tmp, JSON.stringify(items, null, 2));
19374
20352
  try {
19375
- if (fs16.existsSync(path10)) fs16.copyFileSync(path10, `${path10}.bak`);
20353
+ if (fs16.existsSync(path11)) fs16.copyFileSync(path11, `${path11}.bak`);
19376
20354
  } catch {
19377
20355
  }
19378
20356
  try {
19379
- fs16.renameSync(tmp, path10);
20357
+ fs16.renameSync(tmp, path11);
19380
20358
  } catch {
19381
- fs16.copyFileSync(tmp, path10);
20359
+ fs16.copyFileSync(tmp, path11);
19382
20360
  try {
19383
20361
  fs16.unlinkSync(tmp);
19384
20362
  } catch {
19385
20363
  }
19386
20364
  }
19387
20365
  }, "writeAll");
19388
- nowIso3 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
20366
+ nowIso4 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
19389
20367
  parentDir2 = /* @__PURE__ */ __name((p) => p.substring(0, Math.max(p.lastIndexOf("/"), p.lastIndexOf("\\"))), "parentDir");
19390
20368
  registerSession = /* @__PURE__ */ __name(async (input) => {
19391
20369
  const run = /* @__PURE__ */ __name(async () => {
@@ -19402,10 +20380,10 @@ var init_session_registry = __esm({
19402
20380
  projectId: input.projectId ?? null,
19403
20381
  dayKey: input.dayKey,
19404
20382
  status: "active",
19405
- startedAt: idx >= 0 ? items[idx].startedAt : input.startedAt ?? nowIso3(),
19406
- lastSeenAt: nowIso3(),
20383
+ startedAt: idx >= 0 ? items[idx].startedAt : input.startedAt ?? nowIso4(),
20384
+ lastSeenAt: nowIso4(),
19407
20385
  cursor: idx >= 0 ? items[idx].cursor : input.cursor ?? input.lastCursor ?? 0,
19408
- metadata: { ...idx >= 0 ? items[idx].metadata : {}, ...input.metadata ?? {} }
20386
+ metadata: { ...idx >= 0 ? items[idx].metadata : {}, ...input.metadata }
19409
20387
  };
19410
20388
  if (idx >= 0) items[idx] = rec;
19411
20389
  else items.push(rec);
@@ -19423,9 +20401,9 @@ var init_session_registry = __esm({
19423
20401
  const items = readAll3();
19424
20402
  const idx = items.findIndex((s) => s.sessionId === sessionId);
19425
20403
  if (idx < 0) return;
19426
- items[idx].lastSeenAt = nowIso3();
20404
+ items[idx].lastSeenAt = nowIso4();
19427
20405
  items[idx].status = "active";
19428
- if (metadata) items[idx].metadata = { ...items[idx].metadata ?? {}, ...metadata };
20406
+ if (metadata) items[idx].metadata = { ...items[idx].metadata, ...metadata };
19429
20407
  writeAll3(items);
19430
20408
  }, "run");
19431
20409
  try {
@@ -19446,7 +20424,7 @@ var init_session_registry = __esm({
19446
20424
  if (scope?.conversationId !== void 0) items[idx].conversationId = scope.conversationId;
19447
20425
  if (scope?.agentId !== void 0) items[idx].agentId = scope.agentId;
19448
20426
  if (scope?.dayKey !== void 0) items[idx].dayKey = scope.dayKey;
19449
- items[idx].lastSeenAt = nowIso3();
20427
+ items[idx].lastSeenAt = nowIso4();
19450
20428
  writeAll3(items);
19451
20429
  }, "run");
19452
20430
  try {
@@ -19481,7 +20459,7 @@ var init_session_registry = __esm({
19481
20459
  return;
19482
20460
  }
19483
20461
  items[idx].cursor = cursor;
19484
- items[idx].lastSeenAt = nowIso3();
20462
+ items[idx].lastSeenAt = nowIso4();
19485
20463
  writeAll3(items);
19486
20464
  }, "run");
19487
20465
  try {
@@ -19496,8 +20474,8 @@ var init_session_registry = __esm({
19496
20474
  const idx = items.findIndex((s) => s.sessionId === sessionId);
19497
20475
  if (idx < 0) return;
19498
20476
  items[idx].status = "closed";
19499
- items[idx].lastSeenAt = nowIso3();
19500
- if (reason) items[idx].metadata = { ...items[idx].metadata ?? {}, closeReason: reason };
20477
+ items[idx].lastSeenAt = nowIso4();
20478
+ if (reason) items[idx].metadata = { ...items[idx].metadata, closeReason: reason };
19501
20479
  writeAll3(items);
19502
20480
  }, "run");
19503
20481
  try {
@@ -19551,7 +20529,7 @@ __export(cross_chat_propagation_exports, {
19551
20529
  readCrossChatPropagationState: () => readCrossChatPropagationState,
19552
20530
  writeCrossChatPropagationState: () => writeCrossChatPropagationState
19553
20531
  });
19554
- var CROSS_CHAT_PROPAGATION_FILE_NAME, CROSS_CHAT_PROPAGATION_FORMAT_VERSION, emptyState, joinPath7, resolveFilePath, readRaw, writeRaw, validateState, readCrossChatPropagationState, writeCrossChatPropagationState, getCrossChatPropagationStatus, isCrossChatPropagationEnabled, getCrossChatPropagationChangeMarker;
20532
+ var CROSS_CHAT_PROPAGATION_FILE_NAME, CROSS_CHAT_PROPAGATION_FORMAT_VERSION, emptyState, joinPath8, resolveFilePath, readRaw, writeRaw, validateState, readCrossChatPropagationState, writeCrossChatPropagationState, getCrossChatPropagationStatus, isCrossChatPropagationEnabled, getCrossChatPropagationChangeMarker;
19555
20533
  var init_cross_chat_propagation = __esm({
19556
20534
  "core/continuity/cross-chat-propagation.ts"() {
19557
20535
  init_user_paths();
@@ -19563,12 +20541,12 @@ var init_cross_chat_propagation = __esm({
19563
20541
  configured: false,
19564
20542
  changeMarker: 0
19565
20543
  }), "emptyState");
19566
- joinPath7 = /* @__PURE__ */ __name((base, child) => {
20544
+ joinPath8 = /* @__PURE__ */ __name((base, child) => {
19567
20545
  const separator3 = process.platform === "win32" ? "\\" : "/";
19568
20546
  return `${base.replace(/[\\/]+/g, separator3)}${separator3}${child}`;
19569
20547
  }, "joinPath");
19570
20548
  resolveFilePath = /* @__PURE__ */ __name(() => {
19571
- return joinPath7(resolveUserDotMemPath(), CROSS_CHAT_PROPAGATION_FILE_NAME);
20549
+ return joinPath8(resolveUserDotMemPath(), CROSS_CHAT_PROPAGATION_FILE_NAME);
19572
20550
  }, "resolveFilePath");
19573
20551
  readRaw = /* @__PURE__ */ __name(async () => {
19574
20552
  const fs16 = await import('fs/promises');
@@ -19582,16 +20560,16 @@ var init_cross_chat_propagation = __esm({
19582
20560
  }, "readRaw");
19583
20561
  writeRaw = /* @__PURE__ */ __name(async (content) => {
19584
20562
  const fs16 = await import('fs/promises');
19585
- const path10 = resolveFilePath();
19586
- const dir = path10.replace(/[\\/][^\\/]+$/, "");
20563
+ const path11 = resolveFilePath();
20564
+ const dir = path11.replace(/[\\/][^\\/]+$/, "");
19587
20565
  await fs16.mkdir(dir, { recursive: true });
19588
- const temporary = `${path10}.${process.pid}.${Date.now().toString(36)}.tmp`;
20566
+ const temporary = `${path11}.${process.pid}.${Date.now().toString(36)}.tmp`;
19589
20567
  try {
19590
20568
  await fs16.writeFile(temporary, content, "utf8");
19591
- await fs16.rename(temporary, path10);
20569
+ await fs16.rename(temporary, path11);
19592
20570
  } catch {
19593
20571
  await fs16.rm(temporary, { force: true }).catch(() => void 0);
19594
- throw new Error(`Failed to write cross-chat propagation config at ${path10}`);
20572
+ throw new Error(`Failed to write cross-chat propagation config at ${path11}`);
19595
20573
  }
19596
20574
  }, "writeRaw");
19597
20575
  validateState = /* @__PURE__ */ __name((value) => {
@@ -19666,213 +20644,6 @@ var init_cross_chat_propagation = __esm({
19666
20644
  }
19667
20645
  });
19668
20646
 
19669
- // core/context-compiler/index.ts
19670
- var CHARS_PER_TOKEN, estimateTokens, DEFAULT_BUDGETS, dedupe, ContextCompiler, compileContext;
19671
- var init_context_compiler = __esm({
19672
- "core/context-compiler/index.ts"() {
19673
- CHARS_PER_TOKEN = 4;
19674
- estimateTokens = /* @__PURE__ */ __name((text) => Math.ceil((text || "").length / CHARS_PER_TOKEN), "estimateTokens");
19675
- DEFAULT_BUDGETS = {
19676
- identity: 0.1,
19677
- rules: 0.15,
19678
- conversationalState: 0.3,
19679
- retrievedKnowledge: 0.45
19680
- };
19681
- dedupe = /* @__PURE__ */ __name((items) => {
19682
- const seen = /* @__PURE__ */ new Set();
19683
- const result = [];
19684
- for (const item of items) {
19685
- const key = item.trim().toLowerCase();
19686
- if (seen.has(key)) continue;
19687
- seen.add(key);
19688
- result.push(item);
19689
- }
19690
- return result;
19691
- }, "dedupe");
19692
- ContextCompiler = class {
19693
- static {
19694
- __name(this, "ContextCompiler");
19695
- }
19696
- compile(input) {
19697
- const totalBudget = input.tokenBudget ?? 4096;
19698
- const totalChars = totalBudget * CHARS_PER_TOKEN;
19699
- const budgets = {
19700
- identity: Math.floor(totalChars * (input.categoryBudgets?.identity ?? DEFAULT_BUDGETS.identity)),
19701
- rules: Math.floor(totalChars * (input.categoryBudgets?.rules ?? DEFAULT_BUDGETS.rules)),
19702
- conversationalState: Math.floor(totalChars * (input.categoryBudgets?.conversationalState ?? DEFAULT_BUDGETS.conversationalState)),
19703
- retrievedKnowledge: Math.floor(totalChars * (input.categoryBudgets?.retrievedKnowledge ?? DEFAULT_BUDGETS.retrievedKnowledge))
19704
- };
19705
- const omissions = [];
19706
- const identityText = (input.identity ?? "").trim();
19707
- let identityUsed = 0;
19708
- const mandatoryParts = [];
19709
- if (identityText) {
19710
- if (identityText.length <= budgets.identity) {
19711
- mandatoryParts.push(identityText);
19712
- identityUsed = identityText.length;
19713
- } else {
19714
- omissions.push({
19715
- category: "identity",
19716
- whatWasOmitted: identityText,
19717
- whyOmitted: "token budget exceeded",
19718
- wouldBreakContinuity: true
19719
- });
19720
- }
19721
- }
19722
- const rules = input.rules ?? [];
19723
- const activeRules = [];
19724
- let rulesUsed = 0;
19725
- for (const rule of rules) {
19726
- if (rulesUsed + rule.length <= budgets.rules) {
19727
- activeRules.push(rule);
19728
- rulesUsed += rule.length;
19729
- } else {
19730
- omissions.push({
19731
- category: "rules",
19732
- whatWasOmitted: rule,
19733
- whyOmitted: "token budget exceeded",
19734
- wouldBreakContinuity: false
19735
- });
19736
- }
19737
- }
19738
- const state3 = input.conversationalState ?? null;
19739
- const mandatoryStateParts = [];
19740
- if (state3) {
19741
- if (state3.objective) mandatoryStateParts.push(`Objective: ${state3.objective}`);
19742
- if (state3.currentWorkingPosition) mandatoryStateParts.push(`Working position: ${state3.currentWorkingPosition}`);
19743
- if (state3.openLoops.length > 0) {
19744
- mandatoryStateParts.push(`Open loops: ${state3.openLoops.map((l) => l.description).join("; ")}`);
19745
- }
19746
- if (state3.rejectedApproaches.length > 0) {
19747
- mandatoryStateParts.push(`Rejected approaches: ${state3.rejectedApproaches.map((r) => `${r.approach} (${r.reason})`).join("; ")}`);
19748
- }
19749
- }
19750
- const activeParts = [];
19751
- if (state3) {
19752
- if (state3.currentProblem) activeParts.push(`Current problem: ${state3.currentProblem}`);
19753
- if (state3.establishedUnderstanding) activeParts.push(`Established understanding: ${state3.establishedUnderstanding}`);
19754
- if (state3.decisionsMade.length > 0) {
19755
- activeParts.push(`Decisions: ${state3.decisionsMade.map((d) => `${d.decision} (rationale: ${d.rationale})`).join("; ")}`);
19756
- }
19757
- if (state3.pendingDecisions.length > 0) {
19758
- activeParts.push(`Pending decisions: ${state3.pendingDecisions.map((d) => `${d.decision} [${d.options.join(", ")}]`).join("; ")}`);
19759
- }
19760
- if (state3.unresolvedQuestions.length > 0) {
19761
- activeParts.push(`Unresolved questions: ${state3.unresolvedQuestions.map((q) => q.question).join("; ")}`);
19762
- }
19763
- if (state3.reasoningTrajectory.length > 0) {
19764
- activeParts.push(`Reasoning trajectory: ${state3.reasoningTrajectory.map((r) => r.conclusion).join(" -> ")}`);
19765
- }
19766
- if (state3.nextConversationalStep) {
19767
- activeParts.push(`Next step: ${state3.nextConversationalStep}`);
19768
- }
19769
- if (state3.lastCompletedAction) {
19770
- activeParts.push(`Last completed action: ${state3.lastCompletedAction}`);
19771
- }
19772
- }
19773
- const dedupedActive = dedupe(activeParts.filter((part) => !mandatoryStateParts.includes(part)));
19774
- let stateUsed = 0;
19775
- const admittedMandatoryState = [];
19776
- const admittedActive = [];
19777
- for (const part of mandatoryStateParts) {
19778
- if (stateUsed + part.length <= budgets.conversationalState) {
19779
- admittedMandatoryState.push(part);
19780
- stateUsed += part.length;
19781
- } else {
19782
- omissions.push({
19783
- category: "conversationalState",
19784
- whatWasOmitted: part,
19785
- whyOmitted: "token budget exceeded",
19786
- wouldBreakContinuity: true
19787
- });
19788
- }
19789
- }
19790
- for (const part of dedupedActive) {
19791
- if (stateUsed + part.length <= budgets.conversationalState) {
19792
- admittedActive.push(part);
19793
- stateUsed += part.length;
19794
- } else {
19795
- omissions.push({
19796
- category: "conversationalState",
19797
- whatWasOmitted: part,
19798
- whyOmitted: "token budget exceeded",
19799
- wouldBreakContinuity: false
19800
- });
19801
- }
19802
- }
19803
- const refs = [...input.knowledgeReferences ?? []].sort((a, b) => b.relevance - a.relevance);
19804
- const retrievedParts = [];
19805
- let retrievedUsed = 0;
19806
- for (const ref of refs) {
19807
- const text2 = ref.summary ? `${ref.kind}:${ref.identifier} - ${ref.summary}` : `${ref.kind}:${ref.identifier}`;
19808
- if (retrievedUsed + text2.length <= budgets.retrievedKnowledge) {
19809
- retrievedParts.push(text2);
19810
- retrievedUsed += text2.length;
19811
- } else {
19812
- omissions.push({
19813
- category: "retrievedKnowledge",
19814
- whatWasOmitted: text2,
19815
- whyOmitted: "token budget exceeded",
19816
- wouldBreakContinuity: false
19817
- });
19818
- }
19819
- }
19820
- const optionalParts = [];
19821
- let optionalUsed = 0;
19822
- const remainingBudget = totalChars - (identityUsed + rulesUsed + stateUsed + retrievedUsed);
19823
- for (const item of input.historicalContext ?? []) {
19824
- if (optionalUsed + item.length <= remainingBudget) {
19825
- optionalParts.push(item);
19826
- optionalUsed += item.length;
19827
- } else {
19828
- omissions.push({
19829
- category: "historical",
19830
- whatWasOmitted: item,
19831
- whyOmitted: "token budget exceeded",
19832
- wouldBreakContinuity: false
19833
- });
19834
- }
19835
- }
19836
- const admittedSet = new Set([...mandatoryParts, ...admittedMandatoryState, ...admittedActive].map((s) => s.trim().toLowerCase()));
19837
- const isDuplicate = /* @__PURE__ */ __name((item) => {
19838
- const normalized = item.trim().toLowerCase();
19839
- for (const existing of admittedSet) {
19840
- if (existing.includes(normalized) || normalized.includes(existing)) return true;
19841
- }
19842
- return false;
19843
- }, "isDuplicate");
19844
- const finalRetrieved = dedupe(retrievedParts.filter((p) => !isDuplicate(p)));
19845
- const finalOptional = dedupe(optionalParts.filter((p) => !isDuplicate(p) && !finalRetrieved.includes(p)));
19846
- const mandatory = [...mandatoryParts, ...admittedMandatoryState].join("\n");
19847
- const active = [...admittedActive];
19848
- const retrieved = finalRetrieved;
19849
- const optional = finalOptional;
19850
- const text = [mandatory ? `## MANDATORY
19851
- ${mandatory}` : "", active.length ? `## ACTIVE
19852
- ${active.join("\n")}` : "", retrieved.length ? `## RETRIEVED
19853
- ${retrieved.join("\n")}` : "", optional.length ? `## OPTIONAL
19854
- ${optional.join("\n")}` : "", rules.length ? `## RULES
19855
- ${activeRules.join("\n")}` : ""].filter(Boolean).join("\n\n");
19856
- const budgetUsed = estimateTokens(text);
19857
- return {
19858
- mandatory,
19859
- active,
19860
- retrieved,
19861
- optional,
19862
- omissions,
19863
- budgetUsed,
19864
- budgetAvailable: totalBudget,
19865
- text
19866
- };
19867
- }
19868
- };
19869
- compileContext = /* @__PURE__ */ __name((input) => {
19870
- const compiler = new ContextCompiler();
19871
- return compiler.compile(input);
19872
- }, "compileContext");
19873
- }
19874
- });
19875
-
19876
20647
  // core/recovery-service/index.ts
19877
20648
  var RecoveryService;
19878
20649
  var init_recovery_service = __esm({
@@ -19965,7 +20736,7 @@ __export(consolidation_engine_exports, {
19965
20736
  consolidationEngine: () => consolidationEngine,
19966
20737
  getConsolidationEngine: () => getConsolidationEngine
19967
20738
  });
19968
- var DEFAULT_CONFIG3, nowIso4, generateId2, normalizeText2, tokenize3, jaccardSimilarity2, detectOutcome, detectConditions, isDoNotRemember, CONSOLIDATION_STORE_KEY, ConsolidationPersistence, ConsolidationEngine, defaultEngine, getConsolidationEngine, consolidationEngine;
20739
+ var DEFAULT_CONFIG3, nowIso5, generateId2, normalizeText2, tokenize3, jaccardSimilarity2, detectOutcome, detectConditions, isDoNotRemember, CONSOLIDATION_STORE_KEY, ConsolidationPersistence, ConsolidationEngine, defaultEngine, getConsolidationEngine, consolidationEngine;
19969
20740
  var init_consolidation_engine = __esm({
19970
20741
  "core/memory/consolidation-engine.ts"() {
19971
20742
  init_durable_store();
@@ -19976,7 +20747,7 @@ var init_consolidation_engine = __esm({
19976
20747
  similarityThreshold: 0.5,
19977
20748
  minConfidenceForConsolidated: 0.7
19978
20749
  };
19979
- nowIso4 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
20750
+ nowIso5 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
19980
20751
  generateId2 = /* @__PURE__ */ __name(() => `cons-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`, "generateId");
19981
20752
  normalizeText2 = /* @__PURE__ */ __name((text) => {
19982
20753
  return text.normalize("NFKC").toLocaleLowerCase("en-US").replace(/[^\w\s]/g, " ").replace(/\s+/g, " ").trim();
@@ -20001,7 +20772,7 @@ var init_consolidation_engine = __esm({
20001
20772
  if (/if |when |only when|provided that|as long as/i.test(lower)) return "conditional";
20002
20773
  if (/succ(eed|ess)|works|passed|completed|resolved|fixed/i.test(lower)) return "success";
20003
20774
  if (category === "decision") return "success";
20004
- return "unknown";
20775
+ return "any";
20005
20776
  }, "detectOutcome");
20006
20777
  detectConditions = /* @__PURE__ */ __name((statement) => {
20007
20778
  const conditions = [];
@@ -20078,7 +20849,7 @@ var init_consolidation_engine = __esm({
20078
20849
  new DurableMemoryStore({
20079
20850
  filePath: `${resolveUserDotMemPath()}/consolidation-records.kv`,
20080
20851
  storeKey: CONSOLIDATION_STORE_KEY,
20081
- tenantId: this.tenantId
20852
+ tenantId: this.tenantId ?? void 0
20082
20853
  })
20083
20854
  );
20084
20855
  }
@@ -20195,7 +20966,7 @@ var init_consolidation_engine = __esm({
20195
20966
  }
20196
20967
  /** Create a new consolidation record from a group of experiences. */
20197
20968
  async createRecordFromGroup(group) {
20198
- const now3 = nowIso4();
20969
+ const now3 = nowIso5();
20199
20970
  const evidence = group.experiences.map((e) => ({
20200
20971
  experienceId: e.id,
20201
20972
  statement: e.statement,
@@ -20213,7 +20984,7 @@ var init_consolidation_engine = __esm({
20213
20984
  const outcomes = uniqueEvidence.map((e) => e.outcome);
20214
20985
  const hasFailure = outcomes.includes("failure");
20215
20986
  const hasSuccess = outcomes.includes("success");
20216
- const hasUnknown = outcomes.includes("unknown");
20987
+ const hasUnknown = outcomes.includes("any");
20217
20988
  const hasConditional = outcomes.includes("conditional");
20218
20989
  let lifecycleState = "pending";
20219
20990
  if (uniqueEvidence.length < this.config.minExperiencesForAcquired) {
@@ -20229,7 +21000,7 @@ var init_consolidation_engine = __esm({
20229
21000
  applicability["conditions"] = conditions.join("; ");
20230
21001
  }
20231
21002
  const limitations = [];
20232
- if (hasUnknown) limitations.push("Outcome unknown for some experiences");
21003
+ if (hasUnknown) limitations.push("Outcome any for some experiences");
20233
21004
  if (hasConditional) limitations.push("Success is conditional on specific circumstances");
20234
21005
  if (uniqueEvidence.length < this.config.minExperiencesForConsolidated) {
20235
21006
  limitations.push(`Only ${uniqueEvidence.length} supporting experience(s); ${this.config.minExperiencesForConsolidated} required for consolidation`);
@@ -20272,7 +21043,7 @@ var init_consolidation_engine = __esm({
20272
21043
  async updateRecordWithEvidence(record, newExperiences) {
20273
21044
  const newExpIds = newExperiences.map((e) => e.id).filter((id) => !record.supportingExperiences.includes(id));
20274
21045
  if (newExpIds.length === 0) return null;
20275
- const now3 = nowIso4();
21046
+ const now3 = nowIso5();
20276
21047
  const newEvidence = newExperiences.filter((e) => !record.supportingExperiences.includes(e.id)).map((e) => ({
20277
21048
  experienceId: e.id,
20278
21049
  statement: e.statement,
@@ -20330,7 +21101,7 @@ var init_consolidation_engine = __esm({
20330
21101
  if (record.doNotRemember) return false;
20331
21102
  const uniqueEvidence = this.deduplicateEvidence([...record.supportingEvidence, ...record.contradictingEvidence]);
20332
21103
  if (record.lifecycleState === "acquired" && uniqueEvidence.length >= this.config.minExperiencesForConsolidated && record.confidence >= this.config.minConfidenceForConsolidated && record.contradictingEvidence.length === 0) {
20333
- const now3 = nowIso4();
21104
+ const now3 = nowIso5();
20334
21105
  const promoted = {
20335
21106
  ...record,
20336
21107
  lifecycleState: "consolidated",
@@ -20352,7 +21123,7 @@ var init_consolidation_engine = __esm({
20352
21123
  return true;
20353
21124
  }
20354
21125
  if (record.lifecycleState === "insufficient_evidence" && uniqueEvidence.length >= this.config.minExperiencesForAcquired) {
20355
- const now3 = nowIso4();
21126
+ const now3 = nowIso5();
20356
21127
  const promoted = {
20357
21128
  ...record,
20358
21129
  lifecycleState: "acquired",
@@ -20392,7 +21163,7 @@ var init_consolidation_engine = __esm({
20392
21163
  a.history.push({
20393
21164
  from: a.lifecycleState,
20394
21165
  to: "conflicting",
20395
- at: nowIso4(),
21166
+ at: nowIso5(),
20396
21167
  reason: `Contradiction detected with record ${b.id}`
20397
21168
  });
20398
21169
  await this.persistence.saveRecord(a);
@@ -20420,11 +21191,11 @@ var init_consolidation_engine = __esm({
20420
21191
  if (evidence.length === 0) return 0;
20421
21192
  const successes = evidence.filter((e) => e.outcome === "success").length;
20422
21193
  const failures = evidence.filter((e) => e.outcome === "failure").length;
20423
- const unknowns = evidence.filter((e) => e.outcome === "unknown").length;
21194
+ const anys = evidence.filter((e) => e.outcome === "any").length;
20424
21195
  const conditionals = evidence.filter((e) => e.outcome === "conditional").length;
20425
21196
  let confidence = evidence.length > 0 ? successes / evidence.length : 0;
20426
- if (unknowns > 0) {
20427
- confidence *= 1 - unknowns / (evidence.length * 2);
21197
+ if (anys > 0) {
21198
+ confidence *= 1 - anys / (evidence.length * 2);
20428
21199
  }
20429
21200
  if (conditionals > 0) {
20430
21201
  confidence *= 0.9;
@@ -20440,14 +21211,14 @@ var init_consolidation_engine = __esm({
20440
21211
  buildConfidenceJustification(evidence, confidence) {
20441
21212
  const successes = evidence.filter((e) => e.outcome === "success").length;
20442
21213
  const failures = evidence.filter((e) => e.outcome === "failure").length;
20443
- const unknowns = evidence.filter((e) => e.outcome === "unknown").length;
20444
- return `Based on ${evidence.length} unique experience(s): ${successes} success, ${failures} failure, ${unknowns} unknown. Confidence: ${confidence}`;
21214
+ const anys = evidence.filter((e) => e.outcome === "any").length;
21215
+ return `Based on ${evidence.length} unique experience(s): ${successes} success, ${failures} failure, ${anys} any. Confidence: ${confidence}`;
20445
21216
  }
20446
21217
  /** Build limitations list. */
20447
21218
  buildLimitations(evidence, confidence) {
20448
21219
  const limitations = [];
20449
- const unknowns = evidence.filter((e) => e.outcome === "unknown").length;
20450
- if (unknowns > 0) limitations.push(`${unknowns} experience(s) with unknown outcome`);
21220
+ const anys = evidence.filter((e) => e.outcome === "any").length;
21221
+ if (anys > 0) limitations.push(`${anys} experience(s) with any outcome`);
20451
21222
  const conditionals = evidence.filter((e) => e.outcome === "conditional").length;
20452
21223
  if (conditionals > 0) limitations.push(`${conditionals} experience(s) with conditional success`);
20453
21224
  if (confidence < 0.5) limitations.push("Low confidence due to insufficient or conflicting evidence");
@@ -20462,7 +21233,7 @@ var init_consolidation_engine = __esm({
20462
21233
  const record = this.records.get(id);
20463
21234
  if (!record) throw new Error(`Record not found: ${id}`);
20464
21235
  if (record.doNotRemember) throw new Error(`Cannot promote do-not-remember record: ${id}`);
20465
- const now3 = nowIso4();
21236
+ const now3 = nowIso5();
20466
21237
  const promoted = {
20467
21238
  ...record,
20468
21239
  lifecycleState: "consolidated",
@@ -20488,7 +21259,7 @@ var init_consolidation_engine = __esm({
20488
21259
  await this.load();
20489
21260
  const record = this.records.get(id);
20490
21261
  if (!record) throw new Error(`Record not found: ${id}`);
20491
- const now3 = nowIso4();
21262
+ const now3 = nowIso5();
20492
21263
  const superseded = {
20493
21264
  ...record,
20494
21265
  lifecycleState: "superseded",
@@ -20513,7 +21284,7 @@ var init_consolidation_engine = __esm({
20513
21284
  await this.load();
20514
21285
  const record = this.records.get(id);
20515
21286
  if (!record) throw new Error(`Record not found: ${id}`);
20516
- const now3 = nowIso4();
21287
+ const now3 = nowIso5();
20517
21288
  const invalidated = {
20518
21289
  ...record,
20519
21290
  lifecycleState: "invalidated",
@@ -20538,7 +21309,7 @@ var init_consolidation_engine = __esm({
20538
21309
  await this.load();
20539
21310
  const record = this.records.get(id);
20540
21311
  if (!record) throw new Error(`Record not found: ${id}`);
20541
- const now3 = nowIso4();
21312
+ const now3 = nowIso5();
20542
21313
  const reassessed = {
20543
21314
  ...record,
20544
21315
  lifecycleState: "reassessment_required",
@@ -20611,20 +21382,20 @@ __export(session_bootstrap_exports, {
20611
21382
  bootstrapSession: () => bootstrapSession,
20612
21383
  createSessionBootstrap: () => createSessionBootstrap
20613
21384
  });
20614
- var nowIso5, defaultSubject, bootstrapSession, createSessionBootstrap;
21385
+ var nowIso6, defaultSubject, bootstrapSession, createSessionBootstrap;
20615
21386
  var init_session_bootstrap = __esm({
20616
21387
  "core/memory/session-bootstrap.ts"() {
20617
21388
  init_discover();
20618
21389
  init_project();
20619
- init_rules_loader();
21390
+ init_rule_enforcement();
20620
21391
  init_context_constants();
20621
21392
  init_context_compiler();
20622
21393
  init_conversational_state();
20623
21394
  init_recovery_service();
20624
- nowIso5 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
21395
+ nowIso6 = /* @__PURE__ */ __name(() => (/* @__PURE__ */ new Date()).toISOString(), "nowIso");
20625
21396
  defaultSubject = "__default__";
20626
21397
  bootstrapSession = /* @__PURE__ */ __name(async (options = {}) => {
20627
- 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;
21398
+ 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;
20628
21399
  const scopes = {
20629
21400
  userId,
20630
21401
  projectId,
@@ -20682,6 +21453,7 @@ var init_session_bootstrap = __esm({
20682
21453
  let rulesCount = 0;
20683
21454
  let rulesSignature = "";
20684
21455
  let consolidatedKnowledge = [];
21456
+ let enforcementRules = [];
20685
21457
  try {
20686
21458
  const dynamicMemory = await Promise.resolve().then(() => (init_memory(), memory_exports));
20687
21459
  const state3 = await dynamicMemory.loadCombinedKnowledgeState();
@@ -20699,9 +21471,12 @@ var init_session_bootstrap = __esm({
20699
21471
  relevance: 1
20700
21472
  });
20701
21473
  }
20702
- const rules = loadIronRules(state3).rules;
20703
- rulesCount = rules.length;
20704
- rulesSignature = ruleSetSignature(rules);
21474
+ try {
21475
+ enforcementRules = await resolveApplicableRules(situation ?? "", scope);
21476
+ rulesCount = enforcementRules.length;
21477
+ rulesSignature = enforcementRules.map((r) => `${r.id}\0${r.text}`).join("");
21478
+ } catch {
21479
+ }
20705
21480
  try {
20706
21481
  const { consolidationEngine: consolidationEngine2 } = await Promise.resolve().then(() => (init_consolidation_engine(), consolidation_engine_exports));
20707
21482
  await consolidationEngine2.load();
@@ -20731,7 +21506,7 @@ var init_session_bootstrap = __esm({
20731
21506
  }
20732
21507
  const context2 = compileContext({
20733
21508
  conversationalState: recovery?.context?.conversationalState,
20734
- rules: inputRules,
21509
+ rules: enforcementRules.map((r) => `[${r.source.toUpperCase()}] ${r.text}` + (r.appliesWhen ? ` (quando: ${r.appliesWhen})` : "")),
20735
21510
  knowledgeReferences: knowledgeReferences.map((r) => ({
20736
21511
  id: r.id,
20737
21512
  kind: r.kind,
@@ -21109,11 +21884,11 @@ var init_memory = __esm({
21109
21884
  const byTrust = {};
21110
21885
  const byArea = {};
21111
21886
  for (const claim of state3.claims ?? []) {
21112
- const scope = claim.scope ?? "unknown";
21887
+ const scope = claim.scope ?? "any";
21113
21888
  byScope[scope] = (byScope[scope] || 0) + 1;
21114
- const trust = claim.trustBasis ?? "unknown";
21889
+ const trust = claim.trustBasis ?? "any";
21115
21890
  byTrust[trust] = (byTrust[trust] || 0) + 1;
21116
- const area = claim.applicability?.area ?? "unknown";
21891
+ const area = claim.applicability?.area ?? "any";
21117
21892
  byArea[area] = (byArea[area] || 0) + 1;
21118
21893
  }
21119
21894
  return { total: (state3.claims ?? []).length, byScope, byTrust, byArea };
@@ -21223,7 +21998,7 @@ var init_memory = __esm({
21223
21998
  const ids = [];
21224
21999
  for (const stmt of statements) {
21225
22000
  const id = await acquire.acquire({
21226
- knowledge: { hypothesis: stmt, situation: context2?.situation },
22001
+ knowledge: { hypothesis: stmt, ...context2?.situation !== void 0 ? { situation: context2.situation } : {} },
21227
22002
  applicability: context2?.applicability ?? { area: "hypothesis" },
21228
22003
  evidence: [{ id: `hyp-${Date.now()}`, source: "tree-of-thoughts", observedAt: (/* @__PURE__ */ new Date()).toISOString() }],
21229
22004
  epistemicType: "inferred",
@@ -21269,7 +22044,7 @@ var init_memory = __esm({
21269
22044
  },
21270
22045
  async learnFromFailure(claimId, failure, correction) {
21271
22046
  return acquire.acquire({
21272
- knowledge: { failedClaim: claimId, failure, correction },
22047
+ knowledge: { failedClaim: claimId, failure, ...correction !== void 0 ? { correction } : {} },
21273
22048
  applicability: { area: "continual-learning", kind: "correction" },
21274
22049
  evidence: [{ id: `fail-${Date.now()}`, source: "experience", observedAt: (/* @__PURE__ */ new Date()).toISOString() }],
21275
22050
  epistemicType: "observed",
@@ -21284,7 +22059,7 @@ var init_memory = __esm({
21284
22059
  const state3 = await loadCombinedKnowledgeState();
21285
22060
  const groups = {};
21286
22061
  for (const c of state3.claims ?? []) {
21287
- const area = c.applicability?.area ?? "unknown";
22062
+ const area = c.applicability?.area ?? "any";
21288
22063
  if (!groups[area]) groups[area] = [];
21289
22064
  groups[area].push(c.id);
21290
22065
  }
@@ -21354,7 +22129,7 @@ var init_memory = __esm({
21354
22129
  });
21355
22130
  const lines = ["Autobiography:"];
21356
22131
  for (const c of claims) {
21357
- const area = c.applicability?.area ?? "unknown";
22132
+ const area = c.applicability?.area ?? "any";
21358
22133
  lines.push(`- [${c.acquiredAt ?? "?"}] (${area}) ${JSON.stringify(c.knowledge).slice(0, 120)}`);
21359
22134
  }
21360
22135
  return lines.join("\n");