@kenhkl/agent-moss 0.17.40 → 0.17.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1264,38 +1264,68 @@ function hardenExistingPaths() {
1264
1264
  function chainDetailMode() {
1265
1265
  return (env("AGENT_MOSS_CHAIN_DETAIL", "redacted") || "redacted").toLowerCase();
1266
1266
  }
1267
- function redactChain(chain, currentInstanceId = "", currentSessionId = "") {
1267
+ function chainNodeVisible(instanceId, sessionId, currentInstanceId, currentSessionId, sessionAlias) {
1268
+ const inst = String(instanceId ?? "") || "";
1269
+ if (inst) {
1270
+ return !!(currentInstanceId && inst === String(currentInstanceId));
1271
+ }
1272
+ const sid = String(sessionId ?? "") || "";
1273
+ return !!sid && (sid === currentSessionId || sid === sessionAlias);
1274
+ }
1275
+ function redactChain(chain, currentInstanceId = "", currentSessionId = "", opts = {}) {
1268
1276
  if (!chain || chain.length === 0) return [];
1269
1277
  if (chainDetailMode() === "full") return [...chain];
1270
- return chain.map((step) => {
1278
+ const nodes = opts.graph?.nodes || [];
1279
+ return chain.map((step, index) => {
1271
1280
  if (Array.isArray(step) && step.length >= 3) {
1272
- const [sid, seq, , ts] = step;
1273
- const inst = step.length > 5 ? String(step[5] ?? "") : "";
1274
- const sameInstance = !!(inst && currentInstanceId && inst === String(currentInstanceId));
1275
- const sameSessionFallback = !inst && !!currentSessionId && String(sid) === String(currentSessionId);
1276
- if (sameInstance || sameSessionFallback) return [...step];
1277
- return ["<other-session>", seq, "<\u5DF2\u9690\u85CF>", ts ?? ""];
1281
+ const sid = step[0];
1282
+ const seq = step[1];
1283
+ const ts = step.length > 3 ? step[3] : "";
1284
+ let inst = step.length > 5 ? step[5] : "";
1285
+ if (!inst && index < nodes.length) {
1286
+ const node = nodes[index];
1287
+ const detail = String(node.action_detail ?? "");
1288
+ const stepDetail = String(step[2] ?? "");
1289
+ if (String(sid) !== String(node.session_id ?? "") || String(seq) !== String(node.seq ?? "") || stepDetail !== detail && stepDetail !== detail.slice(0, 60)) {
1290
+ return ["<other-session>", seq, "<\u5DF2\u9690\u85CF>", ts];
1291
+ }
1292
+ inst = node.instance_id;
1293
+ }
1294
+ if (chainNodeVisible(inst, sid, currentInstanceId, currentSessionId, opts.sessionAlias || "")) {
1295
+ return [...step];
1296
+ }
1297
+ return ["<other-session>", seq, "<\u5DF2\u9690\u85CF>", ts];
1278
1298
  }
1279
1299
  return step;
1280
1300
  });
1281
1301
  }
1282
- function redactGraph(graph, currentInstanceId = "", currentSessionId = "") {
1302
+ function redactGraph(graph, currentInstanceId = "", currentSessionId = "", opts = {}) {
1283
1303
  if (!graph) return null;
1284
1304
  if (chainDetailMode() === "full") return graph;
1285
- const nodes = (graph.nodes || []).map((n) => {
1305
+ const hidden = /* @__PURE__ */ new Set();
1306
+ const nodes = (graph.nodes || []).map((n, index) => {
1286
1307
  const m = { ...n };
1287
- const inst = String(m.instance_id ?? "") || "";
1288
- const sid = String(m.session_id ?? "") || "";
1289
- const sameInstance = !!(inst && currentInstanceId && inst === String(currentInstanceId));
1290
- const sameSessionFallback = !inst && !!currentSessionId && sid === String(currentSessionId);
1291
- if (!(sameInstance || sameSessionFallback)) {
1308
+ if (!chainNodeVisible(
1309
+ m.instance_id,
1310
+ m.session_id,
1311
+ currentInstanceId,
1312
+ currentSessionId,
1313
+ opts.sessionAlias || ""
1314
+ )) {
1315
+ hidden.add(index);
1292
1316
  m.session_id = "<other-session>";
1293
1317
  m.action_detail = "<\u5DF2\u9690\u85CF>";
1294
1318
  m.resources = [];
1295
1319
  }
1296
1320
  return m;
1297
1321
  });
1298
- const out = { nodes, edges: graph.edges || [] };
1322
+ const edges = (graph.edges || []).map((edge) => {
1323
+ if ("label" in edge && (hidden.has(Number(edge.from)) || hidden.has(Number(edge.to)))) {
1324
+ return { ...edge, label: "" };
1325
+ }
1326
+ return edge;
1327
+ });
1328
+ const out = { nodes, edges };
1299
1329
  for (const key of ["property_id", "property_short", "property_name", "property_expression"]) {
1300
1330
  if (graph[key] !== void 0) out[key] = graph[key];
1301
1331
  }
@@ -1695,6 +1725,157 @@ function hasInlineDangerEvidence(command) {
1695
1725
  for (const re of DANGER_EVIDENCE_RES) if (re.test(code)) return true;
1696
1726
  return false;
1697
1727
  }
1728
+ function literalShellWord(raw) {
1729
+ if (raw.length >= 2 && raw.startsWith("'") && raw.endsWith("'")) {
1730
+ const inner = raw.slice(1, -1);
1731
+ return inner.includes("'") ? null : inner;
1732
+ }
1733
+ if (raw.length >= 2 && raw.startsWith('"') && raw.endsWith('"')) {
1734
+ const inner = raw.slice(1, -1);
1735
+ return /["\\$`]/.test(inner) ? null : inner;
1736
+ }
1737
+ if (!raw || /\s/.test(raw) || !/^[A-Za-z0-9_@%+=:,./-]+$/.test(raw)) return null;
1738
+ return raw;
1739
+ }
1740
+ function pythonStringLiteral(raw) {
1741
+ const text = raw.trim();
1742
+ if (text.length < 2) return null;
1743
+ const quote = text[0];
1744
+ if (quote !== "'" && quote !== '"' || text[text.length - 1] !== quote) return null;
1745
+ const inner = text.slice(1, -1);
1746
+ if (inner.includes(quote) || inner.includes("\\") || inner.includes("\n")) return null;
1747
+ return inner;
1748
+ }
1749
+ function splitPythonArgs(raw) {
1750
+ const parts = [];
1751
+ let current = "";
1752
+ let depth = 0;
1753
+ let quote = null;
1754
+ for (const ch of raw) {
1755
+ if (quote) {
1756
+ current += ch;
1757
+ if (ch === quote) quote = null;
1758
+ continue;
1759
+ }
1760
+ if (ch === "'" || ch === '"') {
1761
+ quote = ch;
1762
+ current += ch;
1763
+ continue;
1764
+ }
1765
+ if (ch === "(" || ch === "[" || ch === "{") depth++;
1766
+ else if (ch === ")" || ch === "]" || ch === "}") depth--;
1767
+ if (ch === "," && depth === 0) {
1768
+ parts.push(current.trim());
1769
+ current = "";
1770
+ continue;
1771
+ }
1772
+ current += ch;
1773
+ }
1774
+ if (quote || depth !== 0) return null;
1775
+ parts.push(current.trim());
1776
+ return parts;
1777
+ }
1778
+ function hasTopLevelChar(raw, target) {
1779
+ let depth = 0;
1780
+ let quote = null;
1781
+ for (const ch of raw) {
1782
+ if (quote) {
1783
+ if (ch === quote) quote = null;
1784
+ continue;
1785
+ }
1786
+ if (ch === "'" || ch === '"') quote = ch;
1787
+ else if (ch === "(" || ch === "[" || ch === "{") depth++;
1788
+ else if (ch === ")" || ch === "]" || ch === "}") depth--;
1789
+ else if (ch === target && depth === 0) return true;
1790
+ }
1791
+ return false;
1792
+ }
1793
+ function splitPythonStatements(code) {
1794
+ const parts = [];
1795
+ let current = "";
1796
+ let depth = 0;
1797
+ let quote = null;
1798
+ for (const ch of code) {
1799
+ if (quote) {
1800
+ current += ch;
1801
+ if (ch === quote) quote = null;
1802
+ continue;
1803
+ }
1804
+ if (ch === "'" || ch === '"') {
1805
+ quote = ch;
1806
+ current += ch;
1807
+ continue;
1808
+ }
1809
+ if (ch === "(" || ch === "[" || ch === "{") depth++;
1810
+ else if (ch === ")" || ch === "]" || ch === "}") depth--;
1811
+ if ((ch === ";" || ch === "\n") && depth === 0) {
1812
+ parts.push(current);
1813
+ current = "";
1814
+ continue;
1815
+ }
1816
+ current += ch;
1817
+ }
1818
+ if (quote || depth !== 0) return null;
1819
+ parts.push(current);
1820
+ return parts.map((s) => s.trim()).filter((s) => s.length > 0);
1821
+ }
1822
+ function isSimpleOpenCall(expr, path9, binding) {
1823
+ const m = expr.match(/^open\s*\(([\s\S]*)\)$/);
1824
+ if (!m || hasTopLevelChar(m[1], "=")) return false;
1825
+ const args = splitPythonArgs(m[1]);
1826
+ if (!args || args.length !== 1 && args.length !== 2) return false;
1827
+ if (args.length === 2 && !["r", "rt", "rb"].includes(pythonStringLiteral(args[1]) ?? "")) {
1828
+ return false;
1829
+ }
1830
+ const target = args[0].trim();
1831
+ const literal = pythonStringLiteral(target);
1832
+ if (literal !== null) return literal === path9;
1833
+ return !!binding && target === binding;
1834
+ }
1835
+ function confirmsInlineRead(command, path9) {
1836
+ if (command.length > 8192 || !path9 || path9.startsWith("~")) return false;
1837
+ if (path9.includes("/") && !path9.startsWith("/")) return false;
1838
+ const wrapper = command.trim().match(/^python3?[ \t]+-c[ \t]+([\s\S]+)$/);
1839
+ if (!wrapper) return false;
1840
+ const code = literalShellWord(wrapper[1]);
1841
+ if (code === null) return false;
1842
+ const statements = splitPythonStatements(code);
1843
+ if (!statements || statements.length !== 1 && statements.length !== 2) return false;
1844
+ let expr;
1845
+ let binding = null;
1846
+ if (statements.length === 2) {
1847
+ const first = statements[0];
1848
+ if (first === "import os") {
1849
+ const sys = statements[1].match(/^os\.system\s*\(([\s\S]*)\)$/);
1850
+ if (!sys || hasTopLevelChar(sys[1], "=")) return false;
1851
+ const args = splitPythonArgs(sys[1]);
1852
+ if (!args || args.length !== 1) return false;
1853
+ const child = pythonStringLiteral(args[0]);
1854
+ if (child === null) return false;
1855
+ const cat = child.trim().match(/^cat[ \t]+([\s\S]+)$/);
1856
+ return !!cat && !path9.startsWith("-") && literalShellWord(cat[1].trim()) === path9;
1857
+ }
1858
+ const assign = first.match(/^([A-Za-z_]\w*)\s*=\s*([\s\S]+)$/);
1859
+ if (!assign) return false;
1860
+ const name = assign[1];
1861
+ const value = pythonStringLiteral(assign[2]);
1862
+ if (value !== path9 || ["open", "print", "__debug__"].includes(name)) return false;
1863
+ binding = name;
1864
+ expr = statements[1];
1865
+ } else {
1866
+ expr = statements[0];
1867
+ }
1868
+ const printCall = expr.match(/^print\s*\(([\s\S]*)\)$/);
1869
+ if (printCall) {
1870
+ if (hasTopLevelChar(printCall[1], "=")) return false;
1871
+ const args = splitPythonArgs(printCall[1]);
1872
+ if (!args || args.length !== 1) return false;
1873
+ expr = args[0];
1874
+ }
1875
+ const readCall = expr.match(/^([\s\S]+)\.read\s*\(\s*\)$/);
1876
+ if (readCall) expr = readCall[1];
1877
+ return isSimpleOpenCall(expr, path9, binding);
1878
+ }
1698
1879
  function analyzeInlineScript(command) {
1699
1880
  const code = extractInlineCode(command);
1700
1881
  if (!code) {
@@ -5334,6 +5515,7 @@ var init_written_content_analyzer = __esm({
5334
5515
  });
5335
5516
 
5336
5517
  // src/engine/heuristic.ts
5518
+ import { posix } from "path";
5337
5519
  function _effectiveDangerousPatterns(osType) {
5338
5520
  return runtimeConfigBridge.current?.effectiveDangerousPatterns(osType) ?? getDangerousPatternsForOs(osType);
5339
5521
  }
@@ -5361,6 +5543,112 @@ function normalizeShellObfuscation(text) {
5361
5543
  t = t.replace(/\$\{IFS\}|\$IFS/gi, " ");
5362
5544
  return t;
5363
5545
  }
5546
+ function shlexSplitLite(s) {
5547
+ const out = [];
5548
+ let cur = "";
5549
+ let quote = null;
5550
+ let quoted = false;
5551
+ for (let i = 0; i < s.length; i++) {
5552
+ const ch = s[i];
5553
+ if (quote) {
5554
+ if (ch === quote) quote = null;
5555
+ else if (ch === "\\" && quote === '"' && i + 1 < s.length) cur += s[++i];
5556
+ else cur += ch;
5557
+ continue;
5558
+ }
5559
+ if (ch === "'" || ch === '"') {
5560
+ quote = ch;
5561
+ quoted = true;
5562
+ continue;
5563
+ }
5564
+ if (/\s/.test(ch)) {
5565
+ if (cur || quoted) {
5566
+ out.push(cur);
5567
+ cur = "";
5568
+ quoted = false;
5569
+ }
5570
+ continue;
5571
+ }
5572
+ if (ch === "\\" && i + 1 < s.length) {
5573
+ cur += s[++i];
5574
+ continue;
5575
+ }
5576
+ cur += ch;
5577
+ }
5578
+ if (cur || quoted) out.push(cur);
5579
+ return out;
5580
+ }
5581
+ function rmExpandVars(token, env2) {
5582
+ let current = token;
5583
+ for (let round = 0; round < 3; round++) {
5584
+ const next = current.replace(RM_VAR_RE, (whole, braced, bare) => {
5585
+ const name = String(braced || bare).toLowerCase();
5586
+ return env2.get(name) ?? whole;
5587
+ });
5588
+ if (next === current) break;
5589
+ current = next;
5590
+ }
5591
+ return current;
5592
+ }
5593
+ function rmResolvedDangerous(resolved) {
5594
+ if (resolved === "/" || resolved.startsWith("/.")) return true;
5595
+ const first = resolved.split("/")[1] || "";
5596
+ if (first === "home") {
5597
+ const parts = resolved.split("/").filter(Boolean);
5598
+ return parts.length <= 2;
5599
+ }
5600
+ if (RM_SENSITIVE_FIRST.has(first)) return true;
5601
+ if (first === "var" && !(resolved === "/var/tmp" || resolved.startsWith("/var/tmp/"))) {
5602
+ return true;
5603
+ }
5604
+ return false;
5605
+ }
5606
+ function checkRmResolvedTargets(text) {
5607
+ const env2 = /* @__PURE__ */ new Map();
5608
+ for (let segment of splitCommandSegments2(text)) {
5609
+ if (!segment) continue;
5610
+ while (true) {
5611
+ const m = segment.match(RM_ASSIGN_RE);
5612
+ if (!m) break;
5613
+ let value = m[2].trim();
5614
+ if (value.length >= 2 && value[0] === value[value.length - 1] && (value[0] === "'" || value[0] === '"')) {
5615
+ value = value.slice(1, -1);
5616
+ }
5617
+ env2.set(m[1].toLowerCase(), rmExpandVars(value, env2));
5618
+ segment = segment.slice(m[0].length);
5619
+ }
5620
+ const parts = shlexSplitLite(segment);
5621
+ if (parts.length === 0) continue;
5622
+ let idx = 0;
5623
+ while (idx < parts.length && RM_COMMAND_PREFIXES.has(parts[idx].toLowerCase())) idx++;
5624
+ if (idx >= parts.length) continue;
5625
+ const commandWord = parts[idx].split("/").pop().replace(/^\\/, "").toLowerCase();
5626
+ if (commandWord !== "rm") continue;
5627
+ let optionsDone = false;
5628
+ for (const token of parts.slice(idx + 1)) {
5629
+ if (token === "--") {
5630
+ optionsDone = true;
5631
+ continue;
5632
+ }
5633
+ if (!optionsDone && token.startsWith("-")) continue;
5634
+ const target = rmExpandVars(token, env2);
5635
+ if (!target.startsWith("/")) continue;
5636
+ const resolved = posix.normalize(target);
5637
+ if (rmResolvedDangerous(resolved)) {
5638
+ return {
5639
+ allowed: false,
5640
+ reason: `\u68C0\u6D4B\u5230\u5220\u9664\u6839\u76EE\u5F55/\u5173\u952E\u7CFB\u7EDF\u76EE\u5F55\uFF08\u89E3\u6790\u540E\u76EE\u6807 ${resolved}\uFF09`,
5641
+ riskLevel: "critical",
5642
+ riskType: "script_execution",
5643
+ confidence: 95,
5644
+ source: "heuristic",
5645
+ violatedLayers: ["L1.1"]
5646
+ };
5647
+ }
5648
+ }
5649
+ }
5650
+ return null;
5651
+ }
5364
5652
  function scanDangerousCommandPatterns(actionType, actionDetail, osType) {
5365
5653
  const scanDetail = normalizePathSegments(stripLiteralTextSegments(actionDetail));
5366
5654
  const scanCommands = String(osType || "").toLowerCase() === "windows" ? [
@@ -5379,16 +5667,19 @@ function scanDangerousCommandPatterns(actionType, actionDetail, osType) {
5379
5667
  }
5380
5668
  }
5381
5669
  }
5382
- if (!top) return null;
5383
- return {
5670
+ const toJudgment = (hit) => ({
5384
5671
  allowed: false,
5385
- reason: `\u68C0\u6D4B\u5230\u9AD8\u5371\u64CD\u4F5C: ${top.desc}`,
5386
- riskLevel: top.sev,
5387
- riskType: top.type,
5672
+ reason: `\u68C0\u6D4B\u5230\u9AD8\u5371\u64CD\u4F5C: ${hit.desc}`,
5673
+ riskLevel: hit.sev,
5674
+ riskType: hit.type,
5388
5675
  confidence: 95,
5389
5676
  source: "heuristic",
5390
5677
  violatedLayers: ["L1.1"]
5391
- };
5678
+ });
5679
+ if (top && severityRank(top.sev) >= severityRank("high")) return toJudgment(top);
5680
+ const rmResolved = checkRmResolvedTargets(scanDetail);
5681
+ if (rmResolved) return rmResolved;
5682
+ return top ? toJudgment(top) : null;
5392
5683
  }
5393
5684
  function allUrlsLoopback(actionDetail) {
5394
5685
  const hosts = actionDetail.match(new RegExp(LOOPBACK_URL_RE.source, "gi"));
@@ -5523,6 +5814,10 @@ function runHeuristicCheck(input) {
5523
5814
  const pathResult = isExcludedType ? null : checkSensitivePath(detailL, input.cwd || "/", agentExt, input.osType);
5524
5815
  const homeResult = handledWrite ? null : checkHomeDeletion(actionTypeL, detailL);
5525
5816
  const mergeResults = [dangerousResult, pathResult, homeResult].filter(Boolean);
5817
+ if (isBashLike && !handledWrite && severityRank(highestSeverity) < severityRank("high") && !mergeResults.some((r) => severityRank(r.riskLevel) >= severityRank("high"))) {
5818
+ const rmResolved = checkRmResolvedTargets(scanDetail);
5819
+ if (rmResolved) mergeResults.push(rmResolved);
5820
+ }
5526
5821
  if (mergeResults.length > 0) {
5527
5822
  let best = mergeResults[0];
5528
5823
  for (const r of mergeResults) {
@@ -5539,6 +5834,9 @@ function runHeuristicCheck(input) {
5539
5834
  violatedLayers: ["L1.1"]
5540
5835
  };
5541
5836
  }
5837
+ if (best !== pathResult && pathResult?.deniedReadPath && best.riskType === "file_access" && best.riskLevel === pathResult.riskLevel) {
5838
+ best = { ...best, deniedReadPath: pathResult.deniedReadPath };
5839
+ }
5542
5840
  return best;
5543
5841
  }
5544
5842
  if (matched.length > 0) {
@@ -5798,7 +6096,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5798
6096
  riskType: "file_access",
5799
6097
  confidence: 90,
5800
6098
  source: "heuristic",
5801
- violatedLayers: ["L1.1"]
6099
+ violatedLayers: ["L1.1"],
6100
+ deniedReadPath: sp.path
5802
6101
  };
5803
6102
  }
5804
6103
  const denyMode = sp.denyMode || (sp.credential ? "deny_both" : sp.readOnly ? "deny_read" : "deny_write");
@@ -5812,7 +6111,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5812
6111
  confidence: 90,
5813
6112
  source: "heuristic",
5814
6113
  violatedLayers: ["L1.1"],
5815
- isCredential: !!sp.credential
6114
+ isCredential: !!sp.credential,
6115
+ deniedReadPath: denyMode === "deny_both" || denyMode === "deny_read" ? sp.path : void 0
5816
6116
  };
5817
6117
  }
5818
6118
  }
@@ -5869,7 +6169,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5869
6169
  confidence: 90,
5870
6170
  source: "heuristic",
5871
6171
  violatedLayers: ["L1.1"],
5872
- isCredential: !!sp.credential
6172
+ isCredential: !!sp.credential,
6173
+ deniedReadPath: denyMode === "deny_both" || denyMode === "deny_read" ? sp.path : void 0
5873
6174
  };
5874
6175
  }
5875
6176
  }
@@ -5892,7 +6193,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5892
6193
  confidence: 90,
5893
6194
  source: "heuristic",
5894
6195
  violatedLayers: ["L1.1"],
5895
- isCredential: !!sp.credential
6196
+ isCredential: !!sp.credential,
6197
+ deniedReadPath: denyMode === "deny_both" || denyMode === "deny_read" ? sp.path : void 0
5896
6198
  };
5897
6199
  }
5898
6200
  }
@@ -5909,7 +6211,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5909
6211
  confidence: 90,
5910
6212
  source: "heuristic",
5911
6213
  violatedLayers: ["L1.1"],
5912
- isCredential: true
6214
+ isCredential: true,
6215
+ deniedReadPath: cp.path
5913
6216
  };
5914
6217
  }
5915
6218
  }
