@kenhkl/agent-moss 0.17.27 → 0.17.29

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.
@@ -1044,21 +1044,6 @@ function isDirectoryTarget(p) {
1044
1044
  return false;
1045
1045
  }
1046
1046
  }
1047
- function intentActionText(actionType, actionDetail) {
1048
- let text = actionDetail || "";
1049
- const at = (actionType || "").toLowerCase();
1050
- if (at === "bash" || at === "executebash" || at === "terminal-executebash") {
1051
- text = stripHeredocBody(text);
1052
- text = text.replace(/(?<!\S)#[^\n]*/g, "");
1053
- text = text.replace(/'[^']*'|"[^"]*"/g, "");
1054
- return text;
1055
- }
1056
- const m = text.match(/^([\s\S]*?)\s*—\s*[\s\S]*$/);
1057
- if (m) text = m[1];
1058
- const m2 = text.match(/^(搜索|search|查找)\s*[::]\s*([\s\S]*?)\s+in\s+([\s\S]*)$/i);
1059
- if (m2) text = `${m2[1]}: in ${m2[3]}`;
1060
- return text;
1061
- }
1062
1047
  function declaredWritePaths(actionDetailRaw, osType) {
1063
1048
  const m = actionDetailRaw.match(DECLARED_WRITE_PATH_RE);
1064
1049
  if (m) return [m[1]];
@@ -1278,78 +1263,128 @@ function isWriteOperation(actionType, actionDetail, writeKeywords = WRITE_KEYWOR
1278
1263
  }
1279
1264
  return false;
1280
1265
  }
1281
- function getIntentPatternsForOs(osType) {
1282
- const effective = runtimeConfigBridge.current?.effectiveIntentPatterns(osType);
1283
- if (effective) {
1284
- return effective.map((p) => ({
1285
- ...p,
1286
- allowIfWriteIntent: p.allowIfWriteIntent ?? INTENT_DEVIATION_PATTERNS.find((d) => d.reason === p.reason)?.allowIfWriteIntent ?? false
1287
- }));
1266
+ function intentCategories(text) {
1267
+ const t = (text || "").toLowerCase();
1268
+ const out = /* @__PURE__ */ new Set();
1269
+ for (const [cat, kws] of Object.entries(INTENT_CATEGORIES)) {
1270
+ if (kws.some((kw) => t.includes(String(kw).toLowerCase()))) out.add(cat);
1288
1271
  }
1289
- const accepted = acceptedOsValues(osType);
1290
- return INTENT_DEVIATION_PATTERNS.filter((p) => accepted.includes(p.os));
1272
+ return out;
1291
1273
  }
1292
- function matchDangerousAction(actionDetail, action) {
1293
- if (/[^\x00-\x7f]/.test(action)) {
1294
- return actionDetail.includes(action);
1274
+ function actionCategory(actionType, actionDetailRaw, osType, extraWriteTools = /* @__PURE__ */ new Set()) {
1275
+ const at = (actionType || "").toLowerCase();
1276
+ const text = (actionDetailRaw || "").replace(DEVNULL_REDIRECT_RE, "");
1277
+ if (["delete", "remove", "rmdir", "unlink"].some((w) => at.includes(w))) return "delete";
1278
+ if (APPEND_MODE_RE.test(text)) return "append";
1279
+ if (/^(?:编辑文件|应用补丁)\s*[::]/.test(text)) return "overwrite";
1280
+ if (/^写入文件\s*[::]/.test(text)) {
1281
+ const paths = declaredWritePaths(text, osType);
1282
+ if (paths.length === 0) return "overwrite";
1283
+ const exists = paths.some((p) => {
1284
+ try {
1285
+ return fs.existsSync(p);
1286
+ } catch {
1287
+ return false;
1288
+ }
1289
+ });
1290
+ return exists ? "overwrite" : "create";
1295
1291
  }
1296
- const escaped = action.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1297
- const re = new RegExp(`(?<![-\\w])${escaped}\\b`, "i");
1298
- return re.test(actionDetail);
1299
- }
1300
- function collectIntentTexts(promptSession, promptHistory) {
1301
- const texts = [];
1302
- if (promptHistory) {
1303
- for (const turn of promptHistory) {
1304
- if (typeof turn === "string") {
1305
- const t2 = turn.trim();
1306
- if (t2) texts.push(t2.toLowerCase());
1307
- continue;
1292
+ if (isPreciseEditTool(at)) return "overwrite";
1293
+ if (isFullOverwriteTool(at, extraWriteTools)) {
1294
+ const paths = declaredWritePaths(text, osType);
1295
+ if (paths.length === 0) return "overwrite";
1296
+ const exists = paths.some((p) => {
1297
+ try {
1298
+ return fs.existsSync(p);
1299
+ } catch {
1300
+ return false;
1308
1301
  }
1309
- const t = (turn?.text || "").trim();
1310
- if (t) texts.push(t.toLowerCase());
1311
- }
1302
+ });
1303
+ return exists ? "overwrite" : "create";
1312
1304
  }
1313
- if (promptSession && promptSession.trim()) {
1314
- texts.push(promptSession.toLowerCase());
1305
+ for (const raw of splitCommandSegments(text)) {
1306
+ const s = raw.trim();
1307
+ if (!s) continue;
1308
+ const fw = (s.split(/\s+/)[0] || "").toLowerCase();
1309
+ if (DELETE_ACTION_WORDS.has(fw)) return "delete";
1310
+ if (fw === "sed" && SED_INPLACE_RE.test(s)) return "overwrite";
1311
+ if (["cp", "mv", "install", "rsync"].includes(fw)) return "overwrite";
1312
+ }
1313
+ if (text.includes(">>")) return "append";
1314
+ if (/(?<![/\-=<>])>\s*(?!&)\S/.test(text)) return "overwrite";
1315
+ return "read";
1316
+ }
1317
+ function intentMatrixViolation(intents, actionCat) {
1318
+ if (intents.size === 0) return null;
1319
+ if (actionCat === "overwrite") {
1320
+ if (intents.has("write")) return null;
1321
+ if (intents.has("delete") && !intents.has("read")) return "delete->overwrite";
1322
+ return "read->overwrite";
1323
+ }
1324
+ if (actionCat === "delete") {
1325
+ if (intents.has("delete")) return null;
1326
+ if (intents.has("write") && !intents.has("read")) return "write->delete";
1327
+ return "read->delete";
1315
1328
  }
1316
- const seen = /* @__PURE__ */ new Set();
1317
- const deduped = [];
1318
- for (const t of texts) {
1319
- if (!seen.has(t)) {
1320
- seen.add(t);
1321
- deduped.push(t);
1329
+ return null;
1330
+ }
1331
+ function resolveIntentText(promptSession, promptHistory, intentKeywords) {
1332
+ const cur = (promptSession || "").trim().toLowerCase();
1333
+ if (intentKeywords.some((kw) => cur.includes(kw))) return cur;
1334
+ if (!REFERENCE_PRIOR_RE.test(cur)) return cur;
1335
+ const turns = (promptHistory || []).slice(-REFERENCE_LOOKBACK);
1336
+ const candidates = [];
1337
+ for (let i = turns.length - 1; i >= 0; i--) {
1338
+ const turn = turns[i];
1339
+ const text = typeof turn === "string" ? turn.trim().toLowerCase() : (turn?.text || "").trim().toLowerCase();
1340
+ if (text && intentKeywords.some((kw) => text.includes(kw))) candidates.push(text);
1341
+ }
1342
+ if (candidates.length === 0) return cur;
1343
+ const firstCats = intentCategories(candidates[0]);
1344
+ for (const other of candidates.slice(1)) {
1345
+ const otherCats = intentCategories(other);
1346
+ const same = otherCats.size === firstCats.size && [...otherCats].every((c) => firstCats.has(c));
1347
+ if (!same) {
1348
+ console.debug(
1349
+ `[intent] \u6307\u4EE3\u524D\u6587\u7684\u56DE\u9000\u7ED3\u679C\u6709\u6B67\u4E49\uFF08\u591A\u6761\u5386\u53F2\u610F\u56FE\u7C7B\u522B\u4E0D\u4E00\u81F4\uFF09\uFF0C\u653E\u884C\u4EA4 L3\uFF1A\u5019\u9009=${candidates.map((c) => c.slice(0, 40)).join(" | ")}`
1350
+ );
1351
+ return cur;
1322
1352
  }
1323
1353
  }
1324
- return deduped;
1354
+ return candidates[0];
1325
1355
  }
1326
- function checkIntentConsistency(input) {
1356
+ function checkIntentConsistency(input, agentExt) {
1327
1357
  const { aNext, promptSession, promptHistory } = input;
1328
1358
  const actionDetail = aNext.actionDetail.toLowerCase();
1329
1359
  const actionType = aNext.actionType.toLowerCase();
1330
1360
  if (EXCLUDED_PREFIXES.some((p) => actionType.startsWith(p))) return null;
1331
1361
  if (INLINE_SCRIPT_RE.test(actionDetail)) return null;
1332
- const intentTexts = collectIntentTexts(promptSession, promptHistory);
1333
- const dangerousText = intentActionText(actionType, actionDetail);
1334
- for (const pattern of getIntentPatternsForOs(input.osType)) {
1335
- const intentMatched = intentTexts.some(
1336
- (text) => pattern.intentKeywords.some((kw) => text.includes(kw))
1362
+ const extraWriteTools = new Set(agentExt?.extra_single_file_write_tools || []);
1363
+ const intentText = resolveIntentText(promptSession, promptHistory, ALL_INTENT_KEYWORDS);
1364
+ let intents = intentCategories(intentText);
1365
+ if (intents.size > 0 && EXEC_REFERENCE_RE.test(intentText) && !intents.has("delete")) {
1366
+ console.debug(
1367
+ `[intent] \u6307\u4EE4\u6307\u5411\u5916\u90E8\u6587\u4EF6/\u8981\u6C42\uFF08\u6267\u884C\u7C7B\u8868\u8FBE\uFF09\uFF0C\u610F\u56FE\u4E0D\u660E\u786E\uFF0C\u653E\u884C\u4EA4 L3: prompt=${(promptSession || "").slice(0, 80)}`
1368
+ );
1369
+ intents = /* @__PURE__ */ new Set();
1370
+ }
1371
+ const actionCat = actionCategory(actionType, aNext.actionDetail, input.osType, extraWriteTools);
1372
+ const reasonKey = intentMatrixViolation(intents, actionCat);
1373
+ if (reasonKey !== null) {
1374
+ return {
1375
+ allowed: false,
1376
+ reason: INTENT_REASONS[reasonKey] || "\u539F\u59CB\u610F\u56FE\u4E0E\u6267\u884C\u52A8\u4F5C\u4E0D\u4E00\u81F4",
1377
+ riskLevel: "high",
1378
+ riskType: "intent_deviation",
1379
+ confidence: 85,
1380
+ source: "logic_rule",
1381
+ violatedLayers: ["L2.1"]
1382
+ };
1383
+ }
1384
+ if ((actionCat === "overwrite" || actionCat === "delete") && intents.size === 0) {
1385
+ console.debug(
1386
+ `[intent] \u610F\u56FE\u4E0D\u660E\u786E\uFF0C\u8DF3\u8FC7\u610F\u56FE\u504F\u79BB\u5224\u5B9A\u5E76\u4EA4 L3: prompt=${(promptSession || "").slice(0, 80)} \u52A8\u4F5C=${actionCat}(${actionDetail.slice(0, 80)})`
1337
1387
  );
1338
- const dangerousMatched = pattern.dangerousActions.some((kw) => matchDangerousAction(dangerousText, kw));
1339
- if (intentMatched && dangerousMatched) {
1340
- if (pattern.allowIfWriteIntent && intentTexts.some((text) => WRITE_INTENT_KEYWORDS.some((kw) => text.includes(kw)))) {
1341
- continue;
1342
- }
1343
- return {
1344
- allowed: false,
1345
- reason: pattern.reason,
1346
- riskLevel: "high",
1347
- riskType: "intent_deviation",
1348
- confidence: 85,
1349
- source: "logic_rule",
1350
- violatedLayers: ["L2.1"]
1351
- };
1352
- }
1353
1388
  }
1354
1389
  return null;
1355
1390
  }
@@ -1372,7 +1407,7 @@ function runLogicCheck(input, opts) {
1372
1407
  );
1373
1408
  if (rbwResult) return rbwResult;
1374
1409
  }
1375
- const intentResult = checkIntentConsistency(input);
1410
+ const intentResult = checkIntentConsistency(input, opts?.agentExt);
1376
1411
  if (intentResult) return intentResult;
1377
1412
  const indirectResult = checkIndirectFileAccess(actionType, actionDetail, resolvedCwd, input.osType);
1378
1413
  if (indirectResult) return indirectResult;
@@ -1836,7 +1871,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
1836
1871
  violatedLayers: ["L2.1"]
1837
1872
  };
1838
1873
  }
1839
- var _LOGIC, _HEURISTIC, EXCLUDED_PREFIXES, TEMP_DIRS, ALL_QUOTES_RE, ROOT_SENSITIVE_PATHS, HOME_SENSITIVE_PATHS, CREDENTIAL_PATHS, ROOT_SENSITIVE_PATHS_WINDOWS, HOME_SENSITIVE_PATHS_WINDOWS, CREDENTIAL_PATHS_WINDOWS, ROOT_SENSITIVE_PATHS_MACOS, HOME_SENSITIVE_PATHS_MACOS, CREDENTIAL_PATHS_MACOS, ROOT_SENSITIVE_PATHS_HARMONY, HOME_SENSITIVE_PATHS_HARMONY, CREDENTIAL_PATHS_HARMONY, _scopeIndex, NON_WRITE_TOOLS, NON_WRITE_TOOL_PREFIXES, PSEUDO_FS_PREFIXES, SINGLE_FILE_WRITE_TOOLS, PRECISE_EDIT_TOOLS, INTERP_HEREDOC_HINT_RE, HEREDOC_BODY_RE, SHELL_ASSIGN_RE, WRITE_INTENT_KEYWORDS, MISSING_WRITE_PATH_RE, DECLARED_WRITE_PATH_RE, DECLARED_WRITE_PATH_JSON_RE, PROTECTED_WRITE_PREFIXES, PROTECTED_HOME_ENTRIES, APPEND_REDIRECT_SOURCE, APPEND_MODE_RE, SHELL_FULL_READ_CMDS, SHELL_PARTIAL_READ_CMDS, SHELL_TRUNCATING_CMDS, HEAD_TAIL_LIMIT_RE, SED_RANGE_RE, PARTIAL_COVER_CHECK_MAX_LINES, WRITE_KEYWORDS, SED_INPLACE_RE, DEVNULL_REDIRECT_RE, CREATE_KEYWORDS, PASSWORD_MODIFY_PATTERNS, USER_DELETION_PATTERNS, INTENT_DEVIATION_PATTERNS, COMBO_STAGES, COMBO_CHAINS, CONSENT_TOPIC, CONSENT_NEGATIVE, CONSENT_AFFIRMATIVE, CONSENT_INPUT_REQUEST, CONSENT_MAX_DISTANCE, CONSENT_TTL_SECONDS, BASH_LIKE_ACTION_TYPES, ASK_USER_ACTION_TYPES, INLINE_SCRIPT_RE, DIR_TRAVERSAL_KW, _IFA, IFA_READ_KEYWORDS, IFA_WRITE_KEYWORDS, IFA_EXEC_KEYWORDS, IFA_OPEN_KEYWORDS;
1874
+ var _LOGIC, _HEURISTIC, EXCLUDED_PREFIXES, TEMP_DIRS, ALL_QUOTES_RE, ROOT_SENSITIVE_PATHS, HOME_SENSITIVE_PATHS, CREDENTIAL_PATHS, ROOT_SENSITIVE_PATHS_WINDOWS, HOME_SENSITIVE_PATHS_WINDOWS, CREDENTIAL_PATHS_WINDOWS, ROOT_SENSITIVE_PATHS_MACOS, HOME_SENSITIVE_PATHS_MACOS, CREDENTIAL_PATHS_MACOS, ROOT_SENSITIVE_PATHS_HARMONY, HOME_SENSITIVE_PATHS_HARMONY, CREDENTIAL_PATHS_HARMONY, _scopeIndex, NON_WRITE_TOOLS, NON_WRITE_TOOL_PREFIXES, PSEUDO_FS_PREFIXES, SINGLE_FILE_WRITE_TOOLS, PRECISE_EDIT_TOOLS, INTERP_HEREDOC_HINT_RE, HEREDOC_BODY_RE, SHELL_ASSIGN_RE, WRITE_INTENT_KEYWORDS, MISSING_WRITE_PATH_RE, DECLARED_WRITE_PATH_RE, DECLARED_WRITE_PATH_JSON_RE, PROTECTED_WRITE_PREFIXES, PROTECTED_HOME_ENTRIES, APPEND_REDIRECT_SOURCE, APPEND_MODE_RE, SHELL_FULL_READ_CMDS, SHELL_PARTIAL_READ_CMDS, SHELL_TRUNCATING_CMDS, HEAD_TAIL_LIMIT_RE, SED_RANGE_RE, PARTIAL_COVER_CHECK_MAX_LINES, WRITE_KEYWORDS, SED_INPLACE_RE, DEVNULL_REDIRECT_RE, CREATE_KEYWORDS, PASSWORD_MODIFY_PATTERNS, USER_DELETION_PATTERNS, INTENT_DEVIATION_PATTERNS, INTENT_MATRIX, INTENT_CATEGORIES, INTENT_REASONS, DELETE_ACTION_WORDS, ALL_INTENT_KEYWORDS, REFERENCE_PRIOR_RE, REFERENCE_LOOKBACK, EXEC_REFERENCE_RE, COMBO_STAGES, COMBO_CHAINS, CONSENT_TOPIC, CONSENT_NEGATIVE, CONSENT_AFFIRMATIVE, CONSENT_INPUT_REQUEST, CONSENT_MAX_DISTANCE, CONSENT_TTL_SECONDS, BASH_LIKE_ACTION_TYPES, ASK_USER_ACTION_TYPES, INLINE_SCRIPT_RE, DIR_TRAVERSAL_KW, _IFA, IFA_READ_KEYWORDS, IFA_WRITE_KEYWORDS, IFA_EXEC_KEYWORDS, IFA_OPEN_KEYWORDS;
1840
1875
  var init_logic_rules = __esm({
1841
1876
  "src/engine/logic-rules.ts"() {
1842
1877
  "use strict";
@@ -1930,6 +1965,16 @@ var init_logic_rules = __esm({
1930
1965
  allowIfWriteIntent: p.allow_if_write_intent === true
1931
1966
  }));
1932
1967
  })();
1968
+ INTENT_MATRIX = loadL2().intent_matrix || {};
1969
+ INTENT_CATEGORIES = INTENT_MATRIX.categories || {};
1970
+ INTENT_REASONS = INTENT_MATRIX.reasons || {};
1971
+ DELETE_ACTION_WORDS = new Set(
1972
+ (INTENT_MATRIX.delete_action_words || []).map((w) => String(w).toLowerCase())
1973
+ );
1974
+ ALL_INTENT_KEYWORDS = Object.values(INTENT_CATEGORIES).flat();
1975
+ REFERENCE_PRIOR_RE = /(?:继续|接着|好的?|可以|嗯+|ok|okay|go\s+on|continue|yes|看(?:一下|下)?上(?:一)?(?:句|条|段|轮|个|步)|根据(?:之前|刚才|上面|上一|前面)|按(?:之前|刚才|上面|上一|前面)|照(?:之前|刚才|上面|上一|前面)|如上|同上|同上一条|保持原样|照旧)/i;
1976
+ REFERENCE_LOOKBACK = 3;
1977
+ EXEC_REFERENCE_RE = /(?:执行|按要求|按指令|按文档|按这个文件|按上面的要求|照做|照着做)/i;
1933
1978
  COMBO_STAGES = (() => {
1934
1979
  const combo = loadL2().combo_chains || {};
1935
1980
  const stages = {};
@@ -4538,7 +4583,16 @@ function runHeuristicCheck(input) {
4538
4583
  }
4539
4584
  }
4540
4585
  const injectionText = isSearchActionType(input.aNext.actionType) ? `${input.aNext.actionType} ${input.reason || ""} ${input.promptSession || ""}`.toLowerCase() : `${input.aNext.actionType} ${input.aNext.actionDetail} ${input.reason || ""} ${input.promptSession || ""}`.toLowerCase();
4541
- const injectionHits = checkInjectionKeywords(injectionText, agentExt?.extra_injection_keywords, input.osType);
4586
+ let pythonWalkOnerrorOnly = false;
4587
+ if (isBashLike && !`${input.reason || ""} ${input.promptSession || ""}`.toLowerCase().includes("onerror=") && !isSearchActionType(input.aNext.actionType)) {
4588
+ pythonWalkOnerrorOnly = onlyPythonWalkOnerrorKeywords(input.aNext.actionDetail);
4589
+ }
4590
+ const injectionHits = checkInjectionKeywords(
4591
+ injectionText,
4592
+ agentExt?.extra_injection_keywords,
4593
+ input.osType,
4594
+ pythonWalkOnerrorOnly
4595
+ );
4542
4596
  if (injectionHits.length > 0) {
4543
4597
  const topHit = injectionHits.reduce((a, b) => severityRank(a.riskLevel) >= severityRank(b.riskLevel) ? a : b);
4544
4598
  matched.push(...injectionHits.map((h) => `\u6CE8\u5165\u5173\u952E\u8BCD [${h.lang}]: ${h.keyword}`));
@@ -4587,10 +4641,27 @@ function runHeuristicCheck(input) {
4587
4641
  if (lateralResult) return lateralResult;
4588
4642
  return null;
4589
4643
  }
4590
- function checkInjectionKeywords(text, extraKeywords, osType) {
4644
+ function onlyPythonWalkOnerrorKeywords(command) {
4645
+ const lower = command.toLowerCase();
4646
+ const occurrences = (lower.match(/onerror=/g) || []).length;
4647
+ if (!occurrences || command.length > 128 * 1024) return false;
4648
+ if (command.includes("$") || command.includes("`")) return false;
4649
+ const m = command.match(/^\s*python(?:3(?:\.\d+)?)?\s+-c\s+(['"])([\s\S]*)\1\s*(?:2>&1\s*)?$/i);
4650
+ if (!m) return false;
4651
+ const code = m[2];
4652
+ if ((code.toLowerCase().match(/onerror=/g) || []).length !== occurrences) return false;
4653
+ const noStr = code.replace(/(['"])(?:\\.|(?!\1)[^\\])*\1/g, "");
4654
+ if ((noStr.toLowerCase().match(/onerror=/g) || []).length !== occurrences) return false;
4655
+ const named = noStr.match(/onerror=\s*[A-Za-z_][\w.]*/g) || [];
4656
+ if (named.length !== occurrences) return false;
4657
+ const walkKws = noStr.match(/os\.walk\s*\([^)]*\bonerror\s*=/g) || [];
4658
+ return walkKws.length > 0;
4659
+ }
4660
+ function checkInjectionKeywords(text, extraKeywords, osType, pythonWalkOnerrorOnly = false) {
4591
4661
  const hits = [];
4592
4662
  const baseKeywords = runtimeConfigBridge.current?.effectiveInjectionKeywords(osType) ?? INJECTION_KEYWORDS;
4593
4663
  for (const entry of baseKeywords) {
4664
+ if (pythonWalkOnerrorOnly && entry.keyword.toLowerCase() === "onerror=") continue;
4594
4665
  if (text.includes(entry.keyword.toLowerCase())) {
4595
4666
  hits.push(entry);
4596
4667
  }
@@ -5259,7 +5330,7 @@ __export(token_stats_exports, {
5259
5330
  resetTokenStats: () => resetTokenStats,
5260
5331
  resetTokenStatsCacheForTests: () => resetTokenStatsCacheForTests
5261
5332
  });
5262
- import { readFileSync as readFileSync12, writeFileSync as writeFileSync2, existsSync as existsSync12, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2, statSync as statSync6 } from "fs";
5333
+ import { readFileSync as readFileSync12, writeFileSync as writeFileSync2, existsSync as existsSync12, mkdirSync as mkdirSync3, renameSync, unlinkSync as unlinkSync2, statSync as statSync6 } from "fs";
5263
5334
  function getStatsPath() {
5264
5335
  const envPath = process.env[ENV_STATS_PATH];
5265
5336
  if (envPath) return envPath;
@@ -5293,7 +5364,16 @@ function saveRecords(statsPath, records) {
5293
5364
  try {
5294
5365
  const dir = statsPath.substring(0, statsPath.lastIndexOf("/"));
5295
5366
  if (dir && !existsSync12(dir)) mkdirSync3(dir, { recursive: true });
5296
- writeFileSync2(statsPath, JSON.stringify(records, null, 2), "utf-8");
5367
+ const tmp = `${statsPath}.${process.pid}.${Date.now()}.tmp`;
5368
+ try {
5369
+ writeFileSync2(tmp, JSON.stringify(records, null, 2), "utf-8");
5370
+ renameSync(tmp, statsPath);
5371
+ } finally {
5372
+ try {
5373
+ unlinkSync2(tmp);
5374
+ } catch {
5375
+ }
5376
+ }
5297
5377
  try {
5298
5378
  const st = statSync6(statsPath);
5299
5379
  _recordsCache = {
@@ -7133,11 +7213,12 @@ function emptyNode(pathStr, depth) {
7133
7213
  };
7134
7214
  }
7135
7215
  var RecursiveTracker = class {
7136
- constructor(commandScanner, maxDepth = DEFAULT_MAX_DEPTH, maxNodes = DEFAULT_MAX_NODES, maxFileSize = DEFAULT_MAX_FILE_SIZE, maxTotalSize = DEFAULT_MAX_TOTAL_SIZE) {
7216
+ constructor(commandScanner, maxDepth = DEFAULT_MAX_DEPTH, maxNodes = DEFAULT_MAX_NODES, maxFileSize = DEFAULT_MAX_FILE_SIZE, maxTotalSize = DEFAULT_MAX_TOTAL_SIZE, stopOnCritical = true) {
7137
7217
  this.maxDepth = maxDepth;
7138
7218
  this.maxNodes = maxNodes;
7139
7219
  this.maxFileSize = maxFileSize;
7140
7220
  this.maxTotalSize = maxTotalSize;
7221
+ this.stopOnCritical = stopOnCritical;
7141
7222
  this._scanner = commandScanner;
7142
7223
  this.result = {
7143
7224
  nodes: [],
@@ -7158,6 +7239,7 @@ var RecursiveTracker = class {
7158
7239
  maxNodes;
7159
7240
  maxFileSize;
7160
7241
  maxTotalSize;
7242
+ stopOnCritical;
7161
7243
  result;
7162
7244
  visiting = /* @__PURE__ */ new Set();
7163
7245
  visitedPaths = /* @__PURE__ */ new Set();
@@ -7222,9 +7304,11 @@ var RecursiveTracker = class {
7222
7304
  node.l1MatchedPatterns = l1.matchedPatterns || [];
7223
7305
  if (l1.riskLevel === "critical") {
7224
7306
  this.result.hasCritical = true;
7225
- this.result.firstHitNode = node;
7226
- this.visiting.delete(pathStr);
7227
- return;
7307
+ if (!this.result.firstHitNode) this.result.firstHitNode = node;
7308
+ if (this.stopOnCritical) {
7309
+ this.visiting.delete(pathStr);
7310
+ return;
7311
+ }
7228
7312
  }
7229
7313
  }
7230
7314
  }
@@ -7234,7 +7318,7 @@ var RecursiveTracker = class {
7234
7318
  const child = resolvePath(call.path, parentDir);
7235
7319
  childPaths.push(child);
7236
7320
  this.visitScript(child, depth + 1, path4.dirname(child), call.args);
7237
- if (this.result.hasCritical) break;
7321
+ if (this.stopOnCritical && this.result.hasCritical) break;
7238
7322
  }
7239
7323
  node.childPaths = childPaths;
7240
7324
  this.visiting.delete(pathStr);
@@ -7552,7 +7636,7 @@ function scanScriptChainKeywords(chain) {
7552
7636
  }
7553
7637
  return chain;
7554
7638
  }
7555
- function analyzeScriptContent2(input, ext) {
7639
+ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
7556
7640
  const actionType = input.aNext.actionType.toLowerCase();
7557
7641
  if (actionType !== "bash") return emptyChain();
7558
7642
  const { path: scriptPath, args: scriptArgs } = extractScriptPathWithArgs(input.aNext.actionDetail);
@@ -7581,7 +7665,14 @@ function analyzeScriptContent2(input, ext) {
7581
7665
  }
7582
7666
  return { hit: false, riskLevel: "", riskType: "", reason: "", matchedPatterns: [] };
7583
7667
  };
7584
- const tracker = new RecursiveTracker(l1Adapter);
7668
+ const tracker = new RecursiveTracker(
7669
+ l1Adapter,
7670
+ void 0,
7671
+ void 0,
7672
+ void 0,
7673
+ void 0,
7674
+ stopOnCritical
7675
+ );
7585
7676
  const chain = tracker.track(resolvedPath, isInline ? null : scriptArgs, input.cwd || process.cwd());
7586
7677
  if (chain.nodes.length === 0) return chain;
7587
7678
  scanScriptChainWithL1(chain, input, ext);
@@ -9098,7 +9189,7 @@ function parseReview(content) {
9098
9189
 
9099
9190
  // src/brain/skill-manager.ts
9100
9191
  init_esm_shims();
9101
- import { existsSync as existsSync14, mkdirSync as mkdirSync5, readFileSync as readFileSync14, renameSync, writeFileSync as writeFileSync4 } from "fs";
9192
+ import { existsSync as existsSync14, mkdirSync as mkdirSync5, readFileSync as readFileSync14, renameSync as renameSync2, writeFileSync as writeFileSync4 } from "fs";
9102
9193
  import { homedir as homedir7 } from "os";
9103
9194
  import { join as join13 } from "path";
9104
9195
  import { randomUUID } from "crypto";
@@ -9135,7 +9226,7 @@ var BrainSkillManager = class {
9135
9226
  const tmp = `${this.metaPath}.tmp`;
9136
9227
  try {
9137
9228
  writeFileSync4(tmp, JSON.stringify(out, null, 2), "utf-8");
9138
- renameSync(tmp, this.metaPath);
9229
+ renameSync2(tmp, this.metaPath);
9139
9230
  } catch {
9140
9231
  }
9141
9232
  }
@@ -10585,7 +10676,8 @@ function _resetBrainForTest() {
10585
10676
  var formalEngine = new FormalEngine();
10586
10677
  async function runAnalysis(input) {
10587
10678
  const observedFormalLayers = [];
10588
- const heuristicResult = isHeuristicEnabled() ? runHeuristicCheck(input) : null;
10679
+ const heuristicEnabled = isHeuristicEnabled();
10680
+ const heuristicResult = heuristicEnabled ? runHeuristicCheck(input) : null;
10589
10681
  if (heuristicResult) {
10590
10682
  traceSummary("l1.result", {
10591
10683
  hit: !heuristicResult.allowed,
@@ -10611,8 +10703,8 @@ async function runAnalysis(input) {
10611
10703
  );
10612
10704
  let scriptChain = null;
10613
10705
  if (input.aNext.actionType.toLowerCase() === "bash") {
10614
- scriptChain = analyzeScriptContent2(input, agentExt);
10615
- if (scriptChain.nodes.length > 0) {
10706
+ scriptChain = analyzeScriptContent2(input, agentExt, heuristicEnabled);
10707
+ if (heuristicEnabled && scriptChain.nodes.length > 0) {
10616
10708
  for (const node of scriptChain.nodes) {
10617
10709
  if (node.unanalyzable) {
10618
10710
  return {
@@ -1,4 +1,68 @@
1
1
  {
2
+ "_intent_matrix_comment": "意图一致性判定矩阵(2026-11 重构):从当前 prompt 提取意图类别(读/写/删,可多选),从当前动作提取动作类别(读/新建/追加/覆盖/删除),按矩阵判定。规则:覆盖动作只在意图含 write 时放行;删除动作只在意图含 delete 时放行;读/新建/追加永远放行;意图提取不到 → 不判(交 L3)。指代前文(继续/看上一句/根据之前说的办)回退到最近 3 条历史 prompt,回退必须唯一,否则视为意图不明。",
3
+ "intent_matrix": {
4
+ "categories": {
5
+ "read": [
6
+ "读取",
7
+ "查看",
8
+ "分析",
9
+ "列出",
10
+ "搜索",
11
+ "查询",
12
+ "read",
13
+ "analyze",
14
+ "view",
15
+ "list",
16
+ "search",
17
+ "query",
18
+ "find"
19
+ ],
20
+ "write": [
21
+ "写入",
22
+ "写文件",
23
+ "写进",
24
+ "保存",
25
+ "生成文件",
26
+ "导出",
27
+ "输出到",
28
+ "创建文件",
29
+ "append",
30
+ "write",
31
+ "save",
32
+ "export",
33
+ "generate"
34
+ ],
35
+ "delete": [
36
+ "删除",
37
+ "移除",
38
+ "清理",
39
+ "清空",
40
+ "remove",
41
+ "delete",
42
+ "rm",
43
+ "rmdir"
44
+ ]
45
+ },
46
+ "delete_action_words": [
47
+ "删除",
48
+ "remove",
49
+ "delete",
50
+ "del",
51
+ "rm",
52
+ "rmdir",
53
+ "unlink",
54
+ "shred",
55
+ "truncate",
56
+ "format",
57
+ "erase"
58
+ ],
59
+ "reasons": {
60
+ "read->overwrite": "原始意图为读取/分析,但执行了修改操作",
61
+ "read->delete": "原始意图为读取/分析,但执行了删除操作",
62
+ "write->delete": "原始意图为写入/保存,但执行了删除操作",
63
+ "delete->overwrite": "原始意图为删除,但执行了修改操作"
64
+ }
65
+ },
2
66
  "intent_consistency": [
3
67
  {
4
68
  "intent_keywords": [
@@ -287,4 +351,4 @@
287
351
  }
288
352
  ]
289
353
  }
290
- }
354
+ }