@kenhkl/agent-moss 0.17.44 → 0.17.46

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.
@@ -4,7 +4,7 @@
4
4
  <meta charset="UTF-8">
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
6
  <title>AgentMoss 安全策略管控台</title>
7
- <script src="/console/static/vendor/echarts.min.js"></script>
7
+ <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
8
8
  <style>
9
9
  /* ===== OpenDesk --ag- design tokens(浅色玻璃态 + dark mode)===== */
10
10
  :root {
@@ -104,6 +104,7 @@ body {
104
104
 
105
105
  /* 分类可折叠 + 大类总开关 */
106
106
  .ag-cat-header { display: flex; align-items: center; justify-content: space-between; cursor: pointer; padding: 4px 0 8px; border-bottom: 1px solid var(--ag-divider); }
107
+ .ag-cat-desc { font-size:11px; font-weight:400; color:var(--ag-text-secondary); margin-top:2px; }
107
108
  .ag-cat-name { font-size: 13px; font-weight: 600; color: var(--ag-text-heading); display: flex; align-items: center; gap: 8px; }
108
109
  .ag-cat-count { font-size: 11px; color: var(--ag-text-secondary); background: var(--ag-code-bg); padding: 1px 8px; border-radius: 10px; }
109
110
  .ag-cat-controls { display: flex; align-items: center; gap: 12px; }
@@ -132,6 +133,16 @@ body {
132
133
  .ag-badge-builtin { background: var(--ag-code-bg); color: var(--ag-text-secondary); font-size: 10px; padding: 1px 6px; border-radius: 3px; }
133
134
  .ag-badge-custom { background: rgba(0,122,255,.12); color: var(--ag-accent); font-size: 10px; padding: 1px 6px; border-radius: 3px; }
134
135
  .ag-badge-removed { background: rgba(255,149,0,.12); color: var(--ag-orange); font-size: 10px; padding: 1px 6px; border-radius: 3px; border: 1px solid rgba(255,149,0,.3); }
136
+ .ag-badge-os { background: var(--ag-code-bg); color: var(--ag-text-secondary); font-size: 10px; padding: 1px 6px; border-radius: 3px; }
137
+ .ag-badge-inactive { background: rgba(255,149,0,.10); color: var(--ag-orange); font-size: 10px; padding: 1px 6px; border-radius: 3px; }
138
+ .ag-badge-ask { background: rgba(64,158,255,.12); color: #409eff; font-size: 10px; padding: 1px 6px; border-radius: 3px; }
139
+ .ag-ask-toggle { display: inline-flex; align-items: center; gap: 4px; font-size: 12px; color: var(--ag-text-secondary); cursor: pointer; user-select: none; white-space: nowrap; }
140
+ .ag-ask-toggle input { cursor: pointer; }
141
+ /* 风险等级说明:两行徽章列等宽,说明文字起始位置对齐 */
142
+ .ag-legend-card { padding: 8px 16px; font-size: 12px; line-height: 1.7; color: var(--ag-text-secondary); }
143
+ .ag-legend-card > b { display: block; margin-bottom: 4px; }
144
+ .ag-legend-grid { display: grid; grid-template-columns: max-content 1fr; column-gap: 10px; row-gap: 2px; align-items: start; }
145
+ .ag-legend-grid .ag-badge { justify-self: start; margin-top: 2px; white-space: nowrap; }
135
146
 
136
147
  /* 风险类型标签(左边框彩色) */
137
148
  .ag-risk-type { font-size: 11px; padding: 2px 8px; border-radius: 4px; font-weight: 500; border-left: 3px solid; background: var(--ag-code-bg); color: var(--ag-text); }
@@ -164,6 +175,12 @@ body {
164
175
  .ag-skip-l3:hover { color: var(--ag-text); }
165
176
  .ag-skip-l3 input { width: 14px; height: 14px; cursor: pointer; accent-color: var(--ag-accent); }
166
177
 
178
+ /* 平台过滤条:勾选框与文字同行居中对齐(默认 baseline 会偏低) */
179
+ .ag-platform-os-toggle { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; line-height: 1.4; color: var(--ag-text-secondary); cursor: pointer; }
180
+ .ag-platform-os-toggle:hover { color: var(--ag-text); }
181
+ .ag-platform-os-toggle input { width: 14px; height: 14px; margin: 0; flex: 0 0 auto; cursor: pointer; accent-color: var(--ag-accent); }
182
+ .ag-platform-os-toggle span { line-height: 1.4; }
183
+
167
184
  /* 搜索结果层标识 */
168
185
  .ag-layer-badge { font-size: 10px; padding: 1px 6px; border-radius: 3px; font-weight: 600; color: #fff; }
169
186
  .ag-layer-l1 { background: #6366f1; }
@@ -391,7 +408,30 @@ async function loadEnvOverrides() {
391
408
  return resp?.overrides || {};
392
409
  }
393
410
 
394
- let state = { config: {}, envOverrides: {}, currentPage: 'overview' };
411
+ // 视图偏好持久化(来源:内置/自定义;分组:按分类/按命令)
412
+ function readPref(key, def) {
413
+ try { return localStorage.getItem(key) || def; } catch { return def; }
414
+ }
415
+ function savePref(key, val) {
416
+ try { localStorage.setItem(key, val); } catch { /* 隐私模式等忽略 */ }
417
+ }
418
+ let state = {
419
+ config: {}, envOverrides: {}, currentPage: 'overview',
420
+ // 当前进程平台(由 /api/config 的 platform 字段下发);默认只展示当前平台适用
421
+ // 的规则——其他平台规则在本机永远不会生效,展示出来会让用户误以为可以配置。
422
+ platform: { os_type: 'linux', accepted_os: ['linux'] },
423
+ showOtherOs: false,
424
+ // 搜索关键词:搜索页里启停规则会触发整页重渲染,必须保留关键词和结果,
425
+ // 否则用户每点一次开关,搜索就被清空(2026-11 用户反馈)。
426
+ searchQuery: '',
427
+ // 一级:规则来源(内置 / 自定义);二级:分组方式(按分类 / 按命令)。
428
+ // 只是展示维度,规则对象、ID、开关/删除操作完全不变。
429
+ ruleOwner: readPref('ag_rule_owner', 'builtin'),
430
+ ruleGroupMode: readPref('ag_rule_group', 'category'),
431
+ // Ask 标记:功能尚未实现真正的 Ask 决策,默认不显示勾选框,避免误以为已支持。
432
+ // 打开后才显示单条/整类 Ask 勾选,并展示"当前只加标签、仍 Deny"的说明。
433
+ showAsk: readPref('ag_show_ask', '0') === '1',
434
+ };
395
435
  const expandedCats = new Set();
396
436
  let currentModalAction = null;
397
437
 
@@ -405,8 +445,9 @@ const LAYER_NAMES = {
405
445
  };
406
446
  const L1_CATEGORY_NAMES = {
407
447
  dangerous_commands: t('⚡ 危险命令检测', '⚡ Dangerous Commands'),
408
- injection_detection: t('🎯 注入攻击检测', '🎯 Injection Attack Detection'),
448
+ injection_detection: t('🎯 注入特征(仅交 L3,不直接拦截)', '🎯 Injection signals (L3 only, no direct block)'),
409
449
  sensitive_path_access: t('🛡️ 敏感路径访问', '🛡️ Sensitive Path Access'),
450
+ builtin_detectors: t('🧩 内置检测器(可单独启停)', '🧩 Built-in detectors (toggleable)'),
410
451
  user_custom: t('🔧 用户自定义', '🔧 User Custom'),
411
452
  };
412
453
  const L2_CATEGORY_NAMES = {
@@ -462,6 +503,12 @@ function denyModeBadge(mode) {
462
503
  const m = mode || 'deny_write';
463
504
  return `<span class="ag-deny-mode ${denyModeClass(m)}" title="${t('拦截模式: ', 'Interception mode: ')}${denyModeLabel(m)}">${denyModeLabel(m)}</span>`;
464
505
  }
506
+ function askBadge(on) {
507
+ return on ? `<span class="ag-badge ag-badge-ask" title="${t('命中后建议询问用户:当前仍返回 Deny,只附带 ask 标签;未来实现 Ask 决策时复用该标记', 'Suggest asking the user on match: still returns Deny today with an ask label; the same flag will drive real Ask decisions later')}">Ask</span>` : '';
508
+ }
509
+ function askToggle(layer, cat, id, on, disabled) {
510
+ return `<label class="ag-ask-toggle" title="${t('勾选不改变判定:原本 Deny 的仍 Deny,原本交 L3 的仍交 L3;只有最终 Deny 时附带 ask_recommended/ask_reason。不会直接 Deny 的规则当前不产生标签', 'Checking does not change the verdict: deny stays deny, L3 hand-off stays. Only a final Deny adds ask_recommended/ask_reason; rules that do not deny directly produce no label today')}" onclick="event.stopPropagation()"><input type="checkbox" ${on ? 'checked' : ''} ${disabled ? 'disabled' : ''} onchange="updateAsk('${layer}','${cat}','${id}',this.checked)"> Ask</label>`;
511
+ }
465
512
  function sourceDenyModeBadges(rule) {
466
513
  if (rule.builtin !== false && rule.source_deny_mode) {
467
514
  let h = `<span class="ag-source-badge" title="${t('源码出厂的原始拦截模式。当前模式与之不同时表示已被用户覆盖', 'Source default interception mode. A different current mode means the user has overridden it')}">${t('原始: ', 'Source: ')}${denyModeLabel(rule.source_deny_mode)}</span>`;
@@ -572,6 +619,10 @@ function agPrompt(title, opts = {}) {
572
619
  // ===== Pages =====
573
620
  async function refreshConfig() {
574
621
  state.config = await api('config');
622
+ // 后端下发的当前进程平台(老版本后端没有该字段时兜底 linux)
623
+ if (state.config.platform && state.config.platform.os_type) {
624
+ state.platform = state.config.platform;
625
+ }
575
626
  // cold / builtin 模式:顶部显示只读横幅(写接口由后端统一 403)
576
627
  const rulesMode = state.config.rules_mode || (state.config.builtin_only ? 'builtin' : 'hot');
577
628
  if (rulesMode === 'cold' || rulesMode === 'builtin') {
@@ -698,13 +749,99 @@ async function loadOverviewToken(days) {
698
749
  el('overview-token-breakdown').innerHTML = html || `<div class="ag-empty">${t('无分项数据', 'No breakdown data')}</div>`;
699
750
  } catch { el('overview-token-summary').innerHTML = `<div class="ag-empty">${t('无数据', 'No data')}</div>`; }
700
751
  }
701
- function countRules(lr) { if (!lr) return 0; return Object.values(lr).reduce((s, c) => s + (c.rules ? c.rules.length : 0), 0); }
752
+ // ===== 平台过滤(2026-11)=====
753
+ // runtime 种子按设计保留全平台规则(多平台配置/迁移需要),但**本机只有当前
754
+ // 平台能生效**。Console 默认只展示当前平台适用的规则;用户显式勾选"显示其他
755
+ // 平台"才全部展示。注意:被层级/大类/单条开关关掉的规则仍然展示(否则用户
756
+ // 无法重新打开),只标注"未生效"并禁用无效开关。
757
+ const OS_LABELS = { linux: 'Linux', windows: 'Windows', macos: 'macOS', harmony: t('鸿蒙', 'HarmonyOS') };
758
+ function platformAcceptedOs() { return new Set((state.platform && state.platform.accepted_os) || ['linux']); }
759
+ function ruleOsOf(r) { return String((r && r.os) || 'linux').toLowerCase(); }
760
+ function ruleAppliesHere(r) {
761
+ if (state.showOtherOs) return true;
762
+ const os = ruleOsOf(r);
763
+ return os === 'all' || platformAcceptedOs().has(os);
764
+ }
765
+ function platformFilteredRules(rules) { return (rules || []).filter(ruleAppliesHere); }
766
+ function osBadge(os) {
767
+ const key = String(os || 'linux').toLowerCase();
768
+ return `<span class="ag-badge ag-badge-os">${escapeHtml(OS_LABELS[key] || key)}</span>`;
769
+ }
770
+ // 命中后的实际行为:直接拦截 / 交 L3 判断(与 coordinator 的判级口径一致)。
771
+ function enforcementOf(layerKey, r) {
772
+ const lvl = String(r.risk_level || '').toLowerCase();
773
+ const rt = String(r.risk_type || '').toLowerCase();
774
+ if (lvl === 'critical' || lvl === 'high') return 'block';
775
+ // Coordinator 特例:L1 medium 的 file_access / resource_exhaustion 也直接 Deny
776
+ if (layerKey === 'L1_rules' && lvl === 'medium'
777
+ && (rt === 'file_access' || rt === 'resource_exhaustion')) return 'block';
778
+ return 'l3';
779
+ }
780
+ function enforcementBadge(layerKey, r) {
781
+ const block = enforcementOf(layerKey, r) === 'block';
782
+ const title = block
783
+ ? t('命中后直接拦截(Deny),不再执行', 'Blocks immediately (Deny) when matched')
784
+ : t('命中后不直接拦截:作为风险线索交给 L3 语义分析;L3 未启用或调用失败(默认 fail_open)时最终放行', 'Does not block directly: the hit is passed to L3 as a risk signal; if L3 is disabled or fails (default fail_open) the action is allowed');
785
+ return `<span class="ag-badge ${block ? 'ag-badge-deny' : 'ag-badge-medium'}" title="${escapeHtml(title)}">${block ? t('命中即拦截', 'blocks on match') : t('交 L3 判断', 'handed to L3')}</span>`;
786
+ }
787
+ // 等级说明:用户必须能看懂 critical/high 和 medium/low 的区别。
788
+ function riskLegendCard() {
789
+ // 两行共用**同一个** grid:徽章列宽取两行最大值,说明文字起始位置才真正对齐。
790
+ // (每行各自一个 grid 时,两列宽度分别计算,文字仍会错开。)
791
+ return `<div class="ag-card ag-legend-card">
792
+ <b>${t('风险等级与拦截方式', 'Risk levels & enforcement')}</b>
793
+ <div class="ag-legend-grid">
794
+ <span class="ag-badge ag-badge-deny">critical / high</span>
795
+ <span>${t('命中后直接拦截(Deny),命令不会执行。', 'Blocks immediately on match (Deny); the command does not run.')}</span>
796
+ <span class="ag-badge ag-badge-medium">medium / low</span>
797
+ <span>${t('命中后不直接拦截:作为风险线索交给 L3 语义分析;L3 未启用或调用失败(默认 fail_open)时最终放行。例外:L1 的 medium 级 file_access / resource_exhaustion 仍直接拦截。', 'Not blocked directly on match: the hit is passed to L3 as a risk signal; if L3 is disabled or fails (default fail_open) it is allowed. Exception: L1 medium file_access / resource_exhaustion still block.')}</span>
798
+ </div>
799
+ </div>`;
800
+ }
801
+ function toggleShowOtherOs(on) {
802
+ state.showOtherOs = !!on;
803
+ renderCurrent();
804
+ if (state.currentPage === 'search') searchRules();
805
+ }
806
+ // 一级:内置 / 自定义(只影响展示,规则对象与操作不变)
807
+ function setRuleOwner(owner) {
808
+ state.ruleOwner = owner === 'custom' ? 'custom' : 'builtin';
809
+ savePref('ag_rule_owner', state.ruleOwner);
810
+ renderCurrent();
811
+ }
812
+ // 二级:按分类 / 按命令(只影响展示分组)
813
+ function setRuleGroupMode(mode) {
814
+ state.ruleGroupMode = mode === 'command' ? 'command' : 'category';
815
+ savePref('ag_rule_group', state.ruleGroupMode);
816
+ renderCurrent();
817
+ }
818
+ function setShowAsk(on) {
819
+ state.showAsk = !!on;
820
+ savePref('ag_show_ask', state.showAsk ? '1' : '0');
821
+ renderCurrent();
822
+ if (state.currentPage === 'search') searchRules();
823
+ }
824
+ function ruleOwnerOf(r) { return r && r.builtin === false ? 'custom' : 'builtin'; }
825
+ function platformBar() {
826
+ const cur = (state.platform && state.platform.os_type) || 'linux';
827
+ const others = (state.platform && state.platform.accepted_os) || [cur];
828
+ return `<div class="ag-card" style="padding:8px 16px;display:flex;align-items:center;gap:12px;flex-wrap:wrap">
829
+ <span style="font-size:12px;line-height:1.4;color:var(--ag-text-secondary)">${t('当前运行平台:', 'Current platform: ')}<b>${escapeHtml(OS_LABELS[cur] || cur)}</b>${t('(生效规则:', ' (effective OS: ')}${escapeHtml(others.join(' / '))})</span>
830
+ <label class="ag-platform-os-toggle">
831
+ <input type="checkbox" ${state.showOtherOs ? 'checked' : ''} onchange="toggleShowOtherOs(this.checked)">
832
+ <span>${t('显示其他平台规则(本机不生效)', 'Show other-platform rules (inactive here)')}</span>
833
+ </label>
834
+ </div>`;
835
+ }
836
+ function countRules(lr) { if (!lr) return 0; return Object.values(lr).reduce((s, c) => s + platformFilteredRules(c.rules).length, 0); }
702
837
  // 统计"启用"的规则数,口径与后端执行一致:层级开 && 大类开 && 单条规则开。
703
838
  // layerKey 为层级总开关(如 L1_heuristic),关闭时返回 0。
704
839
  function countEnabled(lr, layerKey) {
705
840
  if (!lr) return 0;
706
841
  if (layerKey && state.config.layers?.[layerKey] === false) return 0;
707
- return Object.values(lr).reduce((s, c) => s + ((c.rules || []).filter(r => r.enabled && c.category_enabled !== false).length), 0);
842
+ return Object.values(lr).reduce(
843
+ (s, c) => s + platformFilteredRules(c.rules)
844
+ .filter(r => r.enabled && !r.source_removed && c.category_enabled !== false).length, 0);
708
845
  }
709
846
  function countSkills(ls) { if (!ls) return 0; return Object.values(ls).reduce((s, c) => s + (c.skills ? c.skills.length : 0), 0); }
710
847
  // 同 countEnabled:层级关闭时 L3 skills 启用数归 0。
@@ -750,6 +887,16 @@ async function toggleCategory(layer, category) {
750
887
  showToast(t('分类已', 'Category ') + (!cur ? t('启用', 'enabled') : t('禁用', 'disabled')));
751
888
  } catch (e) { showToast(t('操作失败: ', 'Operation failed: ') + e.message, 'error'); }
752
889
  }
890
+ async function toggleInjectionTier(tier) {
891
+ try {
892
+ const cat = state.config.L1_rules?.injection_detection || {};
893
+ const cur = ((cat.tier_enabled || {})[tier]) !== false;
894
+ state.config = await apiPut('rules/tier_enabled', { tier, enabled: !cur });
895
+ renderCurrent();
896
+ showToast(t('注入', 'Injection') + ' ' + (tier === 'strong' ? t('强特征', 'strong') : t('弱特征', 'weak'))
897
+ + t(' 已', ' ') + (!cur ? t('启用', 'enabled') : t('禁用', 'disabled')));
898
+ } catch (e) { showToast(t('操作失败: ', 'Operation failed: ') + e.message, 'error'); }
899
+ }
753
900
  // LTL 大类开关(L2.2 的 category_enabled 存于 view 的顶层,而非 category dict 内)
754
901
  async function toggleLtlCategory(en) {
755
902
  try {
@@ -781,99 +928,319 @@ function toggleExpand(id) {
781
928
  // ===== L1/L2 规则页 =====
782
929
  // 规则层容器 -> 层级总开关 key 的映射(用于大类开关随层级开关联动)
783
930
  const LAYER_SWITCH_KEY = { L1_rules: 'L1_heuristic', L2_rules: 'L2_logic_rules', L3_skills: 'L3_llm_analysis' };
784
- function renderRuleLayer(layerKey, containerId, categoryNames, append = false, showAddBtn = true, strict = false) {
931
+ // ===== 分组视图(2026-11)=====
932
+ // 一级按来源(内置/自定义),二级按分类/命令。两种视图只是展示维度:
933
+ // 规则对象、ID、开关/删除/deny_mode 全部按原始 (层, 分类, 规则ID) 操作。
934
+ const GROUP_COMMANDS = [
935
+ 'systemctl','service','journalctl','systemd-run','loginctl','hostnamectl','timedatectl',
936
+ 'crontab','at','autostart',
937
+ 'curl','wget','aria2c','busybox','toybox',
938
+ 'ssh','scp','sftp','rsync','sshpass','telnet','ftp','nmap','masscan','zmap','nc','ncat','socat','nc.traditional',
939
+ 'iptables','ip6tables','ufw','firewall-cmd','nft','setenforce','apparmor_parser',
940
+ 'docker','podman','kubectl','helm','ctr','crictl',
941
+ 'aws','az','gcloud','gsutil','ossutil',
942
+ 'pip','pip3','npm','pnpm','yarn','gem','cargo','go','composer','nuget','pipx',
943
+ 'git','svn','hg',
944
+ 'bash','sh','zsh','dash','ksh','ash','fish','powershell','pwsh','cmd',
945
+ 'python','python3','perl','ruby','node','deno','php','lua',
946
+ 'rm','rmdir','unlink','shred','dd','mkfs','mkfs.ext4','fdisk','parted','mkswap','wipefs',
947
+ 'chmod','chown','chattr','setfacl','chgrp','umask','sudo','su','doas','pkexec',
948
+ 'passwd','chpasswd','usermod','useradd','userdel','groupadd','groupdel','visudo','shadowconfig',
949
+ 'mount','umount','swapon','sysctl','modprobe','insmod','rmmod',
950
+ 'tar','zip','unzip','7z','7za','rar','gzip','bzip2','xz','zstd',
951
+ 'base64','xxd','openssl','gpg','gpg2',
952
+ 'find','grep','egrep','fgrep','rg','ag','ack','sed','awk','xargs','tee','tr','cut','sort','head','tail',
953
+ 'cat','tac','less','more','cp','mv','ln','touch','mkdir','file','stat','readlink','realpath',
954
+ 'echo','printf','env','export','set','unset','kill','pkill','killall','nohup','screen','tmux',
955
+ 'net','sc','wmic','reg','netsh','icacls','cacls','takeown','attrib','certutil','bitsadmin',
956
+ 'mshta','rundll32','regsvr32','taskkill','schtasks','del','rd','type','copy','move','xcopy','robocopy',
957
+ 'mysql','psql','sqlite3','mongosh','mongo','redis-cli','mysqldump','pg_dump','sqlplus','isql',
958
+ 'nslookup','dig','host','ping','traceroute','tracert','tcpdump','ss','netstat','lsof',
959
+ 'bm','aa','param','hdc','begetctl','hilog','adb','ohpm','hvigor','sdb',
960
+ 'auditctl','ausearch','last','lastlog','who','w','users','id','groups','getent',
961
+ 'nc.traditional','nc.openbsd','pax','cpio','install','rename','truncate',
962
+ ];
963
+
964
+ function extractCommandGroups(rule) {
965
+ let pattern = String(rule && rule.pattern || '');
966
+ if (!pattern) return [];
967
+ // 去掉正则里的词边界/字符类标记:`\bsystemctl\s+` 的字面序列是 "bsystemctl",
968
+ // 不剥掉的话命令词前面永远是非边界的 'b',一条都提取不出来。
969
+ pattern = pattern.replace(/\\[bBwsSdDW]/g, ' ');
970
+ const hits = [];
971
+ for (const cmd of GROUP_COMMANDS) {
972
+ const esc = cmd.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
973
+ // 前后排除路径/扩展名上下文:`/etc/passwd` 不归到 passwd 命令组
974
+ const m = pattern.search(new RegExp(`(?:^|[^A-Za-z0-9_./-])${esc}(?![A-Za-z0-9_-])`, 'i'));
975
+ if (m >= 0) hits.push({ cmd, m });
976
+ }
977
+ if (!hits.length) return [];
978
+ hits.sort((a, b) => a.m - b.m);
979
+ // 只取**同一个位置附近**的命令词:`(?:curl|wget)` → curl / wget;
980
+ // `curl|wget|nc|socat|...` 这种大列表由调用方归入「组合命令」。
981
+ const first = hits[0].m;
982
+ return [...new Set(hits.filter(h => h.m <= first + 3).map(h => h.cmd))];
983
+ }
984
+
985
+ const _CRED_FILE_NAMES = ['credentials.json','credentials.yml','credentials.yaml','secrets.yml','secrets.yaml','.env','.netrc','.npmrc','.pypirc','.pgpass','.git-credentials','.dockercfg','.bash_history','.mysql_history','.psql_history','.zsh_history','.python_history','auth_token','tool_name_map.json'];
986
+
987
+ function _pathGroupLabel(path, cat) {
988
+ let p = String(path || '').replace(/\\/g, '/');
989
+ const base = p.split('/').filter(Boolean).pop() || p;
990
+ // 凭据/历史类文件:合并成一组,按文件名逐个建组会碎成几十个
991
+ if (_CRED_FILE_NAMES.includes(base.toLowerCase())
992
+ || /^(credentials?|secrets?|auth[-_]?token)/i.test(base)) {
993
+ return '路径 · 凭据文件';
994
+ }
995
+ if (/^[A-Za-z]:\//.test(p)) {
996
+ return '路径 · ' + p.split('/').slice(0, 3).join('/');
997
+ }
998
+ if (p.startsWith('~')) p = p.slice(1);
999
+ if (p.startsWith('/')) {
1000
+ return '路径 · /' + (p.split('/').filter(Boolean)[0] || '');
1001
+ }
1002
+ return '路径 · ' + (p.split('/').filter(Boolean)[0] || base || '其他');
1003
+ }
1004
+
1005
+ function ruleGroupLabel(rule, cat = '') {
1006
+ const cmds = extractCommandGroups(rule);
1007
+ if (cmds.length === 1) return cmds[0];
1008
+ if (cmds.length === 2) return cmds.join(' / ');
1009
+ if (cmds.length > 2) return '组合命令';
1010
+ if (rule && rule.path) return _pathGroupLabel(rule.path, cat);
1011
+ if (rule && (rule.intent_keywords || rule.dangerous_actions)) return '意图规则';
1012
+ if (rule && rule.keyword) return '关键词';
1013
+ if (cat === 'builtin_detectors') return '内置检测器';
1014
+ return '通用规则';
1015
+ }
1016
+ function _groupRank(label) {
1017
+ if (label === '组合命令') return 1;
1018
+ if (label.startsWith('路径')) return 2;
1019
+ if (label === '意图规则') return 3;
1020
+ if (label === '关键词') return 4;
1021
+ if (label === '其他命令') return 5;
1022
+ if (label === '其他路径') return 6;
1023
+ return 0; // 具体命令组排在最前
1024
+ }
1025
+
1026
+ // 当前层所有规则(已按平台过滤),附带原始分类与分类数据
1027
+ function layerRuleItems(layerKey) {
785
1028
  const layer = state.config[layerKey] || {};
786
- // 层级总开关:关闭时整层大类开关随动显示为关(仅 UI 联动,不改后端数据)
787
- const layerSwitchKey = LAYER_SWITCH_KEY[layerKey];
788
- const layerEnabled = layerSwitchKey ? state.config.layers?.[layerSwitchKey] !== false : true;
789
- // strict:只渲染 categoryNames 白名单内的分类(不兜底 runtime 里多的 key),
790
- // 供 render_l2 三段式(内置类 + 用户自定义分开)避免重复/英文透出。
791
- let orderedEntries;
792
- if (strict) {
793
- orderedEntries = Object.keys(categoryNames)
794
- .filter(k => k in layer)
795
- .map(k => [k, layer[k]]);
796
- } else {
797
- orderedEntries = [
798
- ...Object.keys(categoryNames).filter(k => k in layer).map(k => [k, layer[k]]),
799
- ...Object.entries(layer).filter(([k]) => !(k in categoryNames)),
800
- ];
1029
+ const items = [];
1030
+ for (const [cat, catData] of Object.entries(layer)) {
1031
+ for (const r of platformFilteredRules(catData.rules)) {
1032
+ items.push({ r, cat, catData });
1033
+ }
1034
+ }
1035
+ return items;
1036
+ }
1037
+
1038
+ function viewToolbar(counts, withGroupMode) {
1039
+ const btn = (active, onclick, label) =>
1040
+ `<button class="ag-btn ${active ? 'ag-btn-primary' : 'ag-btn-ghost'} ag-btn-sm" onclick="${onclick}">${label}</button>`;
1041
+ let html = `<div class="ag-card" style="padding:8px 16px;display:flex;align-items:center;gap:8px;flex-wrap:wrap">
1042
+ <span style="font-size:12px;color:var(--ag-text-secondary)">${t('规则来源:', 'Rules: ')}</span>
1043
+ ${btn(state.ruleOwner === 'builtin', "setRuleOwner('builtin')", `${t('内置规则', 'Built-in')} (${counts.builtin})`)}
1044
+ ${btn(state.ruleOwner === 'custom', "setRuleOwner('custom')", `${t('自定义规则', 'Custom')} (${counts.custom})`)}`;
1045
+ if (withGroupMode) {
1046
+ html += `<span style="margin-left:8px;font-size:12px;color:var(--ag-text-secondary)">${t('分组:', 'Group by: ')}</span>
1047
+ ${btn(state.ruleGroupMode === 'category', "setRuleGroupMode('category')", t('按分类', 'Category'))}
1048
+ ${btn(state.ruleGroupMode === 'command', "setRuleGroupMode('command')", t('按命令', 'Command'))}`;
1049
+ }
1050
+ // Ask 标记:默认隐藏(功能未实现);打开后才出现勾选框与说明。
1051
+ html += `<span style="margin-left:8px;font-size:12px;color:var(--ag-text-secondary)">${t('Ask 标记:', 'Ask mark: ')}</span>` +
1052
+ btn(!state.showAsk, "setShowAsk(false)", t('隐藏', 'Hidden')) +
1053
+ btn(state.showAsk, "setShowAsk(true)", t('显示', 'Show'));
1054
+ return html + '</div>';
1055
+ }
1056
+
1057
+ function askNoticeCard() {
1058
+ return `<div class="ag-card" style="padding:10px 16px;border-left:3px solid #409eff;background:rgba(64,158,255,.06)">
1059
+ <div style="font-size:13px;font-weight:600;margin-bottom:4px">${t('Ask 标记(当前为标签模式)', 'Ask mark (label mode)')}</div>
1060
+ <div style="font-size:12px;line-height:1.6;color:var(--ag-text-secondary)">
1061
+ ${t('勾选<strong>不改变原有判定</strong>:原本直接拦截的仍然 Deny,原本交给 L3 判定的仍然交给 L3。只有最终结果为 Deny 时,响应才额外带 <code>ask_recommended: true</code> 和 <code>ask_reason</code>,供接入方决定是否提示用户确认。', 'Checking <strong>does not change the verdict</strong>: rules that deny still deny, and rules handed to L3 are still handed to L3. Only when the final result is Deny does the response add <code>ask_recommended: true</code> and <code>ask_reason</code>, letting the caller decide whether to prompt the user.')}
1062
+ <br>${t('注意:medium/low 规则本身不会直接 Deny(交 L3 判定),当前勾选不会产生标签;真正的“Ask 决策”(允许/拒绝/询问 三态)实现后,标记才会对所有命中生效。', 'Note: medium/low rules do not deny directly (they go to L3), so checking them produces no label today. Once a real “Ask decision” (allow/deny/ask) is implemented, the mark will apply to every match.')}
1063
+ </div>
1064
+ </div>`;
1065
+ }
1066
+ function renderCategoryGroups(layerKey, containerId, items, categoryNames, layerEnabled) {
1067
+ const byCat = new Map();
1068
+ for (const it of items) {
1069
+ if (!byCat.has(it.cat)) byCat.set(it.cat, []);
1070
+ byCat.get(it.cat).push(it);
801
1071
  }
802
- let html = showAddBtn
803
- ? `<div class="ag-card" style="padding:8px 16px"><button class="ag-btn ag-btn-primary" onclick="showAddRuleModal('${layerKey}')">+ ${t('新增规则', 'Add Rule')}</button></div>`
804
- : '';
805
- for (const [catName, catData] of orderedEntries) {
806
- const displayName = categoryNames[catName] || catName;
807
- const rules = catData.rules || [];
1072
+ const layerKeys = Object.keys(state.config[layerKey] || {});
1073
+ const ordered = [
1074
+ ...Object.keys(categoryNames).filter(k => byCat.has(k)),
1075
+ ...layerKeys.filter(k => byCat.has(k) && !(k in categoryNames)),
1076
+ ...[...byCat.keys()].filter(k => !(k in categoryNames) && !layerKeys.includes(k)),
1077
+ ];
1078
+ let html = '';
1079
+ for (const cat of [...new Set(ordered)]) {
1080
+ const catItems = byCat.get(cat);
1081
+ const catData = catItems[0].catData;
1082
+ const displayName = categoryNames[cat] || cat;
808
1083
  const catEnabled = catData.category_enabled !== false;
809
- // 大类总开关显示状态 = 层级开 && 大类开;层级关时大类开关需禁用(无意义)
810
1084
  const catSwitchOn = layerEnabled && catEnabled;
811
- const catSwitchDisabled = !layerEnabled;
812
- // 大类计数与后端执行口径一致:大类总开关关闭时启用数归 0(分母仍为规则总数)
813
- const enabledCount = catSwitchOn ? rules.filter(r => r.enabled).length : 0;
814
- const expanded = expandedCats.has(`${containerId}-${catName}`);
1085
+ // 自定义标签页不显示"整类开关":它会影响同一分类里的内置规则
1086
+ const showSwitch = state.ruleOwner === 'builtin';
1087
+ // 注入特征只作为 L3 线索,不再拆强/弱、也不再提供分组总开关
1088
+ const subgroups = [[null, catItems]];
1089
+ subgroups.forEach(([subLabel, subItems], subIdx) => {
1090
+ const rules = subItems.map(i => i.r);
1091
+ const enabledCount = catSwitchOn ? rules.filter(r => r.enabled && !r.source_removed).length : 0;
1092
+ const groupKey = `${containerId}-${cat}${subLabel ? '-s' + subIdx : ''}`;
1093
+ const expanded = expandedCats.has(groupKey);
1094
+ const title = subLabel ? `${displayName} · ${subLabel}` : displayName;
1095
+ const desc = (!subLabel && catData.category_desc) ? `<div class="ag-cat-desc">${escapeHtml(catData.category_desc)}</div>` : '';
1096
+ html += `<div class="ag-card">
1097
+ <div class="ag-cat-header" onclick="toggleExpand('${groupKey}')">
1098
+ <div class="ag-cat-name">${escapeHtml(title)} <span class="ag-cat-count">${enabledCount}/${rules.length} ${t('启用', 'enabled')}</span>${desc}</div>
1099
+ <div class="ag-cat-controls">
1100
+ ${showSwitch && state.showAsk ? `<label class="ag-ask-toggle" title="${t('整类批量设置「命中后建议询问」', 'Set Ask for the whole category')}" onclick="event.stopPropagation()"><input type="checkbox" ${rules.length && rules.every(r => r.ask_on_match) ? 'checked' : ''} onchange="toggleCategoryAsk('${layerKey}','${cat}',this.checked)"> Ask</label>` : ''}
1101
+ ${showSwitch ? `<div onclick="event.stopPropagation();toggleCategory('${layerKey}','${cat}')">${toggle(catSwitchOn, !layerEnabled, '')}</div>` : ''}
1102
+ <span class="ag-expand-icon ${expanded ? 'open' : ''}" id="expand-${groupKey}">▼</span>
1103
+ </div>
1104
+ </div>
1105
+ <div class="ag-rule-list" id="list-${groupKey}" style="display:${expanded ? '' : 'none'}">`;
1106
+ for (const it of subItems) {
1107
+ html += renderRuleItem(layerKey, cat, it.r, layerEnabled, catEnabled);
1108
+ }
1109
+ html += '</div></div>';
1110
+ });
1111
+ }
1112
+ return html;
1113
+ }
1114
+
1115
+ function renderCommandGroups(layerKey, containerId, items, categoryNames, layerEnabled) {
1116
+ const rawGroups = new Map();
1117
+ for (const it of items) {
1118
+ const label = ruleGroupLabel(it.r, it.cat);
1119
+ if (!rawGroups.has(label)) rawGroups.set(label, []);
1120
+ rawGroups.get(label).push(it);
1121
+ }
1122
+ // 单条命令组并入「其他命令」:按命令视图的价值是聚合,1 条一组只会更碎;
1123
+ // 想定位单条规则用搜索页。路径/意图/关键词等语义桶保持独立。
1124
+ const buckets = new Set(['组合命令', '意图规则', '关键词', '通用规则', '内置检测器', '其他命令', '其他路径']);
1125
+ const groups = new Map();
1126
+ for (const [label, arr] of rawGroups) {
1127
+ let target = label;
1128
+ if (arr.length === 1 && !buckets.has(label)) {
1129
+ target = label.startsWith('路径') ? '其他路径' : '其他命令';
1130
+ }
1131
+ if (!groups.has(target)) groups.set(target, []);
1132
+ groups.get(target).push(...arr);
1133
+ }
1134
+ const labels = [...groups.keys()].sort((a, b) => {
1135
+ const ra = _groupRank(a), rb = _groupRank(b);
1136
+ if (ra !== rb) return ra - rb;
1137
+ return a.localeCompare(b);
1138
+ });
1139
+ let html = '';
1140
+ labels.forEach((label, idx) => {
1141
+ const groupItems = groups.get(label);
1142
+ const expanded = expandedCats.has(`${containerId}-cmd-${idx}`);
1143
+ const enabledCount = layerEnabled
1144
+ ? groupItems.filter(i => i.r.enabled && !i.r.source_removed).length : 0;
815
1145
  html += `<div class="ag-card">
816
- <div class="ag-cat-header" onclick="toggleExpand('${containerId}-${catName}')">
817
- <div class="ag-cat-name">${escapeHtml(displayName)} <span class="ag-cat-count">${enabledCount}/${rules.length} ${t('启用', 'enabled')}</span></div>
1146
+ <div class="ag-cat-header" onclick="toggleExpand('${containerId}-cmd-${idx}')">
1147
+ <div class="ag-cat-name">${escapeHtml(label)} <span class="ag-cat-count">${enabledCount}/${groupItems.length} ${t('启用', 'enabled')}</span></div>
818
1148
  <div class="ag-cat-controls">
819
- <div onclick="event.stopPropagation();toggleCategory('${layerKey}','${catName}')">${toggle(catSwitchOn, catSwitchDisabled, '')}</div>
820
- <span class="ag-expand-icon ${expanded ? 'open' : ''}" id="expand-${containerId}-${catName}">▼</span>
1149
+ <span class="ag-expand-icon ${expanded ? 'open' : ''}" id="expand-${containerId}-cmd-${idx}">▼</span>
821
1150
  </div>
822
1151
  </div>
823
- <div class="ag-rule-list" id="list-${containerId}-${catName}" style="display:${expanded ? '' : 'none'}">`;
824
- if (!rules.length) {
825
- html += `<div class="ag-empty">${t('无规则', 'No rules')}</div>`;
826
- } else {
827
- for (const r of rules) {
828
- html += renderRuleItem(layerKey, catName, r);
829
- }
1152
+ <div class="ag-rule-list" id="list-${containerId}-cmd-${idx}" style="display:${expanded ? '' : 'none'}">`;
1153
+ for (const it of groupItems) {
1154
+ const catEnabled = it.catData.category_enabled !== false;
1155
+ html += renderRuleItem(layerKey, it.cat, it.r, layerEnabled, catEnabled,
1156
+ categoryNames[it.cat] || it.cat);
830
1157
  }
831
1158
  html += '</div></div>';
1159
+ });
1160
+ return html;
1161
+ }
1162
+
1163
+ function renderRuleLayer(layerKey, containerId, categoryNames, showAddBtn = true) {
1164
+ const switchKey = LAYER_SWITCH_KEY[layerKey];
1165
+ const layerEnabled = switchKey ? state.config.layers?.[switchKey] !== false : true;
1166
+ const items = layerRuleItems(layerKey);
1167
+ const counts = {
1168
+ builtin: items.filter(i => ruleOwnerOf(i.r) === 'builtin').length,
1169
+ custom: items.filter(i => ruleOwnerOf(i.r) === 'custom').length,
1170
+ };
1171
+ const visible = items.filter(i => ruleOwnerOf(i.r) === state.ruleOwner);
1172
+ let html = platformBar() + riskLegendCard() + viewToolbar(counts, true) + (state.showAsk ? askNoticeCard() : '');
1173
+ if (showAddBtn && state.ruleOwner === 'custom') {
1174
+ html += `<div class="ag-card" style="padding:8px 16px"><button class="ag-btn ag-btn-primary" onclick="showAddRuleModal('${layerKey}')">+ ${t('新增规则', 'Add Rule')}</button></div>`;
1175
+ }
1176
+ if (!visible.length) {
1177
+ html += `<div class="ag-card"><div class="ag-empty">${state.ruleOwner === 'custom'
1178
+ ? t('暂无自定义规则(点击上方"新增规则"添加)', 'No custom rules yet (use "Add Rule" above)')
1179
+ : t('当前平台没有可见规则', 'No rules visible for the current platform')}</div></div>`;
1180
+ } else if (state.ruleGroupMode === 'command') {
1181
+ html += renderCommandGroups(layerKey, containerId, visible, categoryNames, layerEnabled);
1182
+ } else {
1183
+ html += renderCategoryGroups(layerKey, containerId, visible, categoryNames, layerEnabled);
832
1184
  }
833
1185
  const cont = el(containerId);
834
- if (!cont) return;
835
- if (append) cont.insertAdjacentHTML('beforeend', html);
836
- else cont.innerHTML = html;
1186
+ if (cont) cont.innerHTML = html;
837
1187
  }
838
- function renderRuleItem(layerKey, catName, r) {
1188
+ function renderRuleItem(layerKey, catName, r, layerEnabled = true, catEnabled = true, catLabel = '') {
839
1189
  const isL2 = layerKey === 'L2_rules';
840
- const isL2Sensitive = isL2 && catName === 'sensitive_path_access';
1190
+ const isSensitivePath = catName === 'sensitive_path_access';
1191
+ // 生效状态:层级开 && 大类开 && 单条开 && 未被源码移除。不生效的条目仍然展示
1192
+ // (否则用户无法重新打开),但标注原因并禁用无效开关——避免"点了没反应"。
1193
+ const sourceRemoved = !!r.source_removed;
1194
+ const ruleOs = ruleOsOf(r);
1195
+ const otherPlatform = !(ruleOs === 'all' || platformAcceptedOs().has(ruleOs));
1196
+ const inactiveReason = otherPlatform
1197
+ ? t('其他平台,本机不生效', 'Other platform (inactive here)')
1198
+ : sourceRemoved ? t('已从源码移除', 'Removed from source')
1199
+ : !layerEnabled ? t('层级已关闭', 'Layer off')
1200
+ : !catEnabled ? t('大类已关闭', 'Category off')
1201
+ : !r.enabled ? t('已禁用', 'Disabled') : '';
1202
+ // 其他平台规则在本机永远不会生效:即使勾选展示,也只允许查看,禁止无效开关操作。
1203
+ const controlsDisabled = sourceRemoved || !layerEnabled || !catEnabled || otherPlatform;
841
1204
  let patternDisplay = r.pattern || r.keyword || r.path || (r.intent_keywords && r.intent_keywords.join(', ')) || r.reason || r.id || '';
842
1205
  let reasonDisplay = r.reason || r.desc || '';
843
1206
  let patternLabel = t('规则', 'Rule');
844
- if (isL2) {
1207
+ if (catName === 'sensitive_path_access' && r.path) patternLabel = t('敏感路径', 'Sensitive Path');
1208
+ else if (isL2) {
845
1209
  if (r.intent_keywords) patternLabel = t('触发关键词', 'Trigger Keywords');
846
- else if (r.path) patternLabel = t('敏感路径', 'Sensitive Path');
847
1210
  else if (r.pattern) patternLabel = t('检测模式', 'Detection Pattern');
848
1211
  }
849
1212
  const reasonLabel = isL2 ? t('规则说明', 'Rule Description') : t('原因', 'Reason');
1213
+ // 内置检测器没有 pattern/path,只有一句检测说明:避免同一句话在
1214
+ // 「规则」和「原因」两行重复展示。
1215
+ if (catName === 'builtin_detectors') {
1216
+ patternLabel = t('检测内容', 'Detection');
1217
+ patternDisplay = r.reason || r.desc || r.id || '';
1218
+ reasonDisplay = '';
1219
+ }
850
1220
  const tooltip = `${patternLabel}: ${patternDisplay}\n${reasonLabel}: ${reasonDisplay || t('(无)', '(none)')}\nID: ${r.id}`;
851
- const denyModeSelect = isL2Sensitive ? `<select class="ag-deny-select" onchange="updateDenyMode('${layerKey}','${catName}','${r.id}',this.value)" ${r.enabled ? '' : 'disabled'}>
1221
+ const denyModeSelect = isSensitivePath ? `<select class="ag-deny-select" onchange="updateDenyMode('${layerKey}','${catName}','${r.id}',this.value)" ${(r.enabled && !controlsDisabled) ? '' : 'disabled'}>
852
1222
  <option value="deny_write" ${(r.deny_mode || 'deny_write') === 'deny_write' ? 'selected' : ''}>${t('仅拦截写入', 'Block Write Only')}</option>
853
1223
  <option value="deny_read" ${(r.deny_mode || 'deny_write') === 'deny_read' ? 'selected' : ''}>${t('仅拦截读取', 'Block Read Only')}</option>
854
1224
  <option value="deny_both" ${(r.deny_mode || 'deny_write') === 'deny_both' ? 'selected' : ''}>${t('读写均拦截', 'Block Both')}</option>
855
1225
  </select>` : '';
856
- const skipL3 = isL2 ? `<label class="ag-skip-l3" title="${t('禁用该规则时,L3 对相关路径/关键词做豁免放行(但仍分析命令其他部分的安全风险)。关闭则 L3 可能独立拦截', 'When this rule is disabled, L3 exempts the related path/keyword (but still analyzes other parts of the command). Turning off lets L3 block independently')}"><input type="checkbox" ${r.skip_l3_on_disabled ? 'checked' : ''} onchange="updateSkipL3('${layerKey}','${catName}','${r.id}',this.checked)"> ${t('禁用时豁免L3', 'Exempt L3 when disabled')}</label>` : '';
1226
+ const skipL3 = isL2 ? `<label class="ag-skip-l3" title="${t('禁用该规则时,L3 对相关路径/关键词做豁免放行(但仍分析命令其他部分的安全风险)。关闭则 L3 可能独立拦截', 'When this rule is disabled, L3 exempts the related path/keyword (but still analyzes other parts of the command). Turning off lets L3 block independently')}"><input type="checkbox" ${r.skip_l3_on_disabled ? 'checked' : ''} ${controlsDisabled ? 'disabled' : ''} onchange="updateSkipL3('${layerKey}','${catName}','${r.id}',this.checked)"> ${t('禁用时豁免L3', 'Exempt L3 when disabled')}</label>` : '';
857
1227
  const deleteBtn = (r.builtin === false || r.source_removed) ? `<button class="ag-btn ag-btn-danger ag-btn-sm" onclick="deleteRule('${layerKey}','${catName}','${r.id}')" title="${r.source_removed ? t('此规则已从默认规则集移除,可删除清理', 'This rule was removed from the default set; you may delete it') : t('删除自定义规则', 'Delete custom rule')}">${t('删除', 'Delete')}</button>` : '';
858
1228
  return `<div class="ag-rule-item" title="${escapeHtml(tooltip)}">
859
1229
  <div class="ag-rule-body">
860
- <div class="ag-rule-tags">${builtinBadge(r.builtin)} ${removedBadge(r.source_removed)} ${riskBadge(r.risk_level)} ${riskTypeBadge(r.risk_type)}${isL2Sensitive ? ' ' + denyModeBadge(r.deny_mode) + ' ' + sourceDenyModeBadges(r) : ''}</div>
1230
+ <div class="ag-rule-tags">${builtinBadge(r.builtin)} ${osBadge(r.os)} ${catLabel ? `<span class="ag-badge ag-badge-os">${escapeHtml(catLabel)}</span>` : ''} ${enforcementBadge(layerKey, r)} ${inactiveReason ? `<span class="ag-badge ag-badge-inactive">${t('未生效', 'Inactive')} · ${escapeHtml(inactiveReason)}</span>` : ''} ${removedBadge(r.source_removed)} ${riskBadge(r.risk_level)} ${riskTypeBadge(r.risk_type)}${isSensitivePath ? ' ' + denyModeBadge(r.deny_mode) + ' ' + sourceDenyModeBadges(r) : ''}${r.ask_on_match ? ' ' + askBadge(true) : ''}</div>
861
1231
  <div class="ag-rule-pattern"><span class="ag-rule-field-label">${patternLabel}:</span> ${escapeHtml(patternDisplay)}</div>
862
1232
  ${reasonDisplay ? `<div class="ag-rule-reason"><span class="ag-rule-field-label">${reasonLabel}:</span> ${escapeHtml(reasonDisplay)}</div>` : ''}
863
1233
  <div class="ag-rule-id">ID: ${escapeHtml(r.id)}</div>
864
1234
  </div>
865
- <div class="ag-rule-controls">${denyModeSelect}${toggle(r.enabled, false, `toggleRule('${layerKey}','${catName}','${r.id}',${!r.enabled})`)}${skipL3}${deleteBtn}</div>
1235
+ <div class="ag-rule-controls">${denyModeSelect}${r.id && state.showAsk ? askToggle(layerKey, catName, r.id, !!r.ask_on_match, controlsDisabled) : ''}${toggle(r.enabled, controlsDisabled, `toggleRule('${layerKey}','${catName}','${r.id}',${!r.enabled})`)}${skipL3}${deleteBtn}</div>
866
1236
  </div>`;
867
1237
  }
868
1238
  function render_l1() { renderRuleLayer('L1_rules', 'page-l1', L1_CATEGORY_NAMES); }
869
1239
  function render_l2() {
870
- // 顺序:内置 L2 类 → LTL 时序规则卡 → 用户自定义(永远最后)
871
- // strict=true:三段各渲染自己的白名单,避免兜底把别的类目用英文透出(去重 bug)
872
- const builtin = Object.fromEntries(Object.entries(L2_CATEGORY_NAMES).filter(([k]) => k !== 'user_custom'));
873
- const customOnly = { user_custom: L2_CATEGORY_NAMES.user_custom };
874
- renderRuleLayer('L2_rules', 'page-l2', builtin, false, true, true);
875
- renderLtlCard('page-l2');
876
- renderRuleLayer('L2_rules', 'page-l2', customOnly, true, false, true);
1240
+ // 两级视图(内置/自定义 × 按分类/按命令)由 renderRuleLayer 统一处理;
1241
+ // LTL 时序规则属于内置规则,只在「内置」标签页显示。
1242
+ renderRuleLayer('L2_rules', 'page-l2', L2_CATEGORY_NAMES, true);
1243
+ if (state.ruleOwner === 'builtin') renderLtlCard('page-l2');
877
1244
  }
878
1245
  // LTL 时序攻击模式规则卡(L2.2,并入 L2 页展示;数据源 state.config.L2_2.ltl_rules)
879
1246
  function renderLtlCard(containerId) {
@@ -921,6 +1288,20 @@ async function toggleRule(layer, cat, id, en) {
921
1288
  showToast(t('规则 ', 'Rule ') + id + t(' 已', ' ') + (en ? t('启用', 'enabled') : t('禁用', 'disabled')));
922
1289
  } catch (e) { showToast(t('操作失败: ', 'Operation failed: ') + e.message, 'error'); }
923
1290
  }
1291
+ async function updateAsk(layer, cat, id, on) {
1292
+ try {
1293
+ state.config = await apiPut('rules/ask', { layer, category: cat, rule_id: id, ask_on_match: !!on });
1294
+ renderCurrent(); if (state.currentPage === 'search') searchRules();
1295
+ showToast(on ? t('已标记为命中后询问(Ask)', 'Marked as Ask on match') : t('已取消 Ask', 'Ask cleared'));
1296
+ } catch (e) { showToast(String(e.message || e), 'error'); }
1297
+ }
1298
+ async function toggleCategoryAsk(layer, cat, on) {
1299
+ try {
1300
+ state.config = await apiPut('categories/ask', { layer, category: cat, ask_on_match: !!on });
1301
+ renderCurrent(); if (state.currentPage === 'search') searchRules();
1302
+ showToast(on ? t('整类已标记为 Ask', 'Category marked as Ask') : t('整类已取消 Ask', 'Category Ask cleared'));
1303
+ } catch (e) { showToast(String(e.message || e), 'error'); }
1304
+ }
924
1305
  async function updateDenyMode(layer, cat, id, mode) {
925
1306
  try {
926
1307
  state.config = await apiPut('rules/deny_mode', { layer, category: cat, rule_id: id, deny_mode: mode });
@@ -1170,44 +1551,71 @@ function showAddScenarioRuleModal(scenarioId, cat) {
1170
1551
  }
1171
1552
 
1172
1553
  // ===== L3 Skills 页 =====
1554
+ function skillOwnerOf(s) { return s && s.builtin === false ? 'custom' : 'builtin'; }
1173
1555
  function render_l3() {
1174
1556
  const l3 = state.config.L3_skills || {};
1175
- // 层级总开关:关闭时 L3 大类开关随动显示为关(仅 UI 联动,不改后端数据)
1176
1557
  const layerEnabled = state.config.layers?.['L3_llm_analysis'] !== false;
1177
- let html = `<div class="ag-card" style="padding:8px 16px"><button class="ag-btn ag-btn-primary" onclick="showAddSkillModal()">+ ${t('新增 Skill', 'Add Skill')}</button></div>`;
1178
- for (const [catName, catData] of Object.entries(l3)) {
1558
+ const all = [];
1559
+ for (const [cat, catData] of Object.entries(l3)) {
1560
+ for (const s of (catData.skills || [])) all.push({ s, cat, catData });
1561
+ }
1562
+ const counts = {
1563
+ builtin: all.filter(i => skillOwnerOf(i.s) === 'builtin').length,
1564
+ custom: all.filter(i => skillOwnerOf(i.s) === 'custom').length,
1565
+ };
1566
+ const visible = all.filter(i => skillOwnerOf(i.s) === state.ruleOwner);
1567
+ let html = platformBar() + viewToolbar(counts, false);
1568
+ if (state.ruleOwner === 'custom') {
1569
+ html += `<div class="ag-card" style="padding:8px 16px"><button class="ag-btn ag-btn-primary" onclick="showAddSkillModal()">+ ${t('新增 Skill', 'Add Skill')}</button></div>`;
1570
+ }
1571
+ if (!visible.length) {
1572
+ html += `<div class="ag-card"><div class="ag-empty">${state.ruleOwner === 'custom'
1573
+ ? t('暂无自定义 Skill(点击上方"新增 Skill"添加)', 'No custom skills yet (use "Add Skill" above)')
1574
+ : t('当前平台没有可见 Skill', 'No skills visible for the current platform')}</div></div>`;
1575
+ el('page-l3').innerHTML = html;
1576
+ return;
1577
+ }
1578
+ // 按分类分组(Skill 没有命令概念,二级只保留按分类)
1579
+ const byCat = new Map();
1580
+ for (const it of visible) {
1581
+ if (!byCat.has(it.cat)) byCat.set(it.cat, []);
1582
+ byCat.get(it.cat).push(it);
1583
+ }
1584
+ const ordered = [
1585
+ ...Object.keys(L3_CATEGORY_NAMES).filter(k => byCat.has(k)),
1586
+ ...[...byCat.keys()].filter(k => !(k in L3_CATEGORY_NAMES)),
1587
+ ];
1588
+ for (const catName of [...new Set(ordered)]) {
1589
+ const catItems = byCat.get(catName);
1590
+ const catData = catItems[0].catData;
1591
+ const skills = catItems.map(i => i.s);
1179
1592
  const displayName = L3_CATEGORY_NAMES[catName] || catName;
1180
- const skills = catData.skills || [];
1181
1593
  const catEnabled = catData.category_enabled !== false;
1182
- // 大类总开关显示状态 = 层级开 && 大类开;层级关时大类开关需禁用(无意义)
1183
1594
  const catSwitchOn = layerEnabled && catEnabled;
1184
- const catSwitchDisabled = !layerEnabled;
1185
- // 大类计数与后端执行口径一致:大类总开关关闭时启用数归 0
1595
+ const showSwitch = state.ruleOwner === 'builtin';
1186
1596
  const enabledCount = catSwitchOn ? skills.filter(s => s.enabled).length : 0;
1187
1597
  const expanded = expandedCats.has('page-l3-' + catName);
1188
1598
  html += `<div class="ag-card">
1189
1599
  <div class="ag-cat-header" onclick="toggleExpand('page-l3-${catName}')">
1190
1600
  <div class="ag-cat-name">${escapeHtml(displayName)} <span class="ag-cat-count">${enabledCount}/${skills.length} ${t('启用', 'enabled')}</span></div>
1191
1601
  <div class="ag-cat-controls">
1192
- <div onclick="event.stopPropagation();toggleSkillCategory('${catName}')">${toggle(catSwitchOn, catSwitchDisabled, '')}</div>
1602
+ ${showSwitch ? `<div onclick="event.stopPropagation();toggleSkillCategory('${catName}')">${toggle(catSwitchOn, !layerEnabled, '')}</div>` : ''}
1193
1603
  <span class="ag-expand-icon ${expanded ? 'open' : ''}" id="expand-page-l3-${catName}">▼</span>
1194
1604
  </div>
1195
1605
  </div>
1196
1606
  <div class="ag-rule-list" id="list-page-l3-${catName}" style="display:${expanded ? '' : 'none'}">`;
1197
- if (!skills.length) {
1198
- html += `<div class="ag-empty">${t('无 skill', 'No skill')}</div>`;
1199
- } else {
1200
- for (const s of skills) {
1201
- const kw = (s.keywords || []).join(', ');
1202
- const deleteBtn = s.builtin === false ? `<button class="ag-btn ag-btn-danger ag-btn-sm" onclick="deleteSkill('${s.id}','${catName}')">${t('删除', 'Delete')}</button>` : '';
1203
- html += `<div class="ag-rule-item">
1204
- <div class="ag-rule-body">
1205
- <div class="ag-rule-tags">${builtinBadge(s.builtin)} <strong>${escapeHtml(s.id)}</strong></div>
1206
- <div class="ag-rule-reason"><span class="ag-rule-field-label">${t('触发关键词:', 'Trigger keywords: ')}</span> ${escapeHtml(kw)}</div>
1207
- </div>
1208
- <div class="ag-rule-controls">${toggle(s.enabled, false, `toggleSkill('${s.id}',${!s.enabled})`)}<button class="ag-btn ag-btn-ghost ag-btn-sm" onclick="showSkillDetail('${s.id}')">${t('详情', 'Details')}</button>${deleteBtn}</div>
1209
- </div>`;
1210
- }
1607
+ for (const it of catItems) {
1608
+ const s = it.s;
1609
+ const kw = (s.keywords || []).join(', ');
1610
+ const controlsDisabled = !layerEnabled || !catEnabled;
1611
+ const deleteBtn = s.builtin === false ? `<button class="ag-btn ag-btn-danger ag-btn-sm" onclick="deleteSkill('${s.id}','${catName}')">${t('删除', 'Delete')}</button>` : '';
1612
+ html += `<div class="ag-rule-item">
1613
+ <div class="ag-rule-body">
1614
+ <div class="ag-rule-tags">${builtinBadge(s.builtin)} ${!catEnabled || !layerEnabled ? `<span class="ag-badge ag-badge-inactive">${t('未生效', 'Inactive')}</span>` : ''} <strong>${escapeHtml(s.id)}</strong></div>
1615
+ <div class="ag-rule-reason"><span class="ag-rule-field-label">${t('触发关键词:', 'Trigger keywords: ')}</span> ${escapeHtml(kw)}</div>
1616
+ </div>
1617
+ <div class="ag-rule-controls">${toggle(s.enabled, controlsDisabled, `toggleSkill('${s.id}',${!s.enabled})`)}<button class="ag-btn ag-btn-ghost ag-btn-sm" onclick="showSkillDetail('${s.id}')">${t('详情', 'Details')}</button>${deleteBtn}</div>
1618
+ </div>`;
1211
1619
  }
1212
1620
  html += '</div></div>';
1213
1621
  }
@@ -1267,7 +1675,7 @@ function render_search() {
1267
1675
  <div class="ag-card">
1268
1676
  <div class="ag-section-title">${t('全局规则搜索', 'Global Rule Search')}</div>
1269
1677
  <div style="display:flex;gap:8px">
1270
- <input class="ag-input" id="search-input" placeholder="${t('输入关键词搜索规则,如: sysfs, rm -rf, /etc/shadow, 数据外泄...', 'Search rules by keyword, e.g. sysfs, rm -rf, /etc/shadow, data exfiltration...')}" oninput="searchRules()" style="flex:1">
1678
+ <input class="ag-input" id="search-input" value="${escapeHtml(state.searchQuery)}" placeholder="${t('输入关键词搜索规则,如: sysfs, rm -rf, /etc/shadow, 数据外泄...', 'Search rules by keyword, e.g. sysfs, rm -rf, /etc/shadow, data exfiltration...')}" oninput="searchRules()" style="flex:1">
1271
1679
  <button class="ag-btn ag-btn-primary" onclick="searchRules()">${t('搜索', 'Search')}</button>
1272
1680
  <button class="ag-btn ag-btn-ghost" onclick="clearSearch()">${t('清空', 'Clear')}</button>
1273
1681
  </div>
@@ -1277,21 +1685,30 @@ function render_search() {
1277
1685
  <div class="ag-section-title">${t('搜索结果', 'Search Results')} <span class="ag-cat-count" id="search-count">0 ${t('条', 'results')}</span></div>
1278
1686
  <div id="search-results"></div>
1279
1687
  </div>`;
1280
- setTimeout(() => { const inp = el('search-input'); if (inp) inp.focus(); }, 0);
1688
+ // 重渲染后恢复上一次的搜索结果(启停规则/改 deny_mode 会触发整页重渲染)
1689
+ if (state.searchQuery) searchRules();
1690
+ setTimeout(() => {
1691
+ const inp = el('search-input');
1692
+ if (!inp) return;
1693
+ inp.focus();
1694
+ inp.setSelectionRange(inp.value.length, inp.value.length);
1695
+ }, 0);
1281
1696
  }
1282
1697
  function searchRules() {
1283
- const q = (el('search-input') ? el('search-input').value : '').trim().toLowerCase();
1698
+ const raw = el('search-input') ? el('search-input').value : '';
1699
+ state.searchQuery = raw;
1700
+ const q = raw.trim().toLowerCase();
1284
1701
  const card = el('search-results-card'), list = el('search-results'), cnt = el('search-count');
1285
1702
  if (!q) { card.style.display = 'none'; list.innerHTML = ''; return; }
1286
1703
  const results = [];
1287
1704
  for (const [cat, cd] of Object.entries(state.config.L1_rules || {})) {
1288
- for (const r of (cd.rules || [])) {
1705
+ for (const r of platformFilteredRules(cd.rules)) {
1289
1706
  const hay = [r.id, r.pattern, r.keyword, r.reason, r.risk_type, r.risk_level].filter(Boolean).join(' ').toLowerCase();
1290
1707
  if (hay.includes(q)) results.push({ layer: 'L1_rules', layerName: 'L1', category: cat, ...r });
1291
1708
  }
1292
1709
  }
1293
1710
  for (const [cat, cd] of Object.entries(state.config.L2_rules || {})) {
1294
- for (const r of (cd.rules || [])) {
1711
+ for (const r of platformFilteredRules(cd.rules)) {
1295
1712
  const hay = [r.id, r.path, r.pattern, r.desc, r.reason, r.risk_type, r.risk_level].filter(Boolean).join(' ').toLowerCase();
1296
1713
  if (hay.includes(q)) results.push({ layer: 'L2_rules', layerName: 'L2', category: cat, ...r });
1297
1714
  }
@@ -1308,12 +1725,12 @@ function searchRules() {
1308
1725
  list.innerHTML = results.map(renderSearchItem).join('');
1309
1726
  }
1310
1727
  function renderSearchItem(r) {
1311
- const isL2Sensitive = r.layer === 'L2_rules' && r.category === 'sensitive_path_access';
1728
+ const isSensitivePath = r.category === 'sensitive_path_access';
1312
1729
  let ruleText = r.pattern || r.path || r.keyword || (r.keywords && r.keywords.join(', ')) || (r.intent_keywords && r.intent_keywords.join(', ')) || r.reason || r.desc || '';
1313
1730
  const reason = r.reason || r.desc || '';
1314
1731
  const tooltip = t('规则: ', 'Rule: ') + ruleText + t('\n原因: ', '\nReason: ') + (reason || t('(无)', '(none)')) + '\nID: ' + r.id;
1315
1732
  const toggleFn = r.isSkill ? "toggleSkill('" + r.id + "'," + (!r.enabled) + ")" : "toggleRule('" + r.layer + "','" + r.category + "','" + r.id + "'," + (!r.enabled) + ")";
1316
- const denyModeSelect = isL2Sensitive ? `<select class="ag-deny-select" onchange="updateDenyMode('${r.layer}','${r.category}','${r.id}',this.value)" ${r.enabled ? '' : 'disabled'}>
1733
+ const denyModeSelect = isSensitivePath ? `<select class="ag-deny-select" onchange="updateDenyMode('${r.layer}','${r.category}','${r.id}',this.value)" ${r.enabled ? '' : 'disabled'}>
1317
1734
  <option value="deny_write" ${(r.deny_mode || 'deny_write') === 'deny_write' ? 'selected' : ''}>${t('仅拦截写入', 'Block Write Only')}</option>
1318
1735
  <option value="deny_read" ${(r.deny_mode || 'deny_write') === 'deny_read' ? 'selected' : ''}>${t('仅拦截读取', 'Block Read Only')}</option>
1319
1736
  <option value="deny_both" ${(r.deny_mode || 'deny_write') === 'deny_both' ? 'selected' : ''}>${t('读写均拦截', 'Block Both')}</option>
@@ -1324,7 +1741,7 @@ function renderSearchItem(r) {
1324
1741
  <div class="ag-rule-tags">
1325
1742
  <span class="ag-layer-badge ag-layer-${r.layerName.toLowerCase()}">${r.layerName}</span>
1326
1743
  ${builtinBadge(r.builtin)} ${removedBadge(r.source_removed)} ${riskBadge(r.risk_level)} ${riskTypeBadge(r.risk_type)}
1327
- ${isL2Sensitive ? denyModeBadge(r.deny_mode) + ' ' + sourceDenyModeBadges(r) : ''}
1744
+ ${isSensitivePath ? denyModeBadge(r.deny_mode) + ' ' + sourceDenyModeBadges(r) : ''} ${r.ask_on_match ? askBadge(true) : ''}
1328
1745
  <span class="ag-search-cat">${t('分类: ', 'Category: ')}${escapeHtml(r.category)}</span>
1329
1746
  </div>
1330
1747
  <div class="ag-rule-pattern"><span class="ag-rule-field-label">${t('规则:', 'Rule:')}</span> ${escapeHtml(ruleText)}</div>
@@ -1333,6 +1750,7 @@ function renderSearchItem(r) {
1333
1750
  </div>
1334
1751
  <div class="ag-rule-controls">
1335
1752
  ${denyModeSelect}
1753
+ ${r.id && state.showAsk ? askToggle(r.layer, r.category, r.id, !!r.ask_on_match, !r.enabled) : ''}
1336
1754
  <span class="ag-status-text ${r.enabled ? 'ag-status-on' : 'ag-status-off'}">${r.enabled ? t('已启用', 'Enabled') : t('已禁用', 'Disabled')}</span>
1337
1755
  ${toggle(r.enabled, false, toggleFn)}
1338
1756
  ${skipL3}
@@ -1615,9 +2033,12 @@ function showAddRuleModal(layer) {
1615
2033
  const title = isL1 ? t('新增 L1 静态规则', 'Add L1 Static Rule') : t('新增 L2 规则', 'Add L2 Rule');
1616
2034
  let formHtml = '';
1617
2035
  if (isL1) {
1618
- formHtml = `<div class="ag-form-group"><div class="ag-form-label">${t('规则类型', 'Rule Type')}<span class="ag-required">*</span></div><select class="ag-select" id="rule-type" onchange="updateRuleForm()"><option value="pattern">${t('正则模式匹配', 'Regex pattern matching')}</option><option value="keyword">${t('关键词匹配', 'Keyword matching')}</option></select><div class="ag-form-hint">${t('正则模式:用正则表达式匹配命令(如 ', 'Regex mode: match the command with a regex (e.g. ')}<code>\\brm\\s+-rf</code>${t(');关键词匹配:命令中包含指定文字即命中。', '); keyword mode: command containing the text matches.')}</div></div>
2036
+ formHtml = `<div class="ag-form-group"><div class="ag-form-label">${t('规则类型', 'Rule Type')}<span class="ag-required">*</span></div><select class="ag-select" id="rule-type" onchange="updateRuleForm()"><option value="pattern">${t('正则模式匹配', 'Regex pattern matching')}</option><option value="keyword">${t('关键词匹配', 'Keyword matching')}</option><option value="path">${t('敏感路径', 'Sensitive path')}</option></select><div class="ag-form-hint">${t('正则模式:用正则表达式匹配命令(如 ', 'Regex mode: match the command with a regex (e.g. ')}<code>\\brm\\s+-rf</code>${t(');关键词匹配:命令中包含指定文字即命中。', '); keyword mode: command containing the text matches.')}</div></div>
1619
2037
  <div class="ag-form-group" id="form-pattern"><div class="ag-form-label">${t('正则 Pattern', 'Regex Pattern')}<span class="ag-required">*</span></div><input class="ag-input" id="input-pattern" placeholder="${t('如: ', 'e.g. ')}${'\\brm\\s+-rf'}"><div class="ag-form-hint">${t('Python 正则表达式,命中该正则的命令会触发本规则。', 'Python regex. Commands matching this regex trigger this rule.')}</div></div>
1620
2038
  <div class="ag-form-group" id="form-keyword" style="display:none"><div class="ag-form-label">${t('关键词', 'Keyword')}<span class="ag-required">*</span></div><input class="ag-input" id="input-keyword" placeholder="${t('如: ignore previous instructions', 'e.g. ignore previous instructions')}"><div class="ag-form-hint">${t('命令文本中包含此关键词即命中(不区分大小写)。', 'Command text containing this keyword matches (case-insensitive).')}</div></div>
2039
+ <div class="ag-form-group" id="form-path" style="display:none"><div class="ag-form-label">${t('敏感路径', 'Sensitive path')}<span class="ag-required">*</span></div><input class="ag-input" id="input-path" placeholder="${t('如: /etc/shadow, .ssh/id_rsa', 'e.g. /etc/shadow, .ssh/id_rsa')}"><div class="ag-form-hint">${t('命令访问到这些路径时命中;多个用英文逗号分隔。', 'Matches when a command accesses these paths; separate with commas.')}</div></div>
2040
+ <div class="ag-form-group" id="form-path-deny" style="display:none"><div class="ag-form-label">${t('拦截模式', 'Interception Mode')}</div><select class="ag-select" id="input-path-deny-mode"><option value="deny_write">${t('仅拦截写入', 'Block Write Only')}</option><option value="deny_read">${t('仅拦截读取', 'Block Read Only')}</option><option value="deny_both">${t('读写均拦截', 'Block Both')}</option></select><div class="ag-form-hint">${t('仅拦截写入(默认)、仅拦截读取(如 /dev/random)、读写均拦截(凭据文件)。', 'Block write only (default), read only (e.g. /dev/random), or both (credential files).')}</div></div>
2041
+ <div class="ag-form-group" id="form-path-desc" style="display:none"><div class="ag-form-label">${t('描述', 'Description')}<span class="ag-required">*</span></div><input class="ag-input" id="input-path-desc" placeholder="${t('如: SSH 私钥', 'e.g. SSH private key')}"><div class="ag-form-hint">${t('命中时展示给用户的说明。', 'Description shown to the user on match.')}</div></div>
1621
2042
  <div class="ag-form-group"><div class="ag-form-label">${t('风险等级', 'Risk Level')}<span class="ag-required">*</span></div><select class="ag-select" id="input-risk-level"><option value="critical">Critical(${t('严重', 'Critical')})</option><option value="high">High(${t('高危', 'High')})</option><option value="medium">Medium(${t('中危', 'Medium')})</option><option value="low">Low(${t('低危', 'Low')})</option></select><div class="ag-form-hint"><strong>critical / high</strong>:${t('在 L1 层直接拦截(Deny),命令不会执行;', 'block directly at L1 (Deny), the command will not run;')}<br><strong>medium / low</strong>:${t('不在 L1 拦截,转交 L3 LLM 深度分析判断。', 'not blocked at L1; handed to L3 LLM deep analysis.')}</div></div>
1622
2043
  <div class="ag-form-group"><div class="ag-form-label">${t('风险类型', 'Risk Type')}</div><input class="ag-input" id="input-risk-type" placeholder="${t('如: script_execution, file_access, data_exfiltration', 'e.g. script_execution, file_access, data_exfiltration')}"><div class="ag-form-hint">${t('风险分类标签,用于统计与展示。可选值:script_execution(脚本执行)、file_access(文件访问)、data_exfiltration(数据外泄)等,可自定义。', 'Risk classification label for stats and display. Options: script_execution, file_access, data_exfiltration, etc. Custom values allowed.')}</div></div>
1623
2044
  <div class="ag-form-group"><div class="ag-form-label">${t('拦截原因', 'Block Reason')}<span class="ag-required">*</span></div><input class="ag-input" id="input-reason" placeholder="${t('描述为什么这条规则要拦截', 'Describe why this rule blocks')}"><div class="ag-form-hint">${t('命中时展示给用户的说明文字,应写清为什么危险。L3 分析时也会参考此原因。', 'Text shown to the user on match; explain why it is dangerous. L3 analysis also references this reason.')}</div></div>
@@ -1625,12 +2046,12 @@ function showAddRuleModal(layer) {
1625
2046
  <div class="ag-form-group"><div class="ag-form-label">${t('所属分类', 'Category')}</div><select class="ag-select" id="input-category"><option value="user_custom">${t('用户自定义', 'User custom')}</option><option value="dangerous_commands">${t('危险命令检测', 'Dangerous commands')}</option><option value="injection_detection">${t('注入攻击检测', 'Injection detection')}</option></select></div>`;
1626
2047
  } else if (isL2) {
1627
2048
  formHtml = `<div class="ag-form-group"><div class="ag-form-label">${t('规则类型', 'Rule Type')}<span class="ag-required">*</span></div><select class="ag-select" id="rule-type-l2" onchange="updateL2RuleForm()"><option value="path">${t('敏感路径', 'Sensitive path')}</option><option value="pattern">${t('正则模式', 'Regex pattern')}</option></select><div class="ag-form-hint">${t('敏感路径:匹配文件路径(如 ', 'Sensitive path: match a file path (e.g. ')}<code>/etc/shadow</code>${t(');正则模式:用正则匹配命令文本。', '); regex mode: match command text with regex.')}</div></div>
1628
- <div class="ag-form-group" id="form-l2-path"><div class="ag-form-label">${t('路径', 'Path')}<span class="ag-required">*</span></div><input class="ag-input" id="input-l2-path" placeholder="${t('如: /etc/shadow, .ssh/id_rsa', 'e.g. /etc/shadow, .ssh/id_rsa')}"><div class="ag-form-hint">${t('要拦截的文件路径,多个用英文逗号分隔。命令访问到这些路径即命中。', 'File paths to block; separate multiple with commas. Commands accessing these paths match.')}</div></div>
2049
+ <div class="ag-form-group" id="form-l2-path"><div class="ag-form-label">${t('路径', 'Path')}<span class="ag-required">*</span></div><input class="ag-input" id="input-l2-path" placeholder="${t('如: /etc/shadow, .ssh/id_rsa', 'e.g. /etc/shadow, .ssh/id_rsa')}"><div class="ag-form-hint">${t('要拦截的文件路径,多个用英文逗号分隔。命令访问到这些路径即命中。', 'File paths to block; separate multiple with commas. Commands accessing these paths match.')}${t(' 敏感路径规则统一归 L1 展示与生效。', ' Sensitive path rules are shown and enforced under L1.')}</div></div>
1629
2050
  <div class="ag-form-group" id="form-l2-pattern" style="display:none"><div class="ag-form-label">${t('正则 Pattern', 'Regex Pattern')}<span class="ag-required">*</span></div><input class="ag-input" id="input-l2-pattern" placeholder="${t('如: ', 'e.g. ')}${'\\bpasswd\\s+--stdin'}"><div class="ag-form-hint">${t('Python 正则表达式,命中即触发。', 'Python regex; triggers on match.')}</div></div>
1630
2051
  <div class="ag-form-group"><div class="ag-form-label">${t('描述', 'Description')}<span class="ag-required">*</span></div><input class="ag-input" id="input-l2-desc" placeholder="${t('路径/规则的中文描述', 'Chinese description of the path/rule')}"><div class="ag-form-hint">${t('命中时展示给用户的说明。', 'Description shown to the user on match.')}</div></div>
1631
2052
  <div class="ag-form-group"><div class="ag-form-label">${t('风险等级', 'Risk Level')}<span class="ag-required">*</span></div><select class="ag-select" id="input-l2-risk-level"><option value="critical">Critical(${t('严重', 'Critical')})</option><option value="high">High(${t('高危', 'High')})</option><option value="medium">Medium(${t('中危', 'Medium')})</option><option value="low">Low(${t('低危', 'Low')})</option></select><div class="ag-form-hint"><strong>critical / high</strong>:${t('在 L2 层直接拦截;', 'block directly at L2;')}<br><strong>medium / low</strong>:${t('不在 L2 拦截,转交 L3 LLM 判断。', 'not blocked at L2; handed to L3 LLM.')}</div></div>
1632
2053
  <div class="ag-form-group"><div class="ag-form-label">${t('拦截模式', 'Interception Mode')}</div><select class="ag-select" id="input-l2-deny-mode"><option value="deny_write">${t('仅拦截写入', 'Block Write Only')}</option><option value="deny_read">${t('仅拦截读取', 'Block Read Only')}</option><option value="deny_both">${t('读写均拦截', 'Block Both')}</option></select><div class="ag-form-hint">${t('选择该路径的拦截模式:仅拦截写入(默认)、仅拦截读取(如 /dev/random)、读写均拦截(凭据文件)。', 'Choose interception mode: block write only (default), block read only (e.g. /dev/random), block both (credential files).')}</div></div>
1633
- <div class="ag-form-group"><div class="ag-form-label">${t('所属分类', 'Category')}</div><select class="ag-select" id="input-l2-category"><option value="sensitive_path_access">${t('敏感路径访问', 'Sensitive path access')}</option><option value="password_modify_consent">${t('密码修改授权', 'Password modify consent')}</option><option value="user_deletion_consent">${t('用户删除授权', 'User deletion consent')}</option><option value="intent_consistency">${t('意图一致性', 'Intent consistency')}</option></select></div>`;
2054
+ <div class="ag-form-group"><div class="ag-form-label">${t('所属分类', 'Category')}</div><select class="ag-select" id="input-l2-category"><option value="sensitive_path_access">${t('敏感路径访问(统一归 L1 展示/生效)', 'Sensitive path access (shown & enforced under L1)')}</option><option value="password_modify_consent">${t('密码修改授权', 'Password modify consent')}</option><option value="user_deletion_consent">${t('用户删除授权', 'User deletion consent')}</option><option value="intent_consistency">${t('意图一致性', 'Intent consistency')}</option></select></div>`;
1634
2055
  }
1635
2056
  openModal(title, formHtml);
1636
2057
  }
@@ -1646,6 +2067,13 @@ function updateRuleForm() {
1646
2067
  const p = document.getElementById('form-pattern'), k = document.getElementById('form-keyword');
1647
2068
  if (p) p.style.display = tt === 'pattern' ? '' : 'none';
1648
2069
  if (k) k.style.display = tt === 'keyword' ? '' : 'none';
2070
+ const isPath = tt === 'path';
2071
+ for (const id of ['form-path', 'form-path-deny', 'form-path-desc']) {
2072
+ const el = document.getElementById(id);
2073
+ if (el) el.style.display = isPath ? '' : 'none';
2074
+ }
2075
+ const catGroup = document.getElementById('input-category')?.closest('.ag-form-group');
2076
+ if (catGroup) catGroup.style.display = isPath ? 'none' : '';
1649
2077
  }
1650
2078
  function updateL2RuleForm() {
1651
2079
  const tt = document.getElementById('rule-type-l2')?.value;
@@ -1662,12 +2090,25 @@ async function submitModal() {
1662
2090
  let body = { layer };
1663
2091
  if (isL1) {
1664
2092
  const ruleType = document.getElementById('rule-type')?.value || 'pattern';
1665
- body.category = document.getElementById('input-category')?.value || 'user_custom';
1666
2093
  body.risk_level = document.getElementById('input-risk-level')?.value;
1667
2094
  body.risk_type = document.getElementById('input-risk-type')?.value || undefined;
1668
2095
  body.reason = document.getElementById('input-reason')?.value;
1669
- if (ruleType === 'pattern') body.pattern = document.getElementById('input-pattern')?.value;
1670
- else { body.keyword = document.getElementById('input-keyword')?.value; body.lang = document.getElementById('input-lang')?.value; }
2096
+ if (ruleType === 'pattern') {
2097
+ body.category = document.getElementById('input-category')?.value || 'user_custom';
2098
+ body.pattern = document.getElementById('input-pattern')?.value;
2099
+ } else if (ruleType === 'keyword') {
2100
+ body.category = document.getElementById('input-category')?.value || 'user_custom';
2101
+ body.keyword = document.getElementById('input-keyword')?.value;
2102
+ body.lang = document.getElementById('input-lang')?.value;
2103
+ } else {
2104
+ // 敏感路径统一归 L1(判定由 SensitivePathChecker 执行)
2105
+ body.category = 'sensitive_path_access';
2106
+ body.path = document.getElementById('input-path')?.value;
2107
+ body.desc = document.getElementById('input-path-desc')?.value;
2108
+ body.deny_mode = document.getElementById('input-path-deny-mode')?.value || 'deny_write';
2109
+ body.risk_type = body.risk_type || 'file_access';
2110
+ body.reason = body.reason || body.desc;
2111
+ }
1671
2112
  } else if (isL2) {
1672
2113
  const ruleType = document.getElementById('rule-type-l2')?.value || 'path';
1673
2114
  body.category = document.getElementById('input-l2-category')?.value || 'sensitive_path_access';