@kenhkl/agent-moss 0.17.24 → 0.17.26

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,11 +1431,15 @@ 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";
1237
- const isWrite = isBashLike ? isWriteOperation(actionType, actionDetail, void 0, osType) : getPlatformTraits(osType).writeKeywords.some((kw) => actionType.includes(kw));
1439
+ let isWrite = isBashLike ? isWriteOperation(actionType, actionDetail, void 0, osType) : getPlatformTraits(osType).writeKeywords.some((kw) => actionType.includes(kw));
1440
+ if (!isWrite && /\btar\b/.test(actionDetail) && /(?:^|\s)(?:-[a-zA-Z]*c[a-zA-Z]*|--create)\b/.test(actionDetail)) {
1441
+ isWrite = true;
1442
+ }
1238
1443
  if (!isWrite) return null;
1239
1444
  const WRITE_CMDS = new Set(_LOGIC.write_commands ?? []);
1240
1445
  if (isBashLike) {
@@ -1256,6 +1461,10 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
1256
1461
  hasWriteSeg = true;
1257
1462
  break;
1258
1463
  }
1464
+ if (fw === "tar" && /(?:^|\s)(?:-[a-zA-Z]*c[a-zA-Z]*|--create)\b/.test(trimmed) && /(?:^|\s)(?:-[a-zA-Z]*f[a-zA-Z]*|--file)(?:=|\s+)\S+/.test(trimmed)) {
1465
+ hasWriteSeg = true;
1466
+ break;
1467
+ }
1259
1468
  if ((fw === "wget" || fw === "curl") && (/\s(?:-O|--output-document|--output)(?:=|\s|$)/i.test(trimmed) || /\s-O\S/.test(trimmed))) {
1260
1469
  hasWriteSeg = true;
1261
1470
  break;
@@ -1271,7 +1480,11 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
1271
1480
  const SOURCE_ARG_CMDS = new Set(_LOGIC.source_arg_commands ?? []);
1272
1481
  const REDIRECT_TARGET_RE = new RegExp(`>{1,2}\\s*(?!&)(?:'(/[^']+)'|"(/[^\\"]+)"|(/[^\\s;|&><'\\"]+))`);
1273
1482
  const targetPaths = [];
1274
- for (const seg of splitCommandSegments(actionDetail)) {
1483
+ const singleFileTool = singleFileTools.has(actionType);
1484
+ if (singleFileTool && MISSING_WRITE_PATH_RE.test(actionDetailRaw)) {
1485
+ return null;
1486
+ }
1487
+ for (const seg of singleFileTool ? [] : splitCommandSegments(actionDetailRaw)) {
1275
1488
  const trimmed = seg.trim();
1276
1489
  if (!trimmed) continue;
1277
1490
  const firstWord = trimmed.split(/\s+/)[0]?.toLowerCase() || "";
@@ -1291,6 +1504,11 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
1291
1504
  const segPathsFiltered = firstWord === "wget" || firstWord === "curl" ? segPaths.filter((p) => p !== "/dev/null") : segPaths;
1292
1505
  if (SOURCE_ARG_CMDS.has(firstWord)) {
1293
1506
  if (segPathsFiltered.length > 1) targetPaths.push(...segPathsFiltered.slice(1));
1507
+ } else if (firstWord === "tar") {
1508
+ if (/(?:^|\s)(?:-[a-zA-Z]*c[a-zA-Z]*|--create)\b/.test(trimmed)) {
1509
+ const fm = trimmed.match(/(?:^|\s)(?:-[a-zA-Z]*f[a-zA-Z]*|--file)(?:=|\s+)(\S+)/);
1510
+ if (fm) targetPaths.push(fm[1].replace(/^['"]|['"]$/g, ""));
1511
+ }
1294
1512
  } else if (firstWord === "dd") {
1295
1513
  const ifSourceMatches = trimmed.match(/\bif=(\/[^\s;|&><'"]+)/g);
1296
1514
  const ifSourcePaths = new Set(ifSourceMatches ? ifSourceMatches.map((m) => m.replace(/^if=/, "")) : []);
@@ -1303,16 +1521,31 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
1303
1521
  targetPaths.push(...segPathsFiltered);
1304
1522
  }
1305
1523
  }
1524
+ if (singleFileTool) {
1525
+ targetPaths.length = 0;
1526
+ targetPaths.push(...declaredWritePaths(actionDetailRaw, osType));
1527
+ }
1306
1528
  const uniqueTargetPaths = [...new Set(targetPaths)].filter((p) => !PSEUDO_FS_PREFIXES.some((pfx) => p.startsWith(pfx)));
1307
1529
  if (uniqueTargetPaths.length === 0) return null;
1308
- const historyReadPaths = /* @__PURE__ */ new Set();
1530
+ const historyFullReadPaths = /* @__PURE__ */ new Set();
1531
+ const historyPartialRead = /* @__PURE__ */ new Map();
1309
1532
  for (const action of actionHistory) {
1310
- const histDetail = action.actionDetail.toLowerCase();
1533
+ const histDetailRaw = action.actionDetail;
1311
1534
  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);
1535
+ const traits = getPlatformTraits(osType);
1536
+ const coverage = historyReadCoverage(
1537
+ histType,
1538
+ histDetailRaw,
1539
+ traits.readKeywords,
1540
+ traits.writeKeywords
1541
+ );
1542
+ for (const p of coverage.full) historyFullReadPaths.add(p);
1543
+ for (const [p, upto] of coverage.partial) {
1544
+ if (historyPartialRead.has(p)) {
1545
+ const old = historyPartialRead.get(p);
1546
+ historyPartialRead.set(p, old == null || upto == null ? null : Math.max(old, upto));
1547
+ } else {
1548
+ historyPartialRead.set(p, upto);
1316
1549
  }
1317
1550
  }
1318
1551
  }
@@ -1325,18 +1558,49 @@ function checkReadBeforeWrite(actionType, actionDetail, actionHistory, reason, c
1325
1558
  if (filteredPaths.length === 0) {
1326
1559
  return null;
1327
1560
  }
1561
+ const normalizedTargets = filteredPaths.map((p) => normalizePathForCompare(p, cwd)).filter((p, i, arr) => p && arr.indexOf(p) === i);
1562
+ const normalizedFullReads = new Set(
1563
+ [...historyFullReadPaths].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
1564
+ );
1565
+ const normalizedPartialReads = /* @__PURE__ */ new Map();
1566
+ for (const [p, upto] of historyPartialRead) {
1567
+ const np = normalizePathForCompare(p, cwd);
1568
+ if (np) normalizedPartialReads.set(np, upto);
1569
+ }
1570
+ const appendTargets = appendOnlyTargets(actionDetailRaw, osType);
1571
+ if (APPEND_MODE_RE.test(actionDetailRaw)) {
1572
+ for (const p of filteredPaths) appendTargets.add(p);
1573
+ }
1574
+ let checkTargets = normalizedTargets;
1575
+ if (appendTargets.size > 0) {
1576
+ const appendNorm = new Set(
1577
+ [...appendTargets].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
1578
+ );
1579
+ checkTargets = normalizedTargets.filter((p) => !([...appendNorm].some((ap) => pathIsSameOrUnder(p, ap) || pathIsSameOrUnder(ap, p)) && !isProtectedWritePath(p)));
1580
+ if (checkTargets.length === 0) return null;
1581
+ }
1328
1582
  const unreadPaths = [];
1329
- for (const path6 of filteredPaths) {
1330
- const hasRead = [...historyReadPaths].some(
1331
- (rp) => path6 === rp || path6.startsWith(rp) || rp.startsWith(path6)
1583
+ for (const path7 of checkTargets) {
1584
+ const isFullRead = [...normalizedFullReads].some(
1585
+ (rp) => pathIsSameOrUnder(path7, rp) || pathIsSameOrUnder(rp, path7)
1332
1586
  );
1333
- if (!hasRead) {
1334
- let isCreate = !fs.existsSync(path6);
1587
+ let isPartialCovered = false;
1588
+ if (!isFullRead) {
1589
+ for (const [pp, upto] of normalizedPartialReads) {
1590
+ if (!(pathIsSameOrUnder(path7, pp) || pathIsSameOrUnder(pp, path7))) continue;
1591
+ if (upto != null && fileHasAtMostLines(path7, upto)) {
1592
+ isPartialCovered = true;
1593
+ break;
1594
+ }
1595
+ }
1596
+ }
1597
+ if (!isFullRead && !isPartialCovered) {
1598
+ let isCreate = !fs.existsSync(path7);
1335
1599
  if (!isCreate) {
1336
1600
  isCreate = CREATE_KEYWORDS.some((kw) => reason.toLowerCase().includes(kw) || actionDetail.includes(kw));
1337
1601
  }
1338
1602
  if (!isCreate) {
1339
- unreadPaths.push(path6);
1603
+ unreadPaths.push(path7);
1340
1604
  }
1341
1605
  }
1342
1606
  }
@@ -1513,7 +1777,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
1513
1777
  violatedLayers: ["L2.1"]
1514
1778
  };
1515
1779
  }
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;
1780
+ 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
1781
  var init_logic_rules = __esm({
1518
1782
  "src/engine/logic-rules.ts"() {
1519
1783
  "use strict";
@@ -1530,16 +1794,16 @@ var init_logic_rules = __esm({
1530
1794
  ALL_QUOTES_RE = /'[^']*'|"[^"]*"/g;
1531
1795
  ROOT_SENSITIVE_PATHS = _loadSensitivePathScope("root");
1532
1796
  HOME_SENSITIVE_PATHS = _loadSensitivePathScope("home");
1533
- CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path6, riskLevel, desc, dirDelOnly }) => ({ path: path6, riskLevel, desc, credential: true, dirDelOnly }));
1797
+ CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
1534
1798
  ROOT_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("root", "windows");
1535
1799
  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 }));
1800
+ CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
1537
1801
  ROOT_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("root", "macos");
1538
1802
  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 }));
1803
+ CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
1540
1804
  ROOT_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("root", "harmony");
1541
1805
  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 }));
1806
+ CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path7, riskLevel, desc, dirDelOnly }) => ({ path: path7, riskLevel, desc, credential: true, dirDelOnly }));
1543
1807
  _scopeIndex = null;
