@kenhkl/agent-moss 0.17.26 → 0.17.28

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.
@@ -1019,6 +1019,31 @@ function getSensitivePathsForOsBuiltin(osType) {
1019
1019
  }
1020
1020
  return { root: ROOT_SENSITIVE_PATHS, home: HOME_SENSITIVE_PATHS, credential: CREDENTIAL_PATHS };
1021
1021
  }
1022
+ function isPreciseEditTool(actionType) {
1023
+ const at = (actionType || "").toLowerCase();
1024
+ if (PRECISE_EDIT_TOOLS.has(at)) return true;
1025
+ for (const s of PRECISE_EDIT_TOOLS) if (at.endsWith(s)) return true;
1026
+ return false;
1027
+ }
1028
+ function isFullOverwriteTool(actionType, extraTools) {
1029
+ const at = (actionType || "").toLowerCase();
1030
+ const isWriteTool = SINGLE_FILE_WRITE_TOOLS.has(at) || extraTools.has(at) || [...SINGLE_FILE_WRITE_TOOLS].some((s) => at.endsWith(s)) || [...extraTools].some((s) => at.endsWith(s));
1031
+ if (!isWriteTool) return false;
1032
+ return !isPreciseEditTool(at);
1033
+ }
1034
+ function stripHeredocBody(text) {
1035
+ if (!text || INTERP_HEREDOC_HINT_RE.test(text)) return text;
1036
+ return text.replace(HEREDOC_BODY_RE, "<<heredoc>>\n");
1037
+ }
1038
+ function isDirectoryTarget(p) {
1039
+ if (!p) return false;
1040
+ if (p.endsWith("/")) return true;
1041
+ try {
1042
+ return fs.statSync(p).isDirectory();
1043
+ } catch {
1044
+ return false;
1045
+ }
1046
+ }
1022
1047
  function declaredWritePaths(actionDetailRaw, osType) {
1023
1048
  const m = actionDetailRaw.match(DECLARED_WRITE_PATH_RE);
1024
1049
  if (m) return [m[1]];
@@ -1238,77 +1263,128 @@ function isWriteOperation(actionType, actionDetail, writeKeywords = WRITE_KEYWOR
1238
1263
  }
1239
1264
  return false;
1240
1265
  }
1241
- function getIntentPatternsForOs(osType) {
1242
- const effective = runtimeConfigBridge.current?.effectiveIntentPatterns(osType);
1243
- if (effective) {
1244
- return effective.map((p) => ({
1245
- ...p,
1246
- allowIfWriteIntent: p.allowIfWriteIntent ?? INTENT_DEVIATION_PATTERNS.find((d) => d.reason === p.reason)?.allowIfWriteIntent ?? false
1247
- }));
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);
1248
1271
  }
1249
- const accepted = acceptedOsValues(osType);
1250
- return INTENT_DEVIATION_PATTERNS.filter((p) => accepted.includes(p.os));
1272
+ return out;
1251
1273
  }
1252
- function matchDangerousAction(actionDetail, action) {
1253
- if (/[^\x00-\x7f]/.test(action)) {
1254
- 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";
1255
1291
  }
1256
- const escaped = action.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1257
- const re = new RegExp(`(?<![-\\w])${escaped}\\b`, "i");
1258
- return re.test(actionDetail);
1259
- }
1260
- function collectIntentTexts(promptSession, promptHistory) {
1261
- const texts = [];
1262
- if (promptHistory) {
1263
- for (const turn of promptHistory) {
1264
- if (typeof turn === "string") {
1265
- const t2 = turn.trim();
1266
- if (t2) texts.push(t2.toLowerCase());
1267
- 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;
1268
1301
  }
1269
- const t = (turn?.text || "").trim();
1270
- if (t) texts.push(t.toLowerCase());
1271
- }
1302
+ });
1303
+ return exists ? "overwrite" : "create";
1272
1304
  }
1273
- if (promptSession && promptSession.trim()) {
1274
- 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";
1275
1328
  }
