@kenhkl/agent-moss 0.17.23 → 0.17.25

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.
@@ -442,22 +442,22 @@ function loadToolRegistry() {
442
442
  data.tools = tools;
443
443
  return data;
444
444
  }
445
- function scanStructEntry(cat, value, path6) {
445
+ function scanStructEntry(cat, value, path7) {
446
446
  if (cat === "skills") {
447
447
  if (!value || typeof value !== "object" || Array.isArray(value)) {
448
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 skills \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u7C7B\u522B: {\u6280\u80FD\u540D: [\u5173\u952E\u8BCD]}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
448
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 skills \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u7C7B\u522B: {\u6280\u80FD\u540D: [\u5173\u952E\u8BCD]}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
449
449
  return null;
450
450
  }
451
451
  const out = {};
452
452
  for (const [skCat, skills] of Object.entries(value)) {
453
453
  if (!skills || typeof skills !== "object" || Array.isArray(skills)) {
454
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 skills.${skCat} \u5E94\u4E3A\u5BF9\u8C61\uFF08\u6280\u80FD\u540D \u2192 \u5173\u952E\u8BCD\u6570\u7EC4\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
454
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 skills.${skCat} \u5E94\u4E3A\u5BF9\u8C61\uFF08\u6280\u80FD\u540D \u2192 \u5173\u952E\u8BCD\u6570\u7EC4\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
455
455
  continue;
456
456
  }
457
457
  const keep = {};
458
458
  for (const [name, kws] of Object.entries(skills)) {
459
459
  if (Array.isArray(kws)) keep[name] = kws;
460
- else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 skills.${skCat}.${name} \u5173\u952E\u8BCD\u4E0D\u662F\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
460
+ else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 skills.${skCat}.${name} \u5173\u952E\u8BCD\u4E0D\u662F\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
461
461
  }
462
462
  if (Object.keys(keep).length > 0) out[skCat] = keep;
463
463
  }
@@ -465,37 +465,37 @@ function scanStructEntry(cat, value, path6) {
465
465
  }
466
466
  if (cat === "ltl_rules") {
467
467
  if (!Array.isArray(value)) {
468
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 ltl_rules \u5E94\u4E3A\u5BF9\u8C61\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
468
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 ltl_rules \u5E94\u4E3A\u5BF9\u8C61\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
469
469
  return null;
470
470
  }
471
471
  const keep = value.filter((r) => r && typeof r === "object" && r.id);
472
472
  if (keep.length !== value.length) {
473
- console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 ltl_rules \u6709\u6761\u76EE\u7F3A id \u6216\u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
473
+ console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 ltl_rules \u6709\u6761\u76EE\u7F3A id \u6216\u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
474
474
  }
475
475
  return keep.length > 0 ? keep : null;
476
476
  }
477
477
  if (cat === "tools") {
478
478
  if (!value || typeof value !== "object" || Array.isArray(value)) {
479
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 tools \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u5DE5\u5177\u540D: {actionClass, ...}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
479
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 tools \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u5DE5\u5177\u540D: {actionClass, ...}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
480
480
  return null;
481
481
  }
482
482
  const keep = {};
483
483
  for (const [k, v] of Object.entries(value)) {
484
484
  if (v && typeof v === "object" && !Array.isArray(v)) keep[k] = v;
485
- else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684 tools.${k} \u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
485
+ else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684 tools.${k} \u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
486
486
  }
487
487
  return Object.keys(keep).length > 0 ? keep : null;
488
488
  }
489
489
  return null;
490
490
  }
491
- function scanRulesFile(path6, kind) {
491
+ function scanRulesFile(path7, kind) {
492
492
  const out = {};
493
493
  const label = kind === "override" ? "\u8986\u76D6" : "\u8FFD\u52A0";
494
494
  let parsed;
495
495
  try {
496
- parsed = JSON.parse(readFileSync2(path6, "utf-8"));
496
+ parsed = JSON.parse(readFileSync2(path7, "utf-8"));
497
497
  } catch (e) {
498
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u635F\u574F/\u4E0D\u53EF\u8BFB\uFF0C\u5DF2\u8DF3\u8FC7\uFF08${kind} \u89C4\u5219\u4E0D\u751F\u6548\uFF09: ${e.message}`);
498
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u635F\u574F/\u4E0D\u53EF\u8BFB\uFF0C\u5DF2\u8DF3\u8FC7\uFF08${kind} \u89C4\u5219\u4E0D\u751F\u6548\uFF09: ${e.message}`);
499
499
  return out;
500
500
  }
501
501
  const classifyFlat = (r) => {
@@ -519,44 +519,44 @@ function scanRulesFile(path6, kind) {
519
519
  }
520
520
  if (flatBad > 0) {
521
521
  console.warn(
522
- `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u6709 ${flatBad} \u6761\u5E73\u94FA\u6761\u76EE\u65E0\u6CD5\u5F52\u7C7B\uFF08\u88F8 pattern \u4E0D\u5E26 risk_level/risk_type \u65F6\u533A\u5206\u4E0D\u4E86 L1 \u5371\u9669\u547D\u4EE4\u4E0E L2 \u6388\u6743\u7C7B\uFF09\u2014\u2014 \u8BF7\u6539\u7528\u5BF9\u8C61\u5F62\u5F0F\uFF1A{"\u7C7B\u522B\u952E": [\u6761\u76EE...]}\u3002`
522
+ `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u6709 ${flatBad} \u6761\u5E73\u94FA\u6761\u76EE\u65E0\u6CD5\u5F52\u7C7B\uFF08\u88F8 pattern \u4E0D\u5E26 risk_level/risk_type \u65F6\u533A\u5206\u4E0D\u4E86 L1 \u5371\u9669\u547D\u4EE4\u4E0E L2 \u6388\u6743\u7C7B\uFF09\u2014\u2014 \u8BF7\u6539\u7528\u5BF9\u8C61\u5F62\u5F0F\uFF1A{"\u7C7B\u522B\u952E": [\u6761\u76EE...]}\u3002`
523
523
  );
524
524
  }
525
525
  } else {
526
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u9876\u5C42\u5E94\u662F\u5BF9\u8C61\uFF08\u7C7B\u522B\u952E\u2192\u6761\u76EE\u6570\u7EC4\uFF09\u6216\u6570\u7EC4\uFF0C\u5DF2\u8DF3\u8FC7\u3002`);
526
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u9876\u5C42\u5E94\u662F\u5BF9\u8C61\uFF08\u7C7B\u522B\u952E\u2192\u6761\u76EE\u6570\u7EC4\uFF09\u6216\u6570\u7EC4\uFF0C\u5DF2\u8DF3\u8FC7\u3002`);
527
527
  return out;
528
528
  }
529
529
  for (const [cat, rules] of pairs) {
530
530
  if (String(cat).startsWith("_")) continue;
531
531
  if (STRUCT_KEYS.includes(cat)) {
532
- const got = scanStructEntry(cat, rules, path6);
532
+ const got = scanStructEntry(cat, rules, path7);
533
533
  if (got !== null) out[cat] = got;
534
534
  continue;
535
535
  }
536
536
  const required = EXTRA_CATEGORIES[cat];
537
537
  if (!required) {
538
538
  console.warn(
539
- `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u542B\u672A\u77E5\u7C7B\u522B\u952E "${cat}"\uFF08\u53EF\u7528\uFF1A${Object.keys(EXTRA_CATEGORIES).join(", ")}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`
539
+ `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u542B\u672A\u77E5\u7C7B\u522B\u952E "${cat}"\uFF08\u53EF\u7528\uFF1A${Object.keys(EXTRA_CATEGORIES).join(", ")}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`
540
540
  );
541
541
  continue;
542
542
  }
543
543
  if (rules && typeof rules === "object" && !Array.isArray(rules)) {
544
544
  console.error(
545
- `[AgentMoss] \u274C \u89C4\u5219\u6587\u4EF6 ${path6} \u7684\u7C7B\u522B "${cat}" \u662F**\u5BF9\u8C61**\uFF0C\u5E94\u4E3A**\u5BF9\u8C61\u6570\u7EC4** \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002
545
+ `[AgentMoss] \u274C \u89C4\u5219\u6587\u4EF6 ${path7} \u7684\u7C7B\u522B "${cat}" \u662F**\u5BF9\u8C61**\uFF0C\u5E94\u4E3A**\u5BF9\u8C61\u6570\u7EC4** \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002
546
546
  \u6B63\u786E\u5199\u6CD5: {"${cat}": [{"pattern": "...", "risk_level": "high", ...}]}
547
547
  \u4F60\u5199\u7684\u50CF\u662F runtime config \u7684\u683C\u5F0F\uFF08{"category_enabled": ..., "rules": [...]}\uFF09\u2014\u2014\u90A3\u662F ~/.config/agentmoss/agent_moss_runtime.json \u7684\u683C\u5F0F\uFF0C\u4E0D\u80FD\u76F4\u63A5\u5F53\u89C4\u5219\u6587\u4EF6\u7528\u3002`
548
548
  );
549
549
  continue;
550
550
  }
551
551
  if (!Array.isArray(rules)) {
552
- console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7684\u7C7B\u522B "${cat}" \u5E94\u4E3A\u6570\u7EC4\uFF0C\u5B9E\u9645\u662F ${typeof rules} \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
552
+ console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7684\u7C7B\u522B "${cat}" \u5E94\u4E3A\u6570\u7EC4\uFF0C\u5B9E\u9645\u662F ${typeof rules} \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
553
553
  continue;
554
554
  }
555
555
  const items = [];
556
556
  for (const r of rules) {
557
557
  if (!r || typeof r !== "object" || !required.every((k) => r[k])) {
558
558
  console.warn(
559
- `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path6} \u7C7B\u522B ${cat} \u6709\u6761\u76EE\u7F3A\u5FC5\u9700\u5B57\u6BB5 [${required.join(", ")}] \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`
559
+ `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path7} \u7C7B\u522B ${cat} \u6709\u6761\u76EE\u7F3A\u5FC5\u9700\u5B57\u6BB5 [${required.join(", ")}] \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`
560
560
  );
561
561
  continue;
562
562
  }
@@ -566,7 +566,7 @@ function scanRulesFile(path6, kind) {
566
566
  }
567
567
  if (Object.keys(out).length > 0) {
568
568
  console.info(
569
- `[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${path6}\uFF1A` + Object.entries(out).map(([k, v]) => `${k}\xD7${v.length}`).join(", ")
569
+ `[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${path7}\uFF1A` + Object.entries(out).map(([k, v]) => `${k}\xD7${v.length}`).join(", ")
570
570
  );
571
571
  }
572
572
  return out;
@@ -941,6 +941,8 @@ var init_platform_traits = __esm({
941
941
 
942
942
  // src/engine/logic-rules.ts
943
943
  import * as fs from "fs";
944
+ import * as path2 from "path";
945
+ import * as os from "os";
944
946
  function hasExecBypassChain(actionDetail) {
945
947
  const execAfter = "&&|\\|\\||;|\\n|\\|";
946
948
  return />\s*[/~]\S*\.(sh|py|pl|rb)\b/.test(actionDetail) && new RegExp(`(?:${execAfter})\\s*(?:bash|sh|zsh|dash|python|perl|ruby|node)`).test(actionDetail) || /\|\s*(?:bash|sh|zsh|dash|python|perl|ruby|node|crontab|at)\b/.test(actionDetail);
@@ -967,7 +969,7 @@ function _loadSensitivePathScope(scope, osType = "linux") {
967
969
  os: String(sp.os || "linux").toLowerCase()
968
970
  }));
969
971
  }
970
- function _scopeOf(os3, path6) {
972
+ function _scopeOf(os4, path7) {
971
973
  if (!_scopeIndex) {
972
974
  _scopeIndex = /* @__PURE__ */ new Map();
973
975
  for (const sp of loadL1().sensitive_path_access || []) {
@@ -975,7 +977,7 @@ function _scopeOf(os3, path6) {
975
977
  if (!_scopeIndex.has(key)) _scopeIndex.set(key, sp.scope);
976
978
  }
977
979
  }
978
- return _scopeIndex.get(`${String(os3 || "linux").toLowerCase()}|${path6}`) || "root";
980
+ return _scopeIndex.get(`${String(os4 || "linux").toLowerCase()}|${path7}`) || "root";
979
981
  }
980
982
  function getSensitivePathsForOs(osType) {
981
983
  const effective = runtimeConfigBridge.current?.effectiveSensitivePaths(osType);
@@ -1017,6 +1019,188 @@ function getSensitivePathsForOsBuiltin(osType) {
1017
1019
  }
1018
1020
  return { root: ROOT_SENSITIVE_PATHS, home: HOME_SENSITIVE_PATHS, credential: CREDENTIAL_PATHS };
1019
1021
  }
1022
+ function declaredWritePaths(actionDetailRaw, osType) {
1023
+ const m = actionDetailRaw.match(DECLARED_WRITE_PATH_RE);
1024
+ if (m) return [m[1]];
1025
+ const j = actionDetailRaw.match(DECLARED_WRITE_PATH_JSON_RE);
1026
+ if (j) return [j[1]];
1027
+ return extractFilePaths(actionDetailRaw, osType).slice(0, 1);
1028
+ }
1029
+ function normalizePathForCompare(p, cwd) {
1030
+ if (!p) return p;
1031
+ let expanded = p;
1032
+ if (expanded === "~" || expanded.startsWith("~/") || expanded.startsWith("~\\")) {
1033
+ expanded = os.homedir() + expanded.slice(1);
1034
+ }
1035
+ if (!path2.isAbsolute(expanded) && cwd) expanded = path2.join(cwd, expanded);
1036
+ return path2.normalize(expanded);
1037
+ }
1038
+ function pathIsSameOrUnder(p, base) {
1039
+ if (!p || !base) return false;
1040
+ if (p === base) return true;
1041
+ return p.startsWith(base.replace(/[\\/]+$/, "") + path2.sep);
1042
+ }
1043
+ function isProtectedWritePath(p) {
1044
+ if (!p) return false;
1045
+ if (PROTECTED_WRITE_PREFIXES.some((prefix) => p.startsWith(prefix))) return true;
1046
+ const home = os.homedir();
1047
+ if (home && (p === home || p.startsWith(home + path2.sep))) {
1048
+ const rel = p.slice(home.length).replace(/^[\\/]+/, "");
1049
+ const first = rel.split(/[\\/]/)[0] || "";
1050
+ return PROTECTED_HOME_ENTRIES.has(first);
1051
+ }
1052
+ return false;
1053
+ }
1054
+ function historyCommandText(histDetailRaw) {
1055
+ const text = histDetailRaw.trim();
1056
+ if (text.startsWith("{")) {
1057
+ try {
1058
+ const obj = JSON.parse(text);
1059
+ if (obj && typeof obj === "object") {
1060
+ for (const key of ["command", "cmd"]) {
1061
+ if (typeof obj[key] === "string" && obj[key].trim()) return obj[key];
1062
+ }
1063
+ }
1064
+ } catch {
1065
+ }
1066
+ }
1067
+ return histDetailRaw;
1068
+ }
1069
+ function parseHeadTailLimit(seg) {
1070
+ const firstWord = seg.trim().split(/\s+/)[0]?.toLowerCase() || "";
1071
+ if (firstWord !== "head" && firstWord !== "tail") return null;
1072
+ const m = seg.match(HEAD_TAIL_LIMIT_RE);
1073
+ return m ? Number(m[1]) : 10;
1074
+ }
1075
+ function parseHeadTailLimitForPipeline(segments) {
1076
+ for (const rawSeg of segments) {
1077
+ const seg = rawSeg.trim();
1078
+ if (!seg) continue;
1079
+ if (seg.startsWith("head") || seg.startsWith("tail")) return parseHeadTailLimit(seg);
1080
+ }
1081
+ return null;
1082
+ }
1083
+ function historyReadCoverage(histType, histDetailRaw, readKeywords, writeKeywords) {
1084
+ const full = /* @__PURE__ */ new Set();
1085
+ const partial = /* @__PURE__ */ new Map();
1086
+ const addPartial = (paths, upto) => {
1087
+ for (const p of paths) {
1088
+ if (partial.has(p)) {
1089
+ const old = partial.get(p);
1090
+ partial.set(p, old == null || upto == null ? null : Math.max(old, upto));
1091
+ } else {
1092
+ partial.set(p, upto);
1093
+ }
1094
+ }
1095
+ };
1096
+ if (writeKeywords.some((kw) => histType.includes(kw))) return { full, partial };
1097
+ if (histType === "bash" || histType === "executebash" || histType === "terminal-executebash") {
1098
+ const segments = splitCommandSegments(historyCommandText(histDetailRaw));
1099
+ const words = segments.map((s) => s.trim().split(/\s+/)[0]?.toLowerCase() || "").filter(Boolean);
1100
+ const hasTruncatingPipe = words.some((w) => SHELL_TRUNCATING_CMDS.has(w));
1101
+ for (const rawSeg of segments) {
1102
+ const seg = rawSeg.trim();
1103
+ if (!seg) continue;
1104
+ const firstWord = seg.split(/\s+/)[0]?.toLowerCase() || "";
1105
+ const paths = extractFilePaths(seg);
1106
+ if (paths.length === 0) continue;
1107
+ if (SHELL_FULL_READ_CMDS.includes(firstWord)) {
1108
+ if (hasTruncatingPipe) addPartial(paths, parseHeadTailLimitForPipeline(segments));
1109
+ else for (const p of paths) full.add(p);
1110
+ } else if (firstWord === "head" || firstWord === "tail") {
1111
+ addPartial(paths, parseHeadTailLimit(seg));
1112
+ } else if (SHELL_PARTIAL_READ_CMDS.includes(firstWord)) {
1113
+ addPartial(paths, null);
1114
+ } else if (firstWord === "sed") {
1115
+ if (SED_INPLACE_RE.test(seg)) continue;
1116
+ const m = seg.match(SED_RANGE_RE);
1117
+ if (m) {
1118
+ if (m[2] === "$" && m[1] === "1") for (const p of paths) full.add(p);
1119
+ else addPartial(paths, null);
1120
+ } else {
1121
+ for (const p of paths) full.add(p);
1122
+ }
1123
+ }
1124
+ }
1125
+ return { full, partial };
1126
+ }
1127
+ let offset;
1128
+ let limit;
1129
+ const detail = histDetailRaw.trim();
1130
+ if (detail.startsWith("{")) {
1131
+ try {
1132
+ const obj = JSON.parse(detail);
1133
+ if (obj && typeof obj === "object") {
1134
+ offset = obj.offset;
1135
+ limit = obj.limit;
1136
+ }
1137
+ } catch {
1138
+ }
1139
+ }
1140
+ if (histType.includes("read")) {
1141
+ if (offset != null || limit != null) {
1142
+ const off = typeof offset === "number" ? offset : Number(offset) || 1;
1143
+ const lim = typeof limit === "number" ? limit : limit != null ? Number(limit) || null : null;
1144
+ const upto = off === 1 && lim != null ? off + lim - 1 : null;
1145
+ addPartial(extractFilePaths(detail), upto);
1146
+ } else {
1147
+ for (const p of extractFilePaths(detail)) full.add(p);
1148
+ }
1149
+ } else if (histType.includes("grep") || histType.includes("search")) {
1150
+ addPartial(extractFilePaths(detail), null);
1151
+ } else if (histType.includes("glob") || histType.includes("list")) {
1152
+ } else if (readKeywords.some((kw) => histType.includes(kw))) {
1153
+ addPartial(extractFilePaths(detail), null);
1154
+ }
1155
+ return { full, partial };
1156
+ }
1157
+ function fileHasAtMostLines(filePath, limit) {
1158
+ if (limit <= 0 || limit > PARTIAL_COVER_CHECK_MAX_LINES) return false;
1159
+ try {
1160
+ const fd = fs.openSync(filePath, "r");
1161
+ try {
1162
+ const buf = Buffer.alloc(64 * 1024);
1163
+ let lines = 0;
1164
+ for (; ; ) {
1165
+ const n = fs.readSync(fd, buf, 0, buf.length, null);
1166
+ if (n <= 0) break;
1167
+ for (let i = 0; i < n; i++) {
1168
+ if (buf[i] === 10) {
1169
+ lines++;
1170
+ if (lines > limit) return false;
1171
+ }
1172
+ }
1173
+ }
1174
+ return true;
1175
+ } finally {
1176
+ fs.closeSync(fd);
1177
+ }
1178
+ } catch {
1179
+ return false;
1180
+ }
1181
+ }
1182
+ function appendOnlyTargets(actionDetailRaw, osType) {
1183
+ const out = /* @__PURE__ */ new Set();
1184
+ for (const rawSeg of splitCommandSegments(actionDetailRaw)) {
1185
+ const seg = rawSeg.trim();
1186
+ if (!seg) continue;
1187
+ const segNoAppend = seg.replace(new RegExp(APPEND_REDIRECT_SOURCE, "g"), " ");
1188
+ const segNoQuotes = segNoAppend.replace(/'[^']*'|"[^"]*"/g, "");
1189
+ const hasOverwrite = /(?<![/\-=>])>\s*(?!&)\S/.test(segNoQuotes);
1190
+ if (hasOverwrite) continue;
1191
+ const re = new RegExp(APPEND_REDIRECT_SOURCE, "g");
1192
+ let m;
1193
+ while ((m = re.exec(seg)) !== null) {
1194
+ const p = m[1] || m[2] || m[3];
1195
+ if (p) out.add(p);
1196
+ }
1197
+ const firstWord = seg.split(/\s+/)[0]?.toLowerCase() || "";
1198
+ if (firstWord === "tee" && /(?:^|\s)(?:-a|--append)(?:\s|$)/.test(seg)) {
1199
+ for (const p of extractFilePaths(seg, osType)) out.add(p);
1200
+ }
1201
+ }
1202
+ return out;
1203
+ }
1020
1204
  function isWriteOperation(actionType, actionDetail, writeKeywords = WRITE_KEYWORDS, osType) {
1021
1205
  if (writeKeywords.some((kw) => actionType.includes(kw) || actionDetail.includes(kw))) return true;
1022
1206
  const { writeCommandRes } = getPlatformTraits(osType);
@@ -1056,7 +1240,12 @@ function isWriteOperation(actionType, actionDetail, writeKeywords = WRITE_KEYWOR
1056
1240
  }
1057
1241
  function getIntentPatternsForOs(osType) {
1058
1242
  const effective = runtimeConfigBridge.current?.effectiveIntentPatterns(osType);
1059
- if (effective) return effective;
1243
+ if (effective) {
1244
+ return effective.map((p) => ({
1245
+ ...p,
1246
+ allowIfWriteIntent: p.allowIfWriteIntent ?? INTENT_DEVIATION_PATTERNS.find((d) => d.reason === p.reason)?.allowIfWriteIntent ?? false
1247
+ }));
1248
+ }
1060
1249
  const accepted = acceptedOsValues(osType);
1061
1250
  return INTENT_DEVIATION_PATTERNS.filter((p) => accepted.includes(p.os));
1062
1251
  }
@@ -1107,6 +1296,9 @@ function checkIntentConsistency(input) {
1107
1296
  );
1108
1297
  const dangerousMatched = pattern.dangerousActions.some((kw) => matchDangerousAction(actionDetail, kw));
1109
1298
  if (intentMatched && dangerousMatched) {
1299
+ if (pattern.allowIfWriteIntent && intentTexts.some((text) => WRITE_INTENT_KEYWORDS.some((kw) => text.includes(kw)))) {
1300
+ continue;
1301
+ }
1110
1302
  return {
1111
1303
  allowed: false,
1112
1304
  reason: pattern.reason,
@@ -1127,7 +1319,16 @@ function runLogicCheck(input, opts) {
1127
1319
  const resolvedCwd = cwd || "/";
1128
1320
  const isExcludedType = EXCLUDED_PREFIXES.some((p) => actionType.startsWith(p));
1129
1321
  if (!opts?.skipReadBeforeWrite) {
1130
- const rbwResult = checkReadBeforeWrite(actionType, actionDetail, actionHistory, input.reason, resolvedCwd, input.osType);
1322
+ const singleFileTools = opts?.agentExt?.extra_single_file_write_tools?.length ? /* @__PURE__ */ new Set([...SINGLE_FILE_WRITE_TOOLS, ...opts.agentExt.extra_single_file_write_tools]) : SINGLE_FILE_WRITE_TOOLS;
1323
+ const rbwResult = checkReadBeforeWrite(
1324
+ actionType,
1325
+ aNext.actionDetail,
1326
+ actionHistory,
1327
+ input.reason,
1328
+ resolvedCwd,
1329
+ input.osType,
1330
+ singleFileTools
1331
+ );
1131
1332
  if (rbwResult) return rbwResult;
1132
1333
  }
1133
1334
  const intentResult = checkIntentConsistency(input);
@@ -1230,7 +1431,8 @@ function extractFilePaths(text, osType) {
1230
1431
  }
1231
1432
  return [...new Set(paths)];
1232
1433
  }
1233
- function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, cwd, osType) {
1434
+ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason, cwd, osType, singleFileTools = SINGLE_FILE_WRITE_TOOLS) {
1435
+ const actionDetail = actionDetailRaw.toLowerCase();
1234
1436
  if (NON_WRITE_TOOL_PREFIXES.some((p) => actionType.startsWith(p))) return null;
1235
1437
  if (NON_WRITE_TOOLS.has(actionType)) return null;
1236
1438
  const isBashLike = actionType === "bash" || actionType === "executebash" || actionType === "terminal-executebash";
@@ -1271,7 +1473,11 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
1271
1473
  const SOURCE_ARG_CMDS = new Set(_LOGIC.source_arg_commands ?? []);
1272
1474
  const REDIRECT_TARGET_RE = new RegExp(`>{1,2}\\s*(?!&)(?:'(/[^']+)'|"(/[^\\"]+)"|(/[^\\s;|&><'\\"]+))`);
1273
1475
  const targetPaths = [];
1274
- for (const seg of splitCommandSegments(actionDetail)) {
1476
+ const singleFileTool = singleFileTools.has(actionType);
1477
+ if (singleFileTool && MISSING_WRITE_PATH_RE.test(actionDetailRaw)) {
1478
+ return null;
1479
+ }
1480
+ for (const seg of singleFileTool ? [] : splitCommandSegments(actionDetailRaw)) {
1275
1481
  const trimmed = seg.trim();
1276
1482
  if (!trimmed) continue;
1277
1483
  const firstWord = trimmed.split(/\s+/)[0]?.toLowerCase() || "";
@@ -1303,16 +1509,31 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
1303
1509
  targetPaths.push(...segPathsFiltered);
1304
1510
  }
1305
1511
  }
1512
+ if (singleFileTool) {
1513
+ targetPaths.length = 0;
1514
+ targetPaths.push(...declaredWritePaths(actionDetailRaw, osType));
1515
+ }
1306
1516
  const uniqueTargetPaths = [...new Set(targetPaths)].filter((p) => !PSEUDO_FS_PREFIXES.some((pfx) => p.startsWith(pfx)));
1307
1517
  if (uniqueTargetPaths.length === 0) return null;
1308
- const historyReadPaths = /* @__PURE__ */ new Set();
1518
+ const historyFullReadPaths = /* @__PURE__ */ new Set();
1519
+ const historyPartialRead = /* @__PURE__ */ new Map();
1309
1520
  for (const action of actionHistory) {
1310
- const histDetail = action.actionDetail.toLowerCase();
1521
+ const histDetailRaw = action.actionDetail;
1311
1522
  const histType = action.actionType.toLowerCase();
1312
- const isRead = getPlatformTraits(osType).readKeywords.some((kw) => histType.includes(kw) || histDetail.includes(kw));
1313
- if (isRead) {
1314
- for (const p of extractFilePaths(histDetail, osType)) {
1315
- historyReadPaths.add(p);
1523
+ const traits = getPlatformTraits(osType);
1524
+ const coverage = historyReadCoverage(
1525
+ histType,
1526
+ histDetailRaw,
1527
+ traits.readKeywords,
1528
+ traits.writeKeywords
1529
+ );
1530
+ for (const p of coverage.full) historyFullReadPaths.add(p);
1531
+ for (const [p, upto] of coverage.partial) {
1532
+ if (historyPartialRead.has(p)) {
1533
+ const old = historyPartialRead.get(p);
1534
+ historyPartialRead.set(p, old == null || upto == null ? null : Math.max(old, upto));
1535
+ } else {
1536
+ historyPartialRead.set(p, upto);
1316
1537
  }
1317
1538
  }
1318
1539
  }
@@ -1325,18 +1546,49 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
1325
1546
  if (filteredPaths.length === 0) {
1326
1547
  return null;
1327
1548
  }
1549
+ const normalizedTargets = filteredPaths.map((p) => normalizePathForCompare(p, cwd)).filter((p, i, arr) => p && arr.indexOf(p) === i);
1550
+ const normalizedFullReads = new Set(
1551
+ [...historyFullReadPaths].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
1552
+ );
1553
+ const normalizedPartialReads = /* @__PURE__ */ new Map();
1554
+ for (const [p, upto] of historyPartialRead) {
1555
+ const np = normalizePathForCompare(p, cwd);
1556
+ if (np) normalizedPartialReads.set(np, upto);
1557
+ }
1558
+ const appendTargets = appendOnlyTargets(actionDetailRaw, osType);
1559
+ if (APPEND_MODE_RE.test(actionDetailRaw)) {
1560
+ for (const p of filteredPaths) appendTargets.add(p);
1561
+ }
1562
+ let checkTargets = normalizedTargets;
1563
+ if (appendTargets.size > 0) {
1564
+ const appendNorm = new Set(
1565
+ [...appendTargets].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
1566
+ );
1567
+ checkTargets = normalizedTargets.filter((p) => !([...appendNorm].some((ap) => pathIsSameOrUnder(p, ap) || pathIsSameOrUnder(ap, p)) && !isProtectedWritePath(p)));
1568
+ if (checkTargets.length === 0) return null;
1569
+ }
1328
1570
  const unreadPaths = [];
1329
- for (const path6 of filteredPaths) {
1330
- const hasRead = [...historyReadPaths].some(
1331
- (rp) => path6 === rp || path6.startsWith(rp) || rp.startsWith(path6)
1571
+ for (const path7 of checkTargets) {
1572
+ const isFullRead = [...normalizedFullReads].some(
1573
+ (rp) => pathIsSameOrUnder(path7, rp) || pathIsSameOrUnder(rp, path7)
1332
1574
  );
1333
- if (!hasRead) {
1334
- let isCreate = !fs.existsSync(path6);
1575
+ let isPartialCovered = false;
1576
+ if (!isFullRead) {
1577
+ for (const [pp, upto] of normalizedPartialReads) {
1578
+ if (!(pathIsSameOrUnder(path7, pp) || pathIsSameOrUnder(pp, path7))) continue;
1579
+ if (upto != null && fileHasAtMostLines(path7, upto)) {
1580
+ isPartialCovered = true;
1581
+ break;
1582
+ }
1583
+ }
1584
+ }
1585
+ if (!isFullRead && !isPartialCovered) {
1586
+ let isCreate = !fs.existsSync(path7);
1335
1587
  if (!isCreate) {
1336
1588
  isCreate = CREATE_KEYWORDS.some((kw) => reason.toLowerCase().includes(kw) || actionDetail.includes(kw));
1337
1589
  }
1338
1590
  if (!isCreate) {
1339
- unreadPaths.push(path6);
1591
+ unreadPaths.push(path7);
1340
1592
  }
1341
1593
  }
1342
1594
  }
@@ -1513,7 +1765,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
1513
1765
  violatedLayers: ["L2.1"]
1514
1766
  };
1515
1767
  }
1516
- var _LOGIC, _HEURISTIC, EXCLUDED_PREFIXES, TEMP_DIRS, ALL_QUOTES_RE, ROOT_SENSITIVE_PATHS, HOME_SENSITIVE_PATHS, CREDENTIAL_PATHS, ROOT_SENSITIVE_PATHS_WINDOWS, HOME_SENSITIVE_PATHS_WINDOWS, CREDENTIAL_PATHS_WINDOWS, ROOT_SENSITIVE_PATHS_MACOS, HOME_SENSITIVE_PATHS_MACOS, CREDENTIAL_PATHS_MACOS, ROOT_SENSITIVE_PATHS_HARMONY, HOME_SENSITIVE_PATHS_HARMONY, CREDENTIAL_PATHS_HARMONY, _scopeIndex, NON_WRITE_TOOLS, NON_WRITE_TOOL_PREFIXES, PSEUDO_FS_PREFIXES, WRITE_KEYWORDS, SED_INPLACE_RE, DEVNULL_REDIRECT_RE, CREATE_KEYWORDS, PASSWORD_MODIFY_PATTERNS, USER_DELETION_PATTERNS, INTENT_DEVIATION_PATTERNS, COMBO_STAGES, COMBO_CHAINS, CONSENT_TOPIC, CONSENT_NEGATIVE, CONSENT_AFFIRMATIVE, CONSENT_INPUT_REQUEST, CONSENT_MAX_DISTANCE, CONSENT_TTL_SECONDS, BASH_LIKE_ACTION_TYPES, ASK_USER_ACTION_TYPES, INLINE_SCRIPT_RE, DIR_TRAVERSAL_KW, _IFA, IFA_READ_KEYWORDS, IFA_WRITE_KEYWORDS, IFA_EXEC_KEYWORDS, IFA_OPEN_KEYWORDS;
1768
+ var _LOGIC, _HEURISTIC, EXCLUDED_PREFIXES, TEMP_DIRS, ALL_QUOTES_RE, ROOT_SENSITIVE_PATHS, HOME_SENSITIVE_PATHS, CREDENTIAL_PATHS, ROOT_SENSITIVE_PATHS_WINDOWS, HOME_SENSITIVE_PATHS_WINDOWS, CREDENTIAL_PATHS_WINDOWS, ROOT_SENSITIVE_PATHS_MACOS, HOME_SENSITIVE_PATHS_MACOS, CREDENTIAL_PATHS_MACOS, ROOT_SENSITIVE_PATHS_HARMONY, HOME_SENSITIVE_PATHS_HARMONY, CREDENTIAL_PATHS_HARMONY, _scopeIndex, NON_WRITE_TOOLS, NON_WRITE_TOOL_PREFIXES, PSEUDO_FS_PREFIXES, SINGLE_FILE_WRITE_TOOLS, WRITE_INTENT_KEYWORDS, MISSING_WRITE_PATH_RE, DECLARED_WRITE_PATH_RE, DECLARED_WRITE_PATH_JSON_RE, PROTECTED_WRITE_PREFIXES, PROTECTED_HOME_ENTRIES, APPEND_REDIRECT_SOURCE, APPEND_MODE_RE, SHELL_FULL_READ_CMDS, SHELL_PARTIAL_READ_CMDS, SHELL_TRUNCATING_CMDS, HEAD_TAIL_LIMIT_RE, SED_RANGE_RE, PARTIAL_COVER_CHECK_MAX_LINES, WRITE_KEYWORDS, SED_INPLACE_RE, DEVNULL_REDIRECT_RE, CREATE_KEYWORDS, PASSWORD_MODIFY_PATTERNS, USER_DELETION_PATTERNS, INTENT_DEVIATION_PATTERNS, COMBO_STAGES, COMBO_CHAINS, CONSENT_TOPIC, CONSENT_NEGATIVE, CONSENT_AFFIRMATIVE, CONSENT_INPUT_REQUEST, CONSENT_MAX_DISTANCE, CONSENT_TTL_SECONDS, BASH_LIKE_ACTION_TYPES, ASK_USER_ACTION_TYPES, INLINE_SCRIPT_RE, DIR_TRAVERSAL_KW, _IFA, IFA_READ_KEYWORDS, IFA_WRITE_KEYWORDS, IFA_EXEC_KEYWORDS, IFA_OPEN_KEYWORDS;
1517
1769
  var init_logic_rules = __esm({
1518
1770
  "src/engine/logic-rules.ts"() {
1519
1771
  "use strict";
@@ -1530,16 +1782,16 @@ var init_logic_rules = __esm({
1530
1782
  ALL_QUOTES_RE = /'[^']*'|"[^"]*"/g;
1531
1783
  ROOT_SENSITIVE_PATHS = _loadSensitivePathScope("root");
1532
1784
  HOME_SENSITIVE_PATHS = _loadSensitivePathScope("home");
1533
- CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path6, riskLevel, desc, dirDelOnly }) => ({ path: path6, riskLevel, desc, credential: true, dirDelOnly }));
1785
+ CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
1534
1786
  ROOT_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("root", "windows");
1535
1787
  HOME_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("home", "windows");
1536
- CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path6, riskLevel, desc, dirDelOnly }) => ({ path: path6, riskLevel, desc, credential: true, dirDelOnly }));
1788
+ CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
1537
1789
  ROOT_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("root", "macos");
1538
1790
  HOME_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("home", "macos");
1539
- CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path6, riskLevel, desc, dirDelOnly }) => ({ path: path6, riskLevel, desc, credential: true, dirDelOnly }));
1791
+ CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
1540
1792
  ROOT_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("root", "harmony");
1541
1793
  HOME_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("home", "harmony");
1542
- CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path6, riskLevel, desc, dirDelOnly }) => ({ path: path6, riskLevel, desc, credential: true, dirDelOnly }));
1794
+ CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
1543
1795
  _scopeIndex = null;