1544
1808
  NON_WRITE_TOOLS = /* @__PURE__ */ new Set([
1545
1809
  "ask_user_question",
@@ -1562,6 +1826,23 @@ var init_logic_rules = __esm({
1562
1826
  ]);
1563
1827
  NON_WRITE_TOOL_PREFIXES = _LOGIC.non_write_tool_prefixes ?? [];
1564
1828
  PSEUDO_FS_PREFIXES = ["/sys/", "/proc/", "/dev/", "/run/"];
1829
+ SINGLE_FILE_WRITE_TOOLS = new Set(
1830
+ _LOGIC.single_file_write_tools ?? []
1831
+ );
1832
+ WRITE_INTENT_KEYWORDS = _LOGIC.write_intent_keywords ?? [];
1833
+ MISSING_WRITE_PATH_RE = /(?:写入文件|编辑文件|写入|编辑)\s*[::]\s*\?/;
1834
+ DECLARED_WRITE_PATH_RE = /(?:写入文件|编辑文件|应用补丁|写入|编辑)\s*[::]\s*([~./][^\s—|,;]+)/;
1835
+ DECLARED_WRITE_PATH_JSON_RE = /"(?:file_path|filePath|path)"\s*:\s*"([^"]+)"/;
1836
+ PROTECTED_WRITE_PREFIXES = _LOGIC.protected_write_prefixes ?? [];
1837
+ PROTECTED_HOME_ENTRIES = new Set(_LOGIC.protected_home_entries ?? []);
1838
+ APPEND_REDIRECT_SOURCE = String.raw`(?<!>)>{2}(?!>)\s*(?!&)(?:'([^']+)'|"([^"]+)"|([^\s;|&><'"]+))`;
1839
+ APPEND_MODE_RE = /\(\s*追加\s*\)|(\s*追加\s*)|"mode"\s*:\s*"append"/i;
1840
+ SHELL_FULL_READ_CMDS = ["cat", "less", "more", "view", "open", "load"];
1841
+ SHELL_PARTIAL_READ_CMDS = ["head", "tail", "grep", "egrep", "fgrep", "rg", "awk"];
1842
+ SHELL_TRUNCATING_CMDS = new Set(SHELL_PARTIAL_READ_CMDS);
1843
+ HEAD_TAIL_LIMIT_RE = /(?:-n\s*|-\s*)(\d+)/;
1844
+ SED_RANGE_RE = /-n\s+['"]?(\d+)\s*,\s*(\d+|\$)\s*p/;
1845
+ PARTIAL_COVER_CHECK_MAX_LINES = 1e5;
1565
1846
  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
1847
  SED_INPLACE_RE = /\bsed\s+(?:-\S+\s+)*(?:-[a-zA-Z]*i[a-zA-Z]*|--in-place)\b/i;
1567
1848
  DEVNULL_REDIRECT_RE = /(?:2|&|1)?\s*>\s*\/dev\/null\b/g;
@@ -1580,7 +1861,8 @@ var init_logic_rules = __esm({
1580
1861
  intentKeywords: p.intent_keywords,
1581
1862
  dangerousActions: p.dangerous_actions,
1582
1863
  reason: p.reason,
1583
- os: String(p.os || "linux").toLowerCase()
1864
+ os: String(p.os || "linux").toLowerCase(),
1865
+ allowIfWriteIntent: p.allow_if_write_intent === true
1584
1866
  }));
1585
1867
  })();