@@ -6212,7 +6515,7 @@ function checkLateralMovement(actionDetail) {
6212
6515
  }
6213
6516
  return null;
6214
6517
  }
6215
- var INJECTION_KEYWORDS, DANGEROUS_PATTERNS2, DANGEROUS_PATTERNS_WINDOWS, DANGEROUS_PATTERNS_MACOS, DANGEROUS_PATTERNS_HARMONY, LOOPBACK_URL_RE, HEURISTIC_RULES, LOOPBACK_HOSTS, TEMP_DIRS2, PATH_CONTEXT_TRIGGER_RE, HOME_PREFIX_RE, PY_EXEC_IO_RE, PY_PRINT_RE, PY_BIGNUM_RE, PY_INLINE_C_RE, PY_CMD_SUBST_C_RE, QUOTED_SAFE_PASSWORD_PATTERN_SOURCES, COMMAND_SEGMENT_TOKEN_RE, TEXT_SEARCH_COMMANDS, COMMAND_PREFIX_WORDS, SENSITIVE_EXCLUDED_PREFIXES, SEARCH_ACTION_PREFIXES, SEARCH_ACTION_EXACT, HOME_TARGET_RE, HOME_ASSIGN_RE;
6518
+ var INJECTION_KEYWORDS, DANGEROUS_PATTERNS2, DANGEROUS_PATTERNS_WINDOWS, DANGEROUS_PATTERNS_MACOS, DANGEROUS_PATTERNS_HARMONY, RM_ASSIGN_RE, RM_VAR_RE, RM_COMMAND_PREFIXES, RM_SENSITIVE_FIRST, LOOPBACK_URL_RE, HEURISTIC_RULES, LOOPBACK_HOSTS, TEMP_DIRS2, PATH_CONTEXT_TRIGGER_RE, HOME_PREFIX_RE, PY_EXEC_IO_RE, PY_PRINT_RE, PY_BIGNUM_RE, PY_INLINE_C_RE, PY_CMD_SUBST_C_RE, QUOTED_SAFE_PASSWORD_PATTERN_SOURCES, COMMAND_SEGMENT_TOKEN_RE, TEXT_SEARCH_COMMANDS, COMMAND_PREFIX_WORDS, SENSITIVE_EXCLUDED_PREFIXES, SEARCH_ACTION_PREFIXES, SEARCH_ACTION_EXACT, HOME_TARGET_RE, HOME_ASSIGN_RE;
6216
6519
  var init_heuristic = __esm({
6217
6520
  "src/engine/heuristic.ts"() {
6218
6521
  "use strict";
@@ -6238,6 +6541,10 @@ var init_heuristic = __esm({
6238
6541
  DANGEROUS_PATTERNS_WINDOWS = _loadDangerousPatterns("windows");
6239
6542
  DANGEROUS_PATTERNS_MACOS = _loadDangerousPatterns("macos");
6240
6543
  DANGEROUS_PATTERNS_HARMONY = _loadDangerousPatterns("harmony");
6544
+ RM_ASSIGN_RE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|]+)\s*/;
6545
+ RM_VAR_RE = /\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))/g;
6546
+ RM_COMMAND_PREFIXES = /* @__PURE__ */ new Set(["sudo", "env", "command", "builtin", "exec", "nohup", "time"]);
6547
+ RM_SENSITIVE_FIRST = /* @__PURE__ */ new Set(["etc", "usr", "boot", "root", "opt", "srv", "sys", "proc", "home"]);
6241
6548
  LOOPBACK_URL_RE = /https?:\/\/([^\/\s;'"|&)]+)/i;
6242
6549
  HEURISTIC_RULES = loadHeuristicRules();
6243
6550
  LOOPBACK_HOSTS = new Set(HEURISTIC_RULES.loopback_hosts ?? []);
@@ -9317,12 +9624,14 @@ ${scriptAnalysisText}` : ""}
9317
9624
  \u8F93\u51FA\u683C\u5F0F:
9318
9625
  {"allowed": true/false, "reason": "\u5224\u65AD\u7406\u7531", "riskLevel": "low|medium|high|critical", "riskType": "\u98CE\u9669\u7C7B\u578B", "confidence": 0-100}`;
9319
9626
  }
9320
- function formatPromptHistory(promptHistory, maxTextChars = 500) {
9627
+ function formatPromptHistory(promptHistory, maxTextChars = 500, maxTurns = getNumSetting("AGENT_MOSS_LLM_PROMPT_HISTORY_MAX_TURNS", 20)) {
9321
9628
  if (!promptHistory || promptHistory.length === 0) {
9322
9629
  return "\uFF08\u672A\u63D0\u4F9B\u5386\u53F2\u610F\u56FE\uFF09";
9323
9630
  }
9631
+ const limit = Math.max(0, Math.floor(maxTurns));
9632
+ const firstTurnIndex = limit > 0 ? Math.max(0, promptHistory.length - limit) : 0;
9324
9633
  const lines = [];
9325
- for (let i = 0; i < promptHistory.length; i++) {
9634
+ for (let i = firstTurnIndex; i < promptHistory.length; i++) {
9326
9635
  const turn = promptHistory[i];
9327
9636
  const text = (typeof turn === "string" ? turn : turn?.text || "").trim();
9328
9637
  if (!text) continue;
@@ -11944,6 +12253,7 @@ var init_engine = __esm({
11944
12253
  });
11945
12254
 
11946
12255
  // src/engine/formal-engine/stateful.ts
12256
+ import { createHash as createHash4 } from "crypto";
11947
12257
  import * as fs5 from "fs";
11948
12258
  import * as os3 from "os";
11949
12259
  import * as path6 from "path";
@@ -12084,7 +12394,36 @@ function cleanupChainArchives(dir, maxBytes = envInt3("AGENT_MOSS_CHAIN_ARCHIVE_
12084
12394
  }
12085
12395
  return { deleted: removed, files: remainFiles, bytes: remainBytes };
12086
12396
  }
12087
- var DESTROY_RE, NEVER_ACTIVATED_RE, CRED_FILE_RE2, EXFIL_RE2, PORT_RE, BARE_PORT_RE, SOCK_RE, UNIT_RE, PORT_STAGE_RE, STAGES_PATTERNS, CHAINS, COMMON_DIR_RESOURCES2, MAX_NODES, StatefulChainTracker;
12397
+ function canonicalActionType(actionType) {
12398
+ const low = String(actionType || "").trim().toLowerCase();
12399
+ return SHELL_ACTION_ALIASES[low] || low;
12400
+ }
12401
+ function canonicalDetail(actionDetail) {
12402
+ const detail = String(actionDetail || "");
12403
+ const m = TRUNCATED_DETAIL_RE.exec(detail);
12404
+ const digest = m ? m[1] : createHash4("sha256").update(detail).digest("hex").slice(0, 16);
12405
+ return `sha256:${digest}`;
12406
+ }
12407
+ function canonicalCalledAt(calledAt) {
12408
+ const value = String(calledAt || "").trim();
12409
+ if (!value) return "";
12410
+ let normalized = value;
12411
+ if (/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?$/.test(normalized)) {
12412
+ normalized = normalized.replace(" ", "T") + "Z";
12413
+ }
12414
+ const ms = Date.parse(normalized);
12415
+ return Number.isFinite(ms) ? String(Math.floor(ms / 1e3)) : value;
12416
+ }
12417
+ function fingerprint(sessionId, actionType, actionDetail, calledAt) {
12418
+ const raw = [
12419
+ String(sessionId),
12420
+ canonicalActionType(actionType),
12421
+ canonicalDetail(actionDetail),
12422
+ canonicalCalledAt(calledAt)
12423
+ ].join("\0");
12424
+ return createHash4("blake2b512").update(raw).digest("hex").slice(0, 16);
12425
+ }
12426
+ var DESTROY_RE, NEVER_ACTIVATED_RE, CRED_FILE_RE2, EXFIL_RE2, PORT_RE, BARE_PORT_RE, SOCK_RE, UNIT_RE, PORT_STAGE_RE, STAGES_PATTERNS, CHAINS, COMMON_DIR_RESOURCES2, MAX_NODES, TRUNCATED_DETAIL_RE, SHELL_ACTION_ALIASES, StatefulChainTracker;
12088
12427
  var init_stateful = __esm({
12089
12428
  "src/engine/formal-engine/stateful.ts"() {
12090
12429
  "use strict";
@@ -12116,6 +12455,13 @@ var init_stateful = __esm({
12116
12455
  "/storage"
12117
12456
  ]);
12118
12457
  MAX_NODES = resolveMaxNodes();
12458
+ TRUNCATED_DETAIL_RE = /…\[truncated \d+B sha256:([0-9a-f]{16})\]$/;
12459
+ SHELL_ACTION_ALIASES = {
12460
+ executebash: "bash",
12461
+ "terminal-executebash": "bash",
12462
+ execute_bash: "bash",
12463
+ terminal_execute_bash: "bash"
12464
+ };
12119
12465
  StatefulChainTracker = class _StatefulChainTracker {
12120
12466
  /** 本地接收时刻(实时路径无 called_at 时的兜底时间戳,ISO)。 */
12121
12467
  static now() {
@@ -12135,6 +12481,7 @@ var init_stateful = __esm({
12135
12481
  taintedResources = /* @__PURE__ */ new Set();
12136
12482
  aliveResources = {};
12137
12483
  seqNext = 0;
12484
+ seededKeys = /* @__PURE__ */ new Set();
12138
12485
  constructor(agentId = "") {
12139
12486
  this.agentId = agentId;
12140
12487
  loadRules();
@@ -12277,6 +12624,9 @@ var init_stateful = __esm({
12277
12624
  const ad = String(action.actionDetail || "");
12278
12625
  const at = String(action.actionType || "");
12279
12626
  if (!ad) return null;
12627
+ const suppliedCalledAt = typeof action.calledAt === "string" ? action.calledAt : "";
12628
+ const dedupeKey = suppliedCalledAt ? fingerprint(sessionId, at, ad, suppliedCalledAt) : "";
12629
+ if (dedupeKey && this.seededKeys.has(dedupeKey)) return null;
12280
12630
  if (this.nodes_.length >= MAX_NODES) {
12281
12631
  try {
12282
12632
  const r = this.rotate();
@@ -12299,10 +12649,11 @@ var init_stateful = __esm({
12299
12649
  agentId: String(action.agentId || agentId || ""),
12300
12650
  instanceId: String(action.instanceId || instanceId || ""),
12301
12651
  lifecycle: lifecycleFor(ad, stage, isError),
12302
- timestamp: typeof action.calledAt === "string" ? action.calledAt : _StatefulChainTracker.now()
12652
+ timestamp: suppliedCalledAt || _StatefulChainTracker.now()
12303
12653
  };
12304
12654
  this.nodes_.push(node);
12305
12655
  this.seqNext += 1;
12656
+ if (dedupeKey) this.seededKeys.add(dedupeKey);
12306
12657
  return node;
12307
12658
  }
12308
12659
  recordLifecycle(node) {
@@ -12628,12 +12979,14 @@ var init_stateful = __esm({
12628
12979
  taint_parent: Object.fromEntries([...this.taintParent.entries()].map(([k, v]) => [String(k), v])),
12629
12980
  taint_origin: Object.fromEntries([...this.taintOrigin.entries()]),
12630
12981
  alive: { ...this.aliveResources },
12631
- seq_next: this.seqNext
12982
+ seq_next: this.seqNext,
12983
+ seeded_keys: [...this.seededKeys].sort()
12632
12984
  };
12633
12985
  }
12634
12986
  restore(snapshot) {
12635
12987
  if (!snapshot) return;
12636
12988
  this.agentId = String(snapshot.agent_id || this.agentId);
12989
+ this.seededKeys = new Set((snapshot.seeded_keys || []).map(String));
12637
12990
  for (const raw of snapshot.nodes || []) {
12638
12991
  this.nodes_.push({
12639
12992
  seq: Number(raw.seq || 0),
@@ -12654,6 +13007,11 @@ var init_stateful = __esm({
12654
13007
  });
12655
13008
  }
12656
13009
  this.seqNext = Number(snapshot.seq_next || this.nodes_.length);
13010
+ for (const n of this.nodes_) {
13011
+ if (n.timestamp) {
13012
+ this.seededKeys.add(fingerprint(n.sessionId, n.actionType, n.actionDetail, n.timestamp));
13013
+ }
13014
+ }
12657
13015
  this.ptr = Object.fromEntries(Object.entries(snapshot.ptrs || {}).map(([k, v]) => [k, Number(v)]));
12658
13016
  this.tainted = new Set((snapshot.tainted || []).map(Number));
12659
13017
  this.taintParent = new Map(
@@ -12711,12 +13069,12 @@ var init_stateful = __esm({
12711
13069
  import * as fs6 from "fs";
12712
13070
  import * as os4 from "os";
12713
13071
  import * as path7 from "path";
12714
- import { createHash as createHash4 } from "crypto";
13072
+ import { createHash as createHash5 } from "crypto";
12715
13073
  function defaultStateDbPath() {
12716
13074
  const base = process.env.AGENT_MOSS_STATE_DIR || path7.join(os4.homedir(), ".agentmoss");
12717
13075
  const instance = (process.env.AGENT_MOSS_INSTANCE || "").trim().replace(/^[/\\]+|[/\\]+$/g, "");
12718
13076
  const dir = instance ? path7.join(base, instance) : base;
12719
- const tag = createHash4("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
13077
+ const tag = createHash5("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
12720
13078
  const target = path7.join(dir, `stateful_chains_${tag}.json`);
12721
13079
  if (instance) {
12722
13080
  const legacy = path7.join(base, `stateful_chains_${tag}.json`);
@@ -12970,6 +13328,7 @@ __export(coordinator_exports, {
12970
13328
  TRUSTED_SKILLS_BASE: () => TRUSTED_SKILLS_BASE,
12971
13329
  _resetBrainForTest: () => _resetBrainForTest,
12972
13330
  extractFirstCommand: () => extractFirstCommand,
13331
+ independentFileCommand: () => independentFileCommand,
12973
13332
  matchesAny: () => matchesAny,
12974
13333
  runAnalysis: () => runAnalysis,
12975
13334
  splitCommandSegments: () => splitCommandSegments,
@@ -12989,6 +13348,25 @@ function extractRawCommand(detail) {
12989
13348
  const m = detail.match(/command=([^,]+)/);
12990
13349
  return m ? m[1].trim() : detail;
12991
13350
  }
13351
+ function independentFileCommand(command, osType) {
13352
+ if (String(osType).toLowerCase() === "windows") return "";
13353
+ if (["\\", "#", "<<", "<(", ">(", "`", "$"].some((mark) => command.includes(mark))) return "";
13354
+ const parts = splitCommandSegments(command);
13355
+ if (parts.length !== 2) return "";
13356
+ const ordinary = parts.filter((part2) => !isInlineScriptCommand(part2.toLowerCase()));
13357
+ if (ordinary.length !== 1) return "";
13358
+ const part = ordinary[0];
13359
+ const name = part.trim().split(/\s+/)[0] || "";
13360
+ const { writeCommandRes } = getPlatformTraits(osType);
13361
+ const isWriteCommandName = writeCommandRes.some((rx) => {
13362
+ const flags = rx.flags.replace("g", "");
13363
+ return new RegExp(`^(?:${rx.source})$`, flags).test(name);
13364
+ });
13365
+ if (SHELL_FULL_READ_CMDS.includes(name) || isWriteCommandName) {
13366
+ return part;
13367
+ }
13368
+ return "";
13369
+ }
12992
13370
  function matchesAny(cmd, patterns) {
12993
13371
  return patterns.some((p) => p.test(cmd));
12994
13372
  }
@@ -13066,13 +13444,24 @@ async function runAnalysis(input) {
13066
13444
  const isInlineScriptCmd = isInlineScriptCommand(input.aNext.actionDetail.toLowerCase());
13067
13445
  const isLiteralTextCmd = isLiteralTextCommand(input.aNext.actionDetail.toLowerCase());
13068
13446
  if (heuristicResult && !heuristicResult.allowed) {
13069
- const skipInlineFileAccess = (isInlineScriptCmd || isLiteralTextCmd) && heuristicResult.riskType === "file_access";
13070
- if (!skipInlineFileAccess) {
13071
- const shouldDenyL1 = heuristicResult.riskLevel === "high" || heuristicResult.riskLevel === "critical" || heuristicResult.riskLevel === "medium" && heuristicResult.riskType === "file_access" || heuristicResult.riskLevel === "medium" && heuristicResult.riskType === "resource_exhaustion";
13072
- if (shouldDenyL1) {
13073
- return heuristicResult;
13447
+ let skipInlineFileAccess = (isInlineScriptCmd || isLiteralTextCmd) && heuristicResult.riskType === "file_access";
13448
+ const shouldDenyL1 = heuristicResult.riskLevel === "high" || heuristicResult.riskLevel === "critical" || heuristicResult.riskLevel === "medium" && heuristicResult.riskType === "file_access" || heuristicResult.riskLevel === "medium" && heuristicResult.riskType === "resource_exhaustion";
13449
+ const bashLike = ["bash", "executebash", "terminal-executebash"].includes(input.aNext.actionType.toLowerCase());
13450
+ if (skipInlineFileAccess && shouldDenyL1 && isInlineScriptCmd && bashLike) {
13451
+ const detail = input.aNext.actionDetail;
13452
+ const command = independentFileCommand(detail, input.osType);
13453
+ if (command) {
13454
+ const hit = runHeuristicCheck({ ...input, aNext: { ...input.aNext, actionDetail: command } });
13455
+ if (hit && !hit.allowed && hit.riskType === "file_access" && ["medium", "high", "critical"].includes(hit.riskLevel)) {
13456
+ return hit;
13457
+ }
13458
+ } else if (String(input.osType || "").toLowerCase() !== "windows" && heuristicResult.deniedReadPath) {
13459
+ skipInlineFileAccess = !confirmsInlineRead(detail, heuristicResult.deniedReadPath);
13074
13460
  }
13075
13461
  }
13462
+ if (!skipInlineFileAccess && shouldDenyL1) {
13463
+ return heuristicResult;
13464
+ }
13076
13465
  }
13077
13466
  const agentExt = mergeAgentExtensions(
13078
13467
  isLayerEnabled("agent_rules_enabled") ? getAgentExtensions(input.agentId) : null,
@@ -13486,7 +13875,7 @@ var init_types = __esm({
13486
13875
  });
13487
13876
 
13488
13877
  // src/infra/policy-cache.ts
13489
- import { createHash as createHash5 } from "crypto";
13878
+ import { createHash as createHash6 } from "crypto";
13490
13879
  import { existsSync as existsSync17, lstatSync as lstatSync2, readdirSync as readdirSync6, readFileSync as readFileSync17, rmdirSync, unlinkSync as unlinkSync5 } from "fs";
13491
13880
  import { tmpdir as tmpdir3 } from "os";
13492
13881
  import { join as join18 } from "path";
@@ -13531,7 +13920,7 @@ var init_policy_cache = __esm({
13531
13920
  return `${sessionId}::${promptSession}`;
13532
13921
  }
13533
13922
  cacheFilePath(sessionId, promptSession) {
13534
- const promptHash = createHash5("md5").update(promptSession).digest("hex").slice(0, 12);
13923
+ const promptHash = createHash6("md5").update(promptSession).digest("hex").slice(0, 12);
13535
13924
  const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
13536
13925
  return join18(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
13537
13926
  }
@@ -14190,12 +14579,14 @@ import * as fs8 from "fs";
14190
14579
  import * as os5 from "os";
14191
14580
  import * as path8 from "path";
14192
14581
  function normalizeAction(row) {
14193
- return {
14582
+ const act = {
14194
14583
  actionType: String(row.action_type || row.tool_name || row.name || ""),
14195
14584
  actionDetail: String(row.action_detail || row.command || row.input || "")
14196
14585
  };
14586
+ if (row.called_at) act.calledAt = String(row.called_at);
14587
+ return act;
14197
14588
  }
14198
- function readJsonDir(dirPath, limit = 1e5) {
14589
+ function readJsonDir(dirPath, limit = 1e5, strict = false) {
14199
14590
  const sessions = /* @__PURE__ */ new Map();
14200
14591
  try {
14201
14592
  const files = fs8.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
@@ -14217,15 +14608,17 @@ function readJsonDir(dirPath, limit = 1e5) {
14217
14608
  for (const v of sessions.values()) total += v.length;
14218
14609
  if (total > limit) break;
14219
14610
  }
14220
- } catch {
14611
+ } catch (err) {
14612
+ if (strict) throw err;
14221
14613
  }
14222
14614
  return [...sessions.entries()].map(([sessionId, actionHistory]) => ({ sessionId, actionHistory }));
14223
14615
  }
14224
- function readSqlite(dbPath, limit = 1e5) {
14616
+ function readSqlite(dbPath, limit = 1e5, strict = false) {
14225
14617
  let Database;
14226
14618
  try {
14227
14619
  Database = esmRequire("better-sqlite3");
14228
- } catch {
14620
+ } catch (err) {
14621
+ if (strict) throw err;
14229
14622
  return [];
14230
14623
  }
14231
14624
  let db;
@@ -14246,7 +14639,8 @@ function readSqlite(dbPath, limit = 1e5) {
14246
14639
  sessions.set(sid, list);
14247
14640
  }
14248
14641
  return [...sessions.entries()].map(([sessionId, actionHistory]) => ({ sessionId, actionHistory }));
14249
- } catch {
14642
+ } catch (err) {
14643
+ if (strict) throw err;
14250
14644
  return [];
14251
14645
  } finally {
14252
14646
  try {
@@ -14257,15 +14651,10 @@ function readSqlite(dbPath, limit = 1e5) {
14257
14651
  }
14258
14652
  function loadAgentGateSessions(dbPath = "") {
14259
14653
  if (dbPath) {
14260
- try {
14261
- if (fs8.statSync(dbPath).isDirectory()) {
14262
- return readJsonDir(dbPath);
14263
- }
14264
- } catch {
14265
- }
14266
- const sql2 = readSqlite(dbPath);
14267
- if (sql2.length > 0) return sql2;
14268
- return readJsonDir(dbPath);
14654
+ const target = dbPath.replace(/^~(?=$|\/)/, os5.homedir());
14655
+ const stat = fs8.statSync(target);
14656
+ if (stat.isDirectory()) return readJsonDir(target, 1e5, true);
14657
+ return readSqlite(target, 1e5, true);
14269
14658
  }
14270
14659
  const sql = readSqlite(DEFAULT_AGENTGATE_SQLITE);
14271
14660
  if (sql.length > 0) return sql;
@@ -14519,7 +14908,7 @@ async function analyzeRoute(c) {
14519
14908
  session_history: req.session_history,
14520
14909
  metadata: req.metadata
14521
14910
  });
14522
- const result = await analyze({
14911
+ let result = await analyze({
14523
14912
  sessionId: req.session_id,
14524
14913
  promptSession: req.prompt_session,
14525
14914
  // output 必须透传:L2 的「授权(consent)」判定看的是**用户对提问的回答**,
@@ -14577,6 +14966,47 @@ async function analyzeRoute(c) {
14577
14966
  llmConfig: perRequestLlmEnabled() ? req.metadata?.llm_config : void 0,
14578
14967
  llmLogPath: req.metadata?.llm_log_path
14579
14968
  });
14969
+ const meta = req.metadata || {};
14970
+ const incEnabled = String(meta.stateful_incremental || "").toLowerCase();
14971
+ let finding = null;
14972
+ if (incEnabled === "1" || incEnabled === "true" || incEnabled === "yes" || incEnabled === "on") {
14973
+ try {
14974
+ const store = getChainStateStoreFor(agentId);
14975
+ const inc = store.applyAction(
14976
+ chainBucket(agentId),
14977
+ { actionType: req.a_next.action_type, actionDetail: req.a_next.action_detail },
14978
+ req.session_id,
14979
+ Boolean(meta.is_error),
14980
+ agentId,
14981
+ // 来源:真实 agent(桶 key 可能是 __system__)
14982
+ instanceId
14983
+ );
14984
+ try {
14985
+ const total = store.stats().nodes;
14986
+ const pct = Math.round(total / MAX_NODES * 1e3) / 10;
14987
+ if (total >= MAX_NODES) {
14988
+ degradedNotes.push(
14989
+ `\u3010\u5DF2\u964D\u7EA7\u3011\u94FE\u72B6\u6001\u7F13\u5B58\u8FBE\u5230\u4E0A\u9650\uFF08${total}/${MAX_NODES} \u8282\u70B9\uFF09\uFF1A\u7CFB\u7EDF\u4F1A\u81EA\u52A8\u5F52\u6863\u65E7\u8282\u70B9\u5E76\u4FDD\u7559\u6700\u8FD1\u7A97\u53E3\uFF0C\u4E0D\u9700\u8981\u624B\u5DE5 state reset\uFF1B\u82E5\u6301\u7EED\u51FA\u73B0\uFF0C\u68C0\u67E5\u5F52\u6863\u76EE\u5F55\u6743\u9650/\u78C1\u76D8\u7A7A\u95F4\u3002L1/L2.1/L3 \u6B63\u5E38\u3002\u8BE6\u89C1 docs/deploy/UPGRADE_GUIDE.md`
14990
+ );
14991
+ } else if (pct >= 90) {
14992
+ degradedNotes.push(
14993
+ `\u3010\u9884\u8B66\u3011\u94FE\u72B6\u6001\u7F13\u5B58\u5DF2\u7528 ${pct}%\uFF08${total}/${MAX_NODES} \u8282\u70B9\uFF09\uFF1A\u8FBE\u5230\u4E0A\u9650\u540E\u4F1A\u81EA\u52A8\u5F52\u6863\u65E7\u8282\u70B9\u5E76\u4FDD\u7559\u6700\u8FD1\u7A97\u53E3\uFF0C\u4E0D\u4F1A\u5BFC\u81F4\u7EC4\u5408\u94FE\u68C0\u6D4B\u5931\u6548\uFF1B\u65E0\u9700\u624B\u5DE5 state reset\u3002\u8BE6\u89C1 docs/deploy/PERFORMANCE_TUNING.md \u7B2C 5 \u8282`
14994
+ );
14995
+ }
14996
+ } catch {
14997
+ }
14998
+ finding = incMatchedToDeny(inc);
14999
+ } catch (err) {
15000
+ console.error("[AgentMoss] stateful incremental error (non-fatal):", err);
15001
+ }
15002
+ }
15003
+ result = publicFormalResult(
15004
+ result,
15005
+ finding,
15006
+ instanceId,
15007
+ req.session_id,
15008
+ req.session_history || []
15009
+ );
14580
15010
  const durationMs = performance.now() - t0;
14581
15011
  const _l3FailMsg = String(result.reason || "").slice(0, 160);
14582
15012
  if (result.l3_outcome === "reasoning_fallback") {
@@ -14611,8 +15041,10 @@ async function analyzeRoute(c) {
14611
15041
  l3_outcome: result.l3_outcome || ""
14612
15042
  });
14613
15043
  ANALYZE_DURATION.observe(Math.max(0, durationMs / 1e3), { decision: result.decision });
14614
- for (const layer of result.violated_layers || []) {
14615
- LAYER_HIT_TOTAL.inc(1, { layer: String(layer).split("-")[0] });
15044
+ for (const layer of new Set(
15045
+ (result.violated_layers || []).map((layer2) => String(layer2).split("-")[0])
15046
+ )) {
15047
+ LAYER_HIT_TOTAL.inc(1, { layer });
14616
15048
  }
14617
15049
  } catch {
14618
15050
  }
@@ -14644,62 +15076,6 @@ async function analyzeRoute(c) {
14644
15076
  });
14645
15077
  } catch {
14646
15078
  }
14647
- const meta = req.metadata || {};
14648
- const incEnabled = String(meta.stateful_incremental || "").toLowerCase();
14649
- if (incEnabled === "1" || incEnabled === "true" || incEnabled === "yes" || incEnabled === "on") {
14650
- try {
14651
- const store = getChainStateStoreFor(agentId);
14652
- const inc = store.applyAction(
14653
- chainBucket(agentId),
14654
- { actionType: req.a_next.action_type, actionDetail: req.a_next.action_detail },
14655
- req.session_id,
14656
- Boolean(meta.is_error),
14657
- agentId,
14658
- // 来源:真实 agent(桶 key 可能是 __system__)
14659
- instanceId
14660
- );
14661
- try {
14662
- const total = store.stats().nodes;
14663
- const pct = Math.round(total / MAX_NODES * 1e3) / 10;
14664
- if (total >= MAX_NODES) {
14665
- degradedNotes.push(
14666
- `\u3010\u5DF2\u964D\u7EA7\u3011\u94FE\u72B6\u6001\u7F13\u5B58\u8FBE\u5230\u4E0A\u9650\uFF08${total}/${MAX_NODES} \u8282\u70B9\uFF09\uFF1A\u7CFB\u7EDF\u4F1A\u81EA\u52A8\u5F52\u6863\u65E7\u8282\u70B9\u5E76\u4FDD\u7559\u6700\u8FD1\u7A97\u53E3\uFF0C\u4E0D\u9700\u8981\u624B\u5DE5 state reset\uFF1B\u82E5\u6301\u7EED\u51FA\u73B0\uFF0C\u68C0\u67E5\u5F52\u6863\u76EE\u5F55\u6743\u9650/\u78C1\u76D8\u7A7A\u95F4\u3002L1/L2.1/L3 \u6B63\u5E38\u3002\u8BE6\u89C1 docs/deploy/UPGRADE_GUIDE.md`
14667
- );
14668
- } else if (pct >= 90) {
14669
- degradedNotes.push(
14670
- `\u3010\u9884\u8B66\u3011\u94FE\u72B6\u6001\u7F13\u5B58\u5DF2\u7528 ${pct}%\uFF08${total}/${MAX_NODES} \u8282\u70B9\uFF09\uFF1A\u8FBE\u5230\u4E0A\u9650\u540E\u4F1A\u81EA\u52A8\u5F52\u6863\u65E7\u8282\u70B9\u5E76\u4FDD\u7559\u6700\u8FD1\u7A97\u53E3\uFF0C\u4E0D\u4F1A\u5BFC\u81F4\u7EC4\u5408\u94FE\u68C0\u6D4B\u5931\u6548\uFF1B\u65E0\u9700\u624B\u5DE5 state reset\u3002\u8BE6\u89C1 docs/deploy/PERFORMANCE_TUNING.md \u7B2C 5 \u8282`
14671
- );
14672
- }
14673
- } catch {
14674
- }
14675
- const judgment = incMatchedToDeny(inc);
14676
- if (judgment) {
14677
- const layers = [...result.violated_layers];
14678
- if (!layers.includes("L2.2-stateful")) layers.push("L2.2-stateful");
14679
- console.error(
14680
- `[AgentMoss] stateful \u589E\u91CF\u62E6\u622A: agent=${agentId || "-"} property=${judgment.property_id} risk=${judgment.risk_level}`
14681
- );
14682
- return c.json(
14683
- AnalyzeResponseSchema.parse({
14684
- decision: "Deny",
14685
- reason: judgment.reason,
14686
- risk_level: judgment.risk_level,
14687
- risk_type: "formal_verification",
14688
- violated_layers: layers,
14689
- policy: "",
14690
- violated_policy: "",
14691
- confidence: 90,
14692
- analysis_duration_ms: Math.round((performance.now() - t0) * 10) / 10,
14693
- // 跨会话节点脱敏(时间线按 agent_id 共享,原样返回等于泄露别人的命令原文)
14694
- violation_chain: redactChain(judgment.violation_chain, instanceId, req.session_id),
14695
- violation_graph: redactGraph(judgment.violation_graph, instanceId, req.session_id)
14696
- })
14697
- );
14698
- }
14699
- } catch (err) {
14700
- console.error("[AgentMoss] stateful incremental error (non-fatal):", err);
14701
- }
14702
- }
14703
15079
  return c.json(
14704
15080
  AnalyzeResponseSchema.parse({
14705
15081
  decision: result.decision,
@@ -14713,8 +15089,10 @@ async function analyzeRoute(c) {
14713
15089
  violated_policy: result.violated_policy,
14714
15090
  confidence: result.confidence,
14715
15091
  analysis_duration_ms: Math.round(durationMs * 10) / 10,
15092
+ // 已在 publicFormalResult 中按静态/增量来源选定并脱敏;这里不能再按
15093
+ // 真实 session 二次脱敏,否则会把静态引擎的 `current` 别名节点误隐藏。
14716
15094
  violation_chain: result.violation_chain ?? [],
14717
- violation_graph: redactGraph(result.violation_graph, instanceId, req.session_id),
15095
+ violation_graph: result.violation_graph ?? null,
14718
15096
  // 能力降级说明(对齐 Python):链状态触顶后本次动作没参与 L2.2
14719
15097
  degraded: degradedNotes,
14720
15098
  // L3 结局(2026-11,对齐 Python):调用方不读日志就能区分
@@ -14741,6 +15119,83 @@ async function analyzeRoute(c) {
14741
15119
  function getChainStateStoreFor(_agentId) {
14742
15120
  return getChainStateStore();
14743
15121
  }
15122
+ function mergeStatefulDenial(result, finding) {
15123
+ const level = String(finding.risk_level || "high");
15124
+ const outcome = result.l3_outcome;
15125
+ const statefulWins = result.decision !== "Deny" || ["llm_failure_fallback", "llm_circuit_open", "llm_failure_with_violation"].includes(result.source) || (RISK_PRIORITY[level] ?? 0) > (RISK_PRIORITY[result.risk_level] ?? -1);
15126
+ const merged = { ...result };
15127
+ if (statefulWins) {
15128
+ const reason = finding.reason || "\u6709\u72B6\u6001\u589E\u91CF\u94FE\u5224\u5B9A\uFF1A\u7EC4\u5408\u653B\u51FB\u94FE\u547D\u4E2D";
15129
+ Object.assign(merged, {
15130
+ decision: "Deny",
15131
+ reason,
15132
+ risk_level: level,
15133
+ risk_type: "formal_verification",
15134
+ source: "formal_engine",
15135
+ confidence: 90,
15136
+ policy: "",
15137
+ violated_policy: `[formal_verification] ${reason}`
15138
+ });
15139
+ }
15140
+ const layers = Array.isArray(result.violated_layers) ? result.violated_layers : [];
15141
+ merged.violated_layers = [.../* @__PURE__ */ new Set([...layers, "L2.2-stateful"])];
15142
+ if (outcome === "fail_open" || outcome === "fail_closed") {
15143
+ merged.l3_outcome = "failed_but_blocked";
15144
+ }
15145
+ console.error(
15146
+ `[AgentMoss] stateful \u589E\u91CF\u62E6\u622A: property=${finding.property_id || "?"} risk=${level} final_risk=${merged.risk_level}`
15147
+ );
15148
+ return { result: merged, wins: statefulWins };
15149
+ }
15150
+ function publicFormalResult(result, finding, instanceId, sessionId, sessionHistory) {
15151
+ let graph = result.violation_graph;
15152
+ let chain = result.violation_chain;
15153
+ let propertyId = graph?.property_id;
15154
+ let staticEvidence = Boolean(chain && chain.length || graph);
15155
+ if (!finding && !staticEvidence) return result;
15156
+ if (finding) {
15157
+ const merged = mergeStatefulDenial(result, finding);
15158
+ result = merged.result;
15159
+ if (merged.wins) propertyId = finding.property_id;
15160
+ const incrementalGraph = finding.violation_graph || {};
15161
+ const fillsMissingGraph = !graph && (finding.risk_level || "high") === result.risk_level && finding.violation_chain && incrementalGraph.nodes;
15162
+ if (merged.wins || !staticEvidence || fillsMissingGraph) {
15163
+ chain = finding.violation_chain;
15164
+ graph = incrementalGraph;
15165
+ staticEvidence = false;
15166
+ }
15167
+ }
15168
+ let publicSessionId = sessionId;
15169
+ let alias = "";
15170
+ if (staticEvidence) {
15171
+ if (!sessionHistory.some((s) => s.session_id === "current")) {
15172
+ alias = "current";
15173
+ } else if (publicSessionId === "current") {
15174
+ publicSessionId = "";
15175
+ }
15176
+ }
15177
+ const publicGraph = redactGraph(graph, instanceId, publicSessionId, { sessionAlias: alias });
15178
+ const out = {
15179
+ ...result,
15180
+ violation_chain: redactChain(chain || [], instanceId, publicSessionId, {
15181
+ graph,
15182
+ sessionAlias: alias
15183
+ }),
15184
+ violation_graph: publicGraph
15185
+ };
15186
+ if (propertyId === "sensitive-data-flow" && chainDetailMode() !== "full") {
15187
+ const nodes = publicGraph?.nodes || [];
15188
+ let reason = "\u654F\u611F\u6570\u636E\u4F20\u64AD\u5916\u4F20\uFF1A\u68C0\u6D4B\u5230\u7ECF\u5171\u4EAB\u8F7D\u4F53\u5916\u53D1";
15189
+ if (nodes.length >= 2) {
15190
+ const src = nodes[0];
15191
+ const dst = nodes[nodes.length - 1];
15192
+ reason = `\u654F\u611F\u6570\u636E\u4F20\u64AD\u5916\u4F20\uFF1A${src.session_id}#${src.seq} \u2192 ${dst.session_id}#${dst.seq} \u7ECF\u5171\u4EAB\u8F7D\u4F53\u5916\u53D1`;
15193
+ }
15194
+ out.reason = reason;
15195
+ out.violated_policy = `[formal_verification] ${reason}`;
15196
+ }
15197
+ return out;
15198
+ }
14744
15199
  function incMatchedToDeny(inc) {
14745
15200
  if (inc.matched) {
14746
15201
  const chain = (inc.matched.path || []).map((p) => [p.sessionId, p.seq, p.stage, p.timestamp, p.agentId ?? null]);
@@ -14770,12 +15225,6 @@ async function reviewRoute(c) {
14770
15225
  const body = await c.req.json();
14771
15226
  const req = ReviewRequestSchema.parse(body);
14772
15227
  const agentId = req.agent_id || "default";
14773
- const store = getChainStateStoreFor(agentId);
14774
- const bucket = chainBucket(agentId);
14775
- let tracker = store.load(bucket);
14776
- if (!tracker) {
14777
- tracker = new StatefulChainTracker(bucket);
14778
- }
14779
15228
  if (req.db_path && !pathWithin(req.db_path, reviewRoots())) {
14780
15229
  return c.json({
14781
15230
  detail: "db_path \u4E0D\u5728\u5141\u8BB8\u8BFB\u53D6\u7684\u76EE\u5F55\u5185\uFF1B\u6807\u51C6 AgentGate \u90E8\u7F72\u65E0\u9700\u914D\u7F6E\uFF0C\u81EA\u5B9A\u4E49\u8DEF\u5F84\u8BF7\u52A0\u5165 AGENT_MOSS_REVIEW_PATHS"
@@ -14783,24 +15232,35 @@ async function reviewRoute(c) {
14783
15232
  }
14784
15233
  let sessions = [];
14785
15234
  if (req.db_path) {
14786
- sessions = loadAgentGateSessions(req.db_path);
14787
- if (sessions.length === 0) sessions = (req.sessions || []).map((s) => ({
14788
- sessionId: s.session_id,
14789
- actionHistory: s.action_history.map((a) => ({ actionType: a.action_type, actionDetail: a.action_detail }))
14790
- }));
15235
+ try {
15236
+ sessions = loadAgentGateSessions(req.db_path);
15237
+ } catch (err) {
15238
+ if (err?.code === "ENOENT") {
15239
+ return c.json({ detail: "\u6307\u5B9A\u7684\u56DE\u987E\u8DEF\u5F84\u4E0D\u5B58\u5728" }, 404);
15240
+ }
15241
+ throw err;
15242
+ }
14791
15243
  } else {
14792
15244
  sessions = (req.sessions || []).map((s) => ({
14793
15245
  sessionId: s.session_id,
14794
- actionHistory: s.action_history.map((a) => ({ actionType: a.action_type, actionDetail: a.action_detail }))
15246
+ actionHistory: s.action_history.map((a) => ({ actionType: a.action_type, actionDetail: a.action_detail, calledAt: a.called_at }))
14795
15247
  }));
14796
15248
  }
15249
+ const explicitEmpty = !!req.db_path && sessions.length === 0;
15250
+ const store = getChainStateStoreFor(agentId);
15251
+ const bucket = chainBucket(agentId);
15252
+ let tracker = store.load(bucket);
15253
+ if (!tracker) {
15254
+ tracker = new StatefulChainTracker(bucket);
15255
+ }
14797
15256
  const added = sessions.length > 0 ? tracker.seed(sessions) : 0;
14798
15257
  store.save(tracker);
14799
15258
  let verified = true;
14800
15259
  const violations = [];
14801
- if (sessions.length > 0 || tracker.nodes.length > 0) {
15260
+ const shouldVerify = explicitEmpty ? Boolean(req.a_next) : sessions.length > 0 || tracker.nodes.length > 0;
15261
+ if (shouldVerify) {
14802
15262
  const eng = new FormalEngine();
14803
- const verifySessions = sessions.length > 0 ? sessions.map((s) => ({ sessionId: s.sessionId, actionHistory: s.actionHistory })) : tracker.nodes.length > 0 ? [{
15263
+ const verifySessions = explicitEmpty ? [] : sessions.length > 0 ? sessions.map((s) => ({ sessionId: s.sessionId, actionHistory: s.actionHistory })) : tracker.nodes.length > 0 ? [{
14804
15264
  sessionId: tracker.agentId,
14805
15265
  actionHistory: tracker.nodes.map((n) => ({
14806
15266
  actionType: n.actionType,
@@ -14948,7 +15408,7 @@ async function brainImportRoute(c) {
14948
15408
  })));
14949
15409
  return c.json({ imported: rules.length });
14950
15410
  }
14951
- var __dirname9;
15411
+ var __dirname9, RISK_PRIORITY;
14952
15412
  var init_routes = __esm({
14953
15413
  "src/routes.ts"() {
14954
15414
  "use strict";
@@ -14970,6 +15430,7 @@ var init_routes = __esm({
14970
15430
  init_runtime_stats();
14971
15431
  init_metrics();
14972
15432
  __dirname9 = dirname13(fileURLToPath10(import.meta.url));
15433
+ RISK_PRIORITY = { low: 0, medium: 1, high: 2, critical: 3 };
14973
15434
  }
14974
15435
  });
14975
15436