1544
1796
  NON_WRITE_TOOLS = /* @__PURE__ */ new Set([
1545
1797
  "ask_user_question",
@@ -1562,6 +1814,23 @@ var init_logic_rules = __esm({
1562
1814
  ]);
1563
1815
  NON_WRITE_TOOL_PREFIXES = _LOGIC.non_write_tool_prefixes ?? [];
1564
1816
  PSEUDO_FS_PREFIXES = ["/sys/", "/proc/", "/dev/", "/run/"];
1817
+ SINGLE_FILE_WRITE_TOOLS = new Set(
1818
+ _LOGIC.single_file_write_tools ?? []
1819
+ );
1820
+ WRITE_INTENT_KEYWORDS = _LOGIC.write_intent_keywords ?? [];
1821
+ MISSING_WRITE_PATH_RE = /(?:写入文件|编辑文件|写入|编辑)\s*[::]\s*\?/;
1822
+ DECLARED_WRITE_PATH_RE = /(?:写入文件|编辑文件|应用补丁|写入|编辑)\s*[::]\s*([~./][^\s—|,;]+)/;
1823
+ DECLARED_WRITE_PATH_JSON_RE = /"(?:file_path|filePath|path)"\s*:\s*"([^"]+)"/;
1824
+ PROTECTED_WRITE_PREFIXES = _LOGIC.protected_write_prefixes ?? [];
1825
+ PROTECTED_HOME_ENTRIES = new Set(_LOGIC.protected_home_entries ?? []);
1826
+ APPEND_REDIRECT_SOURCE = String.raw`(?<!>)>{2}(?!>)\s*(?!&)(?:'([^']+)'|"([^"]+)"|([^\s;|&><'"]+))`;
1827
+ APPEND_MODE_RE = /\(\s*追加\s*\)|(\s*追加\s*)|"mode"\s*:\s*"append"/i;
1828
+ SHELL_FULL_READ_CMDS = ["cat", "less", "more", "view", "open", "load"];
1829
+ SHELL_PARTIAL_READ_CMDS = ["head", "tail", "grep", "egrep", "fgrep", "rg", "awk"];
1830
+ SHELL_TRUNCATING_CMDS = new Set(SHELL_PARTIAL_READ_CMDS);
1831
+ HEAD_TAIL_LIMIT_RE = /(?:-n\s*|-\s*)(\d+)/;
1832
+ SED_RANGE_RE = /-n\s+['"]?(\d+)\s*,\s*(\d+|\$)\s*p/;
1833
+ PARTIAL_COVER_CHECK_MAX_LINES = 1e5;
1565
1834
  WRITE_KEYWORDS = ["write", "\u5199\u5165", "save", "\u4FDD\u5B58", "modify", "\u4FEE\u6539", "update", "\u66F4\u65B0", "delete", "\u5220\u9664", "remove", "\u79FB\u9664", "create", "\u521B\u5EFA", "append", "\u8FFD\u52A0", "truncate", "\u622A\u65AD", "overwrite", "\u8986\u76D6", "replace", "\u66FF\u6362", "edit"];
1566
1835
  SED_INPLACE_RE = /\bsed\s+(?:-\S+\s+)*(?:-[a-zA-Z]*i[a-zA-Z]*|--in-place)\b/i;
1567
1836
  DEVNULL_REDIRECT_RE = /(?:2|&|1)?\s*>\s*\/dev\/null\b/g;
@@ -1580,7 +1849,8 @@ var init_logic_rules = __esm({
1580
1849
  intentKeywords: p.intent_keywords,
1581
1850
  dangerousActions: p.dangerous_actions,
1582
1851
  reason: p.reason,
1583
- os: String(p.os || "linux").toLowerCase()
1852
+ os: String(p.os || "linux").toLowerCase(),
1853
+ allowIfWriteIntent: p.allow_if_write_intent === true
1584
1854
  }));