1586
1868
  COMBO_STAGES = (() => {
@@ -1621,11 +1903,11 @@ var init_logic_rules = __esm({
1621
1903
 
1622
1904
  // src/engine/asset-dir.ts
1623
1905
  import { existsSync as existsSync3 } from "fs";
1624
- import { join as join3, resolve as resolve2 } from "path";
1906
+ import { join as join4, resolve as resolve2 } from "path";
1625
1907
  function assetDirCandidates(moduleDir, name) {
1626
1908
  const root = getRulesRoot();
1627
1909
  if (root) {
1628
- const p = join3(root, name);
1910
+ const p = join4(root, name);
1629
1911
  return [p, p];
1630
1912
  }
1631
1913
  return [
@@ -1844,7 +2126,7 @@ __export(runtime_config_exports, {
1844
2126
  updateSkillEnabled: () => updateSkillEnabled
1845
2127
  });
1846
2128
  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";
2129
+ import { join as join5 } from "path";
1848
2130
  import { fileURLToPath as fileURLToPath4 } from "url";
1849
2131
  import { dirname as dirname3 } from "path";
1850
2132
  function runtimeDir() {
@@ -1980,8 +2262,8 @@ function filterEnabledRules(rules, categoryEnabled = true) {
1980
2262
  function _filterRulesByOs(rules, osType) {
1981
2263
  const accepted = acceptedOsValues(osType);
1982
2264
  return rules.filter((r) => {
1983
- const os3 = String(r.os || "linux").toLowerCase();
1984
- return os3 === "all" || accepted.includes(os3);
2265
+ const os4 = String(r.os || "linux").toLowerCase();
2266
+ return os4 === "all" || accepted.includes(os4);
1985
2267
  });
1986
2268
  }
1987
2269
  function _userCustomRules(runtime, layers, requiredKey) {
@@ -2183,7 +2465,7 @@ function _l2SensitivePathsToRules() {
2183
2465
  const { root, home, credential } = getSensitivePathsForOsBuiltin(osName);
2184
2466
  const all = [...root, ...home, ...credential];
2185
2467
  for (const sp of all) {
2186
- const os3 = String(sp.os || "linux").toLowerCase();
2468
+ const os4 = String(sp.os || "linux").toLowerCase();
2187
2469
  const denyMode = sp.denyMode || _deriveDenyMode({
2188
2470
  deny_mode: sp.deny_mode,
2189
2471
  credential: sp.credential,
@@ -2193,7 +2475,7 @@ function _l2SensitivePathsToRules() {
2193
2475
  // id = path_<平台>_<slug>_<hash8>:平台段消除跨平台同名(.ssh/.aws 各一条),
2194
2476
  // hash 段消除同平台 slug 撞车(macOS 的 /Library/LaunchAgents 与
2195
2477
  // Library/LaunchAgents)—— Console 按 id 操作,撞 id 会误改别的规则。
2196
- id: `path_${os3}_${_slugify(sp.path)}_${_fnv1a32(sp.path)}`,
2478
+ id: `path_${os4}_${_slugify(sp.path)}_${_fnv1a32(sp.path)}`,
2197
2479
  path: sp.path,
2198
2480
  risk_level: sp.riskLevel,
2199
2481
  desc: sp.desc,
@@ -2202,7 +2484,7 @@ function _l2SensitivePathsToRules() {
2202
2484
  skip_l3_on_disabled: true,
2203
2485
  enabled: true,
2204
2486
  builtin: true,
2205
- os: os3
2487
+ os: os4
2206
2488
  };
2207
2489
  _syncDenyModeFields(rule);
2208
2490
  if (sp.dirDelOnly) rule.dir_del_only = true;
@@ -2220,6 +2502,9 @@ function _l2IntentPatternsToRules() {
2220
2502
  intent_keywords: pat.intentKeywords,
2221
2503
  dangerous_actions: pat.dangerousActions,
2222
2504
  reason: pat.reason,
2505
+ // 旧 runtime 里没有这个字段:缺省 false,但 getIntentPatternsForOs 会按
2506
+ // reason 回填内置默认值,避免旧配置让新豁免失效。
2507
+ allow_if_write_intent: pat.allowIfWriteIntent,
2223
2508
  skip_l3_on_disabled: true,
2224
2509
  enabled: true,
2225
2510
  builtin: true
@@ -2290,7 +2575,7 @@ function _l3SkillsToRules() {
2290
2575
  function _scenarioRulesToDefaults() {
2291
2576
  const out = {};
2292
2577
  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;
2578
+ const scenDir = _root ? join5(_root, "scenarios") : existsSync5(_SCENARIOS_DIR_PROD) ? _SCENARIOS_DIR_PROD : existsSync5(_SCENARIOS_DIR_DEV) ? _SCENARIOS_DIR_DEV : _SCENARIOS_DIR_PROD;
2294
2579
  if (!existsSync5(scenDir)) return out;
2295
2580
  let entries;
2296
2581
  try {
@@ -2299,7 +2584,7 @@ function _scenarioRulesToDefaults() {
2299
2584
  return out;
2300
2585
  }
2301
2586
  for (const scenarioId of entries) {
2302
- const rulesFile = resolveScenarioRulesFile(scenarioId) ?? join4(scenDir, scenarioId, "rules.json");
2587
+ const rulesFile = resolveScenarioRulesFile(scenarioId) ?? join5(scenDir, scenarioId, "rules.json");
2303
2588
  if (!existsSync5(rulesFile)) continue;
2304
2589
  let data;
2305
2590
  try {
@@ -2340,7 +2625,7 @@ function _scenarioRulesToDefaults() {
2340
2625
  function _agentRulesToDefaults() {
2341
2626
  const out = {};
2342
2627
  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;
2628
+ const agentsDir = _root ? join5(_root, "agents") : existsSync5(_AGENTS_DIR_PROD) ? _AGENTS_DIR_PROD : existsSync5(_AGENTS_DIR_DEV) ? _AGENTS_DIR_DEV : _AGENTS_DIR_PROD;
2344
2629
  if (!existsSync5(agentsDir)) return out;
2345
2630
  let entries;
2346
2631
  try {
@@ -2349,7 +2634,7 @@ function _agentRulesToDefaults() {
2349
2634
  return out;
2350
2635
  }
2351
2636
  for (const agentId of entries) {
2352
- const rulesFile = join4(agentsDir, agentId, "rules.json");
2637
+ const rulesFile = join5(agentsDir, agentId, "rules.json");
2353
2638
  if (!existsSync5(rulesFile)) continue;
2354
2639
  let data;
2355
2640
  try {
@@ -2382,6 +2667,11 @@ function _agentRulesToDefaults() {
2382
2667
  category_enabled: true,
2383
2668
  category_desc: "agent \u4E13\u5C5E\u654F\u611F\u8DEF\u5F84\uFF08L1 \u672B\u5C3E\u8FFD\u52A0\uFF09",
2384
2669
  rules: (data.extra_sensitive_paths || []).map((sp) => ({ ...sp, enabled: true, builtin: true }))
2670
+ },
2671
+ extra_single_file_write_tools: {
2672
+ category_enabled: true,
2673
+ category_desc: "agent \u4E13\u5C5E\u5355\u6587\u4EF6\u5199\u5DE5\u5177\uFF08read_before_write \u53EA\u53D6\u58F0\u660E\u8DEF\u5F84\uFF09",
2674
+ rules: (data.extra_single_file_write_tools || []).map((v) => ({ value: v, enabled: true, builtin: true }))
2385
2675
  }
2386
2676
  };
2387
2677
  }
@@ -2686,7 +2976,9 @@ function getEnabledL2IntentPatterns(runtime, osType) {
2686
2976
  return rules.map((r) => ({
2687
2977
  intent_keywords: r.intent_keywords || [],
2688
2978
  dangerous_actions: r.dangerous_actions || [],
2689
- reason: r.reason || ""
2979
+ reason: r.reason || "",
2980
+ allow_if_write_intent: r.allow_if_write_intent === true,
2981
+ os: r.os
2690
2982
  }));
2691
2983
  }
2692
2984
  function getEnabledL2PasswordPatterns(runtime) {
@@ -2730,8 +3022,8 @@ function _filterDefaultsByOs(rules, osType) {
2730
3022
  const accepted = acceptedOsValues(osType);
2731
3023
  return rules.filter((r) => {
2732
3024
  if (!r.os) return true;
2733
- const os3 = String(r.os).toLowerCase();
2734
- return os3 === "all" || accepted.includes(os3);
3025
+ const os4 = String(r.os).toLowerCase();
3026
+ return os4 === "all" || accepted.includes(os4);
2735
3027
  });
2736
3028
  }
2737
3029
  function _hasRulesForOs(rules, osType) {
@@ -2856,7 +3148,8 @@ function effectiveIntentPatterns(osType) {
2856
3148
  intentKeywords: r.intent_keywords || [],
2857
3149
  dangerousActions: r.dangerous_actions || [],
2858
3150
  reason: String(r.reason || ""),
2859
- os: String(r.os || "linux").toLowerCase()
3151
+ os: String(r.os || "linux").toLowerCase(),
3152
+ allowIfWriteIntent: r.allow_if_write_intent === true
2860
3153
  }));
2861
3154
  });
2862
3155
  }
@@ -2961,12 +3254,12 @@ function addCustomSkill(skillId, category, keywords, content) {
2961
3254
  );
2962
3255
  }
2963
3256
  const runtime = loadRuntimeConfig();
2964
- const skillsDir = join4(getRuntimeConfigDir(), "agent_moss_skills");
3257
+ const skillsDir = join5(getRuntimeConfigDir(), "agent_moss_skills");
2965
3258
  try {
2966
3259
  mkdirSync(skillsDir, { recursive: true });
2967
3260
  } catch {
2968
3261
  }
2969
- writeFileSync(join4(skillsDir, `${skillId}.md`), content, "utf-8");
3262
+ writeFileSync(join5(skillsDir, `${skillId}.md`), content, "utf-8");
2970
3263
  const l3 = runtime.L3_skills || (runtime.L3_skills = {});
2971
3264
  const cat = l3[category] || (l3[category] = { category_enabled: true, category_desc: "", skills: [] });
2972
3265
  (cat.skills || (cat.skills = [])).push({ id: skillId, keywords, enabled: true, builtin: false });
@@ -2981,7 +3274,7 @@ function deleteCustomSkill(skillId, category) {
2981
3274
  if (idx >= 0) {
2982
3275
  if (skills[idx].builtin) return null;
2983
3276
  skills.splice(idx, 1);
2984
- const skillPath = join4(getRuntimeConfigDir(), "agent_moss_skills", `${skillId}.md`);
3277
+ const skillPath = join5(getRuntimeConfigDir(), "agent_moss_skills", `${skillId}.md`);
2985
3278
  try {
2986
3279
  if (existsSync5(skillPath)) unlinkSync(skillPath);
2987
3280
  } catch {
@@ -3044,6 +3337,7 @@ function getEnabledAgentExtensions(runtime, agentId) {
3044
3337
  read_only: r.read_only,
3045
3338
  deny_mode: r.deny_mode
3046
3339
  }));
3340
+ const singleFileWriteTools = _agentCategoryEnabledRules(agentData.extra_single_file_write_tools).filter((r) => r.value).map((r) => String(r.value).toLowerCase());
3047
3341
  return {
3048
3342
  agent_id: agentId,
3049
3343
  description: "",
@@ -3052,6 +3346,7 @@ function getEnabledAgentExtensions(runtime, agentId) {
3052
3346
  extra_sensitive_paths: sensitivePaths,
3053
3347
  builtin_safe_skills: safeSkills.filter((r) => r.value).map((r) => r.value),
3054
3348
  builtin_safe_action_types: safeAction.filter((r) => r.value).map((r) => r.value),
3349
+ extra_single_file_write_tools: singleFileWriteTools,
3055
3350
  extra_skills: []
3056
3351
  };
3057
3352
  }
@@ -3130,6 +3425,7 @@ function getEnabledScenarioExtensions(runtime, scenarioId) {
3130
3425
  extra_sensitive_paths: sensitivePaths,
3131
3426
  builtin_safe_skills: [],
3132
3427
  builtin_safe_action_types: [],
3428
+ extra_single_file_write_tools: [],
3133
3429
  extra_skills: []
3134
3430
  };
3135
3431
  }
@@ -3190,7 +3486,7 @@ var init_runtime_config = __esm({
3190
3486
  __dirname4 = dirname3(fileURLToPath4(import.meta.url));
3191
3487
  ENV_RUNTIME_CONFIG_PATH = "AGENT_MOSS_RUNTIME_CONFIG_PATH";
3192
3488
  RUNTIME_CONFIG_DIR = runtimeDir();
3193
- RUNTIME_CONFIG_PATH = join4(RUNTIME_CONFIG_DIR, "agent_moss_runtime.json");
3489
+ RUNTIME_CONFIG_PATH = join5(RUNTIME_CONFIG_DIR, "agent_moss_runtime.json");
3194
3490
  LAYER_DISABLE_ENV = {
3195
3491
  L1_heuristic: "AGENT_MOSS_DISABLE_HEURISTIC",
3196
3492
  L2_logic_rules: "AGENT_MOSS_DISABLE_LOGIC_RULES",
@@ -3218,10 +3514,10 @@ var init_runtime_config = __esm({
3218
3514
  intent_consistency: ["intent_keywords", "reason"]
3219
3515
  };
3220
3516
  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");
3517
+ _AGENTS_DIR_PROD = join5(__dirname4, "agents");
3518
+ _AGENTS_DIR_DEV = join5(__dirname4, "..", "..", "..", "agent_moss", "agents");
3519
+ _SCENARIOS_DIR_PROD = join5(__dirname4, "scenarios");
3520
+ _SCENARIOS_DIR_DEV = join5(__dirname4, "..", "..", "..", "agent_moss", "scenarios");
3225
3521
  _effectiveCache = /* @__PURE__ */ new WeakMap();
3226
3522
  SKILL_ID_RE = /^[A-Za-z0-9_-]+$/;
3227
3523
  registerRuntimeConfigBridge({
@@ -3264,7 +3560,7 @@ __export(config_exports, {
3264
3560
  wildcardToRegExp: () => wildcardToRegExp
3265
3561
  });
3266
3562
  import fs2 from "fs";
3267
- import path2 from "path";
3563
+ import path3 from "path";
3268
3564
  import { fileURLToPath as fileURLToPath5 } from "url";
3269
3565
  function loadConfigFile(filePath) {
3270
3566
  try {
@@ -3277,17 +3573,17 @@ function loadConfigFile(filePath) {
3277
3573
  function resolveConfigPath() {
3278
3574
  const envPath = process.env.AGENT_MOSS_CONFIG_PATH;
3279
3575
  if (envPath) return envPath;
3280
- const userConfig = path2.join(getConfigDir(), "config.json");
3576
+ const userConfig = path3.join(getConfigDir(), "config.json");
3281
3577
  if (fs2.existsSync(userConfig)) return userConfig;
3282
3578
  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")
3579
+ path3.join(__configModuleDir, "config.json.example"),
3580
+ path3.join(__configModuleDir, "..", "config.json.example"),
3581
+ path3.join(__configModuleDir, "..", "..", "agent_moss", "infra", "config.json.example"),
3582
+ path3.join(__configModuleDir, "..", "..", "..", "agent_moss", "infra", "config.json.example")
3287
3583
  ];
3288
3584
  const defaultConfig = defaultCandidates.find((p) => fs2.existsSync(p));
3289
3585
  if (defaultConfig) {
3290
- const configDir = path2.dirname(userConfig);
3586
+ const configDir = path3.dirname(userConfig);
3291
3587
  fs2.mkdirSync(configDir, { recursive: true });
3292
3588
  const pkgConfig = loadConfigFile(defaultConfig);
3293
3589
  const safeConfig = pkgConfig ? { ...pkgConfig, llm: { ...pkgConfig.llm, api_key: "" } } : {};
@@ -3517,7 +3813,7 @@ var init_config = __esm({
3517
3813
  init_rules_mode();
3518
3814
  __configModuleDir = (() => {
3519
3815
  try {
3520
- return path2.dirname(fileURLToPath5(import.meta.url));
3816
+ return path3.dirname(fileURLToPath5(import.meta.url));
3521
3817
  } catch {
3522
3818
  return typeof __dirname !== "undefined" ? __dirname : process.cwd();
3523
3819
  }
@@ -3540,11 +3836,11 @@ var init_config = __esm({
3540
3836
  };
3541
3837
  })();
3542
3838
  USER_RULES_PATHS = [
3543
- path2.join(__configModuleDir, "rules", "user_rules.json"),
3839
+ path3.join(__configModuleDir, "rules", "user_rules.json"),
3544
3840
  // 源在 ts/src/rules(一般不存在)
3545
- path2.join(__configModuleDir, "..", "rules", "user_rules.json"),
3841
+ path3.join(__configModuleDir, "..", "rules", "user_rules.json"),
3546
3842
  // dist: dist/engine/../rules = dist/rules ✅
3547
- path2.join(__configModuleDir, "..", "..", "agent_moss", "rules", "user_rules.json")
3843
+ path3.join(__configModuleDir, "..", "..", "agent_moss", "rules", "user_rules.json")
3548
3844
  // dev src: ts/src/../../agent_moss
3549
3845
  ];
3550
3846
  customRules = loadCustomRules();
@@ -3562,11 +3858,11 @@ var init_config = __esm({
3562
3858
 
3563
3859
  // src/agents/index.ts
3564
3860
  import { readFileSync as readFileSync5, existsSync as existsSync6 } from "fs";
3565
- import { resolve as resolve4, dirname as dirname4, join as join5 } from "path";
3861
+ import { resolve as resolve4, dirname as dirname4, join as join6 } from "path";
3566
3862
  import { fileURLToPath as fileURLToPath6 } from "url";
3567
3863
  function resolveAgentsDir() {
3568
3864
  const root = getRulesRoot();
3569
- if (root) return join5(root, "agents");
3865
+ if (root) return join6(root, "agents");
3570
3866
  if (existsSync6(AGENTS_DIR_PROD)) return AGENTS_DIR_PROD;
3571
3867
  if (existsSync6(AGENTS_DIR_DEV_FALLBACK)) return AGENTS_DIR_DEV_FALLBACK;
3572
3868
  return AGENTS_DIR_PROD;
@@ -3627,6 +3923,7 @@ function mergeAgentExtensions(...exts) {
3627
3923
  extra_sensitive_paths: nonNull.flatMap((e) => e.extra_sensitive_paths || []),
3628
3924
  builtin_safe_skills: nonNull.flatMap((e) => e.builtin_safe_skills || []),
3629
3925
  builtin_safe_action_types: nonNull.flatMap((e) => e.builtin_safe_action_types || []),
3926
+ extra_single_file_write_tools: nonNull.flatMap((e) => e.extra_single_file_write_tools || []),
3630
3927
  extra_skills: nonNull.flatMap((e) => e.extra_skills || [])
3631
3928
  };
3632
3929
  }
@@ -3648,11 +3945,11 @@ var init_agents = __esm({
3648
3945
 
3649
3946
  // src/scenarios/index.ts
3650
3947
  import { readFileSync as readFileSync6, existsSync as existsSync7 } from "fs";
3651
- import { resolve as resolve5, dirname as dirname5, join as join6 } from "path";
3948
+ import { resolve as resolve5, dirname as dirname5, join as join7 } from "path";
3652
3949
  import { fileURLToPath as fileURLToPath7 } from "url";
3653
3950
  function resolveScenariosDir() {
3654
3951
  const root = getRulesRoot();
3655
- if (root) return join6(root, "scenarios");
3952
+ if (root) return join7(root, "scenarios");
3656
3953
  if (existsSync7(SCENARIOS_DIR_PROD)) return SCENARIOS_DIR_PROD;
3657
3954
  if (existsSync7(SCENARIOS_DIR_DEV_FALLBACK)) return SCENARIOS_DIR_DEV_FALLBACK;
3658
3955
  return SCENARIOS_DIR_PROD;
@@ -3710,6 +4007,7 @@ function getScenarioExtensions(scenarioId) {
3710
4007
  extra_sensitive_paths: data.extra_sensitive_paths || [],
3711
4008
  builtin_safe_skills: data.builtin_safe_skills || [],
3712
4009
  builtin_safe_action_types: data.builtin_safe_action_types || [],
4010
+ extra_single_file_write_tools: data.extra_single_file_write_tools || [],
3713
4011
  extra_skills: data.extra_skills || []
3714
4012
  };
3715
4013
  } catch (e) {
@@ -3751,6 +4049,256 @@ var init_scenarios = __esm({
3751
4049
  }
3752
4050
  });
3753
4051
 
4052
+ // src/engine/written-content-analyzer.ts
4053
+ function isFileWriteAction(actionType) {
4054
+ const at = (actionType || "").toLowerCase();
4055
+ if (WRITE_TOOL_EXACT.has(at)) return true;
4056
+ if (WRITE_TOOL_SUFFIXES.some((s) => at.endsWith(s))) return true;
4057
+ return false;
4058
+ }
4059
+ function isApplyPatch(actionType) {
4060
+ const at = (actionType || "").toLowerCase();
4061
+ return APPLY_PATCH_SUFFIXES.some((s) => at.endsWith(s));
4062
+ }
4063
+ function extractWritePayload(actionType, actionDetailRaw) {
4064
+ if (isApplyPatch(actionType)) return null;
4065
+ const detail = actionDetailRaw || "";
4066
+ const m = detail.match(WRITE_PREFIX_RE);
4067
+ if (m) {
4068
+ const path7 = m[1];
4069
+ let content = m[2] || "";
4070
+ if (!path7 || path7 === "?" || path7 === "-" || !content.trim()) return null;
4071
+ if ((actionType || "").toLowerCase().includes("editfile")) {
4072
+ const nm = content.match(EDIT_NEW_RE);
4073
+ if (nm) content = nm[1];
4074
+ }
4075
+ return { path: path7, content };
4076
+ }
4077
+ const stripped = detail.trim();
4078
+ if (stripped.startsWith("{")) {
4079
+ try {
4080
+ const obj = JSON.parse(stripped);
4081
+ if (obj && typeof obj === "object") {
4082
+ const path7 = obj.path || obj.file_path || obj.filePath;
4083
+ const content = obj.content || obj.newString || obj.new_string;
4084
+ if (typeof path7 === "string" && path7 !== "" && path7 !== "?" && path7 !== "-" && typeof content === "string" && content.trim()) {
4085
+ return { path: path7, content };
4086
+ }
4087
+ }
4088
+ } catch {
4089
+ }
4090
+ }
4091
+ return null;
4092
+ }
4093
+ function handlesWrittenContent(actionType, actionDetailRaw) {
4094
+ if (!isFileWriteAction(actionType)) return false;
4095
+ if (extractWritePayload(actionType, actionDetailRaw) !== null) return true;
4096
+ return /^(?:写入文件|编辑文件|应用补丁)\s*[::]/.test(actionDetailRaw || "");
4097
+ }
4098
+ function detectLanguage(path7, content) {
4099
+ const ext = path7.slice(path7.lastIndexOf(".") >= 0 ? path7.lastIndexOf(".") : path7.length).toLowerCase();
4100
+ if (SHELL_EXTS.has(ext)) return "shell";
4101
+ if (PY_EXTS.has(ext)) return "python";
4102
+ if (DATA_EXTS.has(ext)) return "data";
4103
+ if (!ext) {
4104
+ const first = content.trim() ? content.trim().split(/\r?\n/)[0] : "";
4105
+ if (first.startsWith("#!")) {
4106
+ if (/\b(?:ba|z|k|da)?sh\b/.test(first)) return "shell";
4107
+ if (first.includes("python")) return "python";
4108
+ }
4109
+ return "data";
4110
+ }
4111
+ return "other";
4112
+ }
4113
+ function stripShellComments(text) {
4114
+ const out = [];
4115
+ for (const line of text.split(/\r?\n/)) {
4116
+ const res = [];
4117
+ let quote = null;
4118
+ for (let i = 0; i < line.length; i++) {
4119
+ const ch = line[i];
4120
+ if (quote) {
4121
+ res.push(ch);
4122
+ if (ch === quote) quote = null;
4123
+ continue;
4124
+ }
4125
+ if (ch === "'" || ch === '"') {
4126
+ quote = ch;
4127
+ res.push(ch);
4128
+ continue;
4129
+ }
4130
+ if (ch === "#" && (i === 0 || /\s/.test(line[i - 1]))) break;
4131
+ res.push(ch);
4132
+ }
4133
+ out.push(res.join(""));
4134
+ }
4135
+ return out.join("\n");
4136
+ }
4137
+ function stripShellDocsOnly(content) {
4138
+ if (!content) return content;
4139
+ if (INTERP_HEREDOC_RE.test(content)) return content;
4140
+ const withoutHeredoc = content.replace(QUOTED_HEREDOC_RE, "<<quoted-heredoc>>\n");
4141
+ return stripShellComments(withoutHeredoc);
4142
+ }
4143
+ function lineSnippets(content, precheck) {
4144
+ const lines = content.split(/\r?\n/);
4145
+ const picked = /* @__PURE__ */ new Set();
4146
+ for (let i = 0; i < lines.length; i++) {
4147
+ precheck.lastIndex = 0;
4148
+ if (precheck.test(lines[i])) {
4149
+ picked.add(i - 1);
4150
+ picked.add(i);
4151
+ picked.add(i + 1);
4152
+ }
4153
+ }
4154
+ const snippets = [];
4155
+ let total = 0;
4156
+ for (const i of [...picked].sort((a, b) => a - b)) {
4157
+ if (i < 0 || i >= lines.length) continue;
4158
+ const s = lines[i];
4159
+ if (total + s.length > MAX_SCAN) break;
4160
+ snippets.push(s);
4161
+ total += s.length + 1;
4162
+ }
4163
+ return snippets;
4164
+ }
4165
+ function stripPythonLiterals(content) {
4166
+ const chars = content.split("");
4167
+ let i = 0;
4168
+ const n = chars.length;
4169
+ while (i < n) {
4170
+ const ch = chars[i];
4171
+ if (ch === "#") {
4172
+ while (i < n && chars[i] !== "\n") {
4173
+ chars[i] = " ";
4174
+ i++;
4175
+ }
4176
+ continue;
4177
+ }
4178
+ if (ch === "'" || ch === '"') {
4179
+ const triple = chars[i + 1] === ch && chars[i + 2] === ch;
4180
+ const quoteLen = triple ? 3 : 1;
4181
+ const q = ch;
4182
+ i += quoteLen;
4183
+ while (i < n) {
4184
+ if (chars[i] === "\\") {
4185
+ chars[i] = " ";
4186
+ if (i + 1 < n) chars[i + 1] = " ";
4187
+ i += 2;
4188
+ continue;
4189
+ }
4190
+ if (chars[i] === q && (!triple || chars[i + 1] === q && chars[i + 2] === q)) {
4191
+ for (let k = 0; k < quoteLen; k++) {
4192
+ chars[i + k] = " ";
4193
+ }
4194
+ i += quoteLen;
4195
+ break;
4196
+ }
4197
+ chars[i] = " ";
4198
+ i++;
4199
+ }
4200
+ continue;
4201
+ }
4202
+ i++;
4203
+ }
4204
+ return chars.join("");
4205
+ }
4206
+ function balancedArgs(original, openIndex) {
4207
+ let depth = 0;
4208
+ let quote = null;
4209
+ for (let i = openIndex; i < original.length && i < openIndex + 8e3; i++) {
4210
+ const ch = original[i];
4211
+ if (quote) {
4212
+ if (ch === "\\") {
4213
+ i++;
4214
+ continue;
4215
+ }
4216
+ if (ch === quote) quote = null;
4217
+ continue;
4218
+ }
4219
+ if (ch === "'" || ch === '"') {
4220
+ quote = ch;
4221
+ continue;
4222
+ }
4223
+ if (ch === "(") depth++;
4224
+ else if (ch === ")") {
4225
+ depth--;
4226
+ if (depth === 0) return original.slice(openIndex + 1, i);
4227
+ }
4228
+ }
4229
+ return original.slice(openIndex + 1, Math.min(original.length, openIndex + 2e3));
4230
+ }
4231
+ function pythonSnippets(content) {
4232
+ const stripped = stripPythonLiterals(content);
4233
+ const snippets = [];
4234
+ PY_DANGEROUS_CALL_RE.lastIndex = 0;
4235
+ let m;
4236
+ while ((m = PY_DANGEROUS_CALL_RE.exec(stripped)) !== null) {
4237
+ const callName = m[0].replace(/\s*\($/, "").trim();
4238
+ const openIndex = m.index + m[0].length - 1;
4239
+ const args = balancedArgs(content, openIndex);
4240
+ snippets.push(`${callName}(${args})`);
4241
+ if (snippets.length >= 200) break;
4242
+ }
4243
+ return snippets;
4244
+ }
4245
+ function extractDangerousSnippets(actionType, actionDetailRaw, literalStripper) {
4246
+ if (!handlesWrittenContent(actionType, actionDetailRaw)) return null;
4247
+ const payload = extractWritePayload(actionType, actionDetailRaw);
4248
+ if (!payload) return [];
4249
+ const { path: path7, content: rawContent } = payload;
4250
+ const language = detectLanguage(path7, rawContent);
4251
+ if (language === "data") return [];
4252
+ let content = rawContent.replace(/\\r\\n/g, "\n").replace(/\\n/g, "\n").replace(/\\t/g, " ").slice(0, MAX_CONTENT);
4253
+ const started = Date.now();
4254
+ if (language === "python") {
4255
+ if (!PY_PRECHECK.test(content)) return [];
4256
+ return pythonSnippets(content);
4257
+ }
4258
+ content = stripShellDocsOnly(content);
4259
+ if (literalStripper) content = literalStripper(content);
4260
+ if (!SHELL_PRECHECK.test(content)) return [];
4261
+ const snippets = lineSnippets(content, SHELL_PRECHECK);
4262
+ if (Date.now() - started > MAX_MS) {
4263
+ return snippets;
4264
+ }
4265
+ return snippets;
4266
+ }
4267
+ var CFG, DATA_EXTS, SHELL_EXTS, PY_EXTS, SHELL_PRECHECK, PY_PRECHECK, MAX_CONTENT, MAX_SCAN, MAX_MS, WRITE_TOOL_EXACT, WRITE_TOOL_SUFFIXES, APPLY_PATCH_SUFFIXES, WRITE_PREFIX_RE, EDIT_NEW_RE, INTERP_HEREDOC_RE, QUOTED_HEREDOC_RE, PY_DANGEROUS_CALL_RE;
4268
+ var init_written_content_analyzer = __esm({
4269
+ "src/engine/written-content-analyzer.ts"() {
4270
+ "use strict";
4271
+ init_esm_shims();
4272
+ init_rules_loader();
4273
+ CFG = loadHeuristicRules().write_content_analysis || {};
4274
+ DATA_EXTS = new Set((CFG.data_exts || []).map((e) => e.toLowerCase()));
4275
+ SHELL_EXTS = new Set((CFG.shell_exts || []).map((e) => e.toLowerCase()));
4276
+ PY_EXTS = new Set((CFG.python_exts || []).map((e) => e.toLowerCase()));
4277
+ SHELL_PRECHECK = new RegExp(CFG.shell_precheck || "$^");
4278
+ PY_PRECHECK = new RegExp(CFG.python_precheck || "$^");
4279
+ MAX_CONTENT = Number(CFG.max_content_bytes || 262144);
4280
+ MAX_SCAN = Number(CFG.max_scan_bytes || 65536);
4281
+ MAX_MS = Number(CFG.max_scan_ms || 100);
4282
+ WRITE_TOOL_EXACT = /* @__PURE__ */ new Set([
4283
+ "write",
4284
+ "file_write",
4285
+ "writefile",
4286
+ "edit",
4287
+ "file_edit",
4288
+ "editfile",
4289
+ "searchreplace",
4290
+ "search_replace"
4291
+ ]);
4292
+ WRITE_TOOL_SUFFIXES = ["-writefile", "-editfile", "-searchreplace"];
4293
+ APPLY_PATCH_SUFFIXES = ["applypatch", "apply_patch", "-applypatch"];
4294
+ WRITE_PREFIX_RE = /^(?:写入文件|编辑文件|应用补丁|写入|编辑)\s*[::]\s*(.+?)\s*(?:\(\s*追加\s*\))?\s*—\s*([\s\S]*)$/;
4295
+ EDIT_NEW_RE = /\|\s*new:\s*([\s\S]*)$/i;
4296
+ INTERP_HEREDOC_RE = /(?:^|[\s;|&])(?:bash|sh|zsh|dash|python[0-9.]*|perl|ruby|node|php|lua)\s*<<-?\s*['"]?[A-Za-z_]/i;
4297
+ QUOTED_HEREDOC_RE = /<<-?\s*(['"])([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n.*?\n\s*\2\s*(?:\n|$)/g;
4298
+ PY_DANGEROUS_CALL_RE = /(?:os\.(?:system|popen|remove|unlink|rmdir|chmod|chown|kill|spawn\w*)|subprocess\.\w+|pty\.\w+|ctypes\.\w+|eval|exec|compile|__import__|shutil\.(?:rmtree|move|copy\w*))\s*\(/g;
4299
+ }
4300
+ });
4301
+
3754
4302
  // src/engine/heuristic.ts
3755
4303
  function _effectiveDangerousPatterns(osType) {
3756
4304
  return runtimeConfigBridge.current?.effectiveDangerousPatterns(osType) ?? getDangerousPatternsForOs(osType);
@@ -3858,8 +4406,16 @@ function runHeuristicCheck(input) {
3858
4406
  } catch {
3859
4407
  }
3860
4408
  }
3861
- const scanDetail = normalizePathSegments(stripLiteralTextSegments(input.aNext.actionDetail));
3862
- const scanCommands = String(input.osType || "").toLowerCase() === "windows" ? [
4409
+ const scanDetail = normalizePathSegments(
4410
+ stripLiteralTextSegments(stripShellDocsOnly(input.aNext.actionDetail))
4411
+ );
4412
+ const handledWrite = handlesWrittenContent(input.aNext.actionType, input.aNext.actionDetail);
4413
+ const writeSnippets = extractDangerousSnippets(
4414
+ input.aNext.actionType,
4415
+ input.aNext.actionDetail,
4416
+ stripLiteralTextSegments
4417
+ );
4418
+ const scanCommands = writeSnippets !== null ? writeSnippets.flatMap((sn) => [`${input.aNext.actionType}: ${sn}`, sn]) : String(input.osType || "").toLowerCase() === "windows" ? [
3863
4419
  `${input.aNext.actionType}: ${scanDetail}`,
3864
4420
  scanDetail,
3865
4421
  `${input.aNext.actionType}: ${scanDetail.replace(/\//g, "\\")}`,
@@ -3920,9 +4476,9 @@ function runHeuristicCheck(input) {
3920
4476
  const actionTypeL = input.aNext.actionType.toLowerCase();
3921
4477
  const detailL = input.aNext.actionDetail.toLowerCase();
3922
4478
  const isExcludedType = SENSITIVE_EXCLUDED_PREFIXES.some((p) => actionTypeL.startsWith(p));
3923
- const dangerousResult = checkDangerousPatterns(actionTypeL, detailL);
4479
+ const dangerousResult = handledWrite ? null : checkDangerousPatterns(actionTypeL, detailL);
3924
4480
  const pathResult = isExcludedType ? null : checkSensitivePath(detailL, input.cwd || "/", agentExt, input.osType);
3925
- const homeResult = checkHomeDeletion(actionTypeL, detailL);
4481
+ const homeResult = handledWrite ? null : checkHomeDeletion(actionTypeL, detailL);
3926
4482
  const mergeResults = [dangerousResult, pathResult, homeResult].filter(Boolean);
3927
4483
  if (mergeResults.length > 0) {
3928
4484
  let best = mergeResults[0];
@@ -4142,16 +4698,16 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
4142
4698
  if (String(osType || "").toLowerCase() === "windows") {
4143
4699
  pathScanTexts.push(...pathScanTexts.map((t) => t.replace(/\//g, "\\")));
4144
4700
  }
4145
- const pathMatches = (text, path6) => {
4146
- const parts = path6.split(/(\(\?!.*?\))/);
4701
+ const pathMatches = (text, path7) => {
4702
+ const parts = path7.split(/(\(\?!.*?\))/);
4147
4703
  const escaped = parts.map((part) => {
4148
4704
  if (part.startsWith("(?!")) return part;
4149
4705
  return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4150
4706
  }).join("");
4151
- const re = path6.startsWith(".") || path6.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
4707
+ const re = path7.startsWith(".") || path7.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
4152
4708
  return re.test(text);
4153
4709
  };
4154
- const pathMatchesAny = (path6) => pathScanTexts.some((t) => pathMatches(t, path6));
4710
+ const pathMatchesAny = (path7) => pathScanTexts.some((t) => pathMatches(t, path7));
4155
4711
  for (const sp of rootPaths) {
4156
4712
  if (pathMatchesAny(sp.path.toLowerCase())) {
4157
4713
  if (keygenGenerate) continue;
@@ -4294,8 +4850,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
4294
4850
  }
4295
4851
  return null;
4296
4852
  }
4297
- function isHomeValue(path6) {
4298
- let p = path6.trim().toLowerCase();
4853
+ function isHomeValue(path7) {
4854
+ let p = path7.trim().toLowerCase();
4299
4855
  if (p.startsWith("$(") && p.endsWith(")")) {
4300
4856
  const inner = p.slice(2, -1).trim();
4301
4857
  return HOME_TARGET_RE.test(" " + inner);
@@ -4351,15 +4907,15 @@ function checkHomeDeletion(actionType, actionDetail) {
4351
4907
  }
4352
4908
  const assigned = {};
4353
4909
  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;
4910
+ for (const [varName, path7] of Object.entries(assigned)) {
4911
+ if (!isHomeValue(path7)) continue;
4356
4912
  const varRefRe = new RegExp(`(?:${escapeRegExp(varName)}|\\$\\{${escapeRegExp(varName)}\\})`);
4357
4913
  for (const seg of segs) {
4358
4914
  if (!isDeleteCommand(seg)) continue;
4359
4915
  if (varRefRe.test(seg)) {
4360
4916
  return {
4361
4917
  allowed: false,
4362
- reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path6}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
4918
+ reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path7}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
4363
4919
  riskLevel: "high",
4364
4920
  riskType: "script_execution",
4365
4921
  confidence: 90,
@@ -4420,7 +4976,7 @@ function isSshKeygenGenerate(command) {
4420
4976
  }
4421
4977
  function checkDangerousPatterns(actionType, actionDetail) {
4422
4978
  if (actionType === "file_write" || actionType === "file_edit") return null;
4423
- const scan = stripHeredocContent(actionDetail);
4979
+ const scan = stripHeredocContent(stripShellDocsOnly(actionDetail));
4424
4980
  const isTempPath = TEMP_DIRS2.some(
4425
4981
  (td) => new RegExp(`(?:^|[\\s/])${td.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:[\\s/]|$)`).test(actionDetail)
4426
4982
  ) || /(?:^|[\s;]|&&\s*|\|\|\s*)var\/tmp(?:[/\s;]|$)/.test(actionDetail);
@@ -4578,6 +5134,7 @@ var init_heuristic = __esm({
4578
5134
  init_runtime_config();
4579
5135
  init_runtime_config_bridge();
4580
5136
  init_rules_loader();
5137
+ init_written_content_analyzer();
4581
5138
  init_logic_rules();
4582
5139
  INJECTION_KEYWORDS = (() => {
4583
5140
  const kws = loadL1().injection_detection || [];
@@ -4836,9 +5393,9 @@ import { createHash } from "crypto";
4836
5393
  // src/infra/security-policy.ts
4837
5394
  init_esm_shims();
4838
5395
  init_paths();
4839
- import { chmodSync, closeSync, constants as fsConstants, 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";
5396
+ 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";
5397
+ import { homedir as homedir3, tmpdir } from "os";
5398
+ import { basename, isAbsolute as isAbsolute2, join as join8, relative, resolve as resolve6, dirname as dirname6 } from "path";
4842
5399
  var TRUTHY2 = ["1", "true", "yes", "on"];
4843
5400
  function env(name, dflt = "") {
4844
5401
  return (process.env[name] ?? dflt).trim();
@@ -4848,7 +5405,7 @@ function splitList(raw) {
4848
5405
  }
4849
5406
  function homeDir() {
4850
5407
  try {
4851
- const home = homedir2();
5408
+ const home = homedir3();
4852
5409
  if (process.getuid?.() === 0) {
4853
5410
  const explicit = resolveExplicitOwnerHome();
4854
5411
  if (explicit) return explicit;
@@ -4879,7 +5436,7 @@ function realpathLoose(p) {
4879
5436
  parts.unshift(basename(cur));
4880
5437
  cur = parent;
4881
5438
  try {
4882
- return join7(realpathSync(cur), ...parts);
5439
+ return join8(realpathSync(cur), ...parts);
4883
5440
  } catch {
4884
5441
  }
4885
5442
  }
@@ -4892,7 +5449,7 @@ function pathWithin(p, roots) {
4892
5449
  const rootReal = realpathLoose(root);
4893
5450
  if (rootReal === null) continue;
4894
5451
  const rel = relative(rootReal, target);
4895
- if (rel === "" || !rel.startsWith("..") && !isAbsolute(rel)) return true;
5452
+ if (rel === "" || !rel.startsWith("..") && !isAbsolute2(rel)) return true;
4896
5453
  }
4897
5454
  return false;
4898
5455
  }
@@ -4972,7 +5529,7 @@ function loadTemplates() {
4972
5529
  init_esm_shims();
4973
5530
  init_rules_loader();
4974
5531
  import { readFileSync as readFileSync9 } from "fs";
4975
- import { resolve as resolve8, join as join8 } from "path";
5532
+ import { resolve as resolve8, join as join9 } from "path";
4976
5533
  var SCRIPT_RULES = loadScriptRules();
4977
5534
  if (!SCRIPT_RULES || Object.keys(SCRIPT_RULES).length === 0) {
4978
5535
  console.error(
@@ -5042,7 +5599,7 @@ function assessKeywordCombinationRisk(matchedKeywords, scriptContent) {
5042
5599
  }
5043
5600
  function readScriptContent(scriptPath, maxLines = 500) {
5044
5601
  try {
5045
- const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ? join8(process.env.HOME || "/home/user", scriptPath.slice(1)) : resolve8(scriptPath);
5602
+ const expandedPath = scriptPath === "~" || scriptPath.startsWith("~/") ? join9(process.env.HOME || "/home/user", scriptPath.slice(1)) : resolve8(scriptPath);
5046
5603
  const raw = readFileSync9(expandedPath, "utf-8");
5047
5604
  const lines = raw.split("\n").slice(0, maxLines);
5048
5605
  return { content: lines.join("\n"), lineCount: lines.length, error: "" };
@@ -5100,14 +5657,14 @@ init_config();
5100
5657
  init_logic_rules();
5101
5658
  init_inline_analyzer();
5102
5659
  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";
5660
+ import { resolve as resolve10, join as join11, isAbsolute as isAbsolute4 } from "path";
5661
+ import { homedir as homedir5 } from "os";
5105
5662
 
5106
5663
  // src/engine/script-engine/tracker.ts
5107
5664
  init_esm_shims();
5108
5665
  import * as fs3 from "fs";
5109
- import * as path3 from "path";
5110
- import * as os from "os";
5666
+ import * as path4 from "path";
5667
+ import * as os2 from "os";
5111
5668
 
5112
5669
  // src/engine/script-engine/backends/python-backend.ts
5113
5670
  init_esm_shims();
@@ -5537,15 +6094,15 @@ function parseShellString(s) {
5537
6094
  let m;
5538
6095
  while ((m = CHILD_CALL_RE.exec(s)) !== null) {
5539
6096
  const interp = m[1];
5540
- const path6 = m[2].trim();
6097
+ const path7 = m[2].trim();
5541
6098
  let rest = m[3].trim();
5542
- if (path6.startsWith("-") || path6.startsWith("$") || path6.includes("/dev/")) continue;
6099
+ if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
5543
6100
  rest = rest.split(/[;|&<>]/)[0].trim();
5544
6101
  const args = [];
5545
6102
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
5546
6103
  args.push(tm[1] ? tm[2] : tm[3]);
5547
6104
  }
5548
- return { path: path6, args, interpreter: interp };
6105
+ return { path: path7, args, interpreter: interp };
5549
6106
  }
5550
6107
  return null;
5551
6108
  }
@@ -5591,9 +6148,9 @@ function extractCallsFromTree(tree, reachableLines) {
5591
6148
  }
5592
6149
  if (allStr && elts.length >= 2) {
5593
6150
  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 });
6151
+ const path7 = elts[1];
6152
+ if (!path7.startsWith("-") && !path7.startsWith("$") && !path7.includes("/dev/")) {
6153
+ add({ path: path7, args: elts.slice(2), interpreter: interp });
5597
6154
  return true;
5598
6155
  }
5599
6156
  }
@@ -5633,15 +6190,15 @@ function extractCallsRegex(content) {
5633
6190
  let m;
5634
6191
  while ((m = CHILD_CALL_RE.exec(content)) !== null) {
5635
6192
  const interp = m[1];
5636
- const path6 = m[2].trim();
6193
+ const path7 = m[2].trim();
5637
6194
  let rest = m[3].trim();
5638
- if (path6.startsWith("-") || path6.startsWith("$") || path6.includes("/dev/")) continue;
6195
+ if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
5639
6196
  rest = rest.split(/[;|&<>]/)[0].trim();
5640
6197
  const args = [];
5641
6198
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
5642
6199
  args.push(tm[1] ? tm[2] : tm[3]);
5643
6200
  }
5644
- calls.push({ path: path6, args, interpreter: interp });
6201
+ calls.push({ path: path7, args, interpreter: interp });
5645
6202
  }
5646
6203
  return calls;
5647
6204
  }
@@ -6371,15 +6928,15 @@ function extractCallsFromContent(content) {
6371
6928
  CHILD_CALL_RE2.lastIndex = 0;
6372
6929
  while ((m = CHILD_CALL_RE2.exec(content)) !== null) {
6373
6930
  const interp = m[1];
6374
- const path6 = m[2].trim();
6931
+ const path7 = m[2].trim();
6375
6932
  let rest = m[3].trim();
6376
- if (path6.startsWith("-") || path6.startsWith("$") || path6.includes("/dev/")) continue;
6933
+ if (path7.startsWith("-") || path7.startsWith("$") || path7.includes("/dev/")) continue;
6377
6934
  rest = rest.split(/[;|&<>]/)[0].trim();
6378
6935
  const args = [];
6379
6936
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6380
6937
  args.push(tm[1] ? tm[2] : tm[3]);
6381
6938
  }
6382
- calls.push({ path: path6, args, interpreter: interp });
6939
+ calls.push({ path: path7, args, interpreter: interp });
6383
6940
  }
6384
6941
  return calls;
6385
6942
  }
@@ -6452,11 +7009,11 @@ function pickBackend(pathStr) {
6452
7009
  function resolvePath(p, baseDir) {
6453
7010
  let expanded = p;
6454
7011
  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);
7012
+ expanded = path4.join(os2.homedir(), expanded.slice(1));
7013
+ } else if (!path4.isAbsolute(expanded) && baseDir) {
7014
+ expanded = path4.join(baseDir, expanded);
6458
7015
  }
6459
- return path3.resolve(expanded);
7016
+ return path4.resolve(expanded);
6460
7017
  }
6461
7018
  function readScript(pathStr, maxFileSize) {
6462
7019
  try {
@@ -6535,7 +7092,7 @@ var RecursiveTracker = class {
6535
7092
  const baseDir = cwd || process.cwd();
6536
7093
  const resolved = resolvePath(entryPath);
6537
7094
  this.result.entryPath = resolved;
6538
- this.visitScript(resolved, 0, path3.dirname(resolved), entryArgs);
7095
+ this.visitScript(resolved, 0, path4.dirname(resolved), entryArgs);
6539
7096
  const nodes = this.result.nodes;
6540
7097
  this.result.hasCritical = nodes.some((n) => n.l1RiskLevel === "critical" || n.l2RiskLevel === "critical" || n.keywordRiskLevel === "critical") || this.result.hasCritical;
6541
7098
  this.result.hasHigh = nodes.some((n) => ["high", "critical"].includes(n.l1RiskLevel) || ["high", "critical"].includes(n.l2RiskLevel) || ["high", "critical"].includes(n.keywordRiskLevel));
@@ -6597,12 +7154,12 @@ var RecursiveTracker = class {
6597
7154
  }
6598
7155
  }
6599
7156
  }
6600
- const parentDir = path3.dirname(pathStr);
7157
+ const parentDir = path4.dirname(pathStr);
6601
7158
  const childPaths = [];
6602
7159
  for (const call of ir.calls) {
6603
7160
  const child = resolvePath(call.path, parentDir);
6604
7161
  childPaths.push(child);
6605
- this.visitScript(child, depth + 1, path3.dirname(child), call.args);
7162
+ this.visitScript(child, depth + 1, path4.dirname(child), call.args);
6606
7163
  if (this.result.hasCritical) break;
6607
7164
  }
6608
7165
  node.childPaths = childPaths;
@@ -6810,7 +7367,7 @@ function shlexSplit(s) {
6810
7367
  function resolvePath2(p) {
6811
7368
  let expanded = p;
6812
7369
  if (expanded.startsWith("~/") || expanded === "~") {
6813
- expanded = join10(homedir4(), expanded.slice(1));
7370
+ expanded = join11(homedir5(), expanded.slice(1));
6814
7371
  }
6815
7372
  return resolve10(expanded);
6816
7373
  }
@@ -6933,8 +7490,8 @@ function analyzeScriptContent2(input, ext) {
6933
7490
  resolvedPath = inline;
6934
7491
  isInline = true;
6935
7492
  }
6936
- if (resolvedPath && !isAbsolute3(resolvedPath) && !resolvedPath.startsWith("~/")) {
6937
- resolvedPath = join10(input.cwd || process.cwd(), resolvedPath);
7493
+ if (resolvedPath && !isAbsolute4(resolvedPath) && !resolvedPath.startsWith("~/")) {
7494
+ resolvedPath = join11(input.cwd || process.cwd(), resolvedPath);
6938
7495
  }
6939
7496
  const l1Adapter = (content) => {
6940
7497
  const j = scanDangerousCommandPatterns("bash", content, input.osType);
@@ -7021,14 +7578,14 @@ ${contentPreview}
7021
7578
  }
7022
7579
 
7023
7580
  // src/engine/llm-analyzer.ts
7024
- import { openSync as openSync2, writeSync as writeSync2, closeSync as closeSync2, constants as fsConstants2 } from "fs";
7581
+ import { openSync as openSync3, writeSync as writeSync2, closeSync as closeSync3, constants as fsConstants2 } from "fs";
7025
7582
  import OpenAI from "openai";
7026
7583
 
7027
7584
  // src/infra/trace-log.ts
7028
7585
  init_esm_shims();
7029
7586
  init_paths();
7030
7587
  import fs4 from "fs";
7031
- import path4 from "path";
7588
+ import path5 from "path";
7032
7589
  var LEVEL_OFF = 0;
7033
7590
  var LEVEL_SUMMARY = 1;
7034
7591
  var LEVEL_FULL = 2;
@@ -7076,7 +7633,7 @@ function tracePath() {
7076
7633
  const explicit = (process.env.AGENT_MOSS_TRACE_PATH || "").trim();
7077
7634
  if (explicit) return explicit;
7078
7635
  try {
7079
- return path4.join(getDataRoot(), "agent_moss_trace.log");
7636
+ return path5.join(getDataRoot(), "agent_moss_trace.log");
7080
7637
  } catch {
7081
7638
  return "agent_moss_trace.log";
7082
7639
  }
@@ -7115,7 +7672,7 @@ function trace(event, level = LEVEL_SUMMARY, fields = {}) {
7115
7672
  `;
7116
7673
  const file = tracePath();
7117
7674
  try {
7118
- const dir = path4.dirname(file);
7675
+ const dir = path5.dirname(file);
7119
7676
  if (dir && dir !== ".") fs4.mkdirSync(dir, { recursive: true });
7120
7677
  try {
7121
7678
  const st = fs4.statSync(file);
@@ -7560,11 +8117,11 @@ ${prompt}
7560
8117
  `;
7561
8118
  let flags = fsConstants2.O_WRONLY | fsConstants2.O_CREAT | fsConstants2.O_APPEND;
7562
8119
  if (fsConstants2.O_NOFOLLOW) flags |= fsConstants2.O_NOFOLLOW;
7563
- const fd = openSync2(logPath, flags, 384);
8120
+ const fd = openSync3(logPath, flags, 384);
7564
8121
  try {
7565
8122
  writeSync2(fd, line);
7566
8123
  } finally {
7567
- closeSync2(fd);
8124
+ closeSync3(fd);
7568
8125
  }
7569
8126
  } catch (e) {
7570
8127
  console.warn("[AgentMoss] Failed to write LLM prompt to log:", e);
@@ -7852,9 +8409,9 @@ init_esm_shims();
7852
8409
  // src/brain/rule-store.ts
7853
8410
  init_esm_shims();
7854
8411
  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");
8412
+ import { join as join12 } from "path";
8413
+ import { homedir as homedir6 } from "os";
8414
+ var DEFAULT_RULES_PATH = join12(homedir6(), ".agentmoss", "brain", "rules.json");
7858
8415
  var ENV_RULES_PATH = "AGENT_MOSS_BRAIN_RULES_PATH";
7859
8416
  var STATUS_DRAFT = "draft";
7860
8417
  var STATUS_APPROVED = "approved";
@@ -7878,8 +8435,8 @@ function uuid() {
7878
8435
  var BrainRuleStore = class {
7879
8436
  path;
7880
8437
  data;
7881
- constructor(path6) {
7882
- this.path = path6 || getRulesPath();
8438
+ constructor(path7) {
8439
+ this.path = path7 || getRulesPath();
7883
8440
  this.data = this.load();
7884
8441
  }
7885
8442
  load() {
@@ -8325,10 +8882,10 @@ ${reason.slice(0, 500)}
8325
8882
  const pathRe = new RegExp(pathPrefix + pathBody + pathSuffix, "g");
8326
8883
  let mm;
8327
8884
  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);
8885
+ const path7 = mm[1];
8886
+ if (path7.split("/").length < 3) continue;
8887
+ if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path7)) continue;
8888
+ const gen = this.generalizePath(path7);
8332
8889
  if (seen.has(gen)) continue;
8333
8890
  seen.add(gen);
8334
8891
  patterns.push({ pattern: gen, layer: 1, scope: "openat", ruleType: "deny_path" });
@@ -8347,8 +8904,8 @@ ${reason.slice(0, 500)}
8347
8904
  }
8348
8905
  return false;
8349
8906
  }
8350
- generalizePath(path6) {
8351
- const p = path6.toLowerCase();
8907
+ generalizePath(path7) {
8908
+ const p = path7.toLowerCase();
8352
8909
  if (/\/etc\/(shadow|passwd|sudoers|security|ssh)/.test(p)) {
8353
8910
  return "(?:^|[^a-z0-9_-])etc/(?:shadow|passwd|sudoers|security/|ssh/)";
8354
8911
  }
@@ -8468,10 +9025,10 @@ function parseReview(content) {
8468
9025
  // src/brain/skill-manager.ts
8469
9026
  init_esm_shims();
8470
9027
  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";
9028
+ import { homedir as homedir7 } from "os";
9029
+ import { join as join13 } from "path";
8473
9030
  import { randomUUID } from "crypto";
8474
- var DEFAULT_SKILL_META_PATH = join12(homedir6(), ".agentmoss", "brain", "skill_meta.json");
9031
+ var DEFAULT_SKILL_META_PATH = join13(homedir7(), ".agentmoss", "brain", "skill_meta.json");
8475
9032
  var ENV_SKILL_META_PATH = "AGENT_MOSS_BRAIN_SKILL_META_PATH";
8476
9033
  function getMetaPath(override) {
8477
9034
  return override || process.env[ENV_SKILL_META_PATH] || DEFAULT_SKILL_META_PATH;
@@ -8481,7 +9038,7 @@ var BrainSkillManager = class {
8481
9038
  this.skillsDir = skillsDir;
8482
9039
  this.metaPath = getMetaPath(metaPath);
8483
9040
  try {
8484
- mkdirSync5(join12(this.metaPath, ".."), { recursive: true });
9041
+ mkdirSync5(join13(this.metaPath, ".."), { recursive: true });
8485
9042
  } catch {
8486
9043
  }
8487
9044
  this.load();
@@ -8516,7 +9073,7 @@ var BrainSkillManager = class {
8516
9073
  let changed = false;
8517
9074
  for (const sk of this.skills) {
8518
9075
  if (sk.status !== "active") continue;
8519
- if (!existsSync14(join12(this.skillsDir, `${sk.name}.md`))) {
9076
+ if (!existsSync14(join13(this.skillsDir, `${sk.name}.md`))) {
8520
9077
  sk.status = "stale";
8521
9078
  changed = true;
8522
9079
  }
@@ -8528,7 +9085,7 @@ var BrainSkillManager = class {
8528
9085
  const id = skill.id || randomUUID();
8529
9086
  const name = skill.name || `brain_${id.slice(0, 8)}`;
8530
9087
  if (!existsSync14(this.skillsDir)) return "";
8531
- const mdPath = join12(this.skillsDir, `${name}.md`);
9088
+ const mdPath = join13(this.skillsDir, `${name}.md`);
8532
9089
  if (existsSync14(mdPath)) return "";
8533
9090
  try {
8534
9091
  writeFileSync4(mdPath, skill.content, "utf-8");
@@ -8578,7 +9135,7 @@ var BrainSkillManager = class {
8578
9135
  const out = [];
8579
9136
  for (const sk of this.skills) {
8580
9137
  if (sk.origin_node !== "local" || sk.status !== "active") continue;
8581
- const mdPath = join12(this.skillsDir, `${sk.name}.md`);
9138
+ const mdPath = join13(this.skillsDir, `${sk.name}.md`);
8582
9139
  if (!existsSync14(mdPath)) continue;
8583
9140
  out.push({
8584
9141
  name: sk.name,
@@ -9143,12 +9700,12 @@ function allNodesFlat(mg) {
9143
9700
  // src/engine/formal-engine/properties.ts
9144
9701
  init_esm_shims();
9145
9702
  init_rules_loader();
9146
- function graphFromPath(nodes, path6, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
9703
+ function graphFromPath(nodes, path7, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
9147
9704
  const byKey = /* @__PURE__ */ new Map();
9148
9705
  for (const n of nodes) byKey.set(`${n.sessionId}#${n.seq}`, n);
9149
9706
  const gNodes = [];
9150
9707
  const gEdges = [];
9151
- for (const item of path6) {
9708
+ for (const item of path7) {
9152
9709
  const n = byKey.get(`${item.sessionId}#${item.seq}`);
9153
9710
  gNodes.push({
9154
9711
  session_id: item.sessionId,
@@ -9217,22 +9774,22 @@ function checkCrossSessionChain(graph) {
9217
9774
  if (witness !== void 0) {
9218
9775
  if (nodes[witness].stage !== stages[stages.length - 1]) continue;
9219
9776
  let matched = 0;
9220
- const path6 = [];
9777
+ const path7 = [];
9221
9778
  for (let k = 0; k < witness; k++) {
9222
9779
  const n = nodes[k];
9223
9780
  if (matched < stages.length - 1 && n.stage === stages[matched]) {
9224
9781
  matched += 1;
9225
- path6.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
9782
+ path7.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
9226
9783
  }
9227
9784
  }
9228
9785
  if (matched < stages.length - 1) continue;
9229
- path6.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
9786
+ path7.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
9230
9787
  violations.push({
9231
9788
  propertyId: "cross-" + chain.id,
9232
9789
  reason: chain.reason,
9233
9790
  riskLevel: chain.riskLevel,
9234
- path: path6,
9235
- graph: graphFromPath(nodes, path6, "next", {
9791
+ path: path7,
9792
+ graph: graphFromPath(nodes, path7, "next", {
9236
9793
  property_id: "cross-" + chain.id,
9237
9794
  property_short: "P1",
9238
9795
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -9242,11 +9799,11 @@ function checkCrossSessionChain(graph) {
9242
9799
  } else {
9243
9800
  let matched = 0;
9244
9801
  let stageIdx = 0;
9245
- const path6 = [];
9802
+ const path7 = [];
9246
9803
  for (const n of nodes) {
9247
9804
  if (stageIdx < stages.length && n.stage === stages[stageIdx]) {
9248
9805
  matched += 1;
9249
- path6.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
9806
+ path7.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
9250
9807
  stageIdx += 1;
9251
9808
  if (matched >= stages.length) break;
9252
9809
  }
@@ -9256,8 +9813,8 @@ function checkCrossSessionChain(graph) {
9256
9813
  propertyId: "cross-" + chain.id,
9257
9814
  reason: chain.reason,
9258
9815
  riskLevel: chain.riskLevel,
9259
- path: path6,
9260
- graph: graphFromPath(nodes, path6, "next", {
9816
+ path: path7,
9817
+ graph: graphFromPath(nodes, path7, "next", {
9261
9818
  property_id: "cross-" + chain.id,
9262
9819
  property_short: "P1",
9263
9820
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -9486,7 +10043,7 @@ function checkNeverExfilAfterPrivesc(graph) {
9486
10043
  if (candidates.length > 0) {
9487
10044
  const pre = nodes[candidates[candidates.length - 1]];
9488
10045
  const post = nodes[firstEv];
9489
- const path6 = [
10046
+ const path7 = [
9490
10047
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
9491
10048
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
9492
10049
  ];
@@ -9494,8 +10051,8 @@ function checkNeverExfilAfterPrivesc(graph) {
9494
10051
  propertyId: "no-exfil-after-privesc",
9495
10052
  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
10053
  riskLevel: "critical",
9497
- path: path6,
9498
- graph: graphFromPath(nodes, path6, "next", {
10054
+ path: path7,
10055
+ graph: graphFromPath(nodes, path7, "next", {
9499
10056
  property_id: "no-exfil-after-privesc",
9500
10057
  property_short: "P4",
9501
10058
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -9512,7 +10069,7 @@ function checkNeverExfilAfterPrivesc(graph) {
9512
10069
  for (let j = i + 1; j < nodes.length; j++) {
9513
10070
  if (!isExfilNode(nodes[j])) continue;
9514
10071
  if (privescInWindow(nodes, [i], j, windowSec).length === 0) continue;
9515
- const path6 = [
10072
+ const path7 = [
9516
10073
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
9517
10074
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
9518
10075
  ];
@@ -9520,8 +10077,8 @@ function checkNeverExfilAfterPrivesc(graph) {
9520
10077
  propertyId: "no-exfil-after-privesc",
9521
10078
  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
10079
  riskLevel: "critical",
9523
- path: path6,
9524
- graph: graphFromPath(nodes, path6, "next", {
10080
+ path: path7,
10081
+ graph: graphFromPath(nodes, path7, "next", {
9525
10082
  property_id: "no-exfil-after-privesc",
9526
10083
  property_short: "P4",
9527
10084
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -9553,7 +10110,7 @@ function checkNeverExfilAfterCred(graph) {
9553
10110
  }
9554
10111
  if (pre) {
9555
10112
  const post = nodes[firstEv];
9556
- const path6 = [
10113
+ const path7 = [
9557
10114
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
9558
10115
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
9559
10116
  ];
@@ -9561,8 +10118,8 @@ function checkNeverExfilAfterCred(graph) {
9561
10118
  propertyId: "no-exfil-after-credential",
9562
10119
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
9563
10120
  riskLevel: "critical",
9564
- path: path6,
9565
- graph: graphFromPath(nodes, path6, "data", {
10121
+ path: path7,
10122
+ graph: graphFromPath(nodes, path7, "data", {
9566
10123
  property_id: "no-exfil-after-credential",
9567
10124
  property_short: "P5",
9568
10125
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -9578,7 +10135,7 @@ function checkNeverExfilAfterCred(graph) {
9578
10135
  if (!isCredNode(nodes[i])) continue;
9579
10136
  for (let j = i + 1; j < nodes.length; j++) {
9580
10137
  if (isExfilNode(nodes[j])) {
9581
- const path6 = [
10138
+ const path7 = [
9582
10139
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
9583
10140
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
9584
10141
  ];
@@ -9586,8 +10143,8 @@ function checkNeverExfilAfterCred(graph) {
9586
10143
  propertyId: "no-exfil-after-credential",
9587
10144
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
9588
10145
  riskLevel: "critical",
9589
- path: path6,
9590
- graph: graphFromPath(nodes, path6, "data", {
10146
+ path: path7,
10147
+ graph: graphFromPath(nodes, path7, "data", {
9591
10148
  property_id: "no-exfil-after-credential",
9592
10149
  property_short: "P5",
9593
10150
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -9751,13 +10308,13 @@ function checkSensitiveDataAggregation(graph) {
9751
10308
  if (!isExfilNode(n)) continue;
9752
10309
  const srcs = sourcesFor(i);
9753
10310
  if (srcs.size >= 2) {
9754
- const path6 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
10311
+ const path7 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
9755
10312
  violations.push({
9756
10313
  propertyId: "sensitive-data-aggregation",
9757
10314
  reason: `\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20\uFF1Aegress \u805A\u5408 ${srcs.size} \u4E2A\u4E8B\u4EF6\u6E90\u6570\u636E\uFF08Rule 12\uFF09`,
9758
10315
  riskLevel: "critical",
9759
- path: path6,
9760
- graph: graphFromPath(nodes, path6, "next", {
10316
+ path: path7,
10317
+ graph: graphFromPath(nodes, path7, "next", {
9761
10318
  property_id: "sensitive-data-aggregation",
9762
10319
  property_short: "P8",
9763
10320
  property_name: "\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20"
@@ -9848,8 +10405,8 @@ init_rules_loader();
9848
10405
  // src/engine/formal-engine/chain_state.ts
9849
10406
  init_esm_shims();
9850
10407
  import * as fs5 from "fs";
9851
- import * as os2 from "os";
9852
- import * as path5 from "path";
10408
+ import * as os3 from "os";
10409
+ import * as path6 from "path";
9853
10410
  import { createHash as createHash2 } from "crypto";
9854
10411
 
9855
10412
  // src/engine/coordinator.ts
@@ -10091,7 +10648,7 @@ async function runAnalysis(input) {
10091
10648
  skipLLM = true;
10092
10649
  }
10093
10650
  }
10094
- const logicResult = isLogicRulesEnabled() ? runLogicCheck(input) : null;
10651
+ const logicResult = isLogicRulesEnabled() ? runLogicCheck(input, { agentExt }) : null;
10095
10652
  if (logicResult) {
10096
10653
  traceSummary("l2.result", {
10097
10654
  hit: !logicResult.allowed,