1276
- const seen = /* @__PURE__ */ new Set();
1277
- const deduped = [];
1278
- for (const t of texts) {
1279
- if (!seen.has(t)) {
1280
- seen.add(t);
1281
- 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;
1282
1352
  }
1283
1353
  }
1284
- return deduped;
1354
+ return candidates[0];
1285
1355
  }
1286
- function checkIntentConsistency(input) {
1356
+ function checkIntentConsistency(input, agentExt) {
1287
1357
  const { aNext, promptSession, promptHistory } = input;
1288
1358
  const actionDetail = aNext.actionDetail.toLowerCase();
1289
1359
  const actionType = aNext.actionType.toLowerCase();
1290
1360
  if (EXCLUDED_PREFIXES.some((p) => actionType.startsWith(p))) return null;
1291
1361
  if (INLINE_SCRIPT_RE.test(actionDetail)) return null;
1292
- const intentTexts = collectIntentTexts(promptSession, promptHistory);
1293
- for (const pattern of getIntentPatternsForOs(input.osType)) {
1294
- const intentMatched = intentTexts.some(
1295
- (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)})`
1296
1387
  );
1297
- const dangerousMatched = pattern.dangerousActions.some((kw) => matchDangerousAction(actionDetail, kw));
1298
- if (intentMatched && dangerousMatched) {
1299
- if (pattern.allowIfWriteIntent && intentTexts.some((text) => WRITE_INTENT_KEYWORDS.some((kw) => text.includes(kw)))) {
1300
- continue;
1301
- }
1302
- return {
1303
- allowed: false,
1304
- reason: pattern.reason,
1305
- riskLevel: "high",
1306
- riskType: "intent_deviation",
1307
- confidence: 85,
1308
- source: "logic_rule",
1309
- violatedLayers: ["L2.1"]
1310
- };
1311
- }
1312
1388
  }
1313
1389
  return null;
1314
1390
  }
@@ -1331,7 +1407,7 @@ function runLogicCheck(input, opts) {
1331
1407
  );
1332
1408
  if (rbwResult) return rbwResult;
1333
1409
  }
1334
- const intentResult = checkIntentConsistency(input);
1410
+ const intentResult = checkIntentConsistency(input, opts?.agentExt);
1335
1411
  if (intentResult) return intentResult;
1336
1412
  const indirectResult = checkIndirectFileAccess(actionType, actionDetail, resolvedCwd, input.osType);
1337
1413
  if (indirectResult) return indirectResult;
@@ -1432,6 +1508,7 @@ function extractFilePaths(text, osType) {
1432
1508
  return [...new Set(paths)];
1433
1509
  }
1434
1510
  function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason, cwd, osType, singleFileTools = SINGLE_FILE_WRITE_TOOLS) {
1511
+ actionDetailRaw = stripHeredocBody(actionDetailRaw);
1435
1512
  const actionDetail = actionDetailRaw.toLowerCase();
1436
1513
  if (NON_WRITE_TOOL_PREFIXES.some((p) => actionType.startsWith(p))) return null;
1437
1514
  if (NON_WRITE_TOOLS.has(actionType)) return null;
@@ -1491,6 +1568,9 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
1491
1568
  if (firstWord === "cd") {
1492
1569
  continue;
1493
1570
  }
1571
+ if (SHELL_ASSIGN_RE.test(trimmed)) {
1572
+ continue;
1573
+ }
1494
1574
  if (firstWord === "sed" && SED_INPLACE_RE.test(trimmed)) {
1495
1575
  } else if (getPlatformTraits(osType).readOnlyCommands.has(firstWord)) {
1496
1576
  const segUnquoted = trimmed.replace(new RegExp(`>{1,2}\\s*(['"])([~./][^'"]+)\\1`, "g"), (_m, _q, p) => ">" + p);
@@ -1529,6 +1609,7 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
1529
1609
  if (uniqueTargetPaths.length === 0) return null;
1530
1610
  const historyFullReadPaths = /* @__PURE__ */ new Set();
1531
1611
  const historyPartialRead = /* @__PURE__ */ new Map();
1612
+ const historyWrittenPaths = /* @__PURE__ */ new Set();
1532
1613
  for (const action of actionHistory) {
1533
1614
  const histDetailRaw = action.actionDetail;
1534
1615
  const histType = action.actionType.toLowerCase();
@@ -1540,6 +1621,9 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
1540
1621
  traits.writeKeywords
1541
1622
  );
1542
1623
  for (const p of coverage.full) historyFullReadPaths.add(p);
1624
+ if (isFullOverwriteTool(histType, singleFileTools) && !APPEND_MODE_RE.test(histDetailRaw)) {
1625
+ for (const p of declaredWritePaths(histDetailRaw, osType)) historyWrittenPaths.add(p);
1626
+ }
1543
1627
  for (const [p, upto] of coverage.partial) {
1544
1628
  if (historyPartialRead.has(p)) {
1545
1629
  const old = historyPartialRead.get(p);
@@ -1562,6 +1646,9 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
1562
1646
  const normalizedFullReads = new Set(
1563
1647
  [...historyFullReadPaths].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
1564
1648
  );
1649
+ const normalizedWrittenPaths = new Set(
1650
+ [...historyWrittenPaths].map((p) => normalizePathForCompare(p, cwd)).filter(Boolean)
1651
+ );
1565
1652
  const normalizedPartialReads = /* @__PURE__ */ new Map();
1566
1653
  for (const [p, upto] of historyPartialRead) {
1567
1654
  const np = normalizePathForCompare(p, cwd);
@@ -1579,16 +1666,23 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
1579
1666
  checkTargets = normalizedTargets.filter((p) => !([...appendNorm].some((ap) => pathIsSameOrUnder(p, ap) || pathIsSameOrUnder(ap, p)) && !isProtectedWritePath(p)));
1580
1667
  if (checkTargets.length === 0) return null;
1581
1668
  }
1669
+ const preciseEdit = isPreciseEditTool(actionType);
1582
1670
  const unreadPaths = [];
1583
1671
  for (const path7 of checkTargets) {
1584
- const isFullRead = [...normalizedFullReads].some(
1672
+ if (isDirectoryTarget(path7)) continue;
1673
+ let isFullRead = [...normalizedFullReads].some(
1585
1674
  (rp) => pathIsSameOrUnder(path7, rp) || pathIsSameOrUnder(rp, path7)
1586
1675
  );
1676
+ if (!isFullRead && preciseEdit && [...normalizedWrittenPaths].some(
1677
+ (wp) => pathIsSameOrUnder(path7, wp) || pathIsSameOrUnder(wp, path7)
1678
+ )) {
1679
+ isFullRead = true;
1680
+ }
1587
1681
  let isPartialCovered = false;
1588
1682
  if (!isFullRead) {
1589
1683
  for (const [pp, upto] of normalizedPartialReads) {
1590
1684
  if (!(pathIsSameOrUnder(path7, pp) || pathIsSameOrUnder(pp, path7))) continue;
1591
- if (upto != null && fileHasAtMostLines(path7, upto)) {
1685
+ if (preciseEdit || upto != null && fileHasAtMostLines(path7, upto)) {
1592
1686
  isPartialCovered = true;
1593
1687
  break;
1594
1688
  }
@@ -1777,7 +1871,7 @@ function checkIndirectFileAccess(actionType, actionDetail, cwd, osType) {
1777
1871
  violatedLayers: ["L2.1"]
1778
1872
  };
1779
1873
  }
1780
- var _LOGIC, _HEURISTIC, EXCLUDED_PREFIXES, TEMP_DIRS, ALL_QUOTES_RE, ROOT_SENSITIVE_PATHS, HOME_SENSITIVE_PATHS, CREDENTIAL_PATHS, ROOT_SENSITIVE_PATHS_WINDOWS, HOME_SENSITIVE_PATHS_WINDOWS, CREDENTIAL_PATHS_WINDOWS, ROOT_SENSITIVE_PATHS_MACOS, HOME_SENSITIVE_PATHS_MACOS, CREDENTIAL_PATHS_MACOS, ROOT_SENSITIVE_PATHS_HARMONY, HOME_SENSITIVE_PATHS_HARMONY, CREDENTIAL_PATHS_HARMONY, _scopeIndex, NON_WRITE_TOOLS, NON_WRITE_TOOL_PREFIXES, PSEUDO_FS_PREFIXES, SINGLE_FILE_WRITE_TOOLS, WRITE_INTENT_KEYWORDS, MISSING_WRITE_PATH_RE, DECLARED_WRITE_PATH_RE, DECLARED_WRITE_PATH_JSON_RE, PROTECTED_WRITE_PREFIXES, PROTECTED_HOME_ENTRIES, APPEND_REDIRECT_SOURCE, APPEND_MODE_RE, SHELL_FULL_READ_CMDS, SHELL_PARTIAL_READ_CMDS, SHELL_TRUNCATING_CMDS, HEAD_TAIL_LIMIT_RE, SED_RANGE_RE, PARTIAL_COVER_CHECK_MAX_LINES, WRITE_KEYWORDS, SED_INPLACE_RE, DEVNULL_REDIRECT_RE, CREATE_KEYWORDS, PASSWORD_MODIFY_PATTERNS, USER_DELETION_PATTERNS, INTENT_DEVIATION_PATTERNS, COMBO_STAGES, COMBO_CHAINS, CONSENT_TOPIC, CONSENT_NEGATIVE, CONSENT_AFFIRMATIVE, CONSENT_INPUT_REQUEST, CONSENT_MAX_DISTANCE, CONSENT_TTL_SECONDS, BASH_LIKE_ACTION_TYPES, ASK_USER_ACTION_TYPES, INLINE_SCRIPT_RE, DIR_TRAVERSAL_KW, _IFA, IFA_READ_KEYWORDS, IFA_WRITE_KEYWORDS, IFA_EXEC_KEYWORDS, IFA_OPEN_KEYWORDS;
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;
1781
1875
  var init_logic_rules = __esm({
1782
1876
  "src/engine/logic-rules.ts"() {
1783
1877
  "use strict";
@@ -1829,6 +1923,12 @@ var init_logic_rules = __esm({
1829
1923
  SINGLE_FILE_WRITE_TOOLS = new Set(
1830
1924
  _LOGIC.single_file_write_tools ?? []
1831
1925
  );
1926
+ PRECISE_EDIT_TOOLS = new Set(
1927
+ _LOGIC.precise_edit_write_tools ?? []
1928
+ );
1929
+ INTERP_HEREDOC_HINT_RE = /(?:^|[\s;|&])(?:bash|sh|zsh|dash|python[0-9.]*|perl|ruby|node|php|lua)\s+(?:-\S*\s+)?<<-?\s*['"]?[A-Za-z_]/i;
1930
+ HEREDOC_BODY_RE = /<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n[\s\S]*?\n\s*\2\s*(?:\n|$)/g;
1931
+ SHELL_ASSIGN_RE = /^(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*=/;
1832
1932
  WRITE_INTENT_KEYWORDS = _LOGIC.write_intent_keywords ?? [];
1833
1933
  MISSING_WRITE_PATH_RE = /(?:写入文件|编辑文件|写入|编辑)\s*[::]\s*\?/;
1834
1934
  DECLARED_WRITE_PATH_RE = /(?:写入文件|编辑文件|应用补丁|写入|编辑)\s*[::]\s*([~./][^\s—|,;]+)/;
@@ -1865,6 +1965,16 @@ var init_logic_rules = __esm({
1865
1965
  allowIfWriteIntent: p.allow_if_write_intent === true
1866
1966
  }));
1867
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;
1868
1978
  COMBO_STAGES = (() => {
1869
1979
  const combo = loadL2().combo_chains || {};
1870
1980
  const stages = {};
@@ -2125,7 +2235,7 @@ __export(runtime_config_exports, {
2125
2235
  updateSkillCategoryEnabled: () => updateSkillCategoryEnabled,
2126
2236
  updateSkillEnabled: () => updateSkillEnabled
2127
2237
  });
2128
- import { readFileSync as readFileSync4, writeFileSync, existsSync as existsSync5, mkdirSync, unlinkSync, readdirSync as readdirSync4, statSync as statSync2 } from "fs";
2238
+ import { readFileSync as readFileSync4, writeFileSync, existsSync as existsSync5, mkdirSync, unlinkSync, readdirSync as readdirSync4, statSync as statSync3 } from "fs";
2129
2239
  import { join as join5 } from "path";
2130
2240
  import { fileURLToPath as fileURLToPath4 } from "url";
2131
2241
  import { dirname as dirname3 } from "path";
@@ -2141,7 +2251,7 @@ function getRuleSourceFingerprint() {
2141
2251
  if (isRuntimeConfigDisabled()) return `mode:${getRulesMode()}`;
2142
2252
  const p = getRuntimeConfigPath();
2143
2253
  try {
2144
- const st = statSync2(p);
2254
+ const st = statSync3(p);
2145
2255
  return `${p}|${st.mtimeMs}|${st.size}`;
2146
2256
  } catch {
2147
2257
  return `${p}|absent`;
@@ -2198,7 +2308,7 @@ function loadRuntimeConfig() {
2198
2308
  return seeded;
2199
2309
  }
2200
2310
  try {
2201
- const st = statSync2(p);
2311
+ const st = statSync3(p);
2202
2312
  const cacheKey = `${p}|${st.mtimeMs}|${st.size}`;
2203
2313
  if (runtimeConfigCache && runtimeConfigCache.key === cacheKey) {
2204
2314
  return runtimeConfigCache.value;
@@ -2342,7 +2452,7 @@ function hasRuntimeConfig() {
2342
2452
  const p = getRuntimeConfigPath();
2343
2453
  let key;
2344
2454
  try {
2345
- const st = statSync2(p);
2455
+ const st = statSync3(p);
2346
2456
  key = `${p}|${st.mtimeMs}|${st.size}`;
2347
2457
  } catch {
2348
2458
  return false;
@@ -4112,7 +4222,15 @@ function detectLanguage(path7, content) {
4112
4222
  }
4113
4223
  function stripShellComments(text) {
4114
4224
  const out = [];
4225
+ let heredocEnd = null;
4115
4226
  for (const line of text.split(/\r?\n/)) {
4227
+ if (heredocEnd !== null) {
4228
+ out.push(line);
4229
+ if (line.trim() === heredocEnd) heredocEnd = null;
4230
+ continue;
4231
+ }
4232
+ const hm = line.match(HEREDOC_START_RE);
4233
+ if (hm) heredocEnd = hm[1];
4116
4234
  const res = [];
4117
4235
  let quote = null;
4118
4236
  for (let i = 0; i < line.length; i++) {
@@ -4264,7 +4382,7 @@ function extractDangerousSnippets(actionType, actionDetailRaw, literalStripper)
4264
4382
  }
4265
4383
  return snippets;
4266
4384
  }
4267
- var CFG, DATA_EXTS, SHELL_EXTS, PY_EXTS, SHELL_PRECHECK, PY_PRECHECK, MAX_CONTENT, MAX_SCAN, MAX_MS, WRITE_TOOL_EXACT, WRITE_TOOL_SUFFIXES, APPLY_PATCH_SUFFIXES, WRITE_PREFIX_RE, EDIT_NEW_RE, INTERP_HEREDOC_RE, QUOTED_HEREDOC_RE, PY_DANGEROUS_CALL_RE;
4385
+ var CFG, DATA_EXTS, SHELL_EXTS, PY_EXTS, SHELL_PRECHECK, PY_PRECHECK, MAX_CONTENT, MAX_SCAN, MAX_MS, WRITE_TOOL_EXACT, WRITE_TOOL_SUFFIXES, APPLY_PATCH_SUFFIXES, WRITE_PREFIX_RE, EDIT_NEW_RE, INTERP_HEREDOC_RE, QUOTED_HEREDOC_RE, PY_DANGEROUS_CALL_RE, HEREDOC_START_RE;
4268
4386
  var init_written_content_analyzer = __esm({
4269
4387
  "src/engine/written-content-analyzer.ts"() {
4270
4388
  "use strict";
@@ -4296,6 +4414,7 @@ var init_written_content_analyzer = __esm({
4296
4414
  INTERP_HEREDOC_RE = /(?:^|[\s;|&])(?:bash|sh|zsh|dash|python[0-9.]*|perl|ruby|node|php|lua)\s*<<-?\s*['"]?[A-Za-z_]/i;
4297
4415
  QUOTED_HEREDOC_RE = /<<-?\s*(['"])([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n.*?\n\s*\2\s*(?:\n|$)/g;
4298
4416
  PY_DANGEROUS_CALL_RE = /(?:os\.(?:system|popen|remove|unlink|rmdir|chmod|chown|kill|spawn\w*)|subprocess\.\w+|pty\.\w+|ctypes\.\w+|eval|exec|compile|__import__|shutil\.(?:rmtree|move|copy\w*))\s*\(/g;
4417
+ HEREDOC_START_RE = /<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?/;
4299
4418
  }
4300
4419
  });
4301
4420
 
@@ -5185,7 +5304,7 @@ __export(token_stats_exports, {
5185
5304
  resetTokenStats: () => resetTokenStats,
5186
5305
  resetTokenStatsCacheForTests: () => resetTokenStatsCacheForTests
5187
5306
  });
5188
- import { readFileSync as readFileSync12, writeFileSync as writeFileSync2, existsSync as existsSync12, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2, statSync as statSync5 } from "fs";
5307
+ import { readFileSync as readFileSync12, writeFileSync as writeFileSync2, existsSync as existsSync12, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2, statSync as statSync6 } from "fs";
5189
5308
  function getStatsPath() {
5190
5309
  const envPath = process.env[ENV_STATS_PATH];
5191
5310
  if (envPath) return envPath;
@@ -5195,7 +5314,7 @@ function loadAllRecords(statsPath) {
5195
5314
  if (!existsSync12(statsPath)) return [];
5196
5315
  let sig = "";
5197
5316
  try {
5198
- const st = statSync5(statsPath);
5317
+ const st = statSync6(statsPath);
5199
5318
  sig = `${st.mtimeMs}:${st.size}`;
5200
5319
  } catch {
5201
5320
  return [];
@@ -5221,7 +5340,7 @@ function saveRecords(statsPath, records) {
5221
5340
  if (dir && !existsSync12(dir)) mkdirSync3(dir, { recursive: true });
5222
5341
  writeFileSync2(statsPath, JSON.stringify(records, null, 2), "utf-8");
5223
5342
  try {
5224
- const st = statSync5(statsPath);
5343
+ const st = statSync6(statsPath);
5225
5344
  _recordsCache = {
5226
5345
  path: statsPath,
5227
5346
  sig: `${st.mtimeMs}:${st.size}`,
@@ -5656,7 +5775,7 @@ init_heuristic();
5656
5775
  init_config();
5657
5776
  init_logic_rules();
5658
5777
  init_inline_analyzer();
5659
- import { statSync as statSync4, existsSync as existsSync11 } from "fs";
5778
+ import { statSync as statSync5, existsSync as existsSync11 } from "fs";
5660
5779
  import { resolve as resolve10, join as join11, isAbsolute as isAbsolute4 } from "path";
5661
5780
  import { homedir as homedir5 } from "os";
5662
5781
 
@@ -7297,7 +7416,7 @@ function extractInlineScriptPath(actionDetail) {
7297
7416
  try {
7298
7417
  const resolved = resolvePath2(tok.replace(/^['"]|['"]$/g, ""));
7299
7418
  if (existsSync11(resolved)) {
7300
- const stat = statSync4(resolved);
7419
+ const stat = statSync5(resolved);
7301
7420
  if (stat.isFile()) return resolved;
7302
7421
  }
7303
7422
  } catch {
@@ -7311,7 +7430,7 @@ function extractInlineScriptPath(actionDetail) {
7311
7430
  try {
7312
7431
  const resolved = resolvePath2(p);
7313
7432
  if (existsSync11(resolved)) {
7314
- const stat = statSync4(resolved);
7433
+ const stat = statSync5(resolved);
7315
7434
  if (stat.isFile()) return resolved;
7316
7435
  }
7317
7436
  } catch {
@@ -7327,7 +7446,7 @@ function extractInlineScriptPath(actionDetail) {
7327
7446
  try {
7328
7447
  resolved = resolvePath2(p);
7329
7448
  if (existsSync11(resolved)) {
7330
- const stat = statSync4(resolved);
7449
+ const stat = statSync5(resolved);
7331
7450
  if (stat.isFile()) return resolved;
7332
7451
  }
7333
7452
  } catch {
@@ -9554,6 +9673,19 @@ function loadStages() {
9554
9673
  return stages;
9555
9674
  }
9556
9675
  var PATH_RE = /(?:^|\s|[@=])((?:\/|~\/)[\w./~-]+)/g;
9676
+ var COMMON_DIR_RESOURCES = /* @__PURE__ */ new Set([
9677
+ "/",
9678
+ "/tmp",
9679
+ "/var/tmp",
9680
+ "/dev/shm",
9681
+ "/home",
9682
+ "/root",
9683
+ "/usr",
9684
+ "/etc",
9685
+ "/var",
9686
+ "/data",
9687
+ "/storage"
9688
+ ]);
9557
9689
  function extractResources(actionDetail) {
9558
9690
  const resources = /* @__PURE__ */ new Set();
9559
9691
  const text = actionDetail.replace(/'[^']*'|"[^"]*"/g, "");
@@ -9562,6 +9694,7 @@ function extractResources(actionDetail) {
9562
9694
  while ((m = PATH_RE.exec(text)) !== null) {
9563
9695
  const p = m[1];
9564
9696
  if (p.startsWith("/dev/") || p.includes("://")) continue;
9697
+ if (COMMON_DIR_RESOURCES.has(p) || p.endsWith("/")) continue;
9565
9698
  resources.add(p);
9566
9699
  }
9567
9700
  return resources;
@@ -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
+ }
@@ -79,6 +79,14 @@
79
79
  "searchreplace"
80
80
  ],
81
81
  "_single_file_write_tools_comment": "单文件写工具(action_type 已转小写):语义是「把声明的内容写到声明的一个路径」。read_before_write 对它们只取工具声明的路径(command 第一个路径 / JSON 的 file_path|filePath|path),不扫 content —— 否则内容正文里的路径会被误当成写目标。bash 类工具不走这条(重定向目标可能不在第一个)。",
82
+ "precise_edit_write_tools": [
83
+ "edit",
84
+ "file_edit",
85
+ "editfile",
86
+ "searchreplace",
87
+ "search_replace"
88
+ ],
89
+ "_precise_edit_write_tools_comment": "精确编辑工具(action_type 按后缀匹配):只替换 oldString/局部片段,不重写整个文件。read_before_write 对它们只要求「读过」(部分读也算),不要求读到文件末尾 —— 模型读到 oldString 所在片段就能精确编辑;按整文件覆盖的标准要求全量读会误报(2026-11 鸿蒙实测:readFile 带 offset/limit 读一段后 editFile 被拦)。整文件覆盖工具(writefile)仍要求全量读。",
82
90
  "_reused": "不重复存的两组:① 写/删命令词边界正则 = platform_traits.json 的 write_command_res(逐字相同);② 工具排除前缀 = heuristic_rules.json 的 sensitive_excluded_prefixes(逐字相同);③ 临时目录名单 = heuristic_rules.json 的 temp_dirs(L1/L2 共用一份)。",
83
91
  "protected_write_prefixes": [
84
92
  "/etc/",