1585
1855
  })();
1586
1856
  COMBO_STAGES = (() => {
@@ -1621,11 +1891,11 @@ var init_logic_rules = __esm({
1621
1891
 
1622
1892
  // src/engine/asset-dir.ts
1623
1893
  import { existsSync as existsSync3 } from "fs";
1624
- import { join as join3, resolve as resolve2 } from "path";
1894
+ import { join as join4, resolve as resolve2 } from "path";
1625
1895
  function assetDirCandidates(moduleDir, name) {
1626
1896
  const root = getRulesRoot();
1627
1897
  if (root) {
1628
- const p = join3(root, name);
1898
+ const p = join4(root, name);
1629
1899
  return [p, p];
1630
1900
  }
1631
1901
  return [
@@ -1844,7 +2114,7 @@ __export(runtime_config_exports, {
1844
2114
  updateSkillEnabled: () => updateSkillEnabled
1845
2115
  });
1846
2116
  import { readFileSync as readFileSync4, writeFileSync, existsSync as existsSync5, mkdirSync, unlinkSync, readdirSync as readdirSync4, statSync as statSync2 } from "fs";
1847
- import { join as join4 } from "path";
2117
+ import { join as join5 } from "path";
1848
2118
  import { fileURLToPath as fileURLToPath4 } from "url";
1849
2119
  import { dirname as dirname3 } from "path";
1850
2120
  function runtimeDir() {
@@ -1980,8 +2250,8 @@ function filterEnabledRules(rules, categoryEnabled = true) {
1980
2250
  function _filterRulesByOs(rules, osType) {
1981
2251
  const accepted = acceptedOsValues(osType);
1982
2252
  return rules.filter((r) => {
1983
- const os3 = String(r.os || "linux").toLowerCase();
1984
- return os3 === "all" || accepted.includes(os3);
2253
+ const os4 = String(r.os || "linux").toLowerCase();
2254
+ return os4 === "all" || accepted.includes(os4);
1985
2255
  });
1986
2256
  }
1987
2257
  function _userCustomRules(runtime, layers, requiredKey) {
@@ -2183,7 +2453,7 @@ function _l2SensitivePathsToRules() {
2183
2453
  const { root, home, credential } = getSensitivePathsForOsBuiltin(osName);
2184
2454
  const all = [...root, ...home, ...credential];
2185
2455
  for (const sp of all) {
2186
- const os3 = String(sp.os || "linux").toLowerCase();
2456
+ const os4 = String(sp.os || "linux").toLowerCase();
2187
2457
  const denyMode = sp.denyMode || _deriveDenyMode({
2188
2458
  deny_mode: sp.deny_mode,
2189
2459
  credential: sp.credential,
@@ -2193,7 +2463,7 @@ function _l2SensitivePathsToRules() {
2193
2463
  // id = path_<平台>_<slug>_<hash8>:平台段消除跨平台同名(.ssh/.aws 各一条),
2194
2464
  // hash 段消除同平台 slug 撞车(macOS 的 /Library/LaunchAgents 与
2195
2465
  // Library/LaunchAgents)—— Console 按 id 操作,撞 id 会误改别的规则。
2196
- id: `path_${os3}_${_slugify(sp.path)}_${_fnv1a32(sp.path)}`,
2466
+ id: `path_${os4}_${_slugify(sp.path)}_${_fnv1a32(sp.path)}`,
2197
2467
  path: sp.path,
2198
2468
  risk_level: sp.riskLevel,
2199
2469
  desc: sp.desc,
@@ -2202,7 +2472,7 @@ function _l2SensitivePathsToRules() {
2202
2472
  skip_l3_on_disabled: true,
2203
2473
  enabled: true,
2204
2474
  builtin: true,
2205
- os: os3
2475
+ os: os4
2206
2476
  };
2207
2477
  _syncDenyModeFields(rule);
2208
2478
  if (sp.dirDelOnly) rule.dir_del_only = true;
@@ -2220,6 +2490,9 @@ function _l2IntentPatternsToRules() {
2220
2490
  intent_keywords: pat.intentKeywords,
2221
2491
  dangerous_actions: pat.dangerousActions,
2222
2492
  reason: pat.reason,
2493
+ // 旧 runtime 里没有这个字段:缺省 false,但 getIntentPatternsForOs 会按
2494
+ // reason 回填内置默认值,避免旧配置让新豁免失效。
2495
+ allow_if_write_intent: pat.allowIfWriteIntent,
2223
2496
  skip_l3_on_disabled: true,
2224
2497
  enabled: true,
2225
2498
  builtin: true
@@ -2290,7 +2563,7 @@ function _l3SkillsToRules() {
2290
2563
  function _scenarioRulesToDefaults() {
2291
2564
  const out = {};
2292
2565
  const _root = getRulesRoot();
2293
- const scenDir = _root ? join4(_root, "scenarios") : existsSync5(_SCENARIOS_DIR_PROD) ? _SCENARIOS_DIR_PROD : existsSync5(_SCENARIOS_DIR_DEV) ? _SCENARIOS_DIR_DEV : _SCENARIOS_DIR_PROD;
2566
+ const scenDir = _root ? join5(_root, "scenarios") : existsSync5(_SCENARIOS_DIR_PROD) ? _SCENARIOS_DIR_PROD : existsSync5(_SCENARIOS_DIR_DEV) ? _SCENARIOS_DIR_DEV : _SCENARIOS_DIR_PROD;
2294
2567
  if (!existsSync5(scenDir)) return out;
2295
2568
  let entries;
2296
2569
  try {
@@ -2299,7 +2572,7 @@ function _scenarioRulesToDefaults() {
2299
2572
  return out;
2300
2573
  }
2301
2574
  for (const scenarioId of entries) {
2302
- const rulesFile = resolveScenarioRulesFile(scenarioId) ?? join4(scenDir, scenarioId, "rules.json");
2575
+ const rulesFile = resolveScenarioRulesFile(scenarioId) ?? join5(scenDir, scenarioId, "rules.json");
2303
2576
  if (!existsSync5(rulesFile)) continue;
2304
2577
  let data;
2305
2578
  try {
@@ -2340,7 +2613,7 @@ function _scenarioRulesToDefaults() {
2340
2613
  function _agentRulesToDefaults() {
2341
2614
  const out = {};
2342
2615
  const _root = getRulesRoot();
2343
- const agentsDir = _root ? join4(_root, "agents") : existsSync5(_AGENTS_DIR_PROD) ? _AGENTS_DIR_PROD : existsSync5(_AGENTS_DIR_DEV) ? _AGENTS_DIR_DEV : _AGENTS_DIR_PROD;
2616
+ const agentsDir = _root ? join5(_root, "agents") : existsSync5(_AGENTS_DIR_PROD) ? _AGENTS_DIR_PROD : existsSync5(_AGENTS_DIR_DEV) ? _AGENTS_DIR_DEV : _AGENTS_DIR_PROD;
2344
2617
  if (!existsSync5(agentsDir)) return out;
2345
2618
  let entries;
2346
2619
  try {
@@ -2349,7 +2622,7 @@ function _agentRulesToDefaults() {
2349
2622
  return out;
2350
2623
  }
2351
2624
  for (const agentId of entries) {
2352
- const rulesFile = join4(agentsDir, agentId, "rules.json");
2625
+ const rulesFile = join5(agentsDir, agentId, "rules.json");
2353
2626
  if (!existsSync5(rulesFile)) continue;
2354
2627
  let data;
2355
2628
  try {
@@ -2382,6 +2655,11 @@ function _agentRulesToDefaults() {
2382
2655
  category_enabled: true,
2383
2656
  category_desc: "agent \u4E13\u5C5E\u654F\u611F\u8DEF\u5F84\uFF08L1 \u672B\u5C3E\u8FFD\u52A0\uFF09",
2384
2657
  rules: (data.extra_sensitive_paths || []).map((sp) => ({ ...sp, enabled: true, builtin: true }))
2658
+ },
2659
+ extra_single_file_write_tools: {
2660
+ category_enabled: true,
2661
+ category_desc: "agent \u4E13\u5C5E\u5355\u6587\u4EF6\u5199\u5DE5\u5177\uFF08read_before_write \u53EA\u53D6\u58F0\u660E\u8DEF\u5F84\uFF09",
2662
+ rules: (data.extra_single_file_write_tools || []).map((v) => ({ value: v, enabled: true, builtin: true }))
2385
2663
  }
2386
2664
  };
2387
2665
  }
@@ -2730,8 +3008,8 @@ function _filterDefaultsByOs(rules, osType) {
2730
3008
  const accepted = acceptedOsValues(osType);
2731
3009
  return rules.filter((r) => {
2732
3010
  if (!r.os) return true;
2733
- const os3 = String(r.os).toLowerCase();
2734
- return os3 === "all" || accepted.includes(os3);
3011
+ const os4 = String(r.os).toLowerCase();
3012
+ return os4 === "all" || accepted.includes(os4);
2735
3013
  });
2736
3014
  }
2737
3015
  function _hasRulesForOs(rules, osType) {
@@ -2856,7 +3134,8 @@ function effectiveIntentPatterns(osType) {
2856
3134
  intentKeywords: r.intent_keywords || [],
2857
3135
  dangerousActions: r.dangerous_actions || [],
2858
3136
  reason: String(r.reason || ""),
2859
- os: String(r.os || "linux").toLowerCase()
3137
+ os: String(r.os || "linux").toLowerCase(),
3138
+ allowIfWriteIntent: r.allow_if_write_intent === true
2860
3139
  }));
2861
3140
  });
2862
3141
  }
@@ -2961,12 +3240,12 @@ function addCustomSkill(skillId, category, keywords, content) {
2961
3240
  );
2962
3241
  }
2963
3242
  const runtime = loadRuntimeConfig();
2964
- const skillsDir = join4(getRuntimeConfigDir(), "agent_moss_skills");
3243
+ const skillsDir = join5(getRuntimeConfigDir(), "agent_moss_skills");
2965
3244
  try {
2966
3245
  mkdirSync(skillsDir, { recursive: true });
2967
3246
  } catch {
2968
3247
  }
2969
- writeFileSync(join4(skillsDir, `${skillId}.md`), content, "utf-8");
3248
+ writeFileSync(join5(skillsDir, `${skillId}.md`), content, "utf-8");
2970
3249
  const l3 = runtime.L3_skills || (runtime.L3_skills = {});
2971
3250
  const cat = l3[category] || (l3[category] = { category_enabled: true, category_desc: "", skills: [] });
2972
3251
  (cat.skills || (cat.skills = [])).push({ id: skillId, keywords, enabled: true, builtin: false });
@@ -2981,7 +3260,7 @@ function deleteCustomSkill(skillId, category) {
2981
3260
  if (idx >= 0) {
2982
3261
  if (skills[idx].builtin) return null;
2983
3262
  skills.splice(idx, 1);
2984
- const skillPath = join4(getRuntimeConfigDir(), "agent_moss_skills", `${skillId}.md`);
3263
+ const skillPath = join5(getRuntimeConfigDir(), "agent_moss_skills", `${skillId}.md`);
2985
3264
  try {
2986
3265
  if (existsSync5(skillPath)) unlinkSync(skillPath);
2987
3266
  } catch {
@@ -3044,6 +3323,7 @@ function getEnabledAgentExtensions(runtime, agentId) {
3044
3323
  read_only: r.read_only,
3045
3324
  deny_mode: r.deny_mode
3046
3325
  }));
3326
+ const singleFileWriteTools = _agentCategoryEnabledRules(agentData.extra_single_file_write_tools).filter((r) => r.value).map((r) => String(r.value).toLowerCase());
3047
3327
  return {
3048
3328
  agent_id: agentId,
3049
3329
  description: "",
@@ -3052,6 +3332,7 @@ function getEnabledAgentExtensions(runtime, agentId) {
3052
3332
  extra_sensitive_paths: sensitivePaths,
3053
3333
  builtin_safe_skills: safeSkills.filter((r) => r.value).map((r) => r.value),
3054
3334
  builtin_safe_action_types: safeAction.filter((r) => r.value).map((r) => r.value),
3335
+ extra_single_file_write_tools: singleFileWriteTools,
3055
3336
  extra_skills: []
3056
3337
  };
3057
3338
  }
@@ -3130,6 +3411,7 @@ function getEnabledScenarioExtensions(runtime, scenarioId) {
3130
3411
  extra_sensitive_paths: sensitivePaths,
3131
3412
  builtin_safe_skills: [],
3132
3413
  builtin_safe_action_types: [],
3414
+ extra_single_file_write_tools: [],
3133
3415
  extra_skills: []
3134
3416
  };
3135
3417
  }
@@ -3190,7 +3472,7 @@ var init_runtime_config = __esm({
3190
3472
  __dirname4 = dirname3(fileURLToPath4(import.meta.url));
3191
3473
  ENV_RUNTIME_CONFIG_PATH = "AGENT_MOSS_RUNTIME_CONFIG_PATH";
3192
3474
  RUNTIME_CONFIG_DIR = runtimeDir();
3193
- RUNTIME_CONFIG_PATH = join4(RUNTIME_CONFIG_DIR, "agent_moss_runtime.json");
3475
+ RUNTIME_CONFIG_PATH = join5(RUNTIME_CONFIG_DIR, "agent_moss_runtime.json");
3194
3476
  LAYER_DISABLE_ENV = {
3195
3477
  L1_heuristic: "AGENT_MOSS_DISABLE_HEURISTIC",
3196
3478
  L2_logic_rules: "AGENT_MOSS_DISABLE_LOGIC_RULES",
@@ -3218,10 +3500,10 @@ var init_runtime_config = __esm({
3218
3500
  intent_consistency: ["intent_keywords", "reason"]
3219
3501
  };
3220
3502
  hasRuntimeConfigCache = /* @__PURE__ */ new Map();
3221
- _AGENTS_DIR_PROD = join4(__dirname4, "agents");
3222
- _AGENTS_DIR_DEV = join4(__dirname4, "..", "..", "..", "agent_moss", "agents");
3223
- _SCENARIOS_DIR_PROD = join4(__dirname4, "scenarios");
3224
- _SCENARIOS_DIR_DEV = join4(__dirname4, "..", "..", "..", "agent_moss", "scenarios");
3503
+ _AGENTS_DIR_PROD = join5(__dirname4, "agents");
3504
+ _AGENTS_DIR_DEV = join5(__dirname4, "..", "..", "..", "agent_moss", "agents");
3505
+ _SCENARIOS_DIR_PROD = join5(__dirname4, "scenarios");
3506
+ _SCENARIOS_DIR_DEV = join5(__dirname4, "..", "..", "..", "agent_moss", "scenarios");
3225
3507
  _effectiveCache = /* @__PURE__ */ new WeakMap();
3226
3508
  SKILL_ID_RE = /^[A-Za-z0-9_-]+$/;
3227
3509
  registerRuntimeConfigBridge({
@@ -3264,7 +3546,7 @@ __export(config_exports, {
3264
3546
  wildcardToRegExp: () => wildcardToRegExp
3265
3547
  });
3266
3548
  import fs2 from "fs";
3267
- import path2 from "path";
3549
+ import path3 from "path";
3268
3550
  import { fileURLToPath as fileURLToPath5 } from "url";
3269
3551
  function loadConfigFile(filePath) {
3270
3552
  try {
@@ -3277,17 +3559,17 @@ function loadConfigFile(filePath) {
3277
3559
  function resolveConfigPath() {
3278
3560
  const envPath = process.env.AGENT_MOSS_CONFIG_PATH;
3279
3561
  if (envPath) return envPath;
3280
- const userConfig = path2.join(getConfigDir(), "config.json");
3562
+ const userConfig = path3.join(getConfigDir(), "config.json");
3281
3563
  if (fs2.existsSync(userConfig)) return userConfig;
3282
3564
  const defaultCandidates = [
3283
- path2.join(__configModuleDir, "config.json.example"),
3284
- path2.join(__configModuleDir, "..", "config.json.example"),
3285
- path2.join(__configModuleDir, "..", "..", "agent_moss", "infra", "config.json.example"),
3286
- path2.join(__configModuleDir, "..", "..", "..", "agent_moss", "infra", "config.json.example")
3565
+ path3.join(__configModuleDir, "config.json.example"),
3566
+ path3.join(__configModuleDir, "..", "config.json.example"),
3567
+ path3.join(__configModuleDir, "..", "..", "agent_moss", "infra", "config.json.example"),
3568
+ path3.join(__configModuleDir, "..", "..", "..", "agent_moss", "infra", "config.json.example")
3287
3569
  ];
3288
3570
  const defaultConfig = defaultCandidates.find((p) => fs2.existsSync(p));
3289
3571
  if (defaultConfig) {
3290
- const configDir = path2.dirname(userConfig);
3572
+ const configDir = path3.dirname(userConfig);
3291
3573
  fs2.mkdirSync(configDir, { recursive: true });
3292
3574
  const pkgConfig = loadConfigFile(defaultConfig);
3293
3575
  const safeConfig = pkgConfig ? { ...pkgConfig, llm: { ...pkgConfig.llm, api_key: "" } } : {};
@@ -3517,7 +3799,7 @@ var init_config = __esm({
3517
3799
  init_rules_mode();
3518
3800
  __configModuleDir = (() => {
3519
3801
  try {
3520
- return path2.dirname(fileURLToPath5(import.meta.url));
3802
+ return path3.dirname(fileURLToPath5(import.meta.url));
3521
3803
  } catch {
3522
3804
  return typeof __dirname !== "undefined" ? __dirname : process.cwd();
3523
3805
  }
@@ -3540,11 +3822,11 @@ var init_config = __esm({
3540
3822
  };
3541
3823
  })();
3542
3824
  USER_RULES_PATHS = [
3543
- path2.join(__configModuleDir, "rules", "user_rules.json"),
3825
+ path3.join(__configModuleDir, "rules", "user_rules.json"),
3544
3826
  // 源在 ts/src/rules(一般不存在)
3545
- path2.join(__configModuleDir, "..", "rules", "user_rules.json"),
3827
+ path3.join(__configModuleDir, "..", "rules", "user_rules.json"),
3546
3828
  // dist: dist/engine/../rules = dist/rules ✅
3547
- path2.join(__configModuleDir, "..", "..", "agent_moss", "rules", "user_rules.json")
3829
+ path3.join(__configModuleDir, "..", "..", "agent_moss", "rules", "user_rules.json")
3548
3830
  // dev src: ts/src/../../agent_moss
3549
3831
  ];
3550
3832
  customRules = loadCustomRules();
@@ -3562,11 +3844,11 @@ var init_config = __esm({
3562
3844
 
3563
3845
  // src/agents/index.ts
3564
3846
  import { readFileSync as readFileSync5, existsSync as existsSync6 } from "fs";
3565
- import { resolve as resolve4, dirname as dirname4, join as join5 } from "path";
3847
+ import { resolve as resolve4, dirname as dirname4, join as join6 } from "path";
3566
3848
  import { fileURLToPath as fileURLToPath6 } from "url";
3567
3849
  function resolveAgentsDir() {
3568
3850
  const root = getRulesRoot();
3569
- if (root) return join5(root, "agents");
3851
+ if (root) return join6(root, "agents");
3570
3852
  if (existsSync6(AGENTS_DIR_PROD)) return AGENTS_DIR_PROD;
3571
3853
  if (existsSync6(AGENTS_DIR_DEV_FALLBACK)) return AGENTS_DIR_DEV_FALLBACK;
3572
3854
  return AGENTS_DIR_PROD;
@@ -3627,6 +3909,7 @@ function mergeAgentExtensions(...exts) {
3627
3909
  extra_sensitive_paths: nonNull.flatMap((e) => e.extra_sensitive_paths || []),
3628
3910
  builtin_safe_skills: nonNull.flatMap((e) => e.builtin_safe_skills || []),
3629
3911
  builtin_safe_action_types: nonNull.flatMap((e) => e.builtin_safe_action_types || []),
3912
+ extra_single_file_write_tools: nonNull.flatMap((e) => e.extra_single_file_write_tools || []),
3630
3913
  extra_skills: nonNull.flatMap((e) => e.extra_skills || [])
3631
3914
  };
3632
3915
  }
@@ -3648,11 +3931,11 @@ var init_agents = __esm({
3648
3931
 
3649
3932
  // src/scenarios/index.ts
3650
3933
  import { readFileSync as readFileSync6, existsSync as existsSync7 } from "fs";
3651
- import { resolve as resolve5, dirname as dirname5, join as join6 } from "path";
3934
+ import { resolve as resolve5, dirname as dirname5, join as join7 } from "path";
3652
3935
  import { fileURLToPath as fileURLToPath7 } from "url";
3653
3936
  function resolveScenariosDir() {
3654
3937
  const root = getRulesRoot();
3655
- if (root) return join6(root, "scenarios");
3938
+ if (root) return join7(root, "scenarios");
3656
3939
  if (existsSync7(SCENARIOS_DIR_PROD)) return SCENARIOS_DIR_PROD;
3657
3940
  if (existsSync7(SCENARIOS_DIR_DEV_FALLBACK)) return SCENARIOS_DIR_DEV_FALLBACK;
3658
3941
  return SCENARIOS_DIR_PROD;
@@ -3710,6 +3993,7 @@ function getScenarioExtensions(scenarioId) {
3710
3993
  extra_sensitive_paths: data.extra_sensitive_paths || [],
3711
3994
  builtin_safe_skills: data.builtin_safe_skills || [],
3712
3995
  builtin_safe_action_types: data.builtin_safe_action_types || [],
3996
+ extra_single_file_write_tools: data.extra_single_file_write_tools || [],
3713
3997
  extra_skills: data.extra_skills || []
3714
3998
  };
3715
3999
  } catch (e) {
@@ -4142,16 +4426,16 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
4142
4426
  if (String(osType || "").toLowerCase() === "windows") {
4143
4427
  pathScanTexts.push(...pathScanTexts.map((t) => t.replace(/\//g, "\\")));
4144
4428
  }
4145
- const pathMatches = (text, path6) => {
4146
- const parts = path6.split(/(\(\?!.*?\))/);
4429
+ const pathMatches = (text, path7) => {
4430
+ const parts = path7.split(/(\(\?!.*?\))/);
4147
4431
  const escaped = parts.map((part) => {
4148
4432
  if (part.startsWith("(?!")) return part;
4149
4433
  return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4150
4434
  }).join("");
4151
- const re = path6.startsWith(".") || path6.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
4435
+ const re = path7.startsWith(".") || path7.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
4152
4436
  return re.test(text);
4153
4437
  };
4154
- const pathMatchesAny = (path6) => pathScanTexts.some((t) => pathMatches(t, path6));
4438
+ const pathMatchesAny = (path7) => pathScanTexts.some((t) => pathMatches(t, path7));
4155
4439
  for (const sp of rootPaths) {
4156
4440
  if (pathMatchesAny(sp.path.toLowerCase())) {
4157
4441
  if (keygenGenerate) continue;
@@ -4294,8 +4578,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
4294
4578
  }
4295
4579
  return null;
4296
4580
  }
4297
- function isHomeValue(path6) {
4298
- let p = path6.trim().toLowerCase();
4581
+ function isHomeValue(path7) {
4582
+ let p = path7.trim().toLowerCase();
4299
4583
  if (p.startsWith("$(") && p.endsWith(")")) {
4300
4584
  const inner = p.slice(2, -1).trim();
4301
4585
  return HOME_TARGET_RE.test(" " + inner);
@@ -4351,15 +4635,15 @@ function checkHomeDeletion(actionType, actionDetail) {
4351
4635
  }
4352
4636
  const assigned = {};
4353
4637
  for (const m of actionDetail.matchAll(HOME_ASSIGN_RE)) assigned[m[1]] = m[2];
4354
- for (const [varName, path6] of Object.entries(assigned)) {
4355
- if (!isHomeValue(path6)) continue;
4638
+ for (const [varName, path7] of Object.entries(assigned)) {
4639
+ if (!isHomeValue(path7)) continue;
4356
4640
  const varRefRe = new RegExp(`(?:${escapeRegExp(varName)}|\\$\\{${escapeRegExp(varName)}\\})`);
4357
4641
  for (const seg of segs) {
4358
4642
  if (!isDeleteCommand(seg)) continue;
4359
4643
  if (varRefRe.test(seg)) {
4360
4644
  return {
4361
4645
  allowed: false,
4362
- reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path6}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
4646
+ reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path7}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
4363
4647
  riskLevel: "high",
4364
4648
  riskType: "script_execution",
4365
4649
  confidence: 90,
@@ -4836,9 +5120,9 @@ import { createHash } from "crypto";
4836
5120
  // src/infra/security-policy.ts
4837
5121
  init_esm_shims();
4838
5122
  init_paths();
4839
- import { chmodSync, closeSync, existsSync as existsSync8, lstatSync, mkdirSync as mkdirSync2, openSync, readFileSync as readFileSync7, readSync, realpathSync, writeSync } from "fs";
4840
- import { homedir as homedir2, tmpdir } from "os";
4841
- import { basename, isAbsolute, join as join7, relative, resolve as resolve6, dirname as dirname6 } from "path";
5123
+ import { chmodSync, closeSync as closeSync2, constants as fsConstants, existsSync as existsSync8, lstatSync, mkdirSync as mkdirSync2, openSync as openSync2, readFileSync as readFileSync7, readSync as readSync2, realpathSync, writeSync } from "fs";
5124
+ import { homedir as homedir3, tmpdir } from "os";
5125
+ import { basename, isAbsolute as isAbsolute2, join as join8, relative, resolve as resolve6, dirname as dirname6 } from "path";
4842
5126
  var TRUTHY2 = ["1", "true", "yes", "on"];
4843
5127
  function env(name, dflt = "") {
4844
5128
  return (process.env[name] ?? dflt).trim();
@@ -4848,7 +5132,7 @@ function splitList(raw) {
4848
5132
  }
4849
5133
  function homeDir() {
4850
5134
  try {
4851
- const home = homedir2();
5135
+ const home = homedir3();
4852
5136
  if (process.getuid?.() === 0) {
4853
5137
  const explicit = resolveExplicitOwnerHome();
4854
5138
  if (explicit) return explicit;
@@ -4879,7 +5163,7 @@ function realpathLoose(p) {
4879
5163
  parts.unshift(basename(cur));
4880
5164
  cur = parent;
4881
5165
  try {
4882
- return join7(realpathSync(cur), ...parts);
5166
+ return join8(realpathSync(cur), ...parts);
4883
5167
  } catch {
4884
5168
  }
4885
5169
  }
@@ -4892,7 +5176,7 @@ function pathWithin(p, roots) {
4892
5176
  const rootReal = realpathLoose(root);
4893
5177
  if (rootReal === null) continue;
4894
5178
  const rel = relative(rootReal, target);
4895
- if (rel === "" || !rel.startsWith("..") && !isAbsolute(rel)) return true;
5179
+ if (rel === "" || !rel.startsWith("..") && !isAbsolute2(rel)) return true;
4896
5180
  }
4897
5181
  return false;
4898
5182
  }
@@ -4972,7 +5256,7 @@ function loadTemplates() {
4972
5256
  init_esm_shims();
4973
5257
  init_rules_loader();
4974
5258
  import { readFileSync as readFileSync9 } from "fs";
4975
- import { resolve as resolve8, join as join8 } from "path";
5259
+ import { resolve as resolve8, join as join9 } from "path";
4976
5260
  var SCRIPT_RULES = loadScriptRules();
4977
5261
  if (!SCRIPT_RULES || Object.keys(SCRIPT_RULES).length === 0) {
4978
5262
  console.error(
@@ -5042,7 +5326,7 @@ function assessKeywordCombinationRisk(matchedKeywords, scriptContent) {
5042
5326
  }
5043
5327
  function readScriptContent(scriptPath, maxLines = 500) {
5044
5328
  try {
5045
- const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ? join8(process.env.HOME || "/home/user", scriptPath.slice(1)) : resolve8(scriptPath);
5329
+ const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ? join9(process.env.HOME || "/home/user", scriptPath.slice(1)) : resolve8(scriptPath);
5046
5330
  const raw = readFileSync9(expandedPath, "utf-8");
5047
5331
  const lines = raw.split("\n").slice(0, maxLines);
5048
5332
  return { content: lines.join("\n"), lineCount: lines.length, error: "" };
@@ -5100,14 +5384,14 @@ init_config();
5100
5384
  init_logic_rules();
5101
5385
  init_inline_analyzer();
5102
5386
  import { statSync as statSync4, existsSync as existsSync11 } from "fs";
5103
- import { resolve as resolve10, join as join10, isAbsolute as isAbsolute3 } from "path";
5104
- import { homedir as homedir4 } from "os";
5387
+ import { resolve as resolve10, join as join11, isAbsolute as isAbsolute4 } from "path";
5388
+ import { homedir as homedir5 } from "os";
5105
5389
 
5106
5390
  // src/engine/script-engine/tracker.ts
5107
5391
  init_esm_shims();
5108
5392
  import * as fs3 from "fs";
5109
- import * as path3 from "path";
5110
- import * as os from "os";
5393
+ import * as path4 from "path";
5394
+ import * as os2 from "os";
5111
5395
 
5112
5396
  // src/engine/script-engine/backends/python-backend.ts
5113
5397
  init_esm_shims();
@@ -5537,15 +5821,15 @@ function parseShellString(s) {
5537
5821
  let m;
5538
5822
  while ((m = CHILD_CALL_RE.exec(s)) !== null) {
5539
5823
  const interp = m[1];
5540
- const path6 = m[2].trim();
5824
+ const path7 = m[2].trim();
5541
5825
  let rest = m[3].trim();
5542
- if (path6.startsWith("-") || path6.startsWith("$") || path6.includes("/dev/")) continue;
5826
+ if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
5543
5827
  rest = rest.split(/[;|&<>]/)[0].trim();
5544
5828
  const args = [];
5545
5829
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
5546
5830
  args.push(tm[1] ? tm[2] : tm[3]);
5547
5831
  }
5548
- return { path: path6, args, interpreter: interp };
5832
+ return { path: path7, args, interpreter: interp };
5549
5833
  }
5550
5834
  return null;
5551
5835
  }
@@ -5591,9 +5875,9 @@ function extractCallsFromTree(tree, reachableLines) {
5591
5875
  }
5592
5876
  if (allStr && elts.length >= 2) {
5593
5877
  const interp = elts[0];
5594
- const path6 = elts[1];
5595
- if (!path6.startsWith("-") && !path6.startsWith("$") && !path6.includes("/dev/")) {
5596
- add({ path: path6, args: elts.slice(2), interpreter: interp });
5878
+ const path7 = elts[1];
5879
+ if (!path7.startsWith("-") && !path7.startsWith("$") && !path7.includes("/dev/")) {
5880
+ add({ path: path7, args: elts.slice(2), interpreter: interp });
5597
5881
  return true;
5598
5882
  }
5599
5883
  }
@@ -5633,15 +5917,15 @@ function extractCallsRegex(content) {
5633
5917
  let m;
5634
5918
  while ((m = CHILD_CALL_RE.exec(content)) !== null) {
5635
5919
  const interp = m[1];
5636
- const path6 = m[2].trim();
5920
+ const path7 = m[2].trim();
5637
5921
  let rest = m[3].trim();
5638
- if (path6.startsWith("-") || path6.startsWith("$") || path6.includes("/dev/")) continue;
5922
+ if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
5639
5923
  rest = rest.split(/[;|&<>]/)[0].trim();
5640
5924
  const args = [];
5641
5925
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
5642
5926
  args.push(tm[1] ? tm[2] : tm[3]);
5643
5927
  }
5644
- calls.push({ path: path6, args, interpreter: interp });
5928
+ calls.push({ path: path7, args, interpreter: interp });
5645
5929
  }
5646
5930
  return calls;
5647
5931
  }
@@ -6371,15 +6655,15 @@ function extractCallsFromContent(content) {
6371
6655
  CHILD_CALL_RE2.lastIndex = 0;
6372
6656
  while ((m = CHILD_CALL_RE2.exec(content)) !== null) {
6373
6657
  const interp = m[1];
6374
- const path6 = m[2].trim();
6658
+ const path7 = m[2].trim();
6375
6659
  let rest = m[3].trim();
6376
- if (path6.startsWith("-") || path6.startsWith("$") || path6.includes("/dev/")) continue;
6660
+ if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
6377
6661
  rest = rest.split(/[;|&<>]/)[0].trim();
6378
6662
  const args = [];
6379
6663
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6380
6664
  args.push(tm[1] ? tm[2] : tm[3]);
6381
6665
  }
6382
- calls.push({ path: path6, args, interpreter: interp });
6666
+ calls.push({ path: path7, args, interpreter: interp });
6383
6667
  }
6384
6668
  return calls;
6385
6669
  }
@@ -6452,11 +6736,11 @@ function pickBackend(pathStr) {
6452
6736
  function resolvePath(p, baseDir) {
6453
6737
  let expanded = p;
6454
6738
  if (expanded.startsWith("~/") || expanded === "~") {
6455
- expanded = path3.join(os.homedir(), expanded.slice(1));
6456
- } else if (!path3.isAbsolute(expanded) && baseDir) {
6457
- expanded = path3.join(baseDir, expanded);
6739
+ expanded = path4.join(os2.homedir(), expanded.slice(1));
6740
+ } else if (!path4.isAbsolute(expanded) && baseDir) {
6741
+ expanded = path4.join(baseDir, expanded);
6458
6742
  }
6459
- return path3.resolve(expanded);
6743
+ return path4.resolve(expanded);
6460
6744
  }
6461
6745
  function readScript(pathStr, maxFileSize) {
6462
6746
  try {
@@ -6535,7 +6819,7 @@ var RecursiveTracker = class {
6535
6819
  const baseDir = cwd || process.cwd();
6536
6820
  const resolved = resolvePath(entryPath);
6537
6821
  this.result.entryPath = resolved;
6538
- this.visitScript(resolved, 0, path3.dirname(resolved), entryArgs);
6822
+ this.visitScript(resolved, 0, path4.dirname(resolved), entryArgs);
6539
6823
  const nodes = this.result.nodes;
6540
6824
  this.result.hasCritical = nodes.some((n) => n.l1RiskLevel === "critical" || n.l2RiskLevel === "critical" || n.keywordRiskLevel === "critical") || this.result.hasCritical;
6541
6825
  this.result.hasHigh = nodes.some((n) => ["high", "critical"].includes(n.l1RiskLevel) || ["high", "critical"].includes(n.l2RiskLevel) || ["high", "critical"].includes(n.keywordRiskLevel));
@@ -6597,12 +6881,12 @@ var RecursiveTracker = class {
6597
6881
  }
6598
6882
  }
6599
6883
  }
6600
- const parentDir = path3.dirname(pathStr);
6884
+ const parentDir = path4.dirname(pathStr);
6601
6885
  const childPaths = [];
6602
6886
  for (const call of ir.calls) {
6603
6887
  const child = resolvePath(call.path, parentDir);
6604
6888
  childPaths.push(child);
6605
- this.visitScript(child, depth + 1, path3.dirname(child), call.args);
6889
+ this.visitScript(child, depth + 1, path4.dirname(child), call.args);
6606
6890
  if (this.result.hasCritical) break;
6607
6891
  }
6608
6892
  node.childPaths = childPaths;
@@ -6810,7 +7094,7 @@ function shlexSplit(s) {
6810
7094
  function resolvePath2(p) {
6811
7095
  let expanded = p;
6812
7096
  if (expanded.startsWith("~/") || expanded === "~") {
6813
- expanded = join10(homedir4(), expanded.slice(1));
7097
+ expanded = join11(homedir5(), expanded.slice(1));
6814
7098
  }
6815
7099
  return resolve10(expanded);
6816
7100
  }
@@ -6933,8 +7217,8 @@ function analyzeScriptContent2(input, ext) {
6933
7217
  resolvedPath = inline;
6934
7218
  isInline = true;
6935
7219
  }
6936
- if (resolvedPath && !isAbsolute3(resolvedPath) && !resolvedPath.startsWith("~/")) {
6937
- resolvedPath = join10(input.cwd || process.cwd(), resolvedPath);
7220
+ if (resolvedPath && !isAbsolute4(resolvedPath) && !resolvedPath.startsWith("~/")) {
7221
+ resolvedPath = join11(input.cwd || process.cwd(), resolvedPath);
6938
7222
  }
6939
7223
  const l1Adapter = (content) => {
6940
7224
  const j = scanDangerousCommandPatterns("bash", content, input.osType);
@@ -7021,14 +7305,14 @@ ${contentPreview}
7021
7305
  }
7022
7306
 
7023
7307
  // src/engine/llm-analyzer.ts
7024
- import { openSync as openSync2, writeSync as writeSync2, closeSync as closeSync2, constants as fsConstants } from "fs";
7308
+ import { openSync as openSync3, writeSync as writeSync2, closeSync as closeSync3, constants as fsConstants2 } from "fs";
7025
7309
  import OpenAI from "openai";
7026
7310
 
7027
7311
  // src/infra/trace-log.ts
7028
7312
  init_esm_shims();
7029
7313
  init_paths();
7030
7314
  import fs4 from "fs";
7031
- import path4 from "path";
7315
+ import path5 from "path";
7032
7316
  var LEVEL_OFF = 0;
7033
7317
  var LEVEL_SUMMARY = 1;
7034
7318
  var LEVEL_FULL = 2;
@@ -7076,7 +7360,7 @@ function tracePath() {
7076
7360
  const explicit = (process.env.AGENT_MOSS_TRACE_PATH || "").trim();
7077
7361
  if (explicit) return explicit;
7078
7362
  try {
7079
- return path4.join(getDataRoot(), "agent_moss_trace.log");
7363
+ return path5.join(getDataRoot(), "agent_moss_trace.log");
7080
7364
  } catch {
7081
7365
  return "agent_moss_trace.log";
7082
7366
  }
@@ -7115,7 +7399,7 @@ function trace(event, level = LEVEL_SUMMARY, fields = {}) {
7115
7399
  `;
7116
7400
  const file = tracePath();
7117
7401
  try {
7118
- const dir = path4.dirname(file);
7402
+ const dir = path5.dirname(file);
7119
7403
  if (dir && dir !== ".") fs4.mkdirSync(dir, { recursive: true });
7120
7404
  try {
7121
7405
  const st = fs4.statSync(file);
@@ -7558,13 +7842,13 @@ function logPrompt(prompt, aNext, logPath) {
7558
7842
  ${prompt}
7559
7843
  --- END PROMPT ---
7560
7844
  `;
7561
- let flags = fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_APPEND;
7562
- if (fsConstants.O_NOFOLLOW) flags |= fsConstants.O_NOFOLLOW;
7563
- const fd = openSync2(logPath, flags, 384);
7845
+ let flags = fsConstants2.O_WRONLY | fsConstants2.O_CREAT | fsConstants2.O_APPEND;
7846
+ if (fsConstants2.O_NOFOLLOW) flags |= fsConstants2.O_NOFOLLOW;
7847
+ const fd = openSync3(logPath, flags, 384);
7564
7848
  try {
7565
7849
  writeSync2(fd, line);
7566
7850
  } finally {
7567
- closeSync2(fd);
7851
+ closeSync3(fd);
7568
7852
  }
7569
7853
  } catch (e) {
7570
7854
  console.warn("[AgentMoss] Failed to write LLM prompt to log:", e);
@@ -7852,9 +8136,9 @@ init_esm_shims();
7852
8136
  // src/brain/rule-store.ts
7853
8137
  init_esm_shims();
7854
8138
  import { existsSync as existsSync13, readFileSync as readFileSync13, writeFileSync as writeFileSync3, mkdirSync as mkdirSync4 } from "fs";
7855
- import { join as join11 } from "path";
7856
- import { homedir as homedir5 } from "os";
7857
- var DEFAULT_RULES_PATH = join11(homedir5(), ".agentmoss", "brain", "rules.json");
8139
+ import { join as join12 } from "path";
8140
+ import { homedir as homedir6 } from "os";
8141
+ var DEFAULT_RULES_PATH = join12(homedir6(), ".agentmoss", "brain", "rules.json");
7858
8142
  var ENV_RULES_PATH = "AGENT_MOSS_BRAIN_RULES_PATH";
7859
8143
  var STATUS_DRAFT = "draft";
7860
8144
  var STATUS_APPROVED = "approved";
@@ -7878,8 +8162,8 @@ function uuid() {
7878
8162
  var BrainRuleStore = class {
7879
8163
  path;
7880
8164
  data;
7881
- constructor(path6) {
7882
- this.path = path6 || getRulesPath();
8165
+ constructor(path7) {
8166
+ this.path = path7 || getRulesPath();
7883
8167
  this.data = this.load();
7884
8168
  }
7885
8169
  load() {
@@ -8325,10 +8609,10 @@ ${reason.slice(0, 500)}
8325
8609
  const pathRe = new RegExp(pathPrefix + pathBody + pathSuffix, "g");
8326
8610
  let mm;
8327
8611
  while ((mm = pathRe.exec(src)) !== null) {
8328
- const path6 = mm[1];
8329
- if (path6.split("/").length < 3) continue;
8330
- if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path6)) continue;
8331
- const gen = this.generalizePath(path6);
8612
+ const path7 = mm[1];
8613
+ if (path7.split("/").length < 3) continue;
8614
+ if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path7)) continue;
8615
+ const gen = this.generalizePath(path7);
8332
8616
  if (seen.has(gen)) continue;
8333
8617
  seen.add(gen);
8334
8618
  patterns.push({ pattern: gen, layer: 1, scope: "openat", ruleType: "deny_path" });
@@ -8347,8 +8631,8 @@ ${reason.slice(0, 500)}
8347
8631
  }
8348
8632
  return false;
8349
8633
  }
8350
- generalizePath(path6) {
8351
- const p = path6.toLowerCase();
8634
+ generalizePath(path7) {
8635
+ const p = path7.toLowerCase();
8352
8636
  if (/\/etc\/(shadow|passwd|sudoers|security|ssh)/.test(p)) {
8353
8637
  return "(?:^|[^a-z0-9_-])etc/(?:shadow|passwd|sudoers|security/|ssh/)";
8354
8638
  }
@@ -8468,10 +8752,10 @@ function parseReview(content) {
8468
8752
  // src/brain/skill-manager.ts
8469
8753
  init_esm_shims();
8470
8754
  import { existsSync as existsSync14, mkdirSync as mkdirSync5, readFileSync as readFileSync14, renameSync, writeFileSync as writeFileSync4 } from "fs";
8471
- import { homedir as homedir6 } from "os";
8472
- import { join as join12 } from "path";
8755
+ import { homedir as homedir7 } from "os";
8756
+ import { join as join13 } from "path";
8473
8757
  import { randomUUID } from "crypto";
8474
- var DEFAULT_SKILL_META_PATH = join12(homedir6(), ".agentmoss", "brain", "skill_meta.json");
8758
+ var DEFAULT_SKILL_META_PATH = join13(homedir7(), ".agentmoss", "brain", "skill_meta.json");
8475
8759
  var ENV_SKILL_META_PATH = "AGENT_MOSS_BRAIN_SKILL_META_PATH";
8476
8760
  function getMetaPath(override) {
8477
8761
  return override || process.env[ENV_SKILL_META_PATH] || DEFAULT_SKILL_META_PATH;
@@ -8481,7 +8765,7 @@ var BrainSkillManager = class {
8481
8765
  this.skillsDir = skillsDir;
8482
8766
  this.metaPath = getMetaPath(metaPath);
8483
8767
  try {
8484
- mkdirSync5(join12(this.metaPath, ".."), { recursive: true });
8768
+ mkdirSync5(join13(this.metaPath, ".."), { recursive: true });
8485
8769
  } catch {
8486
8770
  }
8487
8771
  this.load();
@@ -8516,7 +8800,7 @@ var BrainSkillManager = class {
8516
8800
  let changed = false;
8517
8801
  for (const sk of this.skills) {
8518
8802
  if (sk.status !== "active") continue;
8519
- if (!existsSync14(join12(this.skillsDir, `${sk.name}.md`))) {
8803
+ if (!existsSync14(join13(this.skillsDir, `${sk.name}.md`))) {
8520
8804
  sk.status = "stale";
8521
8805
  changed = true;
8522
8806
  }
@@ -8528,7 +8812,7 @@ var BrainSkillManager = class {
8528
8812
  const id = skill.id || randomUUID();
8529
8813
  const name = skill.name || `brain_${id.slice(0, 8)}`;
8530
8814
  if (!existsSync14(this.skillsDir)) return "";
8531
- const mdPath = join12(this.skillsDir, `${name}.md`);
8815
+ const mdPath = join13(this.skillsDir, `${name}.md`);
8532
8816
  if (existsSync14(mdPath)) return "";
8533
8817
  try {
8534
8818
  writeFileSync4(mdPath, skill.content, "utf-8");
@@ -8578,7 +8862,7 @@ var BrainSkillManager = class {
8578
8862
  const out = [];
8579
8863
  for (const sk of this.skills) {
8580
8864
  if (sk.origin_node !== "local" || sk.status !== "active") continue;
8581
- const mdPath = join12(this.skillsDir, `${sk.name}.md`);
8865
+ const mdPath = join13(this.skillsDir, `${sk.name}.md`);
8582
8866
  if (!existsSync14(mdPath)) continue;
8583
8867
  out.push({
8584
8868
  name: sk.name,
@@ -9143,12 +9427,12 @@ function allNodesFlat(mg) {
9143
9427
  // src/engine/formal-engine/properties.ts
9144
9428
  init_esm_shims();
9145
9429
  init_rules_loader();
9146
- function graphFromPath(nodes, path6, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
9430
+ function graphFromPath(nodes, path7, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
9147
9431
  const byKey = /* @__PURE__ */ new Map();
9148
9432
  for (const n of nodes) byKey.set(`${n.sessionId}#${n.seq}`, n);
9149
9433
  const gNodes = [];
9150
9434
  const gEdges = [];
9151
- for (const item of path6) {
9435
+ for (const item of path7) {
9152
9436
  const n = byKey.get(`${item.sessionId}#${item.seq}`);
9153
9437
  gNodes.push({
9154
9438
  session_id: item.sessionId,
@@ -9217,22 +9501,22 @@ function checkCrossSessionChain(graph) {
9217
9501
  if (witness !== void 0) {
9218
9502
  if (nodes[witness].stage !== stages[stages.length - 1]) continue;
9219
9503
  let matched = 0;
9220
- const path6 = [];
9504
+ const path7 = [];
9221
9505
  for (let k = 0; k < witness; k++) {
9222
9506
  const n = nodes[k];
9223
9507
  if (matched < stages.length - 1 && n.stage === stages[matched]) {
9224
9508
  matched += 1;
9225
- path6.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
9509
+ path7.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
9226
9510
  }
9227
9511
  }
9228
9512
  if (matched < stages.length - 1) continue;
9229
- path6.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
9513
+ path7.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
9230
9514
  violations.push({
9231
9515
  propertyId: "cross-" + chain.id,
9232
9516
  reason: chain.reason,
9233
9517
  riskLevel: chain.riskLevel,
9234
- path: path6,
9235
- graph: graphFromPath(nodes, path6, "next", {
9518
+ path: path7,
9519
+ graph: graphFromPath(nodes, path7, "next", {
9236
9520
  property_id: "cross-" + chain.id,
9237
9521
  property_short: "P1",
9238
9522
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -9242,11 +9526,11 @@ function checkCrossSessionChain(graph) {
9242
9526
  } else {
9243
9527
  let matched = 0;
9244
9528
  let stageIdx = 0;
9245
- const path6 = [];
9529
+ const path7 = [];
9246
9530
  for (const n of nodes) {
9247
9531
  if (stageIdx < stages.length && n.stage === stages[stageIdx]) {
9248
9532
  matched += 1;
9249
- path6.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
9533
+ path7.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
9250
9534
  stageIdx += 1;
9251
9535
  if (matched >= stages.length) break;
9252
9536
  }
@@ -9256,8 +9540,8 @@ function checkCrossSessionChain(graph) {
9256
9540
  propertyId: "cross-" + chain.id,
9257
9541
  reason: chain.reason,
9258
9542
  riskLevel: chain.riskLevel,
9259
- path: path6,
9260
- graph: graphFromPath(nodes, path6, "next", {
9543
+ path: path7,
9544
+ graph: graphFromPath(nodes, path7, "next", {
9261
9545
  property_id: "cross-" + chain.id,
9262
9546
  property_short: "P1",
9263
9547
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -9486,7 +9770,7 @@ function checkNeverExfilAfterPrivesc(graph) {
9486
9770
  if (candidates.length > 0) {
9487
9771
  const pre = nodes[candidates[candidates.length - 1]];
9488
9772
  const post = nodes[firstEv];
9489
- const path6 = [
9773
+ const path7 = [
9490
9774
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
9491
9775
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
9492
9776
  ];
@@ -9494,8 +9778,8 @@ function checkNeverExfilAfterPrivesc(graph) {
9494
9778
  propertyId: "no-exfil-after-privesc",
9495
9779
  reason: "\u63D0\u6743\u540E\u51FA\u73B0\u5916\u4F20\uFF1A\u63D0\u6743(\u524D) \u2192 \u5916\u4F20(\u540E)\uFF0C\u8FDD\u53CD \u25A1(PRIVESC\u2192\u25C7EXFIL) \u7A97\u53E3\u7EA6\u675F",
9496
9780
  riskLevel: "critical",
9497
- path: path6,
9498
- graph: graphFromPath(nodes, path6, "next", {
9781
+ path: path7,
9782
+ graph: graphFromPath(nodes, path7, "next", {
9499
9783
  property_id: "no-exfil-after-privesc",
9500
9784
  property_short: "P4",
9501
9785
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -9512,7 +9796,7 @@ function checkNeverExfilAfterPrivesc(graph) {
9512
9796
  for (let j = i + 1; j < nodes.length; j++) {
9513
9797
  if (!isExfilNode(nodes[j])) continue;
9514
9798
  if (privescInWindow(nodes, [i], j, windowSec).length === 0) continue;
9515
- const path6 = [
9799
+ const path7 = [
9516
9800
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
9517
9801
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
9518
9802
  ];
@@ -9520,8 +9804,8 @@ function checkNeverExfilAfterPrivesc(graph) {
9520
9804
  propertyId: "no-exfil-after-privesc",
9521
9805
  reason: "\u63D0\u6743\u540E\u51FA\u73B0\u5916\u4F20\uFF1A\u63D0\u6743(\u524D) \u2192 \u5916\u4F20(\u540E)\uFF0C\u8FDD\u53CD \u25A1(PRIVESC\u2192\u25C7EXFIL) \u7A97\u53E3\u7EA6\u675F",
9522
9806
  riskLevel: "critical",
9523
- path: path6,
9524
- graph: graphFromPath(nodes, path6, "next", {
9807
+ path: path7,
9808
+ graph: graphFromPath(nodes, path7, "next", {
9525
9809
  property_id: "no-exfil-after-privesc",
9526
9810
  property_short: "P4",
9527
9811
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -9553,7 +9837,7 @@ function checkNeverExfilAfterCred(graph) {
9553
9837
  }
9554
9838
  if (pre) {
9555
9839
  const post = nodes[firstEv];
9556
- const path6 = [
9840
+ const path7 = [
9557
9841
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
9558
9842
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
9559
9843
  ];
@@ -9561,8 +9845,8 @@ function checkNeverExfilAfterCred(graph) {
9561
9845
  propertyId: "no-exfil-after-credential",
9562
9846
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
9563
9847
  riskLevel: "critical",
9564
- path: path6,
9565
- graph: graphFromPath(nodes, path6, "data", {
9848
+ path: path7,
9849
+ graph: graphFromPath(nodes, path7, "data", {
9566
9850
  property_id: "no-exfil-after-credential",
9567
9851
  property_short: "P5",
9568
9852
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -9578,7 +9862,7 @@ function checkNeverExfilAfterCred(graph) {
9578
9862
  if (!isCredNode(nodes[i])) continue;
9579
9863
  for (let j = i + 1; j < nodes.length; j++) {
9580
9864
  if (isExfilNode(nodes[j])) {
9581
- const path6 = [
9865
+ const path7 = [
9582
9866
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
9583
9867
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
9584
9868
  ];
@@ -9586,8 +9870,8 @@ function checkNeverExfilAfterCred(graph) {
9586
9870
  propertyId: "no-exfil-after-credential",
9587
9871
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
9588
9872
  riskLevel: "critical",
9589
- path: path6,
9590
- graph: graphFromPath(nodes, path6, "data", {
9873
+ path: path7,
9874
+ graph: graphFromPath(nodes, path7, "data", {
9591
9875
  property_id: "no-exfil-after-credential",
9592
9876
  property_short: "P5",
9593
9877
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -9751,13 +10035,13 @@ function checkSensitiveDataAggregation(graph) {
9751
10035
  if (!isExfilNode(n)) continue;
9752
10036
  const srcs = sourcesFor(i);
9753
10037
  if (srcs.size >= 2) {
9754
- const path6 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
10038
+ const path7 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
9755
10039
  violations.push({
9756
10040
  propertyId: "sensitive-data-aggregation",
9757
10041
  reason: `\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20\uFF1Aegress \u805A\u5408 ${srcs.size} \u4E2A\u4E8B\u4EF6\u6E90\u6570\u636E\uFF08Rule 12\uFF09`,
9758
10042
  riskLevel: "critical",
9759
- path: path6,
9760
- graph: graphFromPath(nodes, path6, "next", {
10043
+ path: path7,
10044
+ graph: graphFromPath(nodes, path7, "next", {
9761
10045
  property_id: "sensitive-data-aggregation",
9762
10046
  property_short: "P8",
9763
10047
  property_name: "\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20"
@@ -9848,8 +10132,8 @@ init_rules_loader();
9848
10132
  // src/engine/formal-engine/chain_state.ts
9849
10133
  init_esm_shims();
9850
10134
  import * as fs5 from "fs";
9851
- import * as os2 from "os";
9852
- import * as path5 from "path";
10135
+ import * as os3 from "os";
10136
+ import * as path6 from "path";
9853
10137
  import { createHash as createHash2 } from "crypto";
9854
10138
 
9855
10139
  // src/engine/coordinator.ts
@@ -10091,7 +10375,7 @@ async function runAnalysis(input) {
10091
10375
  skipLLM = true;
10092
10376
  }
10093
10377
  }
10094
- const logicResult = isLogicRulesEnabled() ? runLogicCheck(input) : null;
10378
+ const logicResult = isLogicRulesEnabled() ? runLogicCheck(input, { agentExt }) : null;
10095
10379
  if (logicResult) {
10096
10380
  traceSummary("l2.result", {
10097
10381
  hit: !logicResult.allowed,