@kenhkl/agent-moss 0.17.43 → 0.17.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -442,22 +442,22 @@ function loadToolRegistry() {
442
442
  data.tools = tools;
443
443
  return data;
444
444
  }
445
- function scanStructEntry(cat, value, path8) {
445
+ function scanStructEntry(cat, value, path9) {
446
446
  if (cat === "skills") {
447
447
  if (!value || typeof value !== "object" || Array.isArray(value)) {
448
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684 skills \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u7C7B\u522B: {\u6280\u80FD\u540D: [\u5173\u952E\u8BCD]}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
448
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u7684 skills \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u7C7B\u522B: {\u6280\u80FD\u540D: [\u5173\u952E\u8BCD]}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
449
449
  return null;
450
450
  }
451
451
  const out = {};
452
452
  for (const [skCat, skills] of Object.entries(value)) {
453
453
  if (!skills || typeof skills !== "object" || Array.isArray(skills)) {
454
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684 skills.${skCat} \u5E94\u4E3A\u5BF9\u8C61\uFF08\u6280\u80FD\u540D \u2192 \u5173\u952E\u8BCD\u6570\u7EC4\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
454
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u7684 skills.${skCat} \u5E94\u4E3A\u5BF9\u8C61\uFF08\u6280\u80FD\u540D \u2192 \u5173\u952E\u8BCD\u6570\u7EC4\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
455
455
  continue;
456
456
  }
457
457
  const keep = {};
458
458
  for (const [name, kws] of Object.entries(skills)) {
459
459
  if (Array.isArray(kws)) keep[name] = kws;
460
- else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684 skills.${skCat}.${name} \u5173\u952E\u8BCD\u4E0D\u662F\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
460
+ else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u7684 skills.${skCat}.${name} \u5173\u952E\u8BCD\u4E0D\u662F\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
461
461
  }
462
462
  if (Object.keys(keep).length > 0) out[skCat] = keep;
463
463
  }
@@ -465,37 +465,37 @@ function scanStructEntry(cat, value, path8) {
465
465
  }
466
466
  if (cat === "ltl_rules") {
467
467
  if (!Array.isArray(value)) {
468
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684 ltl_rules \u5E94\u4E3A\u5BF9\u8C61\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
468
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u7684 ltl_rules \u5E94\u4E3A\u5BF9\u8C61\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
469
469
  return null;
470
470
  }
471
471
  const keep = value.filter((r) => r && typeof r === "object" && r.id);
472
472
  if (keep.length !== value.length) {
473
- console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684 ltl_rules \u6709\u6761\u76EE\u7F3A id \u6216\u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
473
+ console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u7684 ltl_rules \u6709\u6761\u76EE\u7F3A id \u6216\u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
474
474
  }
475
475
  return keep.length > 0 ? keep : null;
476
476
  }
477
477
  if (cat === "tools") {
478
478
  if (!value || typeof value !== "object" || Array.isArray(value)) {
479
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684 tools \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u5DE5\u5177\u540D: {actionClass, ...}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
479
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u7684 tools \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u5DE5\u5177\u540D: {actionClass, ...}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
480
480
  return null;
481
481
  }
482
482
  const keep = {};
483
483
  for (const [k, v] of Object.entries(value)) {
484
484
  if (v && typeof v === "object" && !Array.isArray(v)) keep[k] = v;
485
- else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684 tools.${k} \u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
485
+ else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u7684 tools.${k} \u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
486
486
  }
487
487
  return Object.keys(keep).length > 0 ? keep : null;
488
488
  }
489
489
  return null;
490
490
  }
491
- function scanRulesFile(path8, kind) {
491
+ function scanRulesFile(path9, kind) {
492
492
  const out = {};
493
493
  const label = kind === "override" ? "\u8986\u76D6" : "\u8FFD\u52A0";
494
494
  let parsed;
495
495
  try {
496
- parsed = JSON.parse(readFileSync2(path8, "utf-8"));
496
+ parsed = JSON.parse(readFileSync2(path9, "utf-8"));
497
497
  } catch (e) {
498
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u635F\u574F/\u4E0D\u53EF\u8BFB\uFF0C\u5DF2\u8DF3\u8FC7\uFF08${kind} \u89C4\u5219\u4E0D\u751F\u6548\uFF09: ${e.message}`);
498
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u635F\u574F/\u4E0D\u53EF\u8BFB\uFF0C\u5DF2\u8DF3\u8FC7\uFF08${kind} \u89C4\u5219\u4E0D\u751F\u6548\uFF09: ${e.message}`);
499
499
  return out;
500
500
  }
501
501
  const classifyFlat = (r) => {
@@ -519,44 +519,44 @@ function scanRulesFile(path8, kind) {
519
519
  }
520
520
  if (flatBad > 0) {
521
521
  console.warn(
522
- `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u6709 ${flatBad} \u6761\u5E73\u94FA\u6761\u76EE\u65E0\u6CD5\u5F52\u7C7B\uFF08\u88F8 pattern \u4E0D\u5E26 risk_level/risk_type \u65F6\u533A\u5206\u4E0D\u4E86 L1 \u5371\u9669\u547D\u4EE4\u4E0E L2 \u6388\u6743\u7C7B\uFF09\u2014\u2014 \u8BF7\u6539\u7528\u5BF9\u8C61\u5F62\u5F0F\uFF1A{"\u7C7B\u522B\u952E": [\u6761\u76EE...]}\u3002`
522
+ `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u6709 ${flatBad} \u6761\u5E73\u94FA\u6761\u76EE\u65E0\u6CD5\u5F52\u7C7B\uFF08\u88F8 pattern \u4E0D\u5E26 risk_level/risk_type \u65F6\u533A\u5206\u4E0D\u4E86 L1 \u5371\u9669\u547D\u4EE4\u4E0E L2 \u6388\u6743\u7C7B\uFF09\u2014\u2014 \u8BF7\u6539\u7528\u5BF9\u8C61\u5F62\u5F0F\uFF1A{"\u7C7B\u522B\u952E": [\u6761\u76EE...]}\u3002`
523
523
  );
524
524
  }
525
525
  } else {
526
- console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u9876\u5C42\u5E94\u662F\u5BF9\u8C61\uFF08\u7C7B\u522B\u952E\u2192\u6761\u76EE\u6570\u7EC4\uFF09\u6216\u6570\u7EC4\uFF0C\u5DF2\u8DF3\u8FC7\u3002`);
526
+ console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u9876\u5C42\u5E94\u662F\u5BF9\u8C61\uFF08\u7C7B\u522B\u952E\u2192\u6761\u76EE\u6570\u7EC4\uFF09\u6216\u6570\u7EC4\uFF0C\u5DF2\u8DF3\u8FC7\u3002`);
527
527
  return out;
528
528
  }
529
529
  for (const [cat, rules] of pairs) {
530
530
  if (String(cat).startsWith("_")) continue;
531
531
  if (STRUCT_KEYS.includes(cat)) {
532
- const got = scanStructEntry(cat, rules, path8);
532
+ const got = scanStructEntry(cat, rules, path9);
533
533
  if (got !== null) out[cat] = got;
534
534
  continue;
535
535
  }
536
536
  const required = EXTRA_CATEGORIES[cat];
537
537
  if (!required) {
538
538
  console.warn(
539
- `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u542B\u672A\u77E5\u7C7B\u522B\u952E "${cat}"\uFF08\u53EF\u7528\uFF1A${Object.keys(EXTRA_CATEGORIES).join(", ")}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`
539
+ `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u542B\u672A\u77E5\u7C7B\u522B\u952E "${cat}"\uFF08\u53EF\u7528\uFF1A${Object.keys(EXTRA_CATEGORIES).join(", ")}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`
540
540
  );
541
541
  continue;
542
542
  }
543
543
  if (rules && typeof rules === "object" && !Array.isArray(rules)) {
544
544
  console.error(
545
- `[AgentMoss] \u274C \u89C4\u5219\u6587\u4EF6 ${path8} \u7684\u7C7B\u522B "${cat}" \u662F**\u5BF9\u8C61**\uFF0C\u5E94\u4E3A**\u5BF9\u8C61\u6570\u7EC4** \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002
545
+ `[AgentMoss] \u274C \u89C4\u5219\u6587\u4EF6 ${path9} \u7684\u7C7B\u522B "${cat}" \u662F**\u5BF9\u8C61**\uFF0C\u5E94\u4E3A**\u5BF9\u8C61\u6570\u7EC4** \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002
546
546
  \u6B63\u786E\u5199\u6CD5: {"${cat}": [{"pattern": "...", "risk_level": "high", ...}]}
547
547
  \u4F60\u5199\u7684\u50CF\u662F runtime config \u7684\u683C\u5F0F\uFF08{"category_enabled": ..., "rules": [...]}\uFF09\u2014\u2014\u90A3\u662F ~/.config/agentmoss/agent_moss_runtime.json \u7684\u683C\u5F0F\uFF0C\u4E0D\u80FD\u76F4\u63A5\u5F53\u89C4\u5219\u6587\u4EF6\u7528\u3002`
548
548
  );
549
549
  continue;
550
550
  }
551
551
  if (!Array.isArray(rules)) {
552
- console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7684\u7C7B\u522B "${cat}" \u5E94\u4E3A\u6570\u7EC4\uFF0C\u5B9E\u9645\u662F ${typeof rules} \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
552
+ console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u7684\u7C7B\u522B "${cat}" \u5E94\u4E3A\u6570\u7EC4\uFF0C\u5B9E\u9645\u662F ${typeof rules} \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
553
553
  continue;
554
554
  }
555
555
  const items = [];
556
556
  for (const r of rules) {
557
557
  if (!r || typeof r !== "object" || !required.every((k) => r[k])) {
558
558
  console.warn(
559
- `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path8} \u7C7B\u522B ${cat} \u6709\u6761\u76EE\u7F3A\u5FC5\u9700\u5B57\u6BB5 [${required.join(", ")}] \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`
559
+ `[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path9} \u7C7B\u522B ${cat} \u6709\u6761\u76EE\u7F3A\u5FC5\u9700\u5B57\u6BB5 [${required.join(", ")}] \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`
560
560
  );
561
561
  continue;
562
562
  }
@@ -566,7 +566,7 @@ function scanRulesFile(path8, kind) {
566
566
  }
567
567
  if (Object.keys(out).length > 0) {
568
568
  console.info(
569
- `[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${path8}\uFF1A` + Object.entries(out).map(([k, v]) => `${k}\xD7${v.length}`).join(", ")
569
+ `[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${path9}\uFF1A` + Object.entries(out).map(([k, v]) => `${k}\xD7${v.length}`).join(", ")
570
570
  );
571
571
  }
572
572
  return out;
@@ -910,7 +910,7 @@ function splitPythonStatements(code) {
910
910
  parts.push(current);
911
911
  return parts.map((s) => s.trim()).filter((s) => s.length > 0);
912
912
  }
913
- function isSimpleOpenCall(expr, path8, binding) {
913
+ function isSimpleOpenCall(expr, path9, binding) {
914
914
  const m = expr.match(/^open\s*\(([\s\S]*)\)$/);
915
915
  if (!m || hasTopLevelChar(m[1], "=")) return false;
916
916
  const args = splitPythonArgs(m[1]);
@@ -920,12 +920,12 @@ function isSimpleOpenCall(expr, path8, binding) {
920
920
  }
921
921
  const target = args[0].trim();
922
922
  const literal = pythonStringLiteral(target);
923
- if (literal !== null) return literal === path8;
923
+ if (literal !== null) return literal === path9;
924
924
  return !!binding && target === binding;
925
925
  }
926
- function confirmsInlineRead(command, path8) {
927
- if (command.length > 8192 || !path8 || path8.startsWith("~")) return false;
928
- if (path8.includes("/") && !path8.startsWith("/")) return false;
926
+ function confirmsInlineRead(command, path9) {
927
+ if (command.length > 8192 || !path9 || path9.startsWith("~")) return false;
928
+ if (path9.includes("/") && !path9.startsWith("/")) return false;
929
929
  const wrapper = command.trim().match(/^python3?[ \t]+-c[ \t]+([\s\S]+)$/);
930
930
  if (!wrapper) return false;
931
931
  const code = literalShellWord(wrapper[1]);
@@ -944,13 +944,13 @@ function confirmsInlineRead(command, path8) {
944
944
  const child = pythonStringLiteral(args[0]);
945
945
  if (child === null) return false;
946
946
  const cat = child.trim().match(/^cat[ \t]+([\s\S]+)$/);
947
- return !!cat && !path8.startsWith("-") && literalShellWord(cat[1].trim()) === path8;
947
+ return !!cat && !path9.startsWith("-") && literalShellWord(cat[1].trim()) === path9;
948
948
  }
949
949
  const assign = first.match(/^([A-Za-z_]\w*)\s*=\s*([\s\S]+)$/);
950
950
  if (!assign) return false;
951
951
  const name = assign[1];
952
952
  const value = pythonStringLiteral(assign[2]);
953
- if (value !== path8 || ["open", "print", "__debug__"].includes(name)) return false;
953
+ if (value !== path9 || ["open", "print", "__debug__"].includes(name)) return false;
954
954
  binding = name;
955
955
  expr = statements[1];
956
956
  } else {
@@ -965,7 +965,7 @@ function confirmsInlineRead(command, path8) {
965
965
  }
966
966
  const readCall = expr.match(/^([\s\S]+)\.read\s*\(\s*\)$/);
967
967
  if (readCall) expr = readCall[1];
968
- return isSimpleOpenCall(expr, path8, binding);
968
+ return isSimpleOpenCall(expr, path9, binding);
969
969
  }
970
970
  function analyzeInlineScript(command) {
971
971
  const code = extractInlineCode(command);
@@ -1120,7 +1120,7 @@ function _loadSensitivePathScope(scope, osType = "linux") {
1120
1120
  os: String(sp.os || "linux").toLowerCase()
1121
1121
  }));
1122
1122
  }
1123
- function _scopeOf(os5, path8) {
1123
+ function _scopeOf(os5, path9) {
1124
1124
  if (!_scopeIndex) {
1125
1125
  _scopeIndex = /* @__PURE__ */ new Map();
1126
1126
  for (const sp of loadL1().sensitive_path_access || []) {
@@ -1128,7 +1128,7 @@ function _scopeOf(os5, path8) {
1128
1128
  if (!_scopeIndex.has(key)) _scopeIndex.set(key, sp.scope);
1129
1129
  }
1130
1130
  }
1131
- return _scopeIndex.get(`${String(os5 || "linux").toLowerCase()}|${path8}`) || "root";
1131
+ return _scopeIndex.get(`${String(os5 || "linux").toLowerCase()}|${path9}`) || "root";
1132
1132
  }
1133
1133
  function getSensitivePathsForOs(osType) {
1134
1134
  const effective = runtimeConfigBridge.current?.effectiveSensitivePaths(osType);
@@ -1946,36 +1946,36 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
1946
1946
  }
1947
1947
  const preciseEdit = isPreciseEditTool(actionType);
1948
1948
  const unreadPaths = [];
1949
- for (const path8 of checkTargets) {
1950
- if (isDirectoryTarget(path8)) continue;
1949
+ for (const path9 of checkTargets) {
1950
+ if (isDirectoryTarget(path9)) continue;
1951
1951
  let isFullRead = [...normalizedFullReads].some(
1952
- (rp) => pathIsSameOrUnder(path8, rp) || pathIsSameOrUnder(rp, path8)
1952
+ (rp) => pathIsSameOrUnder(path9, rp) || pathIsSameOrUnder(rp, path9)
1953
1953
  );
1954
1954
  if (!isFullRead && preciseEdit && [...normalizedWrittenPaths].some(
1955
- (wp) => pathIsSameOrUnder(path8, wp) || pathIsSameOrUnder(wp, path8)
1955
+ (wp) => pathIsSameOrUnder(path9, wp) || pathIsSameOrUnder(wp, path9)
1956
1956
  )) {
1957
1957
  isFullRead = true;
1958
1958
  }
1959
- if (!isFullRead && !isProtectedWritePath(path8) && isScriptGeneratedTarget(path8, historyWrittenScripts, shellRunActions)) {
1959
+ if (!isFullRead && !isProtectedWritePath(path9) && isScriptGeneratedTarget(path9, historyWrittenScripts, shellRunActions)) {
1960
1960
  isFullRead = true;
1961
1961
  }
1962
1962
  let isPartialCovered = false;
1963
1963
  if (!isFullRead) {
1964
1964
  for (const [pp, upto] of normalizedPartialReads) {
1965
- if (!(pathIsSameOrUnder(path8, pp) || pathIsSameOrUnder(pp, path8))) continue;
1966
- if (preciseEdit || upto != null && fileHasAtMostLines(path8, upto)) {
1965
+ if (!(pathIsSameOrUnder(path9, pp) || pathIsSameOrUnder(pp, path9))) continue;
1966
+ if (preciseEdit || upto != null && fileHasAtMostLines(path9, upto)) {
1967
1967
  isPartialCovered = true;
1968
1968
  break;
1969
1969
  }
1970
1970
  }
1971
1971
  }
1972
1972
  if (!isFullRead && !isPartialCovered) {
1973
- let isCreate = !fs.existsSync(path8);
1973
+ let isCreate = !fs.existsSync(path9);
1974
1974
  if (!isCreate) {
1975
1975
  isCreate = CREATE_KEYWORDS.some((kw) => reason.toLowerCase().includes(kw) || actionDetail.includes(kw));
1976
1976
  }
1977
1977
  if (!isCreate) {
1978
- unreadPaths.push(path8);
1978
+ unreadPaths.push(path9);
1979
1979
  }
1980
1980
  }
1981
1981
  }
@@ -2169,16 +2169,16 @@ var init_logic_rules = __esm({
2169
2169
  ALL_QUOTES_RE = /'[^']*'|"[^"]*"/g;
2170
2170
  ROOT_SENSITIVE_PATHS = _loadSensitivePathScope("root");
2171
2171
  HOME_SENSITIVE_PATHS = _loadSensitivePathScope("home");
2172
- CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
2172
+ CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path9, riskLevel, desc, dirDelOnly }) => ({ path: path9, riskLevel, desc, credential: true, dirDelOnly }));
2173
2173
  ROOT_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("root", "windows");
2174
2174
  HOME_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("home", "windows");
2175
- CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
2175
+ CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path9, riskLevel, desc, dirDelOnly }) => ({ path: path9, riskLevel, desc, credential: true, dirDelOnly }));
2176
2176
  ROOT_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("root", "macos");
2177
2177
  HOME_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("home", "macos");
2178
- CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
2178
+ CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path9, riskLevel, desc, dirDelOnly }) => ({ path: path9, riskLevel, desc, credential: true, dirDelOnly }));
2179
2179
  ROOT_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("root", "harmony");
2180
2180
  HOME_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("home", "harmony");
2181
- CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path8, riskLevel, desc, dirDelOnly }) => ({ path: path8, riskLevel, desc, credential: true, dirDelOnly }));
2181
+ CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path9, riskLevel, desc, dirDelOnly }) => ({ path: path9, riskLevel, desc, credential: true, dirDelOnly }));
2182
2182
  _scopeIndex = null;
2183
2183
  NON_WRITE_TOOLS = /* @__PURE__ */ new Set([
2184
2184
  "ask_user_question",
@@ -4546,24 +4546,24 @@ function extractWritePayload(actionType, actionDetailRaw) {
4546
4546
  const detail = actionDetailRaw || "";
4547
4547
  const m = detail.match(WRITE_PREFIX_RE);
4548
4548
  if (m) {
4549
- const path8 = m[1];
4549
+ const path9 = m[1];
4550
4550
  let content = m[2] || "";
4551
- if (!path8 || path8 === "?" || path8 === "-" || !content.trim()) return null;
4551
+ if (!path9 || path9 === "?" || path9 === "-" || !content.trim()) return null;
4552
4552
  if ((actionType || "").toLowerCase().includes("editfile")) {
4553
4553
  const nm = content.match(EDIT_NEW_RE);
4554
4554
  if (nm) content = nm[1];
4555
4555
  }
4556
- return { path: path8, content };
4556
+ return { path: path9, content };
4557
4557
  }
4558
4558
  const stripped = detail.trim();
4559
4559
  if (stripped.startsWith("{")) {
4560
4560
  try {
4561
4561
  const obj = JSON.parse(stripped);
4562
4562
  if (obj && typeof obj === "object") {
4563
- const path8 = obj.path || obj.file_path || obj.filePath;
4563
+ const path9 = obj.path || obj.file_path || obj.filePath;
4564
4564
  const content = obj.content || obj.newString || obj.new_string;
4565
- if (typeof path8 === "string" && path8 !== "" && path8 !== "?" && path8 !== "-" && typeof content === "string" && content.trim()) {
4566
- return { path: path8, content };
4565
+ if (typeof path9 === "string" && path9 !== "" && path9 !== "?" && path9 !== "-" && typeof content === "string" && content.trim()) {
4566
+ return { path: path9, content };
4567
4567
  }
4568
4568
  }
4569
4569
  } catch {
@@ -4576,8 +4576,8 @@ function handlesWrittenContent(actionType, actionDetailRaw) {
4576
4576
  if (extractWritePayload(actionType, actionDetailRaw) !== null) return true;
4577
4577
  return /^(?:写入文件|编辑文件|应用补丁)\s*[::]/.test(actionDetailRaw || "");
4578
4578
  }
4579
- function detectLanguage(path8, content) {
4580
- const ext = path8.slice(path8.lastIndexOf(".") >= 0 ? path8.lastIndexOf(".") : path8.length).toLowerCase();
4579
+ function detectLanguage(path9, content) {
4580
+ const ext = path9.slice(path9.lastIndexOf(".") >= 0 ? path9.lastIndexOf(".") : path9.length).toLowerCase();
4581
4581
  if (SHELL_EXTS.has(ext)) return "shell";
4582
4582
  if (PY_EXTS.has(ext)) return "python";
4583
4583
  if (DATA_EXTS.has(ext)) return "data";
@@ -4591,8 +4591,8 @@ function detectLanguage(path8, content) {
4591
4591
  }
4592
4592
  return "other";
4593
4593
  }
4594
- function isInstructionTarget(path8) {
4595
- const p = (path8 || "").replace(/\\/g, "/").toLowerCase();
4594
+ function isInstructionTarget(path9) {
4595
+ const p = (path9 || "").replace(/\\/g, "/").toLowerCase();
4596
4596
  if (!p) return false;
4597
4597
  const base = p.split("/").pop() || "";
4598
4598
  if (["agents.md", "claude.md", "system.md", "prompt.md", "instructions.md", ".cursorrules"].includes(base)) {
@@ -4750,8 +4750,8 @@ function extractDangerousSnippets(actionType, actionDetailRaw, literalStripper)
4750
4750
  if (!handlesWrittenContent(actionType, actionDetailRaw)) return null;
4751
4751
  const payload = extractWritePayload(actionType, actionDetailRaw);
4752
4752
  if (!payload) return [];
4753
- const { path: path8, content: rawContent } = payload;
4754
- const language = detectLanguage(path8, rawContent);
4753
+ const { path: path9, content: rawContent } = payload;
4754
+ const language = detectLanguage(path9, rawContent);
4755
4755
  if (language === "data") return [];
4756
4756
  let content = rawContent.replace(/\\r\\n/g, "\n").replace(/\\n/g, "\n").replace(/\\t/g, " ").slice(0, MAX_CONTENT);
4757
4757
  const started = Date.now();
@@ -5452,16 +5452,16 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5452
5452
  if (String(osType || "").toLowerCase() === "windows") {
5453
5453
  pathScanTexts.push(...pathScanTexts.map((t) => t.replace(/\//g, "\\")));
5454
5454
  }
5455
- const pathMatches = (text, path8) => {
5456
- const parts = path8.split(/(\(\?!.*?\))/);
5455
+ const pathMatches = (text, path9) => {
5456
+ const parts = path9.split(/(\(\?!.*?\))/);
5457
5457
  const escaped = parts.map((part) => {
5458
5458
  if (part.startsWith("(?!")) return part;
5459
5459
  return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5460
5460
  }).join("");
5461
- const re = path8.startsWith(".") || path8.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
5461
+ const re = path9.startsWith(".") || path9.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
5462
5462
  return re.test(text);
5463
5463
  };
5464
- const pathMatchesAny = (path8) => pathScanTexts.some((t) => pathMatches(t, path8));
5464
+ const pathMatchesAny = (path9) => pathScanTexts.some((t) => pathMatches(t, path9));
5465
5465
  for (const sp of rootPaths) {
5466
5466
  if (pathMatchesAny(sp.path.toLowerCase())) {
5467
5467
  if (keygenGenerate) continue;
@@ -5609,8 +5609,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
5609
5609
  }
5610
5610
  return null;
5611
5611
  }
5612
- function isHomeValue(path8) {
5613
- let p = path8.trim().toLowerCase();
5612
+ function isHomeValue(path9) {
5613
+ let p = path9.trim().toLowerCase();
5614
5614
  if (p.startsWith("$(") && p.endsWith(")")) {
5615
5615
  const inner = p.slice(2, -1).trim();
5616
5616
  return HOME_TARGET_RE.test(" " + inner);
@@ -5678,15 +5678,15 @@ function checkHomeDeletion(actionType, actionDetail) {
5678
5678
  nameRe.lastIndex = nm.index + nm[0].length;
5679
5679
  }
5680
5680
  }
5681
- for (const [varName, path8] of Object.entries(assigned)) {
5682
- if (!isHomeValue(path8)) continue;
5681
+ for (const [varName, path9] of Object.entries(assigned)) {
5682
+ if (!isHomeValue(path9)) continue;
5683
5683
  const varRefRe = new RegExp(`(?:${escapeRegExp(varName)}|\\$\\{${escapeRegExp(varName)}\\})`);
5684
5684
  for (const seg of segs) {
5685
5685
  if (!isDeleteCommand(seg)) continue;
5686
5686
  if (varRefRe.test(seg)) {
5687
5687
  return {
5688
5688
  allowed: false,
5689
- reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path8}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
5689
+ reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path9}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
5690
5690
  riskLevel: "high",
5691
5691
  riskType: "script_execution",
5692
5692
  confidence: 90,
@@ -6197,7 +6197,7 @@ init_inline_analyzer();
6197
6197
 
6198
6198
  // src/engine/llm-analyzer.ts
6199
6199
  init_esm_shims();
6200
- import { createHash } from "crypto";
6200
+ import { createHash as createHash2 } from "crypto";
6201
6201
 
6202
6202
  // src/infra/security-policy.ts
6203
6203
  init_esm_shims();
@@ -6466,18 +6466,68 @@ init_config();
6466
6466
  init_logic_rules();
6467
6467
  init_inline_analyzer();
6468
6468
  import { statSync as statSync6, existsSync as existsSync12 } from "fs";
6469
- import { resolve as resolve11, join as join12, isAbsolute as isAbsolute4 } from "path";
6469
+ import { resolve as resolve11, join as join12, isAbsolute as isAbsolute5 } from "path";
6470
6470
  import { homedir as homedir5 } from "os";
6471
6471
 
6472
6472
  // src/engine/script-engine/tracker.ts
6473
6473
  init_esm_shims();
6474
6474
  import * as fs3 from "fs";
6475
- import * as path4 from "path";
6475
+ import * as path5 from "path";
6476
6476
  import * as os2 from "os";
6477
6477
 
6478
+ // src/engine/script-engine/ir.ts
6479
+ init_esm_shims();
6480
+ import { createHash } from "crypto";
6481
+ var WORKING_DIRECTORY_UNKNOWN = /* @__PURE__ */ Symbol.for(
6482
+ "agent-moss.script-engine.working-directory-unknown"
6483
+ );
6484
+ function encodeUtf8SurrogatePass(content) {
6485
+ const bytes = [];
6486
+ for (let i = 0; i < content.length; i++) {
6487
+ let codePoint = content.charCodeAt(i);
6488
+ if (codePoint >= 55296 && codePoint <= 56319 && i + 1 < content.length) {
6489
+ const low = content.charCodeAt(i + 1);
6490
+ if (low >= 56320 && low <= 57343) {
6491
+ codePoint = 65536 + (codePoint - 55296 << 10) + (low - 56320);
6492
+ i += 1;
6493
+ }
6494
+ }
6495
+ if (codePoint < 128) {
6496
+ bytes.push(codePoint);
6497
+ } else if (codePoint < 2048) {
6498
+ bytes.push(192 | codePoint >> 6, 128 | codePoint & 63);
6499
+ } else if (codePoint < 65536) {
6500
+ bytes.push(
6501
+ 224 | codePoint >> 12,
6502
+ 128 | codePoint >> 6 & 63,
6503
+ 128 | codePoint & 63
6504
+ );
6505
+ } else {
6506
+ bytes.push(
6507
+ 240 | codePoint >> 18,
6508
+ 128 | codePoint >> 12 & 63,
6509
+ 128 | codePoint >> 6 & 63,
6510
+ 128 | codePoint & 63
6511
+ );
6512
+ }
6513
+ }
6514
+ return Buffer.from(bytes);
6515
+ }
6516
+ function scanFingerprint(content) {
6517
+ const digest = createHash("sha256");
6518
+ let length = 0;
6519
+ for (let start = 0; start < content.length; start += 4096) {
6520
+ const chunk = encodeUtf8SurrogatePass(content.slice(start, start + 4096));
6521
+ length += chunk.length;
6522
+ digest.update(chunk);
6523
+ }
6524
+ return { bytes: length, sha256: digest.digest("hex") };
6525
+ }
6526
+
6478
6527
  // src/engine/script-engine/backends/python-backend.ts
6479
6528
  init_esm_shims();
6480
6529
  import { parser } from "@lezer/python";
6530
+ import * as path4 from "path";
6481
6531
  var MAX_LINES = 500;
6482
6532
  var PURE_BUILTINS = /* @__PURE__ */ new Set([
6483
6533
  "len",
@@ -6561,14 +6611,117 @@ var SOURCE = "";
6561
6611
  function srcSlice(node) {
6562
6612
  return SOURCE.slice(node.from, node.to);
6563
6613
  }
6564
- function stringValue(tokenText) {
6565
- let s = tokenText;
6566
- if (s.length >= 2) {
6567
- const q = s[0];
6568
- if ((q === '"' || q === "'") && s.endsWith(q)) s = s.slice(1, -1);
6614
+ function decodePythonStringLiteral(raw) {
6615
+ const m = /^([rubfRUBF]*)(\"\"\"|'''|"|')/.exec(raw);
6616
+ if (m === null) return null;
6617
+ const prefix = m[1].toLowerCase();
6618
+ const quote = m[2];
6619
+ if (prefix.includes("b") && (prefix.includes("f") || prefix.includes("u"))) return null;
6620
+ if (prefix.includes("f")) return null;
6621
+ if (!raw.endsWith(quote) || raw.length < m[0].length + quote.length) return null;
6622
+ const inner = raw.slice(m[0].length, raw.length - quote.length);
6623
+ const isBytes = prefix.includes("b");
6624
+ if (prefix.includes("r")) {
6625
+ return { value: inner.replace(/\r\n/g, "\n"), bytes: isBytes };
6626
+ }
6627
+ const decoded = unescapePythonString(inner, isBytes);
6628
+ if (decoded === null) return null;
6629
+ return { value: decoded, bytes: isBytes };
6630
+ }
6631
+ function unescapePythonString(text, isBytes) {
6632
+ let out = "";
6633
+ for (let i = 0; i < text.length; i++) {
6634
+ const ch = text[i];
6635
+ if (ch !== "\\") {
6636
+ out += ch;
6637
+ continue;
6638
+ }
6639
+ const next = text[i + 1];
6640
+ if (next === void 0) return null;
6641
+ i += 1;
6642
+ switch (next) {
6643
+ case "\n":
6644
+ break;
6645
+ // line continuation
6646
+ case "\\":
6647
+ out += "\\";
6648
+ break;
6649
+ case "'":
6650
+ out += "'";
6651
+ break;
6652
+ case '"':
6653
+ out += '"';
6654
+ break;
6655
+ case "a":
6656
+ out += "\x07";
6657
+ break;
6658
+ case "b":
6659
+ out += "\b";
6660
+ break;
6661
+ case "f":
6662
+ out += "\f";
6663
+ break;
6664
+ case "n":
6665
+ out += "\n";
6666
+ break;
6667
+ case "r":
6668
+ out += "\r";
6669
+ break;
6670
+ case "t":
6671
+ out += " ";
6672
+ break;
6673
+ case "v":
6674
+ out += "\v";
6675
+ break;
6676
+ case "x": {
6677
+ const hex = text.slice(i + 1, i + 3);
6678
+ if (!/^[0-9a-fA-F]{2}$/.test(hex)) return null;
6679
+ out += String.fromCharCode(parseInt(hex, 16));
6680
+ i += 2;
6681
+ break;
6682
+ }
6683
+ case "u": {
6684
+ if (isBytes) return null;
6685
+ const hex = text.slice(i + 1, i + 5);
6686
+ if (!/^[0-9a-fA-F]{4}$/.test(hex)) return null;
6687
+ out += String.fromCharCode(parseInt(hex, 16));
6688
+ i += 4;
6689
+ break;
6690
+ }
6691
+ case "U": {
6692
+ if (isBytes) return null;
6693
+ const hex = text.slice(i + 1, i + 9);
6694
+ if (!/^[0-9a-fA-F]{8}$/.test(hex)) return null;
6695
+ const cp = parseInt(hex, 16);
6696
+ if (cp > 1114111) return null;
6697
+ out += String.fromCodePoint(cp);
6698
+ i += 8;
6699
+ break;
6700
+ }
6701
+ case "0":
6702
+ case "1":
6703
+ case "2":
6704
+ case "3":
6705
+ case "4":
6706
+ case "5":
6707
+ case "6":
6708
+ case "7": {
6709
+ let oct = next;
6710
+ for (let k = 0; k < 2 && /[0-7]/.test(text[i + 1] ?? ""); k++) {
6711
+ oct += text[i + 1];
6712
+ i += 1;
6713
+ }
6714
+ out += String.fromCharCode(parseInt(oct, 8));
6715
+ break;
6716
+ }
6717
+ case "N":
6718
+ return null;
6719
+ default:
6720
+ out += "\\" + next;
6721
+ break;
6722
+ }
6569
6723
  }
6570
- s = s.replace(/\\n/g, "\n").replace(/\\t/g, " ").replace(/\\r/g, "\r").replace(/\\\\/g, "\\").replace(/\\"/g, '"').replace(/\\'/g, "'");
6571
- return s;
6724
+ return out;
6572
6725
  }
6573
6726
  function isSysArgv(node) {
6574
6727
  if (!node || node.name !== "MemberExpression") return false;
@@ -6580,7 +6733,14 @@ function isSysArgv(node) {
6580
6733
  function evalExpr(node, env2) {
6581
6734
  if (!node) return null;
6582
6735
  const name = node.name;
6583
- if (name === "String") return stringValue(srcSlice(node));
6736
+ if (name === "String") {
6737
+ const decoded = decodePythonStringLiteral(srcSlice(node));
6738
+ return decoded !== null && !decoded.bytes ? decoded.value : null;
6739
+ }
6740
+ if (name === "ContinuedString") {
6741
+ const decoded = literalStringText(node);
6742
+ return decoded;
6743
+ }
6584
6744
  if (name === "Number") return srcSlice(node);
6585
6745
  if (name === "VariableName") {
6586
6746
  const id = srcSlice(node);
@@ -6612,6 +6772,9 @@ function evalExpr(node, env2) {
6612
6772
  }
6613
6773
  return null;
6614
6774
  }
6775
+ if (name === "ParenthesizedExpression") {
6776
+ return evalExpr(firstNamedChild(node), env2);
6777
+ }
6615
6778
  if (name === "ConditionalExpression") {
6616
6779
  const ifKw = node.getChild("if");
6617
6780
  const elseKw = node.getChild("else");
@@ -6655,7 +6818,7 @@ function lastNamedChild(node) {
6655
6818
  function findOp(node) {
6656
6819
  let c = node.firstChild;
6657
6820
  while (c) {
6658
- if (c.name === "CompareOp" || c.name === "and" || c.name === "or" || c.name === "UpdateOp") {
6821
+ if (c.name === "CompareOp" || c.name === "and" || c.name === "or" || c.name === "UpdateOp" || c.name === "ArithOp") {
6659
6822
  return srcSlice(c).trim();
6660
6823
  }
6661
6824
  c = c.nextSibling;
@@ -6665,6 +6828,9 @@ function findOp(node) {
6665
6828
  function evalCondition(node, env2) {
6666
6829
  if (!node) return null;
6667
6830
  const name = node.name;
6831
+ if (name === "ParenthesizedExpression") {
6832
+ return evalCondition(firstNamedChild(node), env2);
6833
+ }
6668
6834
  if (name === "Boolean") {
6669
6835
  const t = srcSlice(node).trim();
6670
6836
  return t === "True" ? true : t === "False" ? false : null;
@@ -6672,7 +6838,7 @@ function evalCondition(node, env2) {
6672
6838
  if (name === "BinaryExpression") {
6673
6839
  const op = findOp(node);
6674
6840
  if (op === "and" || op === "or") {
6675
- const parts2 = namedChildren(node);
6841
+ const parts2 = namedChildren(node).filter((p) => p.name !== "and" && p.name !== "or");
6676
6842
  const vals = parts2.map((p) => evalCondition(p, env2));
6677
6843
  if (op === "and") {
6678
6844
  if (vals.some((v) => v === false)) return false;
@@ -6758,8 +6924,8 @@ function evalCompare(left, opText, right, env2) {
6758
6924
  }
6759
6925
  return null;
6760
6926
  }
6761
- function processStmts(stmts, env2, lineStarts, lines, branches) {
6762
- for (const s of stmts) processStmt(s, env2, lineStarts, lines, branches);
6927
+ function processStmts(stmts, env2, lineStarts, lines, branches, ifDecisions) {
6928
+ for (const s of stmts) processStmt(s, env2, lineStarts, lines, branches, ifDecisions);
6763
6929
  }
6764
6930
  function invalidateEnvOnCalls(node, env2) {
6765
6931
  const cursor = node.cursor();
@@ -6774,15 +6940,31 @@ function invalidateEnvOnCalls(node, env2) {
6774
6940
  return true;
6775
6941
  });
6776
6942
  }
6777
- function processStmt(stmt, env2, lineStarts, lines, branches) {
6943
+ function assignmentParts(stmt) {
6944
+ const targets = [];
6945
+ let lastAssign = null;
6946
+ let c = stmt.firstChild;
6947
+ while (c) {
6948
+ if (c.name === "AssignOp") lastAssign = c;
6949
+ c = c.nextSibling;
6950
+ }
6951
+ if (lastAssign === null) return { targets, value: null };
6952
+ const value = lastAssign.nextSibling;
6953
+ c = stmt.firstChild;
6954
+ while (c && !sameNode(c, lastAssign)) {
6955
+ if (c.name === "VariableName") targets.push(c);
6956
+ c = c.nextSibling;
6957
+ }
6958
+ return { targets, value };
6959
+ }
6960
+ function processStmt(stmt, env2, lineStarts, lines, branches, ifDecisions) {
6778
6961
  const name = stmt.name;
6962
+ if (name === "Comment") return;
6779
6963
  if (name === "AssignStatement") {
6780
- const target = stmt.firstChild;
6781
- if (target && target.name === "VariableName") {
6782
- const valNode = target.nextSibling ? target.nextSibling.nextSibling : null;
6964
+ const { targets, value } = assignmentParts(stmt);
6965
+ if (targets.length === 1) {
6783
6966
  invalidateEnvOnCalls(stmt, env2);
6784
- const val = evalExpr(valNode, env2);
6785
- env2.vars[srcSlice(target)] = val;
6967
+ env2.vars[srcSlice(targets[0])] = evalExpr(value, env2);
6786
6968
  }
6787
6969
  markNodeLines(stmt, lines, lineStarts);
6788
6970
  return;
@@ -6795,34 +6977,34 @@ function processStmt(stmt, env2, lineStarts, lines, branches) {
6795
6977
  return;
6796
6978
  }
6797
6979
  if (name === "IfStatement") {
6798
- processIf(stmt, env2, lineStarts, lines, branches);
6980
+ processIf(stmt, env2, lineStarts, lines, branches, ifDecisions);
6799
6981
  return;
6800
6982
  }
6801
6983
  if (name === "ForStatement" || name === "WhileStatement") {
6802
6984
  markNodeLines(stmt, lines, lineStarts);
6803
6985
  for (const body of stmt.getChildren("Body")) {
6804
- processStmts(bodyStmts(body), { argv: env2.argv, vars: { ...env2.vars } }, lineStarts, lines, branches);
6986
+ processStmts(bodyStmts(body), { argv: env2.argv, vars: { ...env2.vars } }, lineStarts, lines, branches, ifDecisions);
6805
6987
  }
6806
6988
  return;
6807
6989
  }
6808
6990
  if (name === "TryStatement") {
6809
6991
  markNodeLines(stmt, lines, lineStarts);
6810
6992
  for (const body of stmt.getChildren("Body")) {
6811
- processStmts(bodyStmts(body), { argv: env2.argv, vars: { ...env2.vars } }, lineStarts, lines, branches);
6993
+ processStmts(bodyStmts(body), { argv: env2.argv, vars: { ...env2.vars } }, lineStarts, lines, branches, ifDecisions);
6812
6994
  }
6813
6995
  return;
6814
6996
  }
6815
6997
  if (name === "WithStatement") {
6816
6998
  markNodeLines(stmt, lines, lineStarts);
6817
6999
  const body = stmt.getChild("Body");
6818
- if (body) processStmts(bodyStmts(body), { argv: env2.argv, vars: { ...env2.vars } }, lineStarts, lines, branches);
7000
+ if (body) processStmts(bodyStmts(body), { argv: env2.argv, vars: { ...env2.vars } }, lineStarts, lines, branches, ifDecisions);
6819
7001
  return;
6820
7002
  }
6821
7003
  if (name === "MatchStatement") {
6822
7004
  markNodeLines(stmt, lines, lineStarts);
6823
7005
  for (const clause of stmt.getChildren("MatchClause")) {
6824
7006
  const body = clause.getChild("Body");
6825
- if (body) processStmts(bodyStmts(body), { argv: env2.argv, vars: { ...env2.vars } }, lineStarts, lines, branches);
7007
+ if (body) processStmts(bodyStmts(body), { argv: env2.argv, vars: { ...env2.vars } }, lineStarts, lines, branches, ifDecisions);
6826
7008
  }
6827
7009
  return;
6828
7010
  }
@@ -6844,14 +7026,26 @@ function markDefTree(stmt, lines, lineStarts) {
6844
7026
  }
6845
7027
  function bodyStmts(body) {
6846
7028
  const out = [];
7029
+ const append = (node) => {
7030
+ if (node.name === "StatementGroup") {
7031
+ let c2 = node.firstChild;
7032
+ while (c2) {
7033
+ append(c2);
7034
+ c2 = c2.nextSibling;
7035
+ }
7036
+ return;
7037
+ }
7038
+ if (node.name === ":" || node.name === ";" || node.name === "\n") return;
7039
+ out.push(node);
7040
+ };
6847
7041
  let c = body.firstChild;
6848
7042
  while (c) {
6849
- if (c.name !== ":" && c.name !== ";") out.push(c);
7043
+ append(c);
6850
7044
  c = c.nextSibling;
6851
7045
  }
6852
7046
  return out;
6853
7047
  }
6854
- function processIf(stmt, env2, lineStarts, lines, branches) {
7048
+ function collectIfSections(stmt) {
6855
7049
  const sections = [];
6856
7050
  let c = stmt.firstChild;
6857
7051
  while (c) {
@@ -6866,17 +7060,24 @@ function processIf(stmt, env2, lineStarts, lines, branches) {
6866
7060
  }
6867
7061
  c = c.nextSibling;
6868
7062
  }
6869
- processIfSections(stmt, sections, 0, env2, lineStarts, lines, branches);
7063
+ return sections;
6870
7064
  }
6871
- function processIfSections(_stmt, sections, idx, env2, lineStarts, lines, branches) {
7065
+ function processIf(stmt, env2, lineStarts, lines, branches, ifDecisions) {
7066
+ const sections = collectIfSections(stmt);
7067
+ const decisions = [];
7068
+ ifDecisions.set(stmt.from, decisions);
7069
+ processIfSections(sections, decisions, 0, env2, lineStarts, lines, branches, ifDecisions);
7070
+ }
7071
+ function processIfSections(sections, decisions, idx, env2, lineStarts, lines, branches, ifDecisions) {
6872
7072
  if (idx >= sections.length) return;
6873
7073
  const s = sections[idx];
6874
7074
  if (s.cond) markNodeLines(s.cond, lines, lineStarts);
6875
7075
  if (s.isElse) {
6876
- if (s.body) processStmts(bodyStmts(s.body), env2, lineStarts, lines, branches);
7076
+ if (s.body) processStmts(bodyStmts(s.body), env2, lineStarts, lines, branches, ifDecisions);
6877
7077
  return;
6878
7078
  }
6879
7079
  const cond = s.cond ? evalCondition(s.cond, env2) : null;
7080
+ decisions[idx] = cond;
6880
7081
  branches.push({
6881
7082
  kind: "if",
6882
7083
  label: s.cond ? srcSlice(s.cond) : "",
@@ -6884,136 +7085,1181 @@ function processIfSections(_stmt, sections, idx, env2, lineStarts, lines, branch
6884
7085
  reachable: cond !== false
6885
7086
  });
6886
7087
  if (cond === true) {
6887
- if (s.body) processStmts(bodyStmts(s.body), env2, lineStarts, lines, branches);
7088
+ if (s.body) processStmts(bodyStmts(s.body), env2, lineStarts, lines, branches, ifDecisions);
6888
7089
  return;
6889
7090
  }
6890
7091
  if (cond === false) {
6891
- processIfSections(_stmt, sections, idx + 1, env2, lineStarts, lines, branches);
7092
+ processIfSections(sections, decisions, idx + 1, env2, lineStarts, lines, branches, ifDecisions);
6892
7093
  return;
6893
7094
  }
6894
- if (s.body) processStmts(bodyStmts(s.body), env2, lineStarts, lines, branches);
7095
+ if (s.body) processStmts(bodyStmts(s.body), env2, lineStarts, lines, branches, ifDecisions);
6895
7096
  for (let j = idx + 1; j < sections.length; j++) {
6896
7097
  const sj = sections[j];
6897
7098
  if (sj.cond) markNodeLines(sj.cond, lines, lineStarts);
6898
- if (sj.body) processStmts(bodyStmts(sj.body), env2, lineStarts, lines, branches);
7099
+ if (sj.body) processStmts(bodyStmts(sj.body), env2, lineStarts, lines, branches, ifDecisions);
6899
7100
  }
6900
7101
  }
6901
- function parseShellString(s) {
6902
- CHILD_CALL_RE.lastIndex = 0;
6903
- let m;
6904
- while ((m = CHILD_CALL_RE.exec(s)) !== null) {
6905
- const interp = m[1];
6906
- const path8 = m[2].trim();
6907
- let rest = m[3].trim();
6908
- if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
6909
- rest = rest.split(/[;|&<>]/)[0].trim();
6910
- const args = [];
6911
- for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
6912
- args.push(tm[1] ? tm[2] : tm[3]);
7102
+ var CWD_METHODS = /* @__PURE__ */ new Set(["chdir", "fchdir"]);
7103
+ var CALL_FUNCTIONS = {
7104
+ os: /* @__PURE__ */ new Set([...OS_FUNCS, ...CWD_METHODS]),
7105
+ subprocess: SUBPROCESS_FUNCS
7106
+ };
7107
+ var SHELL_INTERPRETERS = /* @__PURE__ */ new Set(["bash", "dash", "sh", "zsh"]);
7108
+ var SCRIPT_INTERPRETERS = /* @__PURE__ */ new Set([
7109
+ ...SHELL_INTERPRETERS,
7110
+ "python",
7111
+ "python3",
7112
+ "node",
7113
+ "ruby",
7114
+ "perl",
7115
+ "php",
7116
+ "lua"
7117
+ ]);
7118
+ var VERSIONED_PYTHON = /^python3\.[0-9]+t?$/;
7119
+ var ENV_PROGRAMS = /* @__PURE__ */ new Set(["env", "/bin/env", "/usr/bin/env"]);
7120
+ var SHELL_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
7121
+ var IO_NUMBER = /^[0-9]+$/;
7122
+ var LITERAL_PART_RE = /[^\s'"\\$`*?\[\]{}();|&<>]+|'[^']*'|"(?:[^"\\$`]|\\.)*"|\\[^\n]/y;
7123
+ var SHELL_DOUBLE_ESCAPE_RE = /\\(["\\$`])/g;
7124
+ var FILE_REDIRECT_RE = />>|>\||>&|<>|<&|[<>]/y;
7125
+ function basenameOf(p) {
7126
+ const index = p.lastIndexOf("/");
7127
+ return index < 0 ? p : p.slice(index + 1);
7128
+ }
7129
+ function callKey(call) {
7130
+ const cwd = call.launchCwd === WORKING_DIRECTORY_UNKNOWN ? "\0UNKNOWN" : call.launchCwd === void 0 || call.launchCwd === null ? "\0NONE" : call.launchCwd;
7131
+ return `${call.path}\0${call.args.join("\0")}\0${call.interpreter}\0${cwd}`;
7132
+ }
7133
+ function sameNode(a, b) {
7134
+ return a !== null && b !== null && a.from === b.from && a.to === b.to && a.name === b.name;
7135
+ }
7136
+ function firstInnerNode(node) {
7137
+ let c = node.firstChild;
7138
+ while (c) {
7139
+ if (!["(", ")", ",", ":", "[", "]", "{", "}"].includes(c.name)) return c;
7140
+ c = c.nextSibling;
7141
+ }
7142
+ return null;
7143
+ }
7144
+ function unwrapParens(node) {
7145
+ let current = node;
7146
+ while (current && current.name === "ParenthesizedExpression") {
7147
+ current = firstInnerNode(current);
7148
+ }
7149
+ return current;
7150
+ }
7151
+ function literalStringText(node) {
7152
+ if (!node) return null;
7153
+ if (node.name === "String") {
7154
+ const decoded = decodePythonStringLiteral(srcSlice(node));
7155
+ return decoded !== null && !decoded.bytes ? decoded.value : null;
7156
+ }
7157
+ if (node.name === "ContinuedString") {
7158
+ let out = "";
7159
+ let c = node.firstChild;
7160
+ while (c) {
7161
+ if (c.name === "String") {
7162
+ const decoded = decodePythonStringLiteral(srcSlice(c));
7163
+ if (decoded === null || decoded.bytes) return null;
7164
+ out += decoded.value;
7165
+ }
7166
+ c = c.nextSibling;
6913
7167
  }
6914
- return { path: path8, args, interpreter: interp };
7168
+ return out;
7169
+ }
7170
+ if (node.name === "ParenthesizedExpression") {
7171
+ return literalStringText(firstInnerNode(node));
7172
+ }
7173
+ if (node.name === "FormatString") {
7174
+ let hasReplacement = false;
7175
+ const cursor = node.cursor();
7176
+ cursor.iterate((n) => {
7177
+ if (n.node.name === "FormatReplacement") {
7178
+ hasReplacement = true;
7179
+ return false;
7180
+ }
7181
+ return true;
7182
+ });
7183
+ if (hasReplacement) return null;
7184
+ const raw = srcSlice(node);
7185
+ const m = /^([rRfF]*)(\"\"\"|'''|"|')/.exec(raw);
7186
+ if (m === null || !raw.endsWith(m[2]) || raw.length < m[0].length + m[2].length) return null;
7187
+ let inner = raw.slice(m[0].length, raw.length - m[2].length);
7188
+ inner = inner.replace(/\{\{/g, "{").replace(/\}\}/g, "}");
7189
+ return m[1].toLowerCase().includes("r") ? inner : unescapePythonString(inner, false);
6915
7190
  }
6916
7191
  return null;
6917
7192
  }
6918
- function extractCallsFromTree(tree, reachableLines) {
7193
+ function literalText(node, bindings) {
7194
+ if (!node) return null;
7195
+ if (node.name === "VariableName") return bindings.strings.get(srcSlice(node)) ?? null;
7196
+ if (node.name === "ParenthesizedExpression") return literalText(firstInnerNode(node), bindings);
7197
+ return literalStringText(node);
7198
+ }
7199
+ function* literalShellCommands(command) {
7200
+ let words = [];
7201
+ let assigned = false;
7202
+ let redirected = false;
7203
+ let redirectTarget = false;
7204
+ let index = 0;
7205
+ let statementStart = 0;
7206
+ while (index <= command.length) {
7207
+ const char = index < command.length ? command[index] : "\n";
7208
+ if (char === " " || char === " ") {
7209
+ index += 1;
7210
+ continue;
7211
+ }
7212
+ if (char === "#") {
7213
+ const newline = command.indexOf("\n", index);
7214
+ index = newline < 0 ? command.length : newline;
7215
+ continue;
7216
+ }
7217
+ if (char === "\n" || char === ";" || command.startsWith("&&", index) || command.startsWith("||", index)) {
7218
+ if (redirectTarget) return;
7219
+ const separator = char === "&" || char === "|" ? command.slice(index, index + 2) : char;
7220
+ if (words.length || redirected || assigned) {
7221
+ yield { words, separator, start: statementStart, redirected };
7222
+ }
7223
+ words = [];
7224
+ assigned = false;
7225
+ redirected = false;
7226
+ index += separator.length;
7227
+ statementStart = index;
7228
+ continue;
7229
+ }
7230
+ if ((char === "<" || char === ">") && !command.startsWith("<<", index)) {
7231
+ if (redirectTarget) return;
7232
+ FILE_REDIRECT_RE.lastIndex = index;
7233
+ const redirect = FILE_REDIRECT_RE.exec(command);
7234
+ if (!redirect || redirect.index !== index) return;
7235
+ index += redirect[0].length;
7236
+ redirected = true;
7237
+ redirectTarget = true;
7238
+ continue;
7239
+ }
7240
+ const start = index;
7241
+ const parts = [];
7242
+ if (char !== "~") {
7243
+ while (true) {
7244
+ LITERAL_PART_RE.lastIndex = index;
7245
+ const match = LITERAL_PART_RE.exec(command);
7246
+ if (!match || match.index !== index) break;
7247
+ const raw = match[0];
7248
+ if (raw.startsWith('"')) parts.push(raw.slice(1, -1).replace(SHELL_DOUBLE_ESCAPE_RE, "$1"));
7249
+ else if (raw.startsWith("'")) parts.push(raw.slice(1, -1));
7250
+ else if (raw.startsWith("\\")) parts.push(raw.slice(1));
7251
+ else parts.push(raw);
7252
+ index += raw.length;
7253
+ }
7254
+ }
7255
+ if (parts.length === 0 || index < command.length && !" \n;<>|&".includes(command[index])) {
7256
+ yield { words: null, separator: "", start: statementStart, redirected };
7257
+ return;
7258
+ }
7259
+ if (redirectTarget) {
7260
+ redirectTarget = false;
7261
+ } else if (words.length === 0 && SHELL_ASSIGNMENT.test(command.slice(start, index))) {
7262
+ assigned = true;
7263
+ } else if (!(index < command.length && "<>".includes(command[index]) && IO_NUMBER.test(command.slice(start, index)))) {
7264
+ words.push(parts.join(""));
7265
+ }
7266
+ }
7267
+ }
7268
+ function legacyLiteralCalls(command, source) {
7269
+ let calls = extractCallsRegex(command);
7270
+ if (calls.length && source !== null && command !== source) {
7271
+ const old = new Set(extractCallsRegex(source).map(callKey));
7272
+ calls = calls.filter((call) => old.has(callKey(call)));
7273
+ }
7274
+ return calls.filter((call) => !call.path.includes("\0"));
7275
+ }
7276
+ function shellProgramOperand(words) {
7277
+ if (!words.length) return null;
7278
+ const name = basenameOf(words[0]);
7279
+ if (!SHELL_INTERPRETERS.has(name)) return null;
7280
+ let kind = "script";
7281
+ for (let index = 1; index < words.length; index++) {
7282
+ const word = words[index];
7283
+ if (word === "--") {
7284
+ return index + 1 < words.length ? { kind, index: index + 1 } : null;
7285
+ }
7286
+ if (!word.startsWith("-") && !word.startsWith("+")) return { kind, index };
7287
+ if (word.length < 2 || [...word.slice(1)].some((flag) => !"acefuvx".includes(flag))) {
7288
+ return null;
7289
+ }
7290
+ if (word.slice(1).includes("c")) kind = "command";
7291
+ }
7292
+ return null;
7293
+ }
7294
+ function envCommand(words) {
7295
+ if (!words.length || !ENV_PROGRAMS.has(words[0])) return words;
7296
+ let index = words.length > 1 && words[1] === "--" ? 2 : 1;
7297
+ while (index < words.length && SHELL_ASSIGNMENT.test(words[index])) {
7298
+ if (words[index].includes("\0")) return [];
7299
+ index += 1;
7300
+ }
7301
+ return words.slice(index);
7302
+ }
7303
+ function literalScriptCall(words) {
7304
+ if (words.length < 2) return null;
7305
+ const interpreter = words[0];
7306
+ const name = basenameOf(interpreter);
7307
+ if (!SCRIPT_INTERPRETERS.has(name) && !VERSIONED_PYTHON.test(name)) return null;
7308
+ if (words.some((word) => word.includes("\0"))) return null;
7309
+ let index = 1;
7310
+ if (SHELL_INTERPRETERS.has(name)) {
7311
+ const operand = shellProgramOperand(words);
7312
+ if (operand === null || operand.kind !== "script") return null;
7313
+ index = operand.index;
7314
+ } else if (words[index].startsWith("-")) {
7315
+ return null;
7316
+ }
7317
+ const scriptPath = words[index];
7318
+ if (!scriptPath || scriptPath.startsWith("$") || scriptPath.startsWith("~") || scriptPath.includes("/dev/")) {
7319
+ return null;
7320
+ }
7321
+ return { path: scriptPath, args: words.slice(index + 1), interpreter };
7322
+ }
7323
+ function literalShellCalls(command, source) {
6919
7324
  const calls = [];
6920
- const seen = /* @__PURE__ */ new Set();
6921
- const add = (c) => {
6922
- const key = `${c.path}\0${c.args.join("\0")}\0${c.interpreter}`;
6923
- if (!seen.has(key)) {
6924
- seen.add(key);
6925
- calls.push(c);
7325
+ let eligible = null;
7326
+ const statuses = /* @__PURE__ */ new Set([true, false]);
7327
+ let required = null;
7328
+ for (const entry of literalShellCommands(command)) {
7329
+ if (entry.words === null) {
7330
+ calls.push(...legacyLiteralCalls(command.slice(entry.start), source));
7331
+ break;
6926
7332
  }
6927
- };
6928
- const lineReachable = (node) => {
6929
- if (reachableLines === null) return true;
6930
- return reachableLines.has(lineAt(buildLineStarts(SOURCE), node.from));
6931
- };
6932
- const cursor = tree.cursor();
7333
+ if (required === null || statuses.has(required)) {
7334
+ if (required === null) statuses.clear();
7335
+ else statuses.delete(required);
7336
+ const words = entry.words;
7337
+ const head = words.length ? words[0] : "";
7338
+ const replacesShell = head === "exec" && words.length > 1;
7339
+ const program = replacesShell ? words.slice(1) : words;
7340
+ const call = literalScriptCall(envCommand(program));
7341
+ if (call !== null) {
7342
+ if (eligible === null || eligible.has(callKey(call))) calls.push(call);
7343
+ } else if (head !== "" && !["echo", "printf", ":", "true", "false", "exit"].includes(head) && !ENV_PROGRAMS.has(head) && eligible === null) {
7344
+ eligible = new Set(legacyLiteralCalls(command, source).map(callKey));
7345
+ }
7346
+ const exits = head === "exit" && (words.length === 1 || words.length === 2 && /^[+-]?[0-9]+$/.test(words[1]));
7347
+ if (exits || call !== null && replacesShell) {
7348
+ if (entry.redirected) statuses.add(false);
7349
+ } else if (!entry.redirected && [":", "true", "false"].includes(head)) {
7350
+ statuses.add(head !== "false");
7351
+ } else {
7352
+ statuses.add(true);
7353
+ statuses.add(false);
7354
+ }
7355
+ if (statuses.size === 0) break;
7356
+ }
7357
+ required = entry.separator === "&&" ? true : entry.separator === "||" ? false : null;
7358
+ }
7359
+ return calls;
7360
+ }
7361
+ function mergeBindings(maps, same) {
7362
+ const out = /* @__PURE__ */ new Map();
7363
+ if (!maps.length) return out;
7364
+ for (const [key, value] of maps[0]) {
7365
+ if (maps.every((map) => map.has(key) && same(map.get(key), value))) {
7366
+ out.set(key, value);
7367
+ }
7368
+ }
7369
+ return out;
7370
+ }
7371
+ function sameTuple(a, b) {
7372
+ return a[0] === b[0] && a[1] === b[1];
7373
+ }
7374
+ function purePathNormalize(p) {
7375
+ const absolute = p.startsWith("/");
7376
+ const parts = p.split("/").filter((part) => part !== "" && part !== ".");
7377
+ if (absolute) return "/" + parts.join("/");
7378
+ return parts.length ? parts.join("/") : ".";
7379
+ }
7380
+ function directoryFor(bindings, directory) {
7381
+ if (directory && !directory.includes("\0")) {
7382
+ if (path4.isAbsolute(directory)) return purePathNormalize(directory);
7383
+ if (bindings.cwd !== WORKING_DIRECTORY_UNKNOWN) {
7384
+ return purePathNormalize(`${bindings.cwd === null ? "." : bindings.cwd}/${directory}`);
7385
+ }
7386
+ }
7387
+ return WORKING_DIRECTORY_UNKNOWN;
7388
+ }
7389
+ var CallBindings = class _CallBindings {
7390
+ cwd;
7391
+ modules = /* @__PURE__ */ new Map([["os", "os"], ["subprocess", "subprocess"]]);
7392
+ builtinPrint = true;
7393
+ functions = /* @__PURE__ */ new Map();
7394
+ wrappers = /* @__PURE__ */ new Map();
7395
+ strings = /* @__PURE__ */ new Map([["__name__", "__main__"]]);
7396
+ constructor(cwd = ".") {
7397
+ this.cwd = cwd;
7398
+ }
7399
+ fork() {
7400
+ const other = new _CallBindings(this.cwd);
7401
+ other.modules = new Map(this.modules);
7402
+ other.functions = new Map(this.functions);
7403
+ other.wrappers = new Map(this.wrappers);
7404
+ other.strings = new Map(this.strings);
7405
+ other.builtinPrint = this.builtinPrint;
7406
+ return other;
7407
+ }
7408
+ merge(paths) {
7409
+ this.modules = mergeBindings(paths.map((p) => p.modules), (a, b) => a === b);
7410
+ this.functions = mergeBindings(paths.map((p) => p.functions), sameTuple);
7411
+ this.strings = mergeBindings(paths.map((p) => p.strings), (a, b) => a === b);
7412
+ this.wrappers = mergeBindings(paths.map((p) => p.wrappers), (a, b) => a === b);
7413
+ const first = paths[0].cwd;
7414
+ this.cwd = paths.every((p) => p.cwd === first) ? first : WORKING_DIRECTORY_UNKNOWN;
7415
+ this.builtinPrint = paths.every((p) => p.builtinPrint);
7416
+ }
7417
+ invalidate() {
7418
+ this.builtinPrint = false;
7419
+ this.functions.clear();
7420
+ this.wrappers.clear();
7421
+ this.strings.clear();
7422
+ for (const [name, module] of [...this.modules]) {
7423
+ if (name !== module) this.modules.delete(name);
7424
+ }
7425
+ }
7426
+ forget(name) {
7427
+ if (name === "print") this.builtinPrint = false;
7428
+ this.functions.delete(name);
7429
+ this.strings.delete(name);
7430
+ this.modules.delete(name);
7431
+ this.wrappers.delete(name);
7432
+ }
7433
+ bindString(name, value) {
7434
+ this.forget(name);
7435
+ if (value !== null) this.strings.set(name, value);
7436
+ }
7437
+ changeDirectory(directory) {
7438
+ this.cwd = directoryFor(this, directory);
7439
+ }
7440
+ };
7441
+ function recordImportText(node, bindings) {
7442
+ const text = srcSlice(node).trim();
7443
+ const fromMatch = /^from\s+([\s\S]*?)\s+import\s+([\s\S]+)$/.exec(text);
7444
+ if (fromMatch !== null) {
7445
+ const head = fromMatch[1].trim();
7446
+ const levelMatch = /^(\.+)([\s\S]*)$/.exec(head);
7447
+ const level = levelMatch === null ? 0 : levelMatch[1].length;
7448
+ const module = (levelMatch === null ? head : levelMatch[2]).trim();
7449
+ for (const part of fromMatch[2].replace(/[()]/g, " ").split(",")) {
7450
+ const trimmed = part.trim();
7451
+ if (trimmed === "*") {
7452
+ bindings.invalidate();
7453
+ continue;
7454
+ }
7455
+ const nameMatch = /^([A-Za-z_][\w.]*)(?:\s+as\s+([A-Za-z_][\w.]*))?$/.exec(trimmed);
7456
+ if (nameMatch === null) continue;
7457
+ const name = nameMatch[1];
7458
+ const bound = nameMatch[2] || name.split(".")[0];
7459
+ bindings.forget(bound);
7460
+ if (level === 0 && module && CALL_FUNCTIONS[module]?.has(name)) {
7461
+ bindings.functions.set(bound, [module, name]);
7462
+ }
7463
+ }
7464
+ return;
7465
+ }
7466
+ const importMatch = /^import\s+([\s\S]+)$/.exec(text);
7467
+ if (importMatch === null) return;
7468
+ for (const part of importMatch[1].split(",")) {
7469
+ const nameMatch = /^([A-Za-z_][\w.]*)(?:\s+as\s+([A-Za-z_][\w.]*))?$/.exec(part.trim());
7470
+ if (nameMatch === null) continue;
7471
+ const full = nameMatch[1];
7472
+ const alias = nameMatch[2];
7473
+ const name = alias || full;
7474
+ const bound = alias || full.split(".")[0];
7475
+ bindings.forget(bound);
7476
+ const module = alias ? full : full.split(".")[0];
7477
+ if (CALL_FUNCTIONS[module]) bindings.modules.set(bound, module);
7478
+ }
7479
+ }
7480
+ function sequenceElements(node) {
7481
+ if (node.name !== "ArrayExpression" && node.name !== "TupleExpression") return null;
7482
+ const out = [];
7483
+ let c = node.firstChild;
7484
+ while (c) {
7485
+ if (!["[", "]", "(", ")", ","].includes(c.name)) out.push(c);
7486
+ c = c.nextSibling;
7487
+ }
7488
+ return out;
7489
+ }
7490
+ function literalKeywordDict(node) {
7491
+ if (!node || node.name !== "DictionaryExpression") return null;
7492
+ const out = /* @__PURE__ */ new Map();
7493
+ let c = node.firstChild;
7494
+ while (c) {
7495
+ if (["{", "}", ","].includes(c.name)) {
7496
+ c = c.nextSibling;
7497
+ continue;
7498
+ }
7499
+ if (c.name === "**") {
7500
+ const nestedNode = c.nextSibling;
7501
+ const nested = nestedNode === null ? null : literalKeywordDict(nestedNode);
7502
+ if (nested === null) return null;
7503
+ for (const [key, value2] of nested) out.set(key, value2);
7504
+ c = nestedNode === null ? null : nestedNode.nextSibling;
7505
+ continue;
7506
+ }
7507
+ const keyNode = c;
7508
+ const colon = keyNode.nextSibling;
7509
+ const value = colon === null ? null : colon.nextSibling;
7510
+ if (colon === null || colon.name !== ":" || value === null) return null;
7511
+ const decoded = keyNode.name === "String" ? decodePythonStringLiteral(srcSlice(keyNode)) : null;
7512
+ if (decoded === null || decoded.bytes) return null;
7513
+ out.set(decoded.value, value);
7514
+ c = value.nextSibling;
7515
+ }
7516
+ return out;
7517
+ }
7518
+ function parseCallArgs(node) {
7519
+ const argList = node.getChild("ArgList");
7520
+ if (!argList) return { positional: [], keywords: /* @__PURE__ */ new Map(), hasStar: false };
7521
+ const positional = [];
7522
+ const keywords = /* @__PURE__ */ new Map();
7523
+ let hasStar = false;
7524
+ let keywordInvalid = false;
7525
+ let c = argList.firstChild;
7526
+ while (c) {
7527
+ const name = c.name;
7528
+ if (name === "(" || name === ")" || name === ",") {
7529
+ c = c.nextSibling;
7530
+ continue;
7531
+ }
7532
+ if (name === "**") {
7533
+ const value = c.nextSibling;
7534
+ const expansion = value === null ? null : literalKeywordDict(value);
7535
+ if (expansion === null) {
7536
+ keywordInvalid = true;
7537
+ } else {
7538
+ for (const [key, val] of expansion) {
7539
+ if (keywords.has(key)) keywordInvalid = true;
7540
+ else keywords.set(key, val);
7541
+ }
7542
+ }
7543
+ c = value === null ? null : value.nextSibling;
7544
+ continue;
7545
+ }
7546
+ if (name === "*") {
7547
+ hasStar = true;
7548
+ const value = c.nextSibling;
7549
+ c = value === null ? null : value.nextSibling;
7550
+ continue;
7551
+ }
7552
+ if (name === "VariableName" && c.nextSibling !== null && c.nextSibling.name === "AssignOp") {
7553
+ const key = srcSlice(c);
7554
+ const value = c.nextSibling.nextSibling;
7555
+ if (value === null || keywords.has(key)) keywordInvalid = true;
7556
+ else keywords.set(key, value);
7557
+ c = value === null ? null : value.nextSibling;
7558
+ continue;
7559
+ }
7560
+ positional.push(c);
7561
+ c = c.nextSibling;
7562
+ }
7563
+ return { positional, keywords: keywordInvalid ? null : keywords, hasStar };
7564
+ }
7565
+ function callIdentity(node, bindings) {
7566
+ const func = unwrapParens(node.firstChild);
7567
+ if (!func) return null;
7568
+ if (func.name === "MemberExpression") {
7569
+ const moduleNode = unwrapParens(func.firstChild);
7570
+ if (!moduleNode || moduleNode.name !== "VariableName") return null;
7571
+ const property = func.getChild("PropertyName");
7572
+ if (!property) return null;
7573
+ const module = bindings.modules.get(srcSlice(moduleNode));
7574
+ const method = srcSlice(property);
7575
+ if (module !== void 0 && CALL_FUNCTIONS[module]?.has(method)) return [module, method];
7576
+ return null;
7577
+ }
7578
+ if (func.name === "VariableName") {
7579
+ return bindings.functions.get(srcSlice(func)) ?? null;
7580
+ }
7581
+ return null;
7582
+ }
7583
+ function isConstantNode(node) {
7584
+ return ["String", "Number", "Boolean", "None"].includes(node.name);
7585
+ }
7586
+ function isLiteralPrint(node, bindings) {
7587
+ if (!bindings.builtinPrint) return false;
7588
+ const func = unwrapParens(node.firstChild);
7589
+ if (!func || func.name !== "VariableName" || srcSlice(func) !== "print") return false;
7590
+ const args = parseCallArgs(node);
7591
+ if (args === null || args.hasStar || args.keywords === null) return false;
7592
+ if (!args.positional.every(isConstantNode)) return false;
7593
+ for (const [key, value] of args.keywords) {
7594
+ if (!["sep", "end", "flush"].includes(key) || !isConstantNode(value)) return false;
7595
+ }
7596
+ return true;
7597
+ }
7598
+ function observeChdir(node, bindings, method, standalone) {
7599
+ let directory = null;
7600
+ if (standalone && method === "chdir") {
7601
+ const args = parseCallArgs(node);
7602
+ if (args !== null && !args.hasStar && args.keywords !== null) {
7603
+ if (args.positional.length === 1 && args.keywords.size === 0) {
7604
+ directory = literalText(args.positional[0], bindings);
7605
+ } else if (args.positional.length === 0 && args.keywords.size === 1 && args.keywords.has("path")) {
7606
+ directory = literalText(args.keywords.get("path"), bindings);
7607
+ }
7608
+ }
7609
+ }
7610
+ bindings.changeDirectory(directory);
7611
+ }
7612
+ function subprocessCalls(command, options, source, bindings) {
7613
+ const executableNode = options.get("executable");
7614
+ const shellNode = options.get("shell");
7615
+ let executable = null;
7616
+ if (executableNode !== void 0) {
7617
+ if (executableNode.name === "None") {
7618
+ executable = null;
7619
+ } else if (executableNode.name === "String") {
7620
+ const decoded = decodePythonStringLiteral(srcSlice(executableNode));
7621
+ if (decoded === null || decoded.bytes || decoded.value === "" || decoded.value.includes("\0")) {
7622
+ return [];
7623
+ }
7624
+ executable = decoded.value;
7625
+ } else {
7626
+ return [];
7627
+ }
7628
+ }
7629
+ let shell = false;
7630
+ if (shellNode !== void 0) {
7631
+ if (shellNode.name !== "Boolean") return [];
7632
+ shell = srcSlice(shellNode) === "True";
7633
+ }
7634
+ if (shell) {
7635
+ if (executable !== null && !SHELL_INTERPRETERS.has(basenameOf(executable))) return [];
7636
+ let commandNode = command;
7637
+ if (commandNode.name === "ArrayExpression" || commandNode.name === "TupleExpression") {
7638
+ const elements2 = sequenceElements(commandNode);
7639
+ if (elements2 !== null && elements2.length) commandNode = elements2[0];
7640
+ }
7641
+ const text = literalText(commandNode, bindings);
7642
+ return text !== null ? literalShellCalls(text, source) : [];
7643
+ }
7644
+ if (shell !== false) return [];
7645
+ const elements = sequenceElements(command);
7646
+ if (elements === null) return [];
7647
+ const words = [];
7648
+ for (const operand of elements) {
7649
+ const word = literalText(operand, bindings);
7650
+ if (word === null || word.includes("\0")) return [];
7651
+ words.push(word);
7652
+ }
7653
+ if (executable !== null && words.length) words[0] = executable;
7654
+ const resolved = envCommand(words);
7655
+ const program = shellProgramOperand(resolved);
7656
+ if (program !== null && program.kind === "command") {
7657
+ return literalShellCalls(resolved[program.index], source);
7658
+ }
7659
+ const call = literalScriptCall(resolved);
7660
+ return call === null ? [] : [call];
7661
+ }
7662
+ function decodeProcessCall(node, module, method, source, bindings) {
7663
+ if (module === "os" && !OS_FUNCS.has(method)) return [];
7664
+ const argumentName = module === "subprocess" ? "args" : method === "system" ? "command" : method === "popen" ? "cmd" : null;
7665
+ const args = parseCallArgs(node);
7666
+ if (args === null || args.hasStar || args.keywords === null) return [];
7667
+ const options = args.keywords;
7668
+ const named = argumentName === null ? void 0 : options.get(argumentName);
7669
+ if (named !== void 0 && args.positional.length) return [];
7670
+ const operand = args.positional.length ? args.positional[0] : named ?? null;
7671
+ if (!operand) return [];
7672
+ if (module === "subprocess") {
7673
+ for (const [name, index] of [["executable", 2], ["shell", 8], ["cwd", 9]]) {
7674
+ if (args.positional.length > index) {
7675
+ if (options.has(name)) return [];
7676
+ options.set(name, args.positional[index]);
7677
+ }
7678
+ }
7679
+ const calls = subprocessCalls(operand, options, source, bindings);
7680
+ const directoryNode = options.get("cwd");
7681
+ if (!calls.length || directoryNode === void 0) return calls;
7682
+ let directory;
7683
+ if (directoryNode.name === "None") {
7684
+ return calls;
7685
+ } else if (directoryNode.name === "String") {
7686
+ const decoded = decodePythonStringLiteral(srcSlice(directoryNode));
7687
+ if (decoded === null || decoded.value === "") return [];
7688
+ directory = decoded.value;
7689
+ } else if (isConstantNode(directoryNode)) {
7690
+ return [];
7691
+ } else {
7692
+ directory = literalText(directoryNode, bindings);
7693
+ }
7694
+ if (directory === "" || directory !== null && directory.includes("\0")) return [];
7695
+ const launchCwd = directoryFor(bindings, directory);
7696
+ for (const call of calls) call.launchCwd = launchCwd;
7697
+ return calls;
7698
+ }
7699
+ const text = literalText(operand, bindings);
7700
+ return text === null ? [] : literalShellCalls(text, source);
7701
+ }
7702
+ function isNodeReachable(node, ctx) {
7703
+ if (ctx.reachableLines === null) return true;
7704
+ return ctx.reachableLines.has(lineAt(ctx.lineStarts, node.from));
7705
+ }
7706
+ function forgetTarget(node, bindings) {
7707
+ const cursor = node.cursor();
6933
7708
  cursor.iterate((n) => {
6934
- const node = n.node;
6935
- if (node.name !== "CallExpression") return true;
6936
- if (!lineReachable(node)) return true;
6937
- const func = node.firstChild;
6938
- if (!func || func.name !== "MemberExpression") return true;
6939
- const modName = func.firstChild;
6940
- if (!modName || modName.name !== "VariableName") return true;
6941
- const funcNameNode = func.getChild("PropertyName");
6942
- if (!funcNameNode) return true;
6943
- const mod = srcSlice(modName);
6944
- const funcName = srcSlice(funcNameNode);
6945
- const argList = node.getChild("ArgList");
6946
- const firstArg = argList ? firstNamedChild(argList) : null;
6947
- if (mod === "subprocess" && SUBPROCESS_FUNCS.has(funcName)) {
6948
- if (firstArg && (firstArg.name === "ArrayExpression" || firstArg.name === "TupleExpression")) {
6949
- const elts = [];
6950
- let allStr = true;
6951
- for (const elt of namedChildren(firstArg)) {
6952
- if (elt.name === "String") elts.push(stringValue(srcSlice(elt)));
6953
- else {
6954
- allStr = false;
6955
- break;
6956
- }
7709
+ if (n.node.name === "VariableName") bindings.forget(srcSlice(n.node));
7710
+ return true;
7711
+ });
7712
+ }
7713
+ function visitExpression(node, bindings, ctx, standaloneRoot = false) {
7714
+ const stack = [
7715
+ { node, standalone: standaloneRoot }
7716
+ ];
7717
+ while (stack.length) {
7718
+ const entry = stack.pop();
7719
+ const current = entry.node;
7720
+ if (current.name === "CallExpression") {
7721
+ handleCall(current, bindings, ctx, entry.standalone);
7722
+ } else if (current.name === "NamedExpression") {
7723
+ const target = current.firstChild;
7724
+ const value = current.lastChild;
7725
+ const literal = value === null || sameNode(value, target) ? null : literalText(value, bindings);
7726
+ if (target !== null && target.name === "VariableName") {
7727
+ bindings.forget(srcSlice(target));
7728
+ if (literal !== null) bindings.strings.set(srcSlice(target), literal);
7729
+ }
7730
+ } else if (current.name === "LambdaExpression") {
7731
+ const params = current.getChild("ParamList");
7732
+ const colon = current.getChild(":");
7733
+ if (params) {
7734
+ let c2 = params.firstChild;
7735
+ while (c2) {
7736
+ if (c2.name !== "ParamList") visitExpression(c2, bindings, ctx);
7737
+ c2 = c2.nextSibling;
6957
7738
  }
6958
- if (allStr && elts.length >= 2) {
6959
- const interp = elts[0];
6960
- const path8 = elts[1];
6961
- if (!path8.startsWith("-") && !path8.startsWith("$") && !path8.includes("/dev/")) {
6962
- add({ path: path8, args: elts.slice(2), interpreter: interp });
6963
- return true;
6964
- }
7739
+ }
7740
+ const local = bindings.fork();
7741
+ if (params) {
7742
+ let c2 = params.firstChild;
7743
+ while (c2) {
7744
+ if (c2.name === "VariableName") local.forget(srcSlice(c2));
7745
+ c2 = c2.nextSibling;
6965
7746
  }
6966
7747
  }
6967
- if (firstArg && firstArg.name === "String") {
6968
- const sc = parseShellString(stringValue(srcSlice(firstArg)));
6969
- if (sc) add(sc);
7748
+ if (colon !== null && colon.nextSibling !== null) {
7749
+ visitExpression(colon.nextSibling, local, ctx);
6970
7750
  }
6971
- } else if (mod === "os" && OS_FUNCS.has(funcName)) {
6972
- if (firstArg && firstArg.name === "String") {
6973
- const sc = parseShellString(stringValue(srcSlice(firstArg)));
6974
- if (sc) add(sc);
7751
+ continue;
7752
+ }
7753
+ const children = [];
7754
+ let c = current.lastChild;
7755
+ while (c) {
7756
+ children.push(c);
7757
+ c = c.prevSibling;
7758
+ }
7759
+ for (const child of children) stack.push({ node: child, standalone: false });
7760
+ }
7761
+ }
7762
+ function functionNameNode(stmt) {
7763
+ let c = stmt.firstChild;
7764
+ while (c) {
7765
+ if (c.name === "VariableName") return c;
7766
+ if (c.name === "Body") return null;
7767
+ c = c.nextSibling;
7768
+ }
7769
+ return null;
7770
+ }
7771
+ function parameterNames(stmt) {
7772
+ const params = stmt.getChild("ParamList");
7773
+ if (!params) return [];
7774
+ const names = [];
7775
+ let c = params.firstChild;
7776
+ while (c) {
7777
+ if (c.name === "VariableName") names.push(srcSlice(c));
7778
+ c = c.nextSibling;
7779
+ }
7780
+ return names;
7781
+ }
7782
+ function isDocstringStatement(stmt) {
7783
+ if (stmt.name !== "ExpressionStatement") return false;
7784
+ const value = firstInnerNode(stmt);
7785
+ return value !== null && ["String", "ContinuedString", "FormatString"].includes(value.name);
7786
+ }
7787
+ function bodyStatements(body) {
7788
+ return body === null ? [] : bodyStmts(body);
7789
+ }
7790
+ function containsCallOrWalrus(node) {
7791
+ let found = false;
7792
+ const cursor = node.cursor();
7793
+ cursor.iterate((n) => {
7794
+ if (n.node.name === "CallExpression" || n.node.name === "NamedExpression") {
7795
+ found = true;
7796
+ return false;
7797
+ }
7798
+ return true;
7799
+ });
7800
+ return found;
7801
+ }
7802
+ function recordWrapper(stmt, bindings) {
7803
+ const params = stmt.getChild("ParamList");
7804
+ if (params !== null) {
7805
+ let c = params.firstChild;
7806
+ while (c) {
7807
+ if (c.name !== "(" && c.name !== ")") return false;
7808
+ c = c.nextSibling;
7809
+ }
7810
+ }
7811
+ const body = stmt.getChild("Body");
7812
+ if (body === null) return false;
7813
+ let statements = bodyStatements(body);
7814
+ if (statements.length && isDocstringStatement(statements[0])) statements = statements.slice(1);
7815
+ if (statements.length !== 1) return false;
7816
+ const only = statements[0];
7817
+ if (only.name !== "ExpressionStatement") return false;
7818
+ const value = firstInnerNode(only);
7819
+ if (value === null || value.name !== "CallExpression") return false;
7820
+ const func = unwrapParens(value.firstChild);
7821
+ if (func === null || func.name !== "VariableName" || !bindings.functions.has(srcSlice(func))) {
7822
+ return false;
7823
+ }
7824
+ const argList = value.getChild("ArgList");
7825
+ if (argList !== null && containsCallOrWalrus(argList)) return false;
7826
+ const nameNode = functionNameNode(stmt);
7827
+ if (nameNode === null) return false;
7828
+ bindings.forget(srcSlice(nameNode));
7829
+ bindings.wrappers.set(srcSlice(nameNode), value);
7830
+ return true;
7831
+ }
7832
+ function wrapperCalls(node, bindings, ctx) {
7833
+ const func = unwrapParens(node.firstChild);
7834
+ if (!func || func.name !== "VariableName") return null;
7835
+ const args = parseCallArgs(node);
7836
+ if (args === null || args.hasStar || args.positional.length || args.keywords !== null && args.keywords.size > 0) {
7837
+ return null;
7838
+ }
7839
+ const stored = bindings.wrappers.get(srcSlice(func));
7840
+ if (stored === void 0) return null;
7841
+ const identity = callIdentity(stored, bindings);
7842
+ if (identity === null) return [];
7843
+ const calls = decodeProcessCall(stored, identity[0], identity[1], ctx.source, bindings);
7844
+ for (const call of calls) {
7845
+ if (call.launchCwd === void 0 || call.launchCwd === null) {
7846
+ call.launchCwd = bindings.cwd === null ? "." : bindings.cwd;
7847
+ }
7848
+ }
7849
+ return calls;
7850
+ }
7851
+ function handleCall(node, bindings, ctx, standalone) {
7852
+ if (!isNodeReachable(node, ctx)) return;
7853
+ const identity = callIdentity(node, bindings);
7854
+ if (identity === null) {
7855
+ const forwarded = wrapperCalls(node, bindings, ctx);
7856
+ if (forwarded !== null) {
7857
+ ctx.found.set(node.from, forwarded);
7858
+ return;
7859
+ }
7860
+ if (!isLiteralPrint(node, bindings)) bindings.invalidate();
7861
+ return;
7862
+ }
7863
+ const [module, method] = identity;
7864
+ if (module === "os" && CWD_METHODS.has(method)) {
7865
+ observeChdir(node, bindings, method, standalone);
7866
+ return;
7867
+ }
7868
+ const calls = decodeProcessCall(node, module, method, ctx.source, bindings);
7869
+ if (!calls.length) return;
7870
+ let directory = bindings.cwd;
7871
+ if (directory === null) {
7872
+ const func = unwrapParens(node.firstChild);
7873
+ const isModuleAttribute = func !== null && func.name === "MemberExpression" && unwrapParens(func.firstChild)?.name === "VariableName" && srcSlice(unwrapParens(func.firstChild)) === module;
7874
+ let capturedArgument = false;
7875
+ const cursor = node.cursor();
7876
+ cursor.iterate((n) => {
7877
+ if (n.node.name === "VariableName" && bindings.strings.has(srcSlice(n.node))) {
7878
+ capturedArgument = true;
7879
+ return false;
6975
7880
  }
7881
+ return true;
7882
+ });
7883
+ if (!isModuleAttribute || capturedArgument) directory = ".";
7884
+ }
7885
+ for (const call of calls) {
7886
+ if (call.launchCwd === void 0 || call.launchCwd === null) call.launchCwd = directory;
7887
+ }
7888
+ ctx.found.set(node.from, calls);
7889
+ }
7890
+ function assignedNamesInBody(body) {
7891
+ const assigned = /* @__PURE__ */ new Set();
7892
+ const external = /* @__PURE__ */ new Set();
7893
+ const walk = (node) => {
7894
+ if (node.name === "AssignStatement") {
7895
+ const { targets } = assignmentParts(node);
7896
+ for (const target of targets) assigned.add(srcSlice(target));
7897
+ } else if (node.name === "UpdateStatement") {
7898
+ const target = node.firstChild;
7899
+ if (target && target.name === "VariableName") assigned.add(srcSlice(target));
7900
+ } else if (node.name === "ForStatement") {
7901
+ const forToken = node.getChild("for");
7902
+ const target = forToken === null ? null : forToken.nextSibling;
7903
+ if (target) forgetTargetInto(target, assigned);
7904
+ } else if (node.name === "FunctionDefinition" || node.name === "ClassDefinition") {
7905
+ const name = functionNameNode(node);
7906
+ if (name) assigned.add(srcSlice(name));
7907
+ } else if (node.name === "ImportStatement") {
7908
+ const text = srcSlice(node);
7909
+ for (const part of text.split(",")) {
7910
+ const m = /([A-Za-z_][\w.]*)(?:\s+as\s+([A-Za-z_][\w.]*))?$/.exec(part.trim());
7911
+ if (m) assigned.add(m[2] || m[1].split(".")[0]);
7912
+ }
7913
+ } else if (node.name === "WithStatement" || node.name === "NamedExpression") {
7914
+ const cursor = node.cursor();
7915
+ let afterAs = false;
7916
+ cursor.iterate((n) => {
7917
+ if (n.node.name === "as") afterAs = true;
7918
+ else if (afterAs && n.node.name === "VariableName") assigned.add(srcSlice(n.node));
7919
+ return true;
7920
+ });
7921
+ } else if (node.name === "GlobalStatement" || node.name === "NonlocalStatement") {
7922
+ const cursor = node.cursor();
7923
+ cursor.iterate((n) => {
7924
+ if (n.node.name === "VariableName") external.add(srcSlice(n.node));
7925
+ return true;
7926
+ });
7927
+ }
7928
+ let c = node.firstChild;
7929
+ while (c) {
7930
+ if (!(node.name === "FunctionDefinition" || node.name === "ClassDefinition")) walk(c);
7931
+ c = c.nextSibling;
6976
7932
  }
7933
+ };
7934
+ walk(body);
7935
+ return { assigned, external };
7936
+ }
7937
+ function forgetTargetInto(node, names) {
7938
+ const cursor = node.cursor();
7939
+ cursor.iterate((n) => {
7940
+ if (n.node.name === "VariableName") names.add(srcSlice(n.node));
6977
7941
  return true;
6978
7942
  });
6979
- const cursor2 = tree.cursor();
6980
- cursor2.iterate((n) => {
7943
+ }
7944
+ function extractFunction(stmt, bindings, ctx) {
7945
+ const body = stmt.getChild("Body");
7946
+ let c = stmt.firstChild;
7947
+ while (c) {
7948
+ if (!sameNode(c, body) && c.name !== "def" && c.name !== "async") {
7949
+ visitExpression(c, bindings, ctx);
7950
+ }
7951
+ c = c.nextSibling;
7952
+ }
7953
+ if (recordWrapper(stmt, bindings)) return;
7954
+ const local = bindings.fork();
7955
+ for (const name of parameterNames(stmt)) local.forget(name);
7956
+ if (body !== null) {
7957
+ const { assigned, external } = assignedNamesInBody(body);
7958
+ for (const name of assigned) {
7959
+ if (!external.has(name)) local.forget(name);
7960
+ }
7961
+ extractBlock(bodyStatements(body), local, ctx);
7962
+ }
7963
+ if (stmt.name === "ClassDefinition") bindings.cwd = local.cwd;
7964
+ const nameNode = functionNameNode(stmt);
7965
+ if (nameNode) bindings.forget(srcSlice(nameNode));
7966
+ }
7967
+ function extractIfSections(sections, decisions, idx, bindings, ctx) {
7968
+ if (idx >= sections.length) return;
7969
+ const section = sections[idx];
7970
+ if (section.cond) visitExpression(section.cond, bindings, ctx);
7971
+ if (section.isElse) {
7972
+ if (section.body) extractBlock(bodyStatements(section.body), bindings, ctx);
7973
+ return;
7974
+ }
7975
+ const decision = decisions[idx] ?? null;
7976
+ if (decision === true) {
7977
+ if (section.body) extractBlock(bodyStatements(section.body), bindings, ctx);
7978
+ return;
7979
+ }
7980
+ if (decision === false) {
7981
+ extractIfSections(sections, decisions, idx + 1, bindings, ctx);
7982
+ return;
7983
+ }
7984
+ const left = bindings.fork();
7985
+ if (section.body) extractBlock(bodyStatements(section.body), left, ctx);
7986
+ const right = bindings.fork();
7987
+ extractIfSections(sections, decisions, idx + 1, right, ctx);
7988
+ bindings.merge([left, right]);
7989
+ }
7990
+ function extractBlock(stmts, bindings, ctx) {
7991
+ for (const stmt of stmts) {
7992
+ if (!isNodeReachable(stmt, ctx) && !(stmt.name === "IfStatement" && ctx.ifDecisions.has(stmt.from))) {
7993
+ continue;
7994
+ }
7995
+ extractStmt(stmt, bindings, ctx);
7996
+ }
7997
+ }
7998
+ function extractStatementExpression(stmt, bindings, ctx) {
7999
+ const value = firstInnerNode(stmt);
8000
+ if (value === null) return;
8001
+ visitExpression(value, bindings, ctx, true);
8002
+ }
8003
+ function extractStmt(stmt, bindings, ctx) {
8004
+ switch (stmt.name) {
8005
+ case "ImportStatement":
8006
+ recordImportText(stmt, bindings);
8007
+ return;
8008
+ case "DecoratedStatement": {
8009
+ let c = stmt.firstChild;
8010
+ while (c) {
8011
+ if (c.name === "Decorator") visitExpression(c, bindings, ctx);
8012
+ else if (c.name === "FunctionDefinition" || c.name === "ClassDefinition") {
8013
+ extractFunction(c, bindings, ctx);
8014
+ }
8015
+ c = c.nextSibling;
8016
+ }
8017
+ return;
8018
+ }
8019
+ case "FunctionDefinition":
8020
+ case "ClassDefinition":
8021
+ extractFunction(stmt, bindings, ctx);
8022
+ return;
8023
+ case "IfStatement": {
8024
+ const sections = collectIfSections(stmt);
8025
+ const decisions = ctx.ifDecisions.get(stmt.from) ?? [];
8026
+ extractIfSections(sections, decisions, 0, bindings, ctx);
8027
+ return;
8028
+ }
8029
+ case "ForStatement": {
8030
+ const forToken = stmt.getChild("for");
8031
+ const target = forToken === null ? null : forToken.nextSibling;
8032
+ const inToken = target === null ? null : target.nextSibling;
8033
+ const iter = inToken === null ? null : inToken.nextSibling;
8034
+ if (iter) visitExpression(iter, bindings, ctx);
8035
+ const bodies = stmt.getChildren("Body");
8036
+ if (bodies.length) {
8037
+ const bodyBindings = bindings.fork();
8038
+ if (target) forgetTarget(target, bodyBindings);
8039
+ extractBlock(bodyStatements(bodies[0]), bodyBindings, ctx);
8040
+ bindings.merge([bindings, bodyBindings]);
8041
+ }
8042
+ if (bodies.length > 1) {
8043
+ const elseBindings = bindings.fork();
8044
+ extractBlock(bodyStatements(bodies[1]), elseBindings, ctx);
8045
+ bindings.merge([bindings, elseBindings]);
8046
+ }
8047
+ return;
8048
+ }
8049
+ case "WhileStatement": {
8050
+ const whileToken = stmt.getChild("while");
8051
+ const body = stmt.getChild("Body");
8052
+ if (whileToken !== null) {
8053
+ const test = whileToken.nextSibling;
8054
+ if (test && !sameNode(test, body)) visitExpression(test, bindings, ctx);
8055
+ }
8056
+ const bodies = stmt.getChildren("Body");
8057
+ if (bodies.length) {
8058
+ const bodyBindings = bindings.fork();
8059
+ extractBlock(bodyStatements(bodies[0]), bodyBindings, ctx);
8060
+ bindings.merge([bindings, bodyBindings]);
8061
+ }
8062
+ if (bodies.length > 1) {
8063
+ const elseBindings = bindings.fork();
8064
+ extractBlock(bodyStatements(bodies[1]), elseBindings, ctx);
8065
+ bindings.merge([bindings, elseBindings]);
8066
+ }
8067
+ return;
8068
+ }
8069
+ case "WithStatement": {
8070
+ const body = stmt.getChild("Body");
8071
+ const bodyBindings = bindings.fork();
8072
+ let afterAs = false;
8073
+ let c = stmt.firstChild;
8074
+ while (c && !sameNode(c, body)) {
8075
+ if (c.name === "as") afterAs = true;
8076
+ else if (afterAs && c.name === "VariableName") {
8077
+ forgetTarget(c, bodyBindings);
8078
+ afterAs = false;
8079
+ } else if (!["with", ",", ":"].includes(c.name)) {
8080
+ visitExpression(c, bodyBindings, ctx);
8081
+ afterAs = false;
8082
+ }
8083
+ c = c.nextSibling;
8084
+ }
8085
+ if (body) extractBlock(bodyStatements(body), bodyBindings, ctx);
8086
+ bindings.merge([bindings, bodyBindings]);
8087
+ return;
8088
+ }
8089
+ case "TryStatement": {
8090
+ const bodies = stmt.getChildren("Body");
8091
+ let finallyToken = null;
8092
+ let c = stmt.firstChild;
8093
+ while (c) {
8094
+ if (c.name === "finally") finallyToken = c;
8095
+ c = c.nextSibling;
8096
+ }
8097
+ const finalBody = finallyToken === null ? null : finallyToken.nextSibling;
8098
+ const alternatives = [];
8099
+ let inExcept = false;
8100
+ const handlerNames = [];
8101
+ c = stmt.firstChild;
8102
+ while (c) {
8103
+ if (c.name === "except") {
8104
+ inExcept = true;
8105
+ handlerNames.length = 0;
8106
+ } else if (c.name === "as" && inExcept) {
8107
+ const nameNode = c.nextSibling;
8108
+ if (nameNode && nameNode.name === "VariableName") handlerNames.push(srcSlice(nameNode));
8109
+ } else if (c.name === "Body" && !sameNode(c, finalBody)) {
8110
+ const fork = bindings.fork();
8111
+ for (const name of handlerNames) fork.forget(name);
8112
+ handlerNames.length = 0;
8113
+ inExcept = false;
8114
+ extractBlock(bodyStatements(c), fork, ctx);
8115
+ alternatives.push(fork);
8116
+ } else if (c.name === "else" || c.name === "finally") {
8117
+ inExcept = false;
8118
+ }
8119
+ c = c.nextSibling;
8120
+ }
8121
+ bindings.merge([bindings, ...alternatives]);
8122
+ if (finalBody) extractBlock(bodyStatements(finalBody), bindings, ctx);
8123
+ return;
8124
+ }
8125
+ case "MatchStatement": {
8126
+ const matchToken = stmt.getChild("match");
8127
+ const matchBody = stmt.getChild("MatchBody");
8128
+ if (matchToken !== null && matchBody !== null) {
8129
+ const subject = matchToken.nextSibling;
8130
+ if (subject && !sameNode(subject, matchBody)) visitExpression(subject, bindings, ctx);
8131
+ }
8132
+ const alternatives = [];
8133
+ if (matchBody !== null) {
8134
+ for (const clause of matchBody.getChildren("MatchClause")) {
8135
+ const fork = bindings.fork();
8136
+ let c = clause.firstChild;
8137
+ const body = clause.getChild("Body");
8138
+ while (c && !sameNode(c, body)) {
8139
+ if (c.name !== "case") visitExpression(c, fork, ctx);
8140
+ c = c.nextSibling;
8141
+ }
8142
+ if (body) extractBlock(bodyStatements(body), fork, ctx);
8143
+ alternatives.push(fork);
8144
+ }
8145
+ }
8146
+ bindings.merge([bindings, ...alternatives]);
8147
+ return;
8148
+ }
8149
+ case "AssignStatement": {
8150
+ const { targets, value } = assignmentParts(stmt);
8151
+ if (value) visitExpression(value, bindings, ctx);
8152
+ if (targets.length === 1) {
8153
+ bindings.bindString(srcSlice(targets[0]), literalText(value, bindings));
8154
+ } else {
8155
+ for (const target of targets) forgetTarget(target, bindings);
8156
+ }
8157
+ return;
8158
+ }
8159
+ case "UpdateStatement": {
8160
+ const target = stmt.firstChild;
8161
+ const value = stmt.lastChild;
8162
+ if (value && value !== target) visitExpression(value, bindings, ctx);
8163
+ if (target && target.name === "VariableName") bindings.forget(srcSlice(target));
8164
+ return;
8165
+ }
8166
+ case "ExpressionStatement":
8167
+ extractStatementExpression(stmt, bindings, ctx);
8168
+ return;
8169
+ default: {
8170
+ let c = stmt.firstChild;
8171
+ while (c) {
8172
+ if (c.name !== "del") visitExpression(c, bindings, ctx);
8173
+ c = c.nextSibling;
8174
+ }
8175
+ }
8176
+ }
8177
+ }
8178
+ function relativeImportCalls(tree) {
8179
+ const calls = [];
8180
+ const cursor = tree.cursor();
8181
+ cursor.iterate((n) => {
6981
8182
  const node = n.node;
6982
8183
  if (node.name !== "ImportStatement") return true;
6983
- const txt = srcSlice(node);
6984
- if (!/^from\s+\./m.test(txt)) return true;
6985
- const m = txt.match(/\bimport\s+(.+)$/m);
6986
- if (m) {
6987
- for (const part of m[1].split(",")) {
6988
- const name = part.trim().replace(/\s+as\s+\w+$/, "");
6989
- if (name && name !== "*") add({ path: name.replace(/\./g, "/") + ".py", args: [], interpreter: "python3" });
8184
+ const text = srcSlice(node);
8185
+ const m = text.match(/^\s*from\s+(\.+)([A-Za-z_][\w.]*)?\s+import\s+([\s\S]+)$/);
8186
+ if (!m) return true;
8187
+ if (m[2]) {
8188
+ calls.push({
8189
+ path: m[2].replace(/\./g, "/") + ".py",
8190
+ args: [],
8191
+ interpreter: "python3",
8192
+ isImport: true
8193
+ });
8194
+ }
8195
+ for (const part of m[3].replace(/[()]/g, "").split(",")) {
8196
+ const name = part.trim().replace(/\s+as\s+\w+$/, "").trim();
8197
+ if (name && name !== "*" && /^[A-Za-z_][\w.]*$/.test(name)) {
8198
+ calls.push({ path: name.replace(/\./g, "/") + ".py", args: [], interpreter: "python3", isImport: true });
6990
8199
  }
6991
8200
  }
6992
8201
  return true;
6993
8202
  });
6994
8203
  return calls;
6995
8204
  }
8205
+ function extractCallsFromTree(tree, reachableLines, ifDecisions, lineStarts) {
8206
+ const ctx = {
8207
+ source: null,
8208
+ reachableLines,
8209
+ lineStarts,
8210
+ ifDecisions,
8211
+ found: /* @__PURE__ */ new Map()
8212
+ };
8213
+ const bindings = new CallBindings(null);
8214
+ extractBlock(bodyStmts(tree), bindings, ctx);
8215
+ const calls = [];
8216
+ const queue = [tree];
8217
+ for (let index = 0; index < queue.length; index++) {
8218
+ const node = queue[index];
8219
+ if (node.name === "CallExpression") {
8220
+ const found = ctx.found.get(node.from);
8221
+ if (found !== void 0) calls.push(...found);
8222
+ }
8223
+ let c = node.firstChild;
8224
+ while (c) {
8225
+ queue.push(c);
8226
+ c = c.nextSibling;
8227
+ }
8228
+ }
8229
+ calls.push(...relativeImportCalls(tree));
8230
+ const seen = /* @__PURE__ */ new Set();
8231
+ const unique = [];
8232
+ for (const call of calls) {
8233
+ const key = callKey(call);
8234
+ if (seen.has(key)) continue;
8235
+ seen.add(key);
8236
+ unique.push(call);
8237
+ }
8238
+ return unique;
8239
+ }
6996
8240
  function extractCallsRegex(content) {
6997
8241
  const calls = [];
6998
8242
  CHILD_CALL_RE.lastIndex = 0;
6999
8243
  let m;
7000
8244
  while ((m = CHILD_CALL_RE.exec(content)) !== null) {
7001
8245
  const interp = m[1];
7002
- const path8 = m[2].trim();
8246
+ const path9 = m[2].trim();
7003
8247
  let rest = m[3].trim();
7004
- if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
8248
+ if (path9.startsWith("-") || path9.startsWith("$") || path9.includes("/dev/")) continue;
7005
8249
  rest = rest.split(/[;|&<>]/)[0].trim();
7006
8250
  const args = [];
7007
8251
  for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
7008
8252
  args.push(tm[1] ? tm[2] : tm[3]);
7009
8253
  }
7010
- calls.push({ path: path8, args, interpreter: interp });
8254
+ calls.push({ path: path9, args, interpreter: interp });
7011
8255
  }
7012
8256
  return calls;
7013
8257
  }
7014
8258
  var PythonBackend = class {
7015
8259
  language = "python";
7016
- parse(content, entryArgs) {
8260
+ parse(content, entryArgs, options = {}) {
8261
+ const diagnostics = options.diagnostics;
8262
+ const argsKnown = options.argsKnown !== false;
7017
8263
  const c = content || "";
7018
8264
  SOURCE = c;
7019
8265
  const sourceLines = c.split("\n");
@@ -7021,7 +8267,16 @@ var PythonBackend = class {
7021
8267
  const env2 = makeEnv(entryArgs || []);
7022
8268
  const lines = /* @__PURE__ */ new Set();
7023
8269
  const branches = [];
8270
+ const ifDecisions = /* @__PURE__ */ new Map();
8271
+ if (diagnostics) {
8272
+ diagnostics.physical_lines = sourceLines.length;
8273
+ diagnostics.line_limit = MAX_LINES;
8274
+ }
7024
8275
  if (sourceLines.length > MAX_LINES) {
8276
+ if (diagnostics) {
8277
+ diagnostics.parser = "python_full";
8278
+ diagnostics.fallback_reason = "line_budget";
8279
+ }
7025
8280
  return {
7026
8281
  reachableContent: c,
7027
8282
  controlFlowResolved: false,
@@ -7035,6 +8290,10 @@ var PythonBackend = class {
7035
8290
  try {
7036
8291
  tree = parser.parse(c).topNode;
7037
8292
  } catch {
8293
+ if (diagnostics) {
8294
+ diagnostics.parser = "python_full";
8295
+ diagnostics.fallback_reason = "syntax_error";
8296
+ }
7038
8297
  return {
7039
8298
  reachableContent: c,
7040
8299
  controlFlowResolved: false,
@@ -7044,11 +8303,32 @@ var PythonBackend = class {
7044
8303
  language: this.language
7045
8304
  };
7046
8305
  }
8306
+ if (!argsKnown) {
8307
+ if (diagnostics) {
8308
+ diagnostics.parser = "python_full";
8309
+ diagnostics.fallback_reason = "unknown_args";
8310
+ diagnostics.child_extractor = "ast";
8311
+ }
8312
+ return {
8313
+ reachableContent: c,
8314
+ controlFlowResolved: false,
8315
+ calls: extractCallsFromTree(tree, null, /* @__PURE__ */ new Map(), lineStarts),
8316
+ branches: [],
8317
+ unresolvedSnippets: [],
8318
+ language: this.language
8319
+ };
8320
+ }
7047
8321
  const stmts = bodyStmts(tree);
7048
- processStmts(stmts, env2, lineStarts, lines, branches);
8322
+ processStmts(stmts, env2, lineStarts, lines, branches, ifDecisions);
7049
8323
  const reachable = reconstruct(sourceLines, lines);
7050
- let calls = extractCallsFromTree(tree, lines);
7051
- if (calls.length === 0) calls = extractCallsRegex(c);
8324
+ const calls = extractCallsFromTree(tree, lines, ifDecisions, lineStarts);
8325
+ if (diagnostics) {
8326
+ diagnostics.parser = "python_ast";
8327
+ diagnostics.child_extractor = "ast";
8328
+ diagnostics.retained_lines = lines.size;
8329
+ diagnostics.branch_count = branches.length;
8330
+ diagnostics.branch_reachable = branches.slice(0, 4).map((b) => b.reachable);
8331
+ }
7052
8332
  const srcNonblank = sourceLines.filter((l) => l.trim().length > 0);
7053
8333
  const rcNonblank = reachable.split("\n").filter((l) => l.trim().length > 0);
7054
8334
  const resolved = rcNonblank.length !== srcNonblank.length || rcNonblank.some((l, i) => l !== srcNonblank[i]);
@@ -7074,7 +8354,6 @@ init_esm_shims();
7074
8354
  function reescape(s) {
7075
8355
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
7076
8356
  }
7077
- var RE_DOTALL = "s";
7078
8357
  var MAX_LINES2 = 500;
7079
8358
  var MAX_BRANCHES = 50;
7080
8359
  var MAX_VARS = 200;
@@ -7100,14 +8379,50 @@ function fold(val) {
7100
8379
  }
7101
8380
  return svalConc(parts.join(""));
7102
8381
  }
7103
- var ASGN_RE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/;
7104
- var CASE_START_RE = /^\s*case\s+/;
7105
- var IF_START_RE = /^\s*if\s+/;
7106
- var NOT_MODELED_RE = /\$\(|`[^`]*`/;
7107
- var CASE_OPEN_RE = /\bcase\b/;
7108
- var CASE_CLOSE_RE = /\besac\b/;
7109
- var IF_OPEN_RE = /\bif\b/;
7110
- var IF_CLOSE_RE = /\bfi\b/;
8382
+ var CASE_QUOTED_PART = String.raw`'[^']*'|"(?:\\[\s\S]|[^"\\])*"|\\[\s\S]`;
8383
+ var CASE_SYNTAX_TOKEN_SOURCE = String.raw`\#[^\n]*` + String.raw`|(?:` + CASE_QUOTED_PART + String.raw`|[^\s;&|()<>'"\\\x60])+` + String.raw`|<<|['"\\\x60]`;
8384
+ var CASE_QUOTED_RE = new RegExp(CASE_QUOTED_PART, "g");
8385
+ function maskCaseLiteral(literal) {
8386
+ const unsupported = literal === "\\\n" || literal.startsWith('"') && (literal.includes("$(") || literal.includes("`"));
8387
+ const mask = unsupported ? "\0" : "x";
8388
+ return literal.replace(/[^\n]/g, mask);
8389
+ }
8390
+ function maskCaseWord(text) {
8391
+ if (text.startsWith("#")) return " ".repeat(text.length);
8392
+ if (text === "<<" || text === "'" || text === '"' || text === "\\" || text === "`") {
8393
+ return "\0".repeat(text.length);
8394
+ }
8395
+ CASE_QUOTED_RE.lastIndex = 0;
8396
+ return text.replace(CASE_QUOTED_RE, maskCaseLiteral);
8397
+ }
8398
+ function caseSyntaxLines(content) {
8399
+ const re = new RegExp(CASE_SYNTAX_TOKEN_SOURCE, "g");
8400
+ return content.replace(re, maskCaseWord).split("\n");
8401
+ }
8402
+ var CASE_COMMAND_START = String.raw`(?:^|(?<=[;|&()]))[ \t]*` + String.raw`(?:(?:if|then|elif|else|while|until|do|\{|!|time(?:[ \t]+-p)?(?:[ \t]+--)?)[ \t]+)*`;
8403
+ var COPROC_PREFIX = String.raw`coproc[ \t]+(?:[^\s;&|()<>]+[ \t]+)?`;
8404
+ var CASE_OPEN_SOURCE = CASE_COMMAND_START + String.raw`(?:` + COPROC_PREFIX + String.raw`)?case[ \t]+(?=[^\s;&|()<>])`;
8405
+ var COPROC_GROUP_SOURCE = CASE_COMMAND_START + COPROC_PREFIX + String.raw`(?:(?:\{|if|for|while|until|select)(?=$|[\s;&|()<>])|\()`;
8406
+ var CASE_FUNCTION_SOURCE = CASE_COMMAND_START + String.raw`(?:function[ \t]+[^\s;&|()<>]+|(?<name>[^\s;&|()<>]+)[ \t]*\([ \t]*)`;
8407
+ var CASE_ARRAY_ASSIGNMENT_SOURCE = String.raw`[A-Za-z_][A-Za-z0-9_]*(?:\[.+\])?\+?=`;
8408
+ var CASE_CLOSE_SOURCE = String.raw`(?:^|(?<=[;&]))[ \t]*esac(?=$|[ \t;&|])`;
8409
+ var CASE_HEADER_LINE_SOURCE = String.raw`[ \t]*case[ \t]+([^\s;&|()<>]+)(?:[ \t]+(in))?[ \t]*`;
8410
+ var CASE_HEADER_RE = /^[ \t]*case[ \t]+/m;
8411
+ var CASE_OPEN_G = new RegExp(CASE_OPEN_SOURCE, "g");
8412
+ var COPROC_GROUP_RE = new RegExp(COPROC_GROUP_SOURCE);
8413
+ var CASE_FUNCTION_G = new RegExp(CASE_FUNCTION_SOURCE, "gd");
8414
+ var CASE_ARRAY_ASSIGNMENT_RE = new RegExp("^(?:" + CASE_ARRAY_ASSIGNMENT_SOURCE + ")$");
8415
+ var CASE_CLOSE_G = new RegExp(CASE_CLOSE_SOURCE, "g");
8416
+ var CASE_HEADER_LINE_RE = new RegExp("^(?:" + CASE_HEADER_LINE_SOURCE + ")$", "d");
8417
+ var CASE_TERMINATOR_RE = /;;&|;&|;;/;
8418
+ var CASE_LABEL_END_RE = new RegExp(String.raw`^\s*\(?([^()]+)\)\s*`, "d");
8419
+ var IF_OPEN_RE = /\bif\b/g;
8420
+ var IF_CLOSE_RE = /\bfi\b/g;
8421
+ var LOOP_OPEN_RE = /\b(?:while|for|until)\b/;
8422
+ var LOOP_DO_RE = /\bdo\b/g;
8423
+ var LOOP_DONE_RE = /\bdone\b/g;
8424
+ var FN_DEF_RE = /^\s*(?:function\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\)\s*\{/;
8425
+ var FN_DEF_KW_RE = /^\s*function\s+[A-Za-z_][A-Za-z0-9_]*\s*\{?/;
7111
8426
  function countMatches(re, s) {
7112
8427
  const m = s.match(re);
7113
8428
  return m ? m.length : 0;
@@ -7120,180 +8435,227 @@ function findBlockEnd(lines, startLine, openRe, closeRe) {
7120
8435
  }
7121
8436
  return -1;
7122
8437
  }
7123
- function findCaseEnd(lines, start) {
7124
- return findBlockEnd(lines, start, CASE_OPEN_RE, CASE_CLOSE_RE);
8438
+ function findIfEnd(lines, startLine) {
8439
+ return findBlockEnd(lines, startLine, IF_OPEN_RE, IF_CLOSE_RE);
7125
8440
  }
7126
- function findIfEnd(lines, start) {
7127
- return findBlockEnd(lines, start, IF_OPEN_RE, IF_CLOSE_RE);
7128
- }
7129
- var LOOP_DO_RE = /\bdo\b/g;
7130
- var LOOP_DONE_RE = /\bdone\b/g;
7131
- function findLoopEnd(lines, start) {
8441
+ function findLoopEnd(lines, startLine) {
7132
8442
  let depth = 0;
7133
- for (let idx = start; idx < lines.length; idx++) {
8443
+ for (let idx = startLine; idx < lines.length; idx++) {
7134
8444
  depth += countMatches(LOOP_DO_RE, lines[idx]) - countMatches(LOOP_DONE_RE, lines[idx]);
7135
- if (depth <= 0 && idx > start) return idx;
8445
+ if (depth <= 0 && idx > startLine) return idx;
7136
8446
  }
7137
8447
  return -1;
7138
8448
  }
7139
- var FN_DEF_RE = /^\s*(?:function\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\)\s*\{/;
7140
- var FN_DEF_KW_RE = /^\s*function\s+[A-Za-z_][A-Za-z0-9_]*\s*\{?/;
7141
- function findFnEnd(lines, start) {
8449
+ function findFnEnd(lines, startLine) {
7142
8450
  let depth = 0;
7143
- for (let idx = start; idx < lines.length; idx++) {
8451
+ for (let idx = startLine; idx < lines.length; idx++) {
7144
8452
  depth += (lines[idx].match(/\{/g) || []).length - (lines[idx].match(/\}/g) || []).length;
7145
- if (depth <= 0 && idx > start) return idx;
8453
+ if (depth <= 0 && idx > startLine) return idx;
7146
8454
  }
7147
8455
  return -1;
7148
8456
  }
7149
- function stripComments(content) {
7150
- return content.split("\n").filter((l) => !l.trimStart().startsWith("#")).join("\n");
7151
- }
7152
- function parseCaseStmt(block) {
7153
- const header = block.match(/\s*case\s+(\S[^;]*?)\s*\bin\b[\s\S]*/);
7154
- if (!header) return null;
7155
- const sel = header[1].trim();
7156
- const lines = block.split("\n");
7157
- let headerLine = 0;
7158
- for (let i = 0; i < lines.length; i++) {
7159
- if (/\bin\b/.test(lines[i]) && /\bcase\b/.test(lines[i])) {
7160
- headerLine = i;
7161
- break;
7162
- }
7163
- }
7164
- const bodyStartLine = headerLine + 1;
7165
- const endLine = findCaseEnd(lines, 0);
7166
- if (endLine === -1) return null;
7167
- const branches = splitCaseBranchesDepthAware(lines.slice(bodyStartLine, endLine));
7168
- if (!branches.length) return null;
7169
- return { kind: "case", line: block, modelable: true, selector: sel, branches };
7170
- }
7171
- function splitCaseBranchesDepthAware(bodyLines) {
7172
- let depth = 0;
7173
- let curPat = null;
7174
- let curBody = [];
7175
- const branches = [];
7176
- const flush = () => {
7177
- if (curPat !== null) {
7178
- branches.push({ pat: curPat, body: curBody.join("\n") });
8457
+ function caseDepthDelta(line, rawLine) {
8458
+ if (COPROC_GROUP_RE.test(line)) return null;
8459
+ CASE_FUNCTION_G.lastIndex = 0;
8460
+ let fn;
8461
+ while ((fn = CASE_FUNCTION_G.exec(line)) !== null) {
8462
+ if (fn[0] === "") {
8463
+ CASE_FUNCTION_G.lastIndex++;
8464
+ continue;
7179
8465
  }
7180
- curPat = null;
7181
- curBody = [];
7182
- };
7183
- for (const ln of bodyLines) {
7184
- const stripped = ln.trim();
7185
- if (depth === 0) {
7186
- const bm = stripped.match(/^([^()]+?)\s*\)\s*(.*)$/);
7187
- if (bm) {
7188
- if (curPat !== null) flush();
7189
- curPat = bm[1].trim().replace(/^["']|["']$/g, "");
7190
- curBody = bm[2].trim() ? [bm[2].trim()] : [];
7191
- continue;
7192
- }
8466
+ const name = fn.groups?.name;
8467
+ if (name === void 0) return null;
8468
+ const range = fn.indices?.groups?.name;
8469
+ if (!range) return null;
8470
+ const [startIdx, endIdx] = range;
8471
+ if (rawLine[endIdx] !== "(" || !CASE_ARRAY_ASSIGNMENT_RE.test(rawLine.slice(startIdx, endIdx))) {
8472
+ return null;
7193
8473
  }
7194
- if (/\bcase\b/.test(stripped)) depth += 1;
7195
- else if (/\besac\b/.test(stripped)) depth = Math.max(0, depth - 1);
7196
- else if (curPat !== null) {
7197
- curBody.push(ln);
7198
- if (depth === 0 && stripped.endsWith(";;")) flush();
8474
+ }
8475
+ const opens = countMatches(CASE_OPEN_G, line);
8476
+ const closes = [];
8477
+ CASE_CLOSE_G.lastIndex = 0;
8478
+ let cm;
8479
+ while ((cm = CASE_CLOSE_G.exec(line)) !== null) {
8480
+ if (cm[0] === "") {
8481
+ CASE_CLOSE_G.lastIndex++;
8482
+ continue;
7199
8483
  }
8484
+ closes.push(cm.index);
7200
8485
  }
7201
- if (curPat !== null && curBody.length) flush();
7202
- return branches;
8486
+ if (opens + closes.length > 1 || closes.length > 0 && closes[0] !== 0) return null;
8487
+ return opens - closes.length;
7203
8488
  }
7204
- function parseIfStmt(block) {
7205
- const m = block.match(/\s*if\s+([^\n;]+?)\s*;\s*then/);
7206
- if (!m) return null;
7207
- const cond = m[1].trim();
7208
- const lines = block.split("\n");
7209
- const fiLine = findIfEnd(lines, 0);
7210
- if (fiLine === -1) return null;
7211
- const body = lines.slice(1, fiLine).join("\n");
7212
- const elseM = /\belse\b/.exec(body);
7213
- let thenBody;
7214
- let elseBody;
7215
- if (elseM) {
7216
- thenBody = body.slice(0, elseM.index);
7217
- elseBody = body.slice(elseM.index + 4);
7218
- } else {
7219
- thenBody = body;
7220
- elseBody = null;
8489
+ function findCaseEnd(lines, syntaxLines, startLine) {
8490
+ let depth = 0;
8491
+ for (let index = startLine; index < lines.length; index++) {
8492
+ const delta = caseDepthDelta(syntaxLines[index], lines[index]);
8493
+ if (delta === null || index === startLine && delta !== 1) return -1;
8494
+ depth += delta;
8495
+ if (depth === 0) return index;
7221
8496
  }
7222
- return { kind: "if", line: block, modelable: true, cond, thenBody, elseBody };
8497
+ return -1;
7223
8498
  }
7224
- function tokenize(content) {
7225
- const lines = stripComments(content).split("\n");
8499
+ var ASGN_RE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/;
8500
+ var NOT_MODELED_RE = /\$\(|`[^`]*`/;
8501
+ function containsCommandSubstitution(line) {
8502
+ return NOT_MODELED_RE.test(line);
8503
+ }
8504
+ function splitStatements(content) {
8505
+ const lines = content.split("\n");
8506
+ const syntaxLines = CASE_HEADER_RE.test(content) ? caseSyntaxLines(content) : lines;
7226
8507
  const stmts = [];
7227
8508
  let i = 0;
7228
- while (i < lines.length) {
8509
+ const n = lines.length;
8510
+ while (i < n) {
7229
8511
  const ln = lines[i];
7230
8512
  const stripped = ln.trim();
7231
- if (!stripped) {
7232
- i++;
8513
+ if (!syntaxLines[i].trim() || stripped.startsWith("#")) {
8514
+ i += 1;
7233
8515
  continue;
7234
8516
  }
7235
- if (/\b(?:while|for|until)\b/.test(stripped) && !CASE_START_RE.test(stripped) && !IF_START_RE.test(stripped)) {
8517
+ if (LOOP_OPEN_RE.test(stripped) && !/^\s*case\s+/.test(stripped) && !/^\s*if\s+/.test(stripped)) {
7236
8518
  const endLine = findLoopEnd(lines, i);
7237
8519
  if (endLine !== -1) {
7238
- for (let k = i; k <= endLine; k++) stmts.push({ kind: "plain", line: lines[k], modelable: false });
8520
+ for (let k = i; k <= endLine; k++) {
8521
+ stmts.push({ kind: "not_modeled", line: lines[k], modelable: false, reason: "loop" });
8522
+ }
7239
8523
  i = endLine + 1;
7240
8524
  continue;
7241
8525
  }
7242
- stmts.push({ kind: "plain", line: ln, modelable: false });
7243
- i++;
8526
+ stmts.push({ kind: "not_modeled", line: ln, modelable: false, reason: "loop" });
8527
+ i += 1;
7244
8528
  continue;
7245
8529
  }
7246
8530
  if (FN_DEF_RE.test(stripped) || FN_DEF_KW_RE.test(stripped)) {
7247
8531
  const endLine = findFnEnd(lines, i);
7248
8532
  if (endLine !== -1) {
7249
- for (let k = i; k <= endLine; k++) stmts.push({ kind: "plain", line: lines[k], modelable: false });
8533
+ for (let k = i; k <= endLine; k++) {
8534
+ stmts.push({ kind: "not_modeled", line: lines[k], modelable: false, reason: "function" });
8535
+ }
7250
8536
  i = endLine + 1;
7251
8537
  continue;
7252
8538
  }
7253
- stmts.push({ kind: "plain", line: ln, modelable: false });
7254
- i++;
8539
+ stmts.push({ kind: "not_modeled", line: ln, modelable: false, reason: "function" });
8540
+ i += 1;
7255
8541
  continue;
7256
8542
  }
7257
- if (CASE_START_RE.test(stripped)) {
7258
- const endLine = findCaseEnd(lines, i);
7259
- if (endLine === -1) {
7260
- stmts.push({ kind: "plain", line: ln, modelable: false });
7261
- i++;
7262
- continue;
7263
- }
7264
- const parsed = parseCaseStmt(lines.slice(i, endLine + 1).join("\n"));
7265
- stmts.push(parsed || { kind: "plain", line: ln, modelable: false });
7266
- i = endLine + 1;
8543
+ if (CASE_HEADER_RE.test(syntaxLines[i])) {
8544
+ const parsed = parseCaseStatement(lines, syntaxLines, i);
8545
+ stmts.push(parsed ?? { kind: "not_modeled", line: ln, modelable: false, reason: "case_syntax" });
8546
+ i += parsed === null ? 1 : parsed.line.split("\n").length;
7267
8547
  continue;
7268
8548
  }
7269
- if (IF_START_RE.test(stripped)) {
8549
+ if (/^\s*if\s+/.test(stripped)) {
7270
8550
  const endLine = findIfEnd(lines, i);
7271
8551
  if (endLine === -1) {
7272
- stmts.push({ kind: "plain", line: ln, modelable: false });
7273
- i++;
8552
+ stmts.push({ kind: "not_modeled", line: ln, modelable: false, reason: "if_syntax" });
8553
+ i += 1;
7274
8554
  continue;
7275
8555
  }
7276
- const parsed = parseIfStmt(lines.slice(i, endLine + 1).join("\n"));
7277
- stmts.push(parsed || { kind: "plain", line: ln, modelable: false });
8556
+ const blockText = lines.slice(i, endLine + 1).join("\n");
8557
+ const parsed = parseIfStmt(blockText);
8558
+ stmts.push(parsed ?? { kind: "not_modeled", line: ln, modelable: false, reason: "if_syntax" });
7278
8559
  i = endLine + 1;
7279
8560
  continue;
7280
8561
  }
7281
8562
  if (/\bshift\b|\bset\s+--(?:\s|$)|[\s;|&]read\b|^\s*read\b/.test(stripped)) {
7282
- stmts.push({ kind: "plain", line: ln, modelable: false });
7283
- i++;
8563
+ stmts.push({ kind: "not_modeled", line: ln, modelable: false, reason: "positional_mutation" });
8564
+ i += 1;
7284
8565
  continue;
7285
8566
  }
7286
- const am = stripped.match(ASGN_RE);
7287
- if (am && !NOT_MODELED_RE.test(stripped)) {
8567
+ const am = ASGN_RE.exec(stripped);
8568
+ if (am && !containsCommandSubstitution(stripped)) {
7288
8569
  stmts.push({ kind: "assign", line: stripped, modelable: true, name: am[1], rhs: am[2].trim() });
7289
- i++;
8570
+ i += 1;
7290
8571
  continue;
7291
8572
  }
7292
- stmts.push(NOT_MODELED_RE.test(stripped) ? { kind: "plain", line: ln, modelable: false } : { kind: "plain", line: ln, modelable: true });
7293
- i++;
8573
+ stmts.push(containsCommandSubstitution(stripped) ? { kind: "not_modeled", line: ln, modelable: false, reason: "command_substitution" } : { kind: "plain", line: ln, modelable: true });
8574
+ i += 1;
7294
8575
  }
7295
8576
  return stmts;
7296
8577
  }
8578
+ function parseCaseStatement(lines, syntaxLines, start) {
8579
+ const header = CASE_HEADER_LINE_RE.exec(syntaxLines[start]);
8580
+ if (header === null) return null;
8581
+ let bodyStart = start + 1;
8582
+ if (header[2] === void 0) {
8583
+ while (bodyStart < syntaxLines.length && !syntaxLines[bodyStart].trim()) bodyStart += 1;
8584
+ if (bodyStart === syntaxLines.length || syntaxLines[bodyStart].trim() !== "in") return null;
8585
+ bodyStart += 1;
8586
+ }
8587
+ const end = findCaseEnd(lines, syntaxLines, start);
8588
+ if (end < bodyStart || !/^\s*esac\s*;?\s*$/.test(syntaxLines[end])) return null;
8589
+ for (let i = start; i <= end; i++) {
8590
+ if (syntaxLines[i].includes("\0") || syntaxLines[i].includes("$(")) return null;
8591
+ }
8592
+ const selectorRange = header.indices?.[1];
8593
+ if (!selectorRange) return null;
8594
+ const selector = lines[start].slice(selectorRange[0], selectorRange[1]);
8595
+ const branches = [];
8596
+ let label = null;
8597
+ let body = [];
8598
+ let depth = 0;
8599
+ for (let index = bodyStart; index < end; index++) {
8600
+ let line = lines[index];
8601
+ let syntax = syntaxLines[index];
8602
+ if (label === null) {
8603
+ if (!syntax.trim()) continue;
8604
+ const branch = CASE_LABEL_END_RE.exec(syntax);
8605
+ if (branch === null) return null;
8606
+ const labelRange = branch.indices?.[1];
8607
+ if (!labelRange) return null;
8608
+ label = line.slice(labelRange[0], labelRange[1]).trim();
8609
+ const consumed = branch[0].length;
8610
+ line = line.slice(consumed);
8611
+ syntax = syntax.slice(consumed);
8612
+ }
8613
+ const delta = caseDepthDelta(syntax, line);
8614
+ if (delta === null || depth + delta < 0) return null;
8615
+ depth += delta;
8616
+ body.push(line);
8617
+ if (depth === 0) {
8618
+ const terminator = CASE_TERMINATOR_RE.exec(syntax);
8619
+ if (terminator !== null) {
8620
+ if (terminator[0] !== ";;" || syntax.slice(terminator.index + terminator[0].length).trim()) {
8621
+ return null;
8622
+ }
8623
+ branches.push({ label, body: body.join("\n") });
8624
+ label = null;
8625
+ body = [];
8626
+ }
8627
+ }
8628
+ }
8629
+ if (depth) return null;
8630
+ if (label !== null) branches.push({ label, body: body.join("\n") });
8631
+ return {
8632
+ kind: "case",
8633
+ line: lines.slice(start, end + 1).join("\n"),
8634
+ modelable: true,
8635
+ selector,
8636
+ branches
8637
+ };
8638
+ }
8639
+ function parseIfStmt(block) {
8640
+ const m = /^\s*if\s+([^\n;]+?)\s*;\s*then/.exec(block);
8641
+ if (!m) return null;
8642
+ const cond = m[1].trim();
8643
+ const blockLines = block.split("\n");
8644
+ const fiLine = findIfEnd(blockLines, 0);
8645
+ if (fiLine === -1) return null;
8646
+ const body = blockLines.slice(1, fiLine).join("\n");
8647
+ const elseM = /\belse\b/.exec(body);
8648
+ let thenBody;
8649
+ let elseBody;
8650
+ if (elseM) {
8651
+ thenBody = body.slice(0, elseM.index);
8652
+ elseBody = body.slice(elseM.index + 4);
8653
+ } else {
8654
+ thenBody = body;
8655
+ elseBody = null;
8656
+ }
8657
+ return { kind: "if", line: block, modelable: true, cond, thenBody, elseBody };
8658
+ }
7297
8659
  var EXPR_SPLIT_RE = /(\$\{[^}]*\}|\$[A-Za-z_][A-Za-z0-9_]*|\$\d+)/;
7298
8660
  function evalExpr2(text, env2) {
7299
8661
  const isSingleQuoted = text.length >= 2 && text[0] === "'" && text[text.length - 1] === "'";
@@ -7381,17 +8743,142 @@ function globToRegex(pattern) {
7381
8743
  }
7382
8744
  i++;
7383
8745
  }
7384
- out += "$";
7385
- return new RegExp(out, RE_DOTALL);
8746
+ out += "$";
8747
+ return new RegExp(out, "s");
8748
+ }
8749
+ function fnmatchCase(value, pattern) {
8750
+ if (!HAS_GLOB.test(pattern)) return pattern === value;
8751
+ return globToRegex(pattern).test(value);
8752
+ }
8753
+ var CASE_BARE_PATTERN = String.raw`(?:[A-Za-z0-9_./:+,@%=-]|\*|\?|\[!?(?:[0-9]-[0-9]|[A-Za-z0-9_.])+\])+`;
8754
+ var CASE_PATTERN = String.raw`(?:` + CASE_BARE_PATTERN + String.raw`|'[^']*'|"[^"\\$\x60]*")`;
8755
+ var CASE_PATTERN_FULL_RE = new RegExp("^(?:" + CASE_PATTERN + ")$");
8756
+ var CASE_PATTERN_ITER_RE = new RegExp(CASE_PATTERN, "g");
8757
+ var CASE_LABEL_FULL_RE = new RegExp(
8758
+ "^(?:" + CASE_PATTERN + String.raw`)(?:[ \t]*\|[ \t]*(?:` + CASE_PATTERN + "))*$"
8759
+ );
8760
+ function matchGlobStrict(pattern, value) {
8761
+ if (!CASE_PATTERN_FULL_RE.test(pattern)) return null;
8762
+ if (pattern.startsWith("'") || pattern.startsWith('"')) {
8763
+ return pattern.slice(1, -1) === value;
8764
+ }
8765
+ if (!/^[\x00-\x7F]*$/.test(value) && (pattern.includes("?") || pattern.includes("["))) {
8766
+ return null;
8767
+ }
8768
+ return fnmatchCase(value, pattern);
8769
+ }
8770
+ function selectCaseBranch(caseStmt, value) {
8771
+ for (let index = 0; index < caseStmt.branches.length; index++) {
8772
+ const label = caseStmt.branches[index].label;
8773
+ if (!CASE_LABEL_FULL_RE.test(label)) return null;
8774
+ CASE_PATTERN_ITER_RE.lastIndex = 0;
8775
+ let m;
8776
+ while ((m = CASE_PATTERN_ITER_RE.exec(label)) !== null) {
8777
+ if (m[0] === "") {
8778
+ CASE_PATTERN_ITER_RE.lastIndex++;
8779
+ continue;
8780
+ }
8781
+ const pattern = m[0];
8782
+ const matched = matchGlobStrict(pattern, value);
8783
+ if (matched === null) return null;
8784
+ if (matched) return [index, pattern === "*" ? "default" : "match"];
8785
+ }
8786
+ }
8787
+ return null;
8788
+ }
8789
+ var DECIMAL_DIGIT_RANGES = [
8790
+ [48, 57],
8791
+ [1632, 1641],
8792
+ [1776, 1785],
8793
+ [1984, 1993],
8794
+ [2406, 2415],
8795
+ [2534, 2543],
8796
+ [2662, 2671],
8797
+ [2790, 2799],
8798
+ [2918, 2927],
8799
+ [3046, 3055],
8800
+ [3174, 3183],
8801
+ [3302, 3311],
8802
+ [3430, 3439],
8803
+ [3558, 3567],
8804
+ [3664, 3673],
8805
+ [3792, 3801],
8806
+ [3872, 3881],
8807
+ [4160, 4169],
8808
+ [4240, 4249],
8809
+ [6112, 6121],
8810
+ [6160, 6169],
8811
+ [6470, 6479],
8812
+ [6608, 6617],
8813
+ [6784, 6793],
8814
+ [6800, 6809],
8815
+ [6992, 7001],
8816
+ [7088, 7097],
8817
+ [7232, 7241],
8818
+ [7248, 7257],
8819
+ [42528, 42537],
8820
+ [43216, 43225],
8821
+ [43264, 43273],
8822
+ [43472, 43481],
8823
+ [43504, 43513],
8824
+ [43600, 43609],
8825
+ [44016, 44025],
8826
+ [65296, 65305],
8827
+ [66720, 66729],
8828
+ [68912, 68921],
8829
+ [69734, 69743],
8830
+ [69872, 69881],
8831
+ [69942, 69951],
8832
+ [70096, 70105],
8833
+ [70384, 70393],
8834
+ [70736, 70745],
8835
+ [70864, 70873],
8836
+ [71248, 71257],
8837
+ [71360, 71369],
8838
+ [71472, 71481],
8839
+ [71904, 71913],
8840
+ [72016, 72025],
8841
+ [72784, 72793],
8842
+ [73040, 73049],
8843
+ [73120, 73129],
8844
+ [92768, 92777],
8845
+ [93008, 93017],
8846
+ [120782, 120831],
8847
+ [123200, 123209],
8848
+ [123632, 123641],
8849
+ [125264, 125273],
8850
+ [130032, 130041]
8851
+ ];
8852
+ function unicodeDigitValue(codePoint) {
8853
+ for (const [start, end] of DECIMAL_DIGIT_RANGES) {
8854
+ if (codePoint >= start && codePoint <= end) {
8855
+ return start === 120782 ? (codePoint - start) % 10 : codePoint - start;
8856
+ }
8857
+ }
8858
+ return null;
8859
+ }
8860
+ function normalizeDecimalDigits(text) {
8861
+ let out = "";
8862
+ for (const ch of text) {
8863
+ const codePoint = ch.codePointAt(0);
8864
+ const digit = unicodeDigitValue(codePoint);
8865
+ out += digit === null ? ch : String(digit);
8866
+ }
8867
+ return out;
7386
8868
  }
7387
- function matchGlob(pattern, value) {
7388
- if (!HAS_GLOB.test(pattern)) return pattern === value;
7389
- return globToRegex(pattern).test(value);
8869
+ function parsePythonInt(text) {
8870
+ const t = normalizeDecimalDigits(text.trim());
8871
+ if (!/^[+-]?\d(?:_?\d)*$/.test(t)) return null;
8872
+ try {
8873
+ return BigInt(t.replace(/_/g, ""));
8874
+ } catch {
8875
+ return null;
8876
+ }
7390
8877
  }
7391
8878
  function evalNumericCompare(op, left, right) {
7392
- const li = parseInt(left, 10);
7393
- const ri = parseInt(right, 10);
7394
- if (isNaN(li) || isNaN(ri)) return null;
8879
+ const li = parsePythonInt(left);
8880
+ const ri = parsePythonInt(right);
8881
+ if (li === null || ri === null) return null;
7395
8882
  switch (op) {
7396
8883
  case "-gt":
7397
8884
  return li > ri;
@@ -7412,99 +8899,203 @@ function resolveVarSide(tok, env2) {
7412
8899
  const ev = evalExpr2(tok, env2);
7413
8900
  return ev.kind === "concrete" ? ev.value : null;
7414
8901
  }
7415
- function evalCondition2(cond, env2) {
7416
- let inner = cond.trim().replace(/^\[\[?|\]\]?$/g, "").trim();
7417
- if (/^-[A-Za-z]\s/.test(inner) || inner.startsWith("-d") || inner.startsWith("-f")) return null;
8902
+ function unquoteConditionToken(tok) {
8903
+ tok = tok.trim();
8904
+ let quoted = false;
8905
+ if (tok.length >= 2 && (tok[0] === '"' || tok[0] === "'") && tok[tok.length - 1] === tok[0]) {
8906
+ tok = tok.slice(1, -1);
8907
+ quoted = true;
8908
+ }
8909
+ if (tok.includes('"') || tok.includes("'") || tok.includes("\\")) return null;
8910
+ return [tok, quoted];
8911
+ }
8912
+ function evalCondition2(cond, env2, diagnostics) {
8913
+ if (diagnostics) {
8914
+ delete diagnostics.condition_operator;
8915
+ delete diagnostics.condition_failure;
8916
+ }
8917
+ const doubleBracket = cond.trim().startsWith("[[");
8918
+ const inner = cond.replace(/^\[\[?|\]\]?$/g, "").trim();
8919
+ if (/^-[A-Za-z]\s/.test(inner) || inner.startsWith("-d") || inner.startsWith("-f")) {
8920
+ if (diagnostics) diagnostics.condition_failure = "unsupported_predicate";
8921
+ return null;
8922
+ }
7418
8923
  const innerQ = inner.replace(/"/g, "").replace(/'/g, "");
7419
8924
  for (const op2 of ["-gt", "-lt", "-eq", "-ge", "-le"]) {
7420
- const re = new RegExp(`\\s${op2}\\s`);
7421
- const opm = re.exec(innerQ);
8925
+ const opm = new RegExp("\\s" + op2 + "\\s").exec(innerQ);
7422
8926
  if (!opm) continue;
7423
8927
  const left2 = innerQ.slice(0, opm.index).trim();
7424
8928
  const right2 = innerQ.slice(opm.index + opm[0].length).trim();
8929
+ if (diagnostics) diagnostics.condition_operator = op2;
7425
8930
  const lv2 = resolveVarSide(left2, env2);
7426
8931
  const rv2 = resolveVarSide(right2, env2);
7427
- if (lv2 === null || rv2 === null) return null;
7428
- return evalNumericCompare(op2, lv2, rv2);
8932
+ if (lv2 === null || rv2 === null) {
8933
+ if (diagnostics) diagnostics.condition_failure = "unbound_operand";
8934
+ return null;
8935
+ }
8936
+ const result = evalNumericCompare(op2, lv2, rv2);
8937
+ if (result === null && diagnostics) diagnostics.condition_failure = "not_integer";
8938
+ return result;
8939
+ }
8940
+ const sm = /(.*?)\s*(=~|==|!=|=)\s*(.*)/.exec(inner);
8941
+ if (!sm) {
8942
+ if (diagnostics) diagnostics.condition_failure = "unsupported_comparison";
8943
+ return null;
7429
8944
  }
7430
- const sm = innerQ.match(/(.*?)\s*(=~|==|!=|=)\s*(.*)/);
7431
- if (!sm) return null;
7432
8945
  const op = sm[2];
7433
- let left = sm[1].trim();
7434
- let right = sm[3].trim();
8946
+ if (diagnostics) diagnostics.condition_operator = op;
8947
+ const leftPair = unquoteConditionToken(sm[1]);
8948
+ const rightPair = unquoteConditionToken(sm[3]);
8949
+ if (leftPair === null || rightPair === null) {
8950
+ if (diagnostics) diagnostics.condition_failure = "unsupported_quoting";
8951
+ return null;
8952
+ }
8953
+ const [left] = leftPair;
8954
+ const [right, rightQuoted] = rightPair;
8955
+ const lv = resolveVarSide(left, env2);
8956
+ if (lv === null) {
8957
+ if (diagnostics) diagnostics.condition_failure = "unbound_operand";
8958
+ return null;
8959
+ }
7435
8960
  if (op === "=~") {
7436
- if (right.startsWith("/") && right.endsWith("/")) right = right.slice(1, -1);
7437
- const lv2 = resolveVarSide(left, env2);
7438
- if (lv2 === null) return null;
8961
+ if (!doubleBracket) {
8962
+ if (diagnostics) diagnostics.condition_failure = "unsupported_operator";
8963
+ return null;
8964
+ }
8965
+ let rv2 = resolveVarSide(right, env2);
8966
+ if (rv2 === null) {
8967
+ if (diagnostics) diagnostics.condition_failure = "unbound_operand";
8968
+ return null;
8969
+ }
8970
+ if (rv2.startsWith("/") && rv2.endsWith("/") && rv2.length > 1) rv2 = rv2.slice(1, -1);
8971
+ const pattern = rightQuoted || right.startsWith("$") ? reescape(rv2) : rv2;
7439
8972
  try {
7440
- return new RegExp(right).test(lv2);
8973
+ return new RegExp(pattern).test(lv);
7441
8974
  } catch {
8975
+ if (diagnostics) diagnostics.condition_failure = "invalid_regex";
7442
8976
  return null;
7443
8977
  }
7444
8978
  }
7445
- const lv = resolveVarSide(left, env2);
7446
8979
  const rv = resolveVarSide(right, env2);
7447
- if (lv === null || rv === null) return null;
7448
- const matched = /[*?[]/.test(rv) ? matchGlob(rv, lv) : lv === rv;
8980
+ if (rv === null) {
8981
+ if (diagnostics) diagnostics.condition_failure = "unbound_operand";
8982
+ return null;
8983
+ }
8984
+ const glob = rv.includes("*") || rv.includes("?") || rv.includes("[");
8985
+ let matched;
8986
+ if (!rightQuoted && (glob || right.startsWith("$"))) {
8987
+ if (!doubleBracket) {
8988
+ if (diagnostics) diagnostics.condition_failure = "pathname_expansion";
8989
+ return null;
8990
+ }
8991
+ matched = glob ? fnmatchCase(lv, rv) : lv === rv;
8992
+ } else {
8993
+ matched = lv === rv;
8994
+ }
7449
8995
  return op === "!=" ? !matched : matched;
7450
8996
  }
7451
- function symbolicProcess(content, entryArgs) {
7452
- if (!content) return null;
7453
- const stmts = tokenize(content);
7454
- if (!stmts.some((s) => s.kind === "case" || s.kind === "if" || s.kind === "assign")) return null;
7455
- if (stmts.some((s) => !s.modelable)) return null;
8997
+ function symbolicProcess(content, entryArgs, diagnostics) {
8998
+ const recordResult = (reason, budget2 = null, variables = 0) => {
8999
+ if (!diagnostics) return;
9000
+ diagnostics.result = reason ? "none" : "text";
9001
+ diagnostics.fallback_reason = reason;
9002
+ diagnostics.lines = budget2 ? budget2.lines : 0;
9003
+ diagnostics.branches = budget2 ? budget2.branches : 0;
9004
+ diagnostics.variables = variables;
9005
+ };
9006
+ if (diagnostics) {
9007
+ diagnostics.line_limit = MAX_LINES2;
9008
+ diagnostics.branch_limit = MAX_BRANCHES;
9009
+ diagnostics.variable_limit = MAX_VARS;
9010
+ }
9011
+ if (content === null || content === void 0) {
9012
+ recordResult("empty");
9013
+ return null;
9014
+ }
9015
+ const stmts = splitStatements(content);
9016
+ if (diagnostics) {
9017
+ diagnostics.statement_count = stmts.length;
9018
+ const unsupported = stmts.find((s) => s.kind === "not_modeled");
9019
+ if (unsupported !== void 0) diagnostics.unsupported = unsupported.reason;
9020
+ }
9021
+ if (!stmts.some((s) => s.kind === "case" || s.kind === "if" || s.kind === "assign")) {
9022
+ recordResult(stmts.length ? "no_modeled_statements" : "empty");
9023
+ return null;
9024
+ }
9025
+ if (stmts.some((s) => !s.modelable)) {
9026
+ recordResult("unsupported_statement");
9027
+ return null;
9028
+ }
9029
+ const budget = { lines: 0, branches: 0 };
7456
9030
  const env2 = initEnv(entryArgs);
7457
- if (env2.size > MAX_VARS) return null;
7458
- let linesBudget = 0;
7459
- let branchesBudget = 0;
7460
- let modelable = false;
9031
+ if (env2.size > MAX_VARS) {
9032
+ recordResult("variable_budget", budget, env2.size);
9033
+ return null;
9034
+ }
7461
9035
  const out = [];
9036
+ let modelableEncountered = false;
9037
+ const choices = diagnostics ? [] : null;
9038
+ if (diagnostics) diagnostics.choices = choices;
7462
9039
  for (const s of stmts) {
7463
- linesBudget++;
7464
- if (linesBudget > MAX_LINES2) return null;
9040
+ budget.lines += 1;
9041
+ if (budget.lines > MAX_LINES2 || budget.branches > MAX_BRANCHES) {
9042
+ recordResult("line_budget", budget, env2.size);
9043
+ return null;
9044
+ }
7465
9045
  if (s.kind === "assign") {
7466
- modelable = true;
7467
- if (!env2.has(s.name) && env2.size >= MAX_VARS) return null;
7468
- const v = evalExpr2(s.rhs, env2);
7469
- env2.set(s.name, fold(v));
9046
+ if (!env2.has(s.name) && env2.size >= MAX_VARS) {
9047
+ recordResult("variable_budget", budget, env2.size);
9048
+ return null;
9049
+ }
9050
+ modelableEncountered = true;
9051
+ env2.set(s.name, fold(evalExpr2(s.rhs, env2)));
7470
9052
  out.push(s.line);
7471
9053
  continue;
7472
9054
  }
7473
9055
  if (s.kind === "case") {
7474
- modelable = true;
7475
- branchesBudget += s.branches.length;
7476
- if (branchesBudget > MAX_BRANCHES) return null;
9056
+ modelableEncountered = true;
9057
+ budget.branches += s.branches.length;
9058
+ if (budget.branches > MAX_BRANCHES) {
9059
+ recordResult("branch_budget", budget, env2.size);
9060
+ return null;
9061
+ }
7477
9062
  const selVal = fold(evalExpr2(s.selector, env2));
7478
- if (selVal.kind !== "concrete") return null;
7479
- const concrete = selVal.value || "";
7480
- let selected = null;
7481
- let fallback = "";
7482
- for (const b of s.branches) {
7483
- const patStripped = b.pat.trim();
7484
- if (patStripped === "*") {
7485
- fallback = b.body;
7486
- continue;
7487
- }
7488
- if (matchGlob(patStripped, concrete)) {
7489
- selected = b.body;
7490
- break;
7491
- }
9063
+ if (selVal.kind !== "concrete") {
9064
+ recordResult("unbound_selector", budget, env2.size);
9065
+ return null;
9066
+ }
9067
+ const selection = selectCaseBranch(s, selVal.value || "");
9068
+ if (selection === null) {
9069
+ recordResult("case_unresolved", budget, env2.size);
9070
+ return null;
9071
+ }
9072
+ const [index, kind] = selection;
9073
+ if (choices !== null && choices.length < 4) {
9074
+ choices.push(`${kind === "default" ? "case_default" : "case"}:${index + 1}`);
7492
9075
  }
7493
- const final = selected !== null ? selected : fallback || null;
7494
- if (final === null) return null;
7495
9076
  out.push(`case ${s.selector} in
7496
- ${final}
9077
+ ${s.branches[index].body}
7497
9078
  esac`);
7498
9079
  continue;
7499
9080
  }
7500
9081
  if (s.kind === "if") {
7501
- modelable = true;
7502
- branchesBudget++;
7503
- if (branchesBudget > MAX_BRANCHES) return null;
7504
- const truth = evalCondition2(s.cond, env2);
7505
- if (truth === null) return null;
9082
+ modelableEncountered = true;
9083
+ budget.branches += 1;
9084
+ if (budget.branches > MAX_BRANCHES) {
9085
+ recordResult("branch_budget", budget, env2.size);
9086
+ return null;
9087
+ }
9088
+ const truth = evalCondition2(s.cond, env2, diagnostics);
9089
+ if (truth === null) {
9090
+ recordResult("condition_unresolved", budget, env2.size);
9091
+ return null;
9092
+ }
7506
9093
  const chosen = truth ? s.thenBody : s.elseBody;
7507
- if (chosen === null) return null;
9094
+ if (chosen === null) {
9095
+ recordResult("missing_else", budget, env2.size);
9096
+ return null;
9097
+ }
9098
+ if (choices !== null && choices.length < 4) choices.push(truth ? "then" : "else");
7508
9099
  out.push(`if ${s.cond}; then
7509
9100
  ${chosen}
7510
9101
  fi`);
@@ -7512,206 +9103,451 @@ fi`);
7512
9103
  }
7513
9104
  out.push(s.line);
7514
9105
  }
7515
- if (!modelable) return null;
9106
+ if (!modelableEncountered) {
9107
+ recordResult("no_modeled_statements", budget, env2.size);
9108
+ return null;
9109
+ }
9110
+ recordResult("", budget, env2.size);
7516
9111
  return out.join("\n");
7517
9112
  }
7518
9113
 
7519
9114
  // src/engine/script-engine/backends/shell-backend.ts
7520
- function bindPositionalArgs(content, args) {
7521
- if (!args.length) return content;
7522
- const allArgs = args.join(" ");
7523
- content = content.replace(/\$\{(\d+|@|\*)(?::?[-]?([^}]*))?\}/g, (full, kind, defv) => {
7524
- if (kind === "@" || kind === "*") return allArgs;
7525
- if (!/^\d+$/.test(kind)) return full;
7526
- const idx = parseInt(kind, 10);
7527
- if (1 <= idx && idx <= args.length) return args[idx - 1];
7528
- return defv !== void 0 ? defv : "";
7529
- });
7530
- content = content.replace(/\$\{(\d+)\}/g, (full, kind) => {
7531
- const idx = parseInt(kind, 10);
7532
- if (1 <= idx && idx <= args.length) return args[idx - 1];
7533
- return "";
7534
- });
7535
- content = content.replace(/\$(\d+)/g, (full, kind) => {
7536
- const idx = parseInt(kind, 10);
7537
- if (1 <= idx && idx <= args.length) return args[idx - 1];
7538
- return "";
7539
- });
7540
- content = content.replace(/\$[@*]/g, allArgs);
7541
- return content;
9115
+ var POSITIONAL_RE = /\$(?:([1-9@*])|\{([1-9][0-9]*|[@*])(?:(:-|-)|\}))/;
9116
+ function positionalMatch(token) {
9117
+ const m = POSITIONAL_RE.exec(token);
9118
+ return m !== null && m.index === 0 ? m : null;
9119
+ }
9120
+ var QUOTED_WORD_PART = String.raw`\$\{|\\[\s\S]|\$[1-9@*]`;
9121
+ var SHELL_WORD_PART = String.raw`'[^']*'|"|` + QUOTED_WORD_PART;
9122
+ var SHELL_SOURCE_PART = String.raw`\#|` + SHELL_WORD_PART;
9123
+ var SUBSTITUTION_START = String.raw`\$\(|\x60`;
9124
+ var DEFAULT_WORD_PART = SUBSTITUTION_START + "|" + SHELL_WORD_PART;
9125
+ var QUOTED_DEFAULT_PART = SUBSTITUTION_START + String.raw`|"|` + QUOTED_WORD_PART;
9126
+ var DOUBLE_QUOTE_END_PART = String.raw`\\[\s\S]|\$\{|` + SUBSTITUTION_START + String.raw`|"`;
9127
+ var DEFAULT_BOUNDARY_PART = String.raw`\\[\s\S]|'[^']*'|"|\$\{|` + SUBSTITUTION_START + String.raw`|[}']`;
9128
+ var SUBSTITUTION_BOUNDARY_PART = String.raw`\\[\s\S]|'[^']*'|"|\$\{|` + SUBSTITUTION_START + String.raw`|[()']|<<` + String.raw`|(?<![^\s;&|()<>])(?:\#[^\n]*|case(?=[ \t]))`;
9129
+ var BACKTICK_PART = String.raw`\x60(?:\\[\s\S]|[^\x60\\])*\x60`;
9130
+ var BACKTICK_ANCHORED_RE = new RegExp("^(?:" + BACKTICK_PART + ")");
9131
+ var SHELL_IFS_RE = /([ \t\n]+)/;
9132
+ var UNRESOLVED = /* @__PURE__ */ Symbol("unresolved");
9133
+ function substitutionEnd(text, startPos, opening, level) {
9134
+ if (level >= MAX_DEFAULT_DEPTH) return null;
9135
+ if (opening === "`") {
9136
+ const m = BACKTICK_ANCHORED_RE.exec(text.slice(startPos - 1));
9137
+ return m ? startPos - 1 + m[0].length : null;
9138
+ }
9139
+ let depth = 1;
9140
+ let start = startPos;
9141
+ const boundary = new RegExp(SUBSTITUTION_BOUNDARY_PART, "g");
9142
+ while (start !== null) {
9143
+ boundary.lastIndex = start;
9144
+ const token = boundary.exec(text);
9145
+ if (!token) return null;
9146
+ const part = token[0];
9147
+ start = token.index + part.length;
9148
+ if (part === "(" || part === "$(") {
9149
+ depth += 1;
9150
+ } else if (part === ")") {
9151
+ depth -= 1;
9152
+ if (!depth) return start;
9153
+ } else if (part === '"') {
9154
+ start = doubleQuoteEnd(text, start, level + 1);
9155
+ } else if (part === "${") {
9156
+ start = bracedWordEnd(text, start, level + 1);
9157
+ } else if (part === "`") {
9158
+ start = substitutionEnd(text, start, part, level + 1);
9159
+ } else if (part === "'" || part === "<<" || part === "case") {
9160
+ return null;
9161
+ }
9162
+ }
9163
+ return null;
7542
9164
  }
7543
- function findSelectorValue(selector, args) {
7544
- if (!args || !args.length) return null;
7545
- const m = selector.match(/^\$\{?(\d+)\}?$/);
7546
- if (m) {
7547
- const idx = parseInt(m[1], 10);
7548
- if (1 <= idx && idx <= args.length) return args[idx - 1];
7549
- return null;
9165
+ function bracedWordEnd(text, startPos, level = 0) {
9166
+ if (level >= MAX_DEFAULT_DEPTH) return null;
9167
+ let depth = 1;
9168
+ let start = startPos;
9169
+ const boundary = new RegExp(DEFAULT_BOUNDARY_PART, "g");
9170
+ while (start !== null) {
9171
+ boundary.lastIndex = start;
9172
+ const token = boundary.exec(text);
9173
+ if (!token) return null;
9174
+ const part = token[0];
9175
+ start = token.index + part.length;
9176
+ if (part === "${") {
9177
+ depth += 1;
9178
+ } else if (part === "}") {
9179
+ depth -= 1;
9180
+ if (!depth) return start;
9181
+ } else if (part === "$(" || part === "`") {
9182
+ start = substitutionEnd(text, start, part, level + 1);
9183
+ } else if (part === '"') {
9184
+ start = doubleQuoteEnd(text, start, level + 1);
9185
+ } else if (part === "'") {
9186
+ return null;
9187
+ }
7550
9188
  }
7551
9189
  return null;
7552
9190
  }
7553
- function splitCaseBody(body) {
7554
- const lines = body.split("\n");
7555
- const branches = [];
7556
- let cur = null;
7557
- for (const ln of lines) {
7558
- const stripped = ln.trim();
7559
- if (/^[\w:-]+\s*\(\)\s*\{/.test(stripped)) continue;
7560
- const m = stripped.match(/^([^()]+?)\s*\)\s*(.*)$/);
7561
- if (m) {
7562
- const pat = m[1].trim().replace(/^["']|["']$/g, "");
7563
- const inline = m[2].trim();
7564
- if (pat) {
7565
- if (cur) branches.push(cur);
7566
- cur = { label: pat, body: inline };
7567
- }
9191
+ function doubleQuoteEnd(text, startPos, level = 0) {
9192
+ if (level >= MAX_DEFAULT_DEPTH) return null;
9193
+ let start = startPos;
9194
+ const boundary = new RegExp(DOUBLE_QUOTE_END_PART, "g");
9195
+ while (start !== null) {
9196
+ boundary.lastIndex = start;
9197
+ const token = boundary.exec(text);
9198
+ if (!token) return null;
9199
+ const part = token[0];
9200
+ if (part === '"') return token.index + part.length;
9201
+ start = token.index + part.length;
9202
+ if (part === "${") {
9203
+ start = bracedWordEnd(text, start, level + 1);
9204
+ } else if (part === "$(" || part === "`") {
9205
+ start = substitutionEnd(text, start, part, level + 1);
9206
+ }
9207
+ }
9208
+ return null;
9209
+ }
9210
+ function* shellWordParts(text, quoted = false, opts = {}) {
9211
+ const syntax = opts.syntax === void 0 ? null : opts.syntax;
9212
+ const defaultText = opts.defaultText === true;
9213
+ let patternSource;
9214
+ if (defaultText) {
9215
+ patternSource = quoted ? QUOTED_DEFAULT_PART : DEFAULT_WORD_PART;
9216
+ } else if (quoted) {
9217
+ patternSource = QUOTED_WORD_PART;
9218
+ } else {
9219
+ patternSource = syntax !== null ? SHELL_SOURCE_PART : SHELL_WORD_PART;
9220
+ }
9221
+ const pattern = new RegExp(patternSource, "g");
9222
+ let offset = 0;
9223
+ while (true) {
9224
+ pattern.lastIndex = offset;
9225
+ const token = pattern.exec(text);
9226
+ if (!token) return;
9227
+ const part = token[0];
9228
+ let end = token.index + part.length;
9229
+ if (part === "#" && syntax !== null && syntax[token.index] === " ") {
9230
+ const newline = text.indexOf("\n", end);
9231
+ if (newline < 0) return;
9232
+ offset = newline + 1;
9233
+ continue;
9234
+ }
9235
+ if (part === "${") {
9236
+ end = bracedWordEnd(text, end);
9237
+ } else if (part === '"') {
9238
+ end = doubleQuoteEnd(text, end);
9239
+ } else if (part === "$(" || part === "`") {
9240
+ end = substitutionEnd(text, end, part, 0);
9241
+ }
9242
+ if (end === null) {
9243
+ if (syntax === null) return;
9244
+ const newline = text.indexOf("\n", token.index + part.length);
9245
+ if (newline < 0) return;
9246
+ offset = newline + 1;
7568
9247
  continue;
7569
9248
  }
7570
- if (cur) {
7571
- cur.body += cur.body ? "\n" + ln : ln;
7572
- if (stripped.endsWith(";;")) {
7573
- branches.push(cur);
7574
- cur = null;
9249
+ yield [token.index, end];
9250
+ offset = end;
9251
+ }
9252
+ }
9253
+ var MAX_DEFAULT_DEPTH = 32;
9254
+ function* splitFields(text) {
9255
+ const parts = text.split(SHELL_IFS_RE);
9256
+ for (let index = 0; index < parts.length; index++) {
9257
+ if (index % 2) yield null;
9258
+ else if (parts[index]) yield parts[index];
9259
+ }
9260
+ }
9261
+ function positionalValue(token, args) {
9262
+ const part = positionalMatch(token);
9263
+ if (part === null) return [token, false];
9264
+ const name = part[1] || part[2];
9265
+ const operator = part[3];
9266
+ if (name === "@") return [args, false];
9267
+ if (name === "*") return [args.join(" "), false];
9268
+ const index = name.length <= String(args.length).length ? parseInt(name, 10) - 1 : args.length;
9269
+ if (index < args.length && (operator !== ":-" || args[index])) {
9270
+ return [args[index], false];
9271
+ }
9272
+ return operator ? [token.slice(part[0].length, -1), true] : ["", false];
9273
+ }
9274
+ function defaultHasSubstitution(text, quoted) {
9275
+ for (const [start, end] of shellWordParts(text, quoted, { defaultText: true })) {
9276
+ const part = text.slice(start, end);
9277
+ if (part.startsWith("$(") || part.startsWith("`")) return true;
9278
+ if (part.startsWith('"') && defaultHasSubstitution(part.slice(1, -1), true)) return true;
9279
+ }
9280
+ return false;
9281
+ }
9282
+ function* argumentParts(word, args, opts = {}) {
9283
+ const quoted = opts.quoted === true;
9284
+ const defaultText = opts.defaultText === true;
9285
+ const defaultDepth = opts.defaultDepth ?? 0;
9286
+ const fieldSplit = !quoted;
9287
+ let offset = 0;
9288
+ for (const [start, end] of shellWordParts(word, quoted, { defaultText })) {
9289
+ if (start > offset) {
9290
+ const literal = word.slice(offset, start);
9291
+ if (fieldSplit) yield* splitFields(literal);
9292
+ else yield literal;
9293
+ }
9294
+ offset = end;
9295
+ const text = word.slice(start, end);
9296
+ if (!quoted && text.startsWith("'")) {
9297
+ yield text.slice(1, -1);
9298
+ } else if (text.startsWith('"')) {
9299
+ if (text === '""') {
9300
+ yield "";
9301
+ } else {
9302
+ yield* argumentParts(text.slice(1, -1), args, { quoted: true, defaultDepth });
9303
+ }
9304
+ } else if (text.startsWith("\\")) {
9305
+ const escaped = text.slice(1);
9306
+ if (escaped !== "\n") {
9307
+ const specials = defaultText ? '$"\\`}' : '$"\\`';
9308
+ yield !quoted || specials.includes(escaped) ? escaped : text;
9309
+ }
9310
+ } else if (positionalMatch(text) === null) {
9311
+ yield text;
9312
+ } else if (args === null) {
9313
+ yield UNRESOLVED;
9314
+ } else {
9315
+ const [value, useDefault] = positionalValue(text, args);
9316
+ if (useDefault) {
9317
+ if (defaultDepth >= MAX_DEFAULT_DEPTH || defaultHasSubstitution(value, quoted)) {
9318
+ yield UNRESOLVED;
9319
+ continue;
9320
+ }
9321
+ yield* argumentParts(value, args, {
9322
+ quoted,
9323
+ defaultText: true,
9324
+ defaultDepth: defaultDepth + 1
9325
+ });
9326
+ if (!value && !fieldSplit) yield "";
9327
+ } else if (!fieldSplit && Array.isArray(value)) {
9328
+ for (let index = 0; index < value.length; index++) {
9329
+ if (index) yield null;
9330
+ yield value[index];
9331
+ }
9332
+ } else if (!fieldSplit) {
9333
+ yield value;
9334
+ } else {
9335
+ yield* splitFields(Array.isArray(value) ? value.join(" ") : value);
7575
9336
  }
7576
9337
  }
7577
9338
  }
7578
- if (cur && cur.body.trim()) {
7579
- if (!branches.includes(cur)) branches.push(cur);
9339
+ if (offset < word.length) {
9340
+ const literal = word.slice(offset);
9341
+ if (fieldSplit) yield* splitFields(literal);
9342
+ else yield literal;
7580
9343
  }
7581
- return branches;
7582
9344
  }
7583
- function parseCase(content, args) {
7584
- const m = content.match(/\bcase\s+(\$\{?\d+\}?|[A-Za-z_]\w*|\$[A-Za-z_]\w*)\s+in/i);
7585
- if (!m) return null;
7586
- const selector = m[1].trim();
7587
- const val = findSelectorValue(selector, args);
7588
- if (val === null) return null;
7589
- const lines = content.split("\n");
7590
- const endMatch = findCaseEndInLines(lines, 0);
7591
- if (endMatch === -1) return null;
7592
- const bodyLines = lines.slice(1, endMatch);
7593
- const body = bodyLines.join("\n");
7594
- const hasNested = /\bcase\s+/.test(body) || /\bif\s+/.test(body);
7595
- let final;
7596
- if (hasNested) {
7597
- final = splitNestedCaseBranches(bodyLines, val);
7598
- if (final === null) return null;
7599
- } else {
7600
- const branches = splitCaseBody(body);
7601
- let selected = null;
7602
- let fallback = "";
7603
- for (const b of branches) {
7604
- const values = b.label.split("|").map((v) => v.trim()).filter(Boolean);
7605
- if (values.includes("*")) fallback = b.body;
7606
- else if (values.includes(val)) selected = b.body;
7607
- }
7608
- final = selected !== null ? selected : fallback || null;
7609
- if (final === null) return null;
7610
- }
7611
- const prefix = content.slice(0, m.index ?? 0);
7612
- const suffix = lines.slice(endMatch + 1).join("\n");
7613
- return `${prefix}
7614
- ${final}
7615
- ${suffix}`;
7616
- }
7617
- function findCaseEndInLines(lines, headerLine) {
7618
- let depth = 0;
7619
- for (let idx = headerLine; idx < lines.length; idx++) {
7620
- const ln = lines[idx];
7621
- const opens = (ln.match(/\bcase\b/g) || []).length;
7622
- const closes = (ln.match(/\besac\b/g) || []).length;
7623
- depth += opens - closes;
7624
- if (depth <= 0 && idx > headerLine) return idx;
9345
+ function expandShellWord(word, args, opts = {}) {
9346
+ const quotedDefault = opts.quotedDefault === true;
9347
+ const fields = [];
9348
+ let pieces = [];
9349
+ for (const part of argumentParts(word, args, {
9350
+ quoted: quotedDefault,
9351
+ defaultText: quotedDefault
9352
+ })) {
9353
+ if (part === UNRESOLVED) return null;
9354
+ if (part !== null) {
9355
+ pieces.push(part);
9356
+ } else if (pieces.length) {
9357
+ fields.push(pieces.join(""));
9358
+ pieces = [];
9359
+ }
7625
9360
  }
7626
- return -1;
9361
+ if (pieces.length) fields.push(pieces.join(""));
9362
+ return fields;
7627
9363
  }
7628
- function splitNestedCaseBranches(bodyLines, selectorVal) {
7629
- let depth = 0;
7630
- let curPat = null;
7631
- let curBody = [];
7632
- let selected = null;
7633
- let fallback = null;
7634
- const flush = () => {
7635
- if (curPat === null) return;
7636
- const values = curPat.split("|").map((v) => v.trim()).filter(Boolean);
7637
- const body = curBody.join("\n");
7638
- if (values.includes("*")) {
7639
- if (fallback === null) fallback = body;
7640
- } else if (values.includes(selectorVal)) {
7641
- selected = body;
7642
- }
7643
- curPat = null;
7644
- curBody = [];
7645
- };
7646
- for (const ln of bodyLines) {
7647
- const stripped = ln.trim();
7648
- if (depth === 0) {
7649
- const bm = stripped.match(/^([^()]+?)\s*\)\s*(.*)$/);
7650
- if (bm) {
7651
- if (curPat !== null) flush();
7652
- curPat = bm[1].trim().replace(/^["']|["']$/g, "");
7653
- curBody = bm[2].trim() ? [bm[2].trim()] : [];
7654
- continue;
9364
+ function bindPositionalArgs(content, args) {
9365
+ if (!args.length || !content.includes("$")) return content;
9366
+ const bindText = (text, quoted = false) => {
9367
+ const out = [];
9368
+ let offset = 0;
9369
+ let syntax = null;
9370
+ if (!quoted) syntax = text.includes("#") ? caseSyntaxLines(text).join("\n") : text;
9371
+ for (const [start, end] of shellWordParts(text, quoted, { syntax })) {
9372
+ const token = text.slice(start, end);
9373
+ out.push(text.slice(offset, start));
9374
+ offset = end;
9375
+ if (token.startsWith('"')) {
9376
+ out.push('"' + bindText(token.slice(1, -1), true) + '"');
9377
+ } else if (positionalMatch(token)) {
9378
+ const [value, useDefault] = positionalValue(token, args);
9379
+ let values = Array.isArray(value) ? value : [value];
9380
+ if (useDefault) {
9381
+ if (defaultHasSubstitution(values[0], quoted)) {
9382
+ out.push(token);
9383
+ continue;
9384
+ }
9385
+ const expanded = expandShellWord(values[0], args, { quotedDefault: quoted });
9386
+ if (expanded === null) {
9387
+ out.push(token);
9388
+ continue;
9389
+ }
9390
+ values = expanded;
9391
+ }
9392
+ if (quoted) values = values.map((item) => item.replace(/([\\$"`])/g, "\\$1"));
9393
+ out.push(values.join(quoted ? '" "' : " "));
9394
+ } else {
9395
+ out.push(token);
7655
9396
  }
7656
9397
  }
7657
- if (/\bcase\b/.test(stripped)) depth += 1;
7658
- else if (/\besac\b/.test(stripped)) depth = Math.max(0, depth - 1);
7659
- else if (curPat !== null) {
7660
- curBody.push(ln);
7661
- if (depth === 0 && stripped.endsWith(";;")) flush();
9398
+ out.push(text.slice(offset));
9399
+ return out.join("");
9400
+ };
9401
+ return bindText(content);
9402
+ }
9403
+ function findSelectorValue(selector, args) {
9404
+ if (!args || !args.length) return null;
9405
+ const m = selector.match(/^\$\{?(\d+)\}?$/);
9406
+ if (m) {
9407
+ const idx = parseInt(m[1], 10);
9408
+ if (1 <= idx && idx <= args.length) return args[idx - 1];
9409
+ return null;
9410
+ }
9411
+ return null;
9412
+ }
9413
+ function parseCase(content, args, diagnostics) {
9414
+ if (!args || !args.length || !CASE_HEADER_RE.test(content)) return null;
9415
+ const lines = content.split("\n");
9416
+ const syntaxLines = caseSyntaxLines(content);
9417
+ let index = -1;
9418
+ for (let i = 0; i < syntaxLines.length; i++) {
9419
+ if (CASE_HEADER_RE.test(syntaxLines[i])) {
9420
+ index = i;
9421
+ break;
7662
9422
  }
7663
9423
  }
7664
- if (curPat !== null && curBody.length) flush();
7665
- return selected !== null ? selected : fallback;
9424
+ if (index < 0) return null;
9425
+ const caseStmt = parseCaseStatement(lines, syntaxLines, index);
9426
+ if (caseStmt === null) return null;
9427
+ const value = findSelectorValue(caseStmt.selector, args);
9428
+ if (value === null) return null;
9429
+ const selection = selectCaseBranch(caseStmt, value);
9430
+ if (selection === null) return null;
9431
+ const [branch, kind] = selection;
9432
+ if (diagnostics) diagnostics.p1_case = kind;
9433
+ const end = index + caseStmt.line.split("\n").length;
9434
+ return [...lines.slice(0, index), caseStmt.branches[branch].body, ...lines.slice(end)].join("\n");
9435
+ }
9436
+ function unquoteIfToken(tok) {
9437
+ tok = tok.trim();
9438
+ let quoted = false;
9439
+ if (tok.length >= 2 && (tok[0] === '"' || tok[0] === "'") && tok[tok.length - 1] === tok[0]) {
9440
+ tok = tok.slice(1, -1);
9441
+ quoted = true;
9442
+ }
9443
+ if (tok.includes('"') || tok.includes("'") || tok.includes("\\")) return null;
9444
+ return [tok, quoted];
7666
9445
  }
7667
9446
  function evalIfCondition(cond, args) {
7668
9447
  if (!args || !args.length) return null;
7669
- const inner = cond.replace(/^\[\[?|\]\]?$/g, "").replace(/"/g, "").replace(/'/g, "").trim();
7670
- const m = inner.match(/(.*?)\s*(=~|==|!=|=)\s*(.*)/);
9448
+ const doubleBracket = cond.trimStart().startsWith("[[");
9449
+ const inner = cond.replace(/^\[\[?|\]\]?$/g, "").trim();
9450
+ const m = /(.*?)\s*(=~|==|!=|=)\s*(.*)/.exec(inner);
7671
9451
  if (!m) return null;
7672
9452
  const op = m[2];
7673
- let left = m[1].trim();
7674
- let right = m[3].trim();
9453
+ const leftPair = unquoteIfToken(m[1]);
9454
+ const rightPair = unquoteIfToken(m[3]);
9455
+ if (leftPair === null || rightPair === null) return null;
9456
+ const [left] = leftPair;
9457
+ const [right, rightQuoted] = rightPair;
7675
9458
  const resolve12 = (tok) => {
7676
9459
  const rm = tok.match(/^\$(\d+)$/);
7677
9460
  if (rm) {
7678
9461
  const idx = parseInt(rm[1], 10);
7679
9462
  return 1 <= idx && idx <= args.length ? args[idx - 1] : null;
7680
9463
  }
7681
- return tok.startsWith("$") ? null : tok;
9464
+ if (tok.startsWith("$")) return null;
9465
+ return tok;
7682
9466
  };
7683
9467
  const lv = resolve12(left);
7684
9468
  const rv = resolve12(right);
7685
9469
  if (lv === null || rv === null) return null;
7686
9470
  if (op === "=~") {
7687
- let re = rv;
7688
- if (re.startsWith("/") && re.endsWith("/") && re.length > 1) re = re.slice(1, -1);
9471
+ if (!doubleBracket) return null;
9472
+ let pattern = rv;
9473
+ if (pattern.startsWith("/") && pattern.endsWith("/") && pattern.length > 1) {
9474
+ pattern = pattern.slice(1, -1);
9475
+ }
9476
+ const source = rightQuoted ? escapeRegex(pattern) : pattern;
7689
9477
  try {
7690
- return new RegExp(re).test(lv);
9478
+ return new RegExp(source).test(lv);
7691
9479
  } catch {
7692
9480
  return null;
7693
9481
  }
7694
9482
  }
7695
- const matched = /[*?[]/.test(rv) ? matchGlob(rv, lv) : lv === rv;
9483
+ let matched;
9484
+ if (!rightQuoted && (rv.includes("*") || rv.includes("?") || rv.includes("["))) {
9485
+ if (!doubleBracket) {
9486
+ return null;
9487
+ }
9488
+ matched = fnmatchCase2(lv, rv);
9489
+ } else {
9490
+ matched = lv === rv;
9491
+ }
7696
9492
  return op === "!=" ? !matched : matched;
7697
9493
  }
7698
- function parseIf(content, args) {
7699
- const m = content.match(/\bif\s+([^\n;]+?)\s*;\s*then/i);
9494
+ function escapeRegex(s) {
9495
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
9496
+ }
9497
+ function fnmatchCase2(value, pattern) {
9498
+ if (!/[*?[]/.test(pattern)) return pattern === value;
9499
+ let out = "^";
9500
+ let i = 0;
9501
+ while (i < pattern.length) {
9502
+ const c = pattern[i];
9503
+ if (c === "*") out += ".*";
9504
+ else if (c === "?") out += ".";
9505
+ else if (c === "[") {
9506
+ let j = i + 1;
9507
+ let neg = false;
9508
+ if (j < pattern.length && (pattern[j] === "!" || pattern[j] === "^")) {
9509
+ neg = true;
9510
+ j++;
9511
+ }
9512
+ let cls = "";
9513
+ while (j < pattern.length && pattern[j] !== "]") {
9514
+ cls += pattern[j];
9515
+ j++;
9516
+ }
9517
+ if (j >= pattern.length) {
9518
+ out += escapeRegex(pattern.slice(i));
9519
+ break;
9520
+ }
9521
+ out += "[" + (neg ? "^" : "") + escapeRegex(cls) + "]";
9522
+ i = j;
9523
+ } else {
9524
+ out += escapeRegex(c);
9525
+ }
9526
+ i++;
9527
+ }
9528
+ out += "$";
9529
+ return new RegExp(out, "s").test(value);
9530
+ }
9531
+ function parseIf(content, args, diagnostics) {
9532
+ const m = /\bif\s+([^\n;]+?)\s*;\s*then/.exec(content);
7700
9533
  if (!m) return null;
7701
- const truth = evalIfCondition(m[1].trim(), args);
9534
+ const cond = m[1].trim();
9535
+ const truth = evalIfCondition(cond, args);
7702
9536
  if (truth === null) return null;
7703
- const start = m.index ?? 0;
9537
+ const start = m.index;
7704
9538
  const thenBodyStart = start + m[0].length;
7705
9539
  const fiPos = content.indexOf("fi", thenBodyStart);
7706
9540
  if (fiPos === -1) return null;
7707
9541
  const segment = content.slice(thenBodyStart, fiPos);
7708
- const elseM = segment.match(/\belse\b/);
9542
+ const elseM = /\belse\b/.exec(segment);
7709
9543
  let chosen;
7710
- if (truth) chosen = elseM ? segment.slice(0, elseM.index) : segment;
7711
- else {
9544
+ if (truth) {
9545
+ chosen = elseM ? segment.slice(0, elseM.index) : segment;
9546
+ } else {
7712
9547
  if (!elseM) return null;
7713
- chosen = segment.slice((elseM.index ?? 0) + 4);
9548
+ chosen = segment.slice(elseM.index + 4);
7714
9549
  }
9550
+ if (diagnostics) diagnostics.p1_if = truth ? "then" : "else";
7715
9551
  return `${content.slice(0, start)}
7716
9552
  ${chosen}
7717
9553
  ${content.slice(fiPos + 2)}`;
@@ -7741,56 +9577,130 @@ function stripNonExecutableLines(content) {
7741
9577
  function markLoopsReachable(content) {
7742
9578
  return content;
7743
9579
  }
7744
- var CHILD_CALL_RE2 = /(?:^|\s|&&|\|\|)\s*((?:\/bin\/)?bash|sh|zsh|(?:python|python3|node|ruby|perl|php|lua))\s+(\S+(?:\.(?:sh|shrc|py|js|rb|pl|php|lua))?)([^\n;|&]*?)$/gmi;
7745
- function extractCallsFromContent(content) {
9580
+ var CHILD_INTERPRETER_RE = /\b(?:bash|sh|zsh|python(?:3(?:\.[0-9]+)?)?|node|ruby|perl|php|lua)\b/;
9581
+ var CHILD_CALL_SOURCE = String.raw`(?:^[ \t]*(?:\(?[^()\n;&<>]+\)[ \t]*)?|(?<=[;&|])(?<![<>][&|]))[ \t]*` + String.raw`(?:(?:if|then|elif|else|while|until|do|!|\{)[ \t]+|\([ \t]*` + String.raw`|command(?:[ \t]+-p)?(?:[ \t]+--)?[ \t]+` + String.raw`|exec(?:[ \t]+(?:-[cl]+|-a[ \t]+[^ \t\n;&|<>()\x00]+))*(?:[ \t]+--)?[ \t]+` + String.raw`|(?:(?:/usr)?/bin/)?time(?:[ \t]+-p)?(?:[ \t]+--)?[ \t]+` + String.raw`|(?:(?:/usr)?/bin/)?env(?:[ \t]+(?:-i|--ignore-environment` + String.raw`|(?:-u[ \t]*|--unset(?:[ \t]+|=))[^ \t\n;&|<>()\x00]+` + String.raw`))*(?:[ \t]+--)?[ \t]+` + String.raw`|[A-Za-z_][A-Za-z0-9_]*=[^ \t\n;&|<>()\x00]*[ \t]+)*` + String.raw`((?:(?:/usr)?(?:/local)?/bin/)?(?:bash|sh|zsh|python(?:3(?:\.[0-9]+)?)?|node|ruby|perl|php|lua))[ \t]+` + String.raw`([^\n;|&<>()\x00]+)`;
9582
+ function extractCallsFromContent(content, entryArgs = null) {
9583
+ if (!CHILD_INTERPRETER_RE.test(content)) return [];
9584
+ let syntax = caseSyntaxLines(content).join("\n");
9585
+ if (content.includes("${")) {
9586
+ const parts = [];
9587
+ let offset = 0;
9588
+ for (const [start, end] of shellWordParts(content, false, { syntax })) {
9589
+ const token = content.slice(start, end);
9590
+ if (!token.includes("${") || syntax[start] === " ") continue;
9591
+ if (token.startsWith('"') && defaultHasSubstitution(token.slice(1, -1), true)) continue;
9592
+ parts.push(syntax.slice(offset, start));
9593
+ parts.push(token.replace(/[^\n]/g, "x"));
9594
+ offset = end;
9595
+ }
9596
+ parts.push(syntax.slice(offset));
9597
+ syntax = parts.join("");
9598
+ }
7746
9599
  const calls = [];
7747
- let m;
7748
- CHILD_CALL_RE2.lastIndex = 0;
7749
- while ((m = CHILD_CALL_RE2.exec(content)) !== null) {
7750
- const interp = m[1];
7751
- const path8 = m[2].trim();
7752
- let rest = m[3].trim();
7753
- if (path8.startsWith("-") || path8.startsWith("$") || path8.includes("/dev/")) continue;
7754
- rest = rest.split(/[;|&<>]/)[0].trim();
7755
- const args = [];
7756
- for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
7757
- args.push(tm[1] ? tm[2] : tm[3]);
9600
+ const re = new RegExp(CHILD_CALL_SOURCE, "gmd");
9601
+ let match;
9602
+ while ((match = re.exec(syntax)) !== null) {
9603
+ if (match[0] === "") {
9604
+ re.lastIndex += 1;
9605
+ continue;
9606
+ }
9607
+ const range = match.indices?.[2];
9608
+ if (!range) continue;
9609
+ const [start, end] = range;
9610
+ const words = [...syntax.slice(start, end).matchAll(/[^ \t]+/g)];
9611
+ const truncated = syntax.slice(end, end + 1) === "\0" && !content.startsWith("<<", end) || syntax.startsWith("$(", end - 1);
9612
+ if (truncated && words.length && words[words.length - 1].index + words[words.length - 1][0].length === end - start) {
9613
+ words.pop();
9614
+ }
9615
+ const argv = [];
9616
+ let argsKnown = !truncated;
9617
+ for (const word of words) {
9618
+ const fields = expandShellWord(
9619
+ content.slice(start + word.index, start + word.index + word[0].length),
9620
+ entryArgs
9621
+ );
9622
+ if (fields === null) {
9623
+ argsKnown = false;
9624
+ break;
9625
+ }
9626
+ argv.push(...fields);
9627
+ }
9628
+ if (argv.length && argv[0] && !argv[0].startsWith("-") && !argv[0].startsWith("$") && !argv[0].includes("/dev/")) {
9629
+ calls.push({
9630
+ path: argv[0],
9631
+ args: argsKnown ? argv.slice(1) : [],
9632
+ interpreter: match[1],
9633
+ argsKnown
9634
+ });
7758
9635
  }
7759
- calls.push({ path: path8, args, interpreter: interp });
7760
9636
  }
7761
9637
  return calls;
7762
9638
  }
7763
9639
  var ShellBackend = class {
7764
9640
  language = "shell";
7765
- parse(content, entryArgs) {
7766
- const c = content || "";
7767
- const orig = c;
7768
- let candidate = c;
9641
+ ENTRY_PATTERNS = [
9642
+ String.raw`(?:^|\s|&&|\|\|)\s*bash\s+(\S+)`,
9643
+ String.raw`(?:^|\s|&&|\|\|)\s*(?:/bin/)?sh\s+(\S+)`,
9644
+ String.raw`(?:^|\s|&&|\|\|)\s*zsh\s+(\S+)`,
9645
+ String.raw`\./(\S+)`,
9646
+ String.raw`(?:^|\s|&&|\|\|)\s*source\s+(\S+)`
9647
+ ];
9648
+ parse(content, entryArgs, options = {}) {
9649
+ const diagnostics = options.diagnostics;
9650
+ const argsKnown = options.argsKnown !== false;
9651
+ let candidate = content || "";
7769
9652
  let resolved = false;
7770
- const p1Safe = !/(?:\bshift\b|\bset\s+--(?:\s|$)|[\s;|&]read\b|^\s*read\b|\(\)\s*\{|function\s+\w+)/.test(c);
9653
+ const P1_UNSAFE_RE = /\bshift\b|\bset\s+--(?:\s|$)|[\s;|&]read\b|^\s*read\b|\(\)\s*\{|function\s+\w+/;
9654
+ const p1Safe = argsKnown && !P1_UNSAFE_RE.test(candidate);
7771
9655
  if (p1Safe) {
7772
- const caseOut = parseCase(candidate, entryArgs);
9656
+ const caseOut = parseCase(candidate, entryArgs, diagnostics);
7773
9657
  if (caseOut !== null && caseOut !== candidate) {
7774
9658
  resolved = true;
7775
9659
  candidate = caseOut;
7776
9660
  }
7777
- const ifOut = parseIf(candidate, entryArgs);
7778
- if (ifOut !== null && ifOut !== candidate) {
7779
- resolved = true;
7780
- candidate = ifOut;
9661
+ if (!CASE_HEADER_RE.test(candidate)) {
9662
+ const ifOut = parseIf(candidate, entryArgs, diagnostics);
9663
+ if (ifOut !== null && ifOut !== candidate) {
9664
+ resolved = true;
9665
+ candidate = ifOut;
9666
+ }
7781
9667
  }
7782
9668
  }
7783
- let bound = p1Safe ? bindPositionalArgs(candidate, entryArgs || []) : candidate;
7784
- if (!resolved) {
7785
- const symOut = symbolicProcess(c, entryArgs);
7786
- if (symOut !== null && symOut !== c) {
9669
+ if (diagnostics) {
9670
+ diagnostics.parser = "shell_p1";
9671
+ diagnostics.p1_safe = p1Safe;
9672
+ diagnostics.child_extractor = "regex";
9673
+ }
9674
+ if (!argsKnown) {
9675
+ if (diagnostics) {
9676
+ diagnostics.parser = "shell_full";
9677
+ diagnostics.fallback_reason = "unknown_args";
9678
+ }
9679
+ } else if (!resolved) {
9680
+ const symbolicDiagnostics = diagnostics ? {} : void 0;
9681
+ const symOut = symbolicProcess(content ?? "", entryArgs, symbolicDiagnostics);
9682
+ if (symOut !== null && symOut !== content) {
7787
9683
  resolved = true;
7788
- bound = symOut;
9684
+ candidate = symOut;
9685
+ }
9686
+ if (diagnostics && symbolicDiagnostics) {
9687
+ diagnostics.parser = resolved ? "shell_litese" : "shell_full";
9688
+ diagnostics.symbolic = symbolicDiagnostics;
9689
+ if (!resolved) {
9690
+ diagnostics.fallback_reason = symbolicDiagnostics.fallback_reason || "no_pruning";
9691
+ }
9692
+ if (symOut !== null && symOut !== void 0) {
9693
+ const fingerprint = scanFingerprint(symOut);
9694
+ symbolicDiagnostics.output_bytes = fingerprint.bytes;
9695
+ symbolicDiagnostics.output_sha256 = fingerprint.sha256;
9696
+ }
7789
9697
  }
7790
9698
  }
7791
- bound = stripNonExecutableLines(bound);
9699
+ candidate = stripNonExecutableLines(candidate);
9700
+ const bindArgs = p1Safe ? entryArgs : null;
9701
+ const calls = extractCallsFromContent(candidate, bindArgs);
9702
+ const bound = bindPositionalArgs(candidate, bindArgs || []);
7792
9703
  const loopMarked = markLoopsReachable(bound);
7793
- const calls = extractCallsFromContent(loopMarked);
7794
9704
  return {
7795
9705
  reachableContent: loopMarked,
7796
9706
  controlFlowResolved: resolved,
@@ -7815,6 +9725,9 @@ function maxFileSizeFromEnv() {
7815
9725
  }
7816
9726
  var DEFAULT_MAX_FILE_SIZE = maxFileSizeFromEnv();
7817
9727
  var DEFAULT_MAX_TOTAL_SIZE = 8 * 1024 * 1024;
9728
+ var DIAGNOSTIC_NODE_LIMIT = 8;
9729
+ var DIAGNOSTIC_CHILD_LIMIT = 4;
9730
+ var MAX_DIAGNOSTIC_CONTENT_BYTES = 8 * 1024;
7818
9731
  var BACKENDS = {
7819
9732
  ".py": new PythonBackend()
7820
9733
  };
@@ -7826,14 +9739,44 @@ function pickBackend(pathStr) {
7826
9739
  }
7827
9740
  return DEFAULT_BACKEND;
7828
9741
  }
9742
+ function realpathBestEffort(absolutePath) {
9743
+ try {
9744
+ return fs3.realpathSync.native(absolutePath);
9745
+ } catch {
9746
+ }
9747
+ try {
9748
+ return fs3.realpathSync(absolutePath);
9749
+ } catch {
9750
+ }
9751
+ const tail = [];
9752
+ let current = absolutePath;
9753
+ while (true) {
9754
+ const parent = path5.dirname(current);
9755
+ if (parent === current) break;
9756
+ tail.unshift(path5.basename(current));
9757
+ current = parent;
9758
+ if (fs3.existsSync(current)) {
9759
+ try {
9760
+ return path5.join(realpathBestEffort(current), ...tail);
9761
+ } catch {
9762
+ break;
9763
+ }
9764
+ }
9765
+ }
9766
+ return absolutePath;
9767
+ }
9768
+ function isAbsoluteExpanded(p) {
9769
+ if (p === "~" || p.startsWith("~/")) return true;
9770
+ return path5.isAbsolute(p);
9771
+ }
7829
9772
  function resolvePath(p, baseDir) {
7830
9773
  let expanded = p;
7831
9774
  if (expanded.startsWith("~/") || expanded === "~") {
7832
- expanded = path4.join(os2.homedir(), expanded.slice(1));
7833
- } else if (!path4.isAbsolute(expanded) && baseDir) {
7834
- expanded = path4.join(baseDir, expanded);
9775
+ expanded = path5.join(os2.homedir(), expanded.slice(1));
9776
+ } else if (!path5.isAbsolute(expanded) && baseDir) {
9777
+ expanded = path5.join(baseDir, expanded);
7835
9778
  }
7836
- return path4.resolve(expanded);
9779
+ return realpathBestEffort(path5.resolve(expanded));
7837
9780
  }
7838
9781
  function readScript(pathStr, maxFileSize) {
7839
9782
  try {
@@ -7878,13 +9821,22 @@ function emptyNode(pathStr, depth) {
7878
9821
  keywordRiskReason: ""
7879
9822
  };
7880
9823
  }
9824
+ function captureReachableContent(details, source, reachable) {
9825
+ details.reachable_content_matches_source = reachable === source;
9826
+ if ([...reachable].length <= MAX_DIAGNOSTIC_CONTENT_BYTES) {
9827
+ details.reachable_content = reachable;
9828
+ } else {
9829
+ details.reachable_content_omitted = true;
9830
+ }
9831
+ }
7881
9832
  var RecursiveTracker = class {
7882
- constructor(commandScanner, maxDepth = DEFAULT_MAX_DEPTH, maxNodes = DEFAULT_MAX_NODES, maxFileSize = DEFAULT_MAX_FILE_SIZE, maxTotalSize = DEFAULT_MAX_TOTAL_SIZE, stopOnCritical = true) {
9833
+ constructor(commandScanner, maxDepth = DEFAULT_MAX_DEPTH, maxNodes = DEFAULT_MAX_NODES, maxFileSize = DEFAULT_MAX_FILE_SIZE, maxTotalSize = DEFAULT_MAX_TOTAL_SIZE, stopOnCritical = true, diagnostics = null) {
7883
9834
  this.maxDepth = maxDepth;
7884
9835
  this.maxNodes = maxNodes;
7885
9836
  this.maxFileSize = maxFileSize;
7886
9837
  this.maxTotalSize = maxTotalSize;
7887
9838
  this.stopOnCritical = stopOnCritical;
9839
+ this.diagnostics = diagnostics;
7888
9840
  this._scanner = commandScanner;
7889
9841
  this.result = {
7890
9842
  nodes: [],
@@ -7906,39 +9858,78 @@ var RecursiveTracker = class {
7906
9858
  maxFileSize;
7907
9859
  maxTotalSize;
7908
9860
  stopOnCritical;
9861
+ diagnostics;
7909
9862
  result;
7910
9863
  visiting = /* @__PURE__ */ new Set();
7911
- visitedPaths = /* @__PURE__ */ new Set();
9864
+ /**
9865
+ * 已处理集合:按 (路径 → 调用上下文) 去重。
9866
+ * 同一脚本可能先以带参直接调用扫描过,再被 import / 另一组参数调用;
9867
+ * sys.argv 分支完全不同,不能因为"路径访问过"就跳过(会漏掉危险分支)。
9868
+ */
9869
+ visited = /* @__PURE__ */ new Map();
7912
9870
  _scanner;
9871
+ _diagnosticNodes = [];
9872
+ _budgetSkips = { depth: 0, nodes: 0, total_bytes: 0 };
7913
9873
  track(entryPath, entryArgs, cwd = "") {
7914
- const baseDir = cwd || process.cwd();
7915
- const resolved = resolvePath(entryPath);
9874
+ const processCwd = resolvePath(cwd || ".");
9875
+ const resolved = resolvePath(entryPath, processCwd);
7916
9876
  this.result.entryPath = resolved;
7917
- this.visitScript(resolved, 0, path4.dirname(resolved), entryArgs);
9877
+ this.visitScript(resolved, 0, processCwd, entryArgs);
7918
9878
  const nodes = this.result.nodes;
7919
9879
  this.result.hasCritical = nodes.some((n) => n.l1RiskLevel === "critical" || n.l2RiskLevel === "critical" || n.keywordRiskLevel === "critical") || this.result.hasCritical;
7920
9880
  this.result.hasHigh = nodes.some((n) => ["high", "critical"].includes(n.l1RiskLevel) || ["high", "critical"].includes(n.l2RiskLevel) || ["high", "critical"].includes(n.keywordRiskLevel));
7921
9881
  this.result.firstHitNode = nodes.find((n) => n.l1Hit || n.l2Hit || n.isSuspicious) || null;
9882
+ if (this.diagnostics !== null) {
9883
+ const maxVisitedDepth = nodes.reduce((max, node) => Math.max(max, node.depth), 0);
9884
+ this.diagnostics.nodes = this._diagnosticNodes;
9885
+ this.diagnostics.node_count = nodes.length;
9886
+ this.diagnostics.omitted_nodes = nodes.length - this._diagnosticNodes.length;
9887
+ this.diagnostics.max_visited_depth = maxVisitedDepth;
9888
+ this.diagnostics.total_bytes = this.result.totalSize;
9889
+ this.diagnostics.budget_skips = this._budgetSkips;
9890
+ this.diagnostics.limits = {
9891
+ depth: this.maxDepth,
9892
+ nodes: this.maxNodes,
9893
+ file_bytes: this.maxFileSize,
9894
+ total_bytes: this.maxTotalSize
9895
+ };
9896
+ }
7922
9897
  return this.result;
7923
9898
  }
7924
- visitScript(pathStr, depth, baseDir, args) {
9899
+ visitScript(pathStr, depth, processCwd, args, isImport = false, argsKnown = true) {
7925
9900
  pathStr = resolvePath(pathStr);
7926
9901
  if (this.visiting.has(pathStr)) return;
7927
- if (this.visitedPaths.has(pathStr)) return;
9902
+ const effectiveArgs = argsKnown ? args : null;
9903
+ const invocation = `${argsKnown ? "1" : "0"}\0${effectiveArgs === null ? "" : JSON.stringify(effectiveArgs)}\0${processCwd === null ? "\0UNKNOWN" : processCwd}`;
9904
+ const seen = this.visited.get(pathStr);
9905
+ if (seen !== void 0 && seen.has(invocation)) return;
7928
9906
  if (depth > this.maxDepth) {
9907
+ if (this.diagnostics !== null) this._budgetSkips.depth += 1;
7929
9908
  this.result.maxDepthReached = true;
7930
9909
  return;
7931
9910
  }
7932
9911
  if (this.result.nodes.length >= this.maxNodes) {
9912
+ if (this.diagnostics !== null) this._budgetSkips.nodes += 1;
7933
9913
  this.result.maxNodesReached = true;
7934
9914
  return;
7935
9915
  }
7936
9916
  if (this.result.totalSize >= this.maxTotalSize) {
9917
+ if (this.diagnostics !== null) this._budgetSkips.total_bytes += 1;
7937
9918
  this.result.maxSizeReached = true;
7938
9919
  return;
7939
9920
  }
7940
9921
  this.visiting.add(pathStr);
7941
- this.visitedPaths.add(pathStr);
9922
+ let seenSet = this.visited.get(pathStr);
9923
+ if (seenSet === void 0) {
9924
+ seenSet = /* @__PURE__ */ new Set();
9925
+ this.visited.set(pathStr, seenSet);
9926
+ }
9927
+ seenSet.add(invocation);
9928
+ let details = null;
9929
+ if (this.diagnostics !== null && this._diagnosticNodes.length < DIAGNOSTIC_NODE_LIMIT) {
9930
+ details = { depth };
9931
+ this._diagnosticNodes.push(details);
9932
+ }
7942
9933
  const { content, lineCount, fileSize, error } = readScript(pathStr, this.maxFileSize);
7943
9934
  if (error) {
7944
9935
  const node2 = emptyNode(pathStr, depth);
@@ -7947,12 +9938,20 @@ var RecursiveTracker = class {
7947
9938
  node2.lineCount = lineCount;
7948
9939
  node2.unanalyzable = error.startsWith("\u811A\u672C\u6587\u4EF6\u8FC7\u5927");
7949
9940
  this.result.nodes.push(node2);
9941
+ if (details !== null) {
9942
+ details.read_status = node2.unanalyzable ? "file_size_limit" : "read_error";
9943
+ details.file_bytes = fileSize;
9944
+ }
7950
9945
  this.visiting.delete(pathStr);
7951
9946
  return;
7952
9947
  }
7953
9948
  this.result.totalSize += fileSize;
7954
9949
  this.result.totalLines += lineCount;
7955
- const ir = pickBackend(pathStr).parse(content, args);
9950
+ const ir = pickBackend(pathStr).parse(
9951
+ content,
9952
+ effectiveArgs,
9953
+ details === null ? { argsKnown } : { argsKnown, diagnostics: details }
9954
+ );
7956
9955
  const node = emptyNode(pathStr, depth);
7957
9956
  node.rawContent = content;
7958
9957
  node.preprocessedContent = ir.reachableContent;
@@ -7960,8 +9959,24 @@ var RecursiveTracker = class {
7960
9959
  node.fileSize = fileSize;
7961
9960
  this.result.nodes.push(node);
7962
9961
  this.result.totalNodes = this.result.nodes.length;
9962
+ if (details !== null) {
9963
+ const fingerprint = scanFingerprint(ir.reachableContent);
9964
+ details.language = ir.language;
9965
+ details.control_flow_resolved = ir.controlFlowResolved;
9966
+ details.file_bytes = fileSize;
9967
+ details.scan_bytes = fingerprint.bytes;
9968
+ details.scan_sha256 = fingerprint.sha256;
9969
+ details.child_count = ir.calls.length;
9970
+ details.child_arg_counts = ir.calls.slice(0, DIAGNOSTIC_CHILD_LIMIT).map((call) => call.args.length);
9971
+ details.inline_l1_scan = false;
9972
+ captureReachableContent(details, content, ir.reachableContent);
9973
+ }
7963
9974
  if (this._scanner && ir.reachableContent) {
7964
9975
  const l1 = this._scanner(ir.reachableContent);
9976
+ if (details !== null) {
9977
+ details.inline_l1_scan = true;
9978
+ details.inline_l1_hit = l1.hit;
9979
+ }
7965
9980
  if (l1.hit) {
7966
9981
  node.l1Hit = true;
7967
9982
  node.l1RiskLevel = l1.riskLevel;
@@ -7978,12 +9993,38 @@ var RecursiveTracker = class {
7978
9993
  }
7979
9994
  }
7980
9995
  }
7981
- const parentDir = path4.dirname(pathStr);
9996
+ const parentDir = path5.dirname(pathStr);
7982
9997
  const childPaths = [];
7983
9998
  for (const call of ir.calls) {
7984
- const child = resolvePath(call.path, parentDir);
9999
+ let childCwd = processCwd;
10000
+ let pathBase = parentDir;
10001
+ const launchCwd = call.launchCwd;
10002
+ if (launchCwd === WORKING_DIRECTORY_UNKNOWN) {
10003
+ childCwd = null;
10004
+ } else if (launchCwd !== void 0 && launchCwd !== null) {
10005
+ if (path5.isAbsolute(launchCwd)) {
10006
+ childCwd = path5.resolve(launchCwd);
10007
+ } else if (processCwd !== null) {
10008
+ childCwd = path5.resolve(processCwd, launchCwd);
10009
+ }
10010
+ }
10011
+ if (launchCwd !== void 0 && launchCwd !== null) {
10012
+ if (childCwd !== null) {
10013
+ pathBase = childCwd;
10014
+ } else if (!isAbsoluteExpanded(call.path)) {
10015
+ continue;
10016
+ }
10017
+ }
10018
+ const child = resolvePath(call.path, pathBase);
7985
10019
  childPaths.push(child);
7986
- this.visitScript(child, depth + 1, path4.dirname(child), call.args);
10020
+ this.visitScript(
10021
+ child,
10022
+ depth + 1,
10023
+ childCwd,
10024
+ call.args,
10025
+ call.isImport === true,
10026
+ call.argsKnown !== false
10027
+ );
7987
10028
  if (this.stopOnCritical && this.result.hasCritical) break;
7988
10029
  }
7989
10030
  node.childPaths = childPaths;
@@ -8279,7 +10320,7 @@ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
8279
10320
  resolvedPath = inline;
8280
10321
  isInline = true;
8281
10322
  }
8282
- if (resolvedPath && !isAbsolute4(resolvedPath) && !resolvedPath.startsWith("~/")) {
10323
+ if (resolvedPath && !isAbsolute5(resolvedPath) && !resolvedPath.startsWith("~/")) {
8283
10324
  resolvedPath = join12(input.cwd || process.cwd(), resolvedPath);
8284
10325
  }
8285
10326
  const l1Adapter = (content) => {
@@ -8390,7 +10431,7 @@ import OpenAI from "openai";
8390
10431
  init_esm_shims();
8391
10432
  init_paths();
8392
10433
  import fs4 from "fs";
8393
- import path5 from "path";
10434
+ import path6 from "path";
8394
10435
  var LEVEL_OFF = 0;
8395
10436
  var LEVEL_SUMMARY = 1;
8396
10437
  var LEVEL_FULL = 2;
@@ -8438,7 +10479,7 @@ function tracePath() {
8438
10479
  const explicit = (process.env.AGENT_MOSS_TRACE_PATH || "").trim();
8439
10480
  if (explicit) return explicit;
8440
10481
  try {
8441
- return path5.join(getDataRoot(), "agent_moss_trace.log");
10482
+ return path6.join(getDataRoot(), "agent_moss_trace.log");
8442
10483
  } catch {
8443
10484
  return "agent_moss_trace.log";
8444
10485
  }
@@ -8477,7 +10518,7 @@ function trace(event, level = LEVEL_SUMMARY, fields = {}) {
8477
10518
  `;
8478
10519
  const file = tracePath();
8479
10520
  try {
8480
- const dir = path5.dirname(file);
10521
+ const dir = path6.dirname(file);
8481
10522
  if (dir && dir !== ".") fs4.mkdirSync(dir, { recursive: true });
8482
10523
  try {
8483
10524
  const st = fs4.statSync(file);
@@ -8876,7 +10917,7 @@ async function runLLMAnalysis(input, previous) {
8876
10917
  }
8877
10918
  const config = perRequest?.apiKey ? { ...globalConfig, ...perRequest } : globalConfig;
8878
10919
  const rawDetail = input.aNext.actionDetail.replace(/^terminal-\w+:\s*command=([^,]+).*/, "$1").trim();
8879
- const cacheKey2 = `${input.aNext.actionType}:${createHash("sha256").update(rawDetail || input.aNext.actionDetail).digest("hex")}`;
10920
+ const cacheKey2 = `${input.aNext.actionType}:${createHash2("sha256").update(rawDetail || input.aNext.actionDetail).digest("hex")}`;
8880
10921
  const cached2 = llmCache.get(cacheKey2);
8881
10922
  if (cached2) {
8882
10923
  console.log("[AgentMoss] LLM cache hit");
@@ -8891,7 +10932,7 @@ async function runLLMAnalysis(input, previous) {
8891
10932
  } else {
8892
10933
  scriptAnalysis = analyzeScriptContent(input.aNext.actionType, input.aNext.actionDetail);
8893
10934
  }
8894
- const maxPromptTokens = getNumSetting("AGENT_MOSS_LLM_MAX_PROMPT_TOKENS", 0);
10935
+ const maxPromptTokens = getMaxPromptTokens();
8895
10936
  const budgetMode = getAgentMossSetting("AGENT_MOSS_LLM_BUDGET_MODE", "hard").trim().toLowerCase() === "soft" ? "soft" : "hard";
8896
10937
  const budgetActive = maxPromptTokens > 0;
8897
10938
  const tokenLimit = budgetActive && budgetMode === "hard" ? Math.floor(maxPromptTokens * 100 / 115) : maxPromptTokens;
@@ -8998,6 +11039,10 @@ function getNumSetting(key, def) {
8998
11039
  const v = parseInt(getAgentMossSetting(key, String(def)), 10);
8999
11040
  return Number.isFinite(v) ? v : def;
9000
11041
  }
11042
+ function getMaxPromptTokens() {
11043
+ const configured = getNumSetting("AGENT_MOSS_LLM_MAX_PROMPT_TOKENS", 0);
11044
+ return configured > 0 ? Math.max(1200, configured) : 0;
11045
+ }
9001
11046
  function truncateDetail(detail, maxChars) {
9002
11047
  if (maxChars <= 0 || detail.length <= maxChars) return detail;
9003
11048
  const head = Math.max(1, Math.floor(maxChars * 0.6));
@@ -9364,8 +11409,8 @@ function uuid() {
9364
11409
  var BrainRuleStore = class {
9365
11410
  path;
9366
11411
  data;
9367
- constructor(path8) {
9368
- this.path = path8 || getRulesPath();
11412
+ constructor(path9) {
11413
+ this.path = path9 || getRulesPath();
9369
11414
  this.data = this.load();
9370
11415
  }
9371
11416
  load() {
@@ -9811,10 +11856,10 @@ ${reason.slice(0, 500)}
9811
11856
  const pathRe = new RegExp(pathPrefix + pathBody + pathSuffix, "g");
9812
11857
  let mm;
9813
11858
  while ((mm = pathRe.exec(src)) !== null) {
9814
- const path8 = mm[1];
9815
- if (path8.split("/").length < 3) continue;
9816
- if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path8)) continue;
9817
- const gen = this.generalizePath(path8);
11859
+ const path9 = mm[1];
11860
+ if (path9.split("/").length < 3) continue;
11861
+ if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path9)) continue;
11862
+ const gen = this.generalizePath(path9);
9818
11863
  if (seen.has(gen)) continue;
9819
11864
  seen.add(gen);
9820
11865
  patterns.push({ pattern: gen, layer: 1, scope: "openat", ruleType: "deny_path" });
@@ -9833,8 +11878,8 @@ ${reason.slice(0, 500)}
9833
11878
  }
9834
11879
  return false;
9835
11880
  }
9836
- generalizePath(path8) {
9837
- const p = path8.toLowerCase();
11881
+ generalizePath(path9) {
11882
+ const p = path9.toLowerCase();
9838
11883
  if (/\/etc\/(shadow|passwd|sudoers|security|ssh)/.test(p)) {
9839
11884
  return "(?:^|[^a-z0-9_-])etc/(?:shadow|passwd|sudoers|security/|ssh/)";
9840
11885
  }
@@ -10459,7 +12504,7 @@ function checkMCRules(graph) {
10459
12504
  if (rule?.type !== "ltl" || !(rule.enabled !== false)) continue;
10460
12505
  if (ruleViolates(rule, trace2, witnessMode)) {
10461
12506
  const pathNodes = nodes.filter((n) => labelEvent(n.actionDetail).size > 0).slice(-3);
10462
- const path8 = pathNodes.map((n) => ({
12507
+ const path9 = pathNodes.map((n) => ({
10463
12508
  sessionId: n.sessionId,
10464
12509
  seq: n.seq,
10465
12510
  detail: n.actionDetail.slice(0, 60)
@@ -10468,7 +12513,7 @@ function checkMCRules(graph) {
10468
12513
  propertyId: String(rule.id || "mc-ltl"),
10469
12514
  reason: String(rule.reason || "L2.2 \u6A21\u578B\u68C0\u6D4B\u89C4\u5219\u547D\u4E2D"),
10470
12515
  riskLevel: String(rule.risk_level || "high"),
10471
- path: path8,
12516
+ path: path9,
10472
12517
  graph: {
10473
12518
  property_id: String(rule.id || "mc-ltl"),
10474
12519
  property_short: "P6",
@@ -10667,12 +12712,12 @@ function allNodesFlat(mg) {
10667
12712
  // src/engine/formal-engine/properties.ts
10668
12713
  init_esm_shims();
10669
12714
  init_rules_loader();
10670
- function graphFromPath(nodes, path8, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
12715
+ function graphFromPath(nodes, path9, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
10671
12716
  const byKey = /* @__PURE__ */ new Map();
10672
12717
  for (const n of nodes) byKey.set(`${n.sessionId}#${n.seq}`, n);
10673
12718
  const gNodes = [];
10674
12719
  const gEdges = [];
10675
- for (const item of path8) {
12720
+ for (const item of path9) {
10676
12721
  const n = byKey.get(`${item.sessionId}#${item.seq}`);
10677
12722
  gNodes.push({
10678
12723
  session_id: item.sessionId,
@@ -10741,22 +12786,22 @@ function checkCrossSessionChain(graph) {
10741
12786
  if (witness !== void 0) {
10742
12787
  if (nodes[witness].stage !== stages[stages.length - 1]) continue;
10743
12788
  let matched = 0;
10744
- const path8 = [];
12789
+ const path9 = [];
10745
12790
  for (let k = 0; k < witness; k++) {
10746
12791
  const n = nodes[k];
10747
12792
  if (matched < stages.length - 1 && n.stage === stages[matched]) {
10748
12793
  matched += 1;
10749
- path8.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
12794
+ path9.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
10750
12795
  }
10751
12796
  }
10752
12797
  if (matched < stages.length - 1) continue;
10753
- path8.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
12798
+ path9.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
10754
12799
  violations.push({
10755
12800
  propertyId: "cross-" + chain.id,
10756
12801
  reason: chain.reason,
10757
12802
  riskLevel: chain.riskLevel,
10758
- path: path8,
10759
- graph: graphFromPath(nodes, path8, "next", {
12803
+ path: path9,
12804
+ graph: graphFromPath(nodes, path9, "next", {
10760
12805
  property_id: "cross-" + chain.id,
10761
12806
  property_short: "P1",
10762
12807
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -10766,11 +12811,11 @@ function checkCrossSessionChain(graph) {
10766
12811
  } else {
10767
12812
  let matched = 0;
10768
12813
  let stageIdx = 0;
10769
- const path8 = [];
12814
+ const path9 = [];
10770
12815
  for (const n of nodes) {
10771
12816
  if (stageIdx < stages.length && n.stage === stages[stageIdx]) {
10772
12817
  matched += 1;
10773
- path8.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
12818
+ path9.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
10774
12819
  stageIdx += 1;
10775
12820
  if (matched >= stages.length) break;
10776
12821
  }
@@ -10780,8 +12825,8 @@ function checkCrossSessionChain(graph) {
10780
12825
  propertyId: "cross-" + chain.id,
10781
12826
  reason: chain.reason,
10782
12827
  riskLevel: chain.riskLevel,
10783
- path: path8,
10784
- graph: graphFromPath(nodes, path8, "next", {
12828
+ path: path9,
12829
+ graph: graphFromPath(nodes, path9, "next", {
10785
12830
  property_id: "cross-" + chain.id,
10786
12831
  property_short: "P1",
10787
12832
  property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
@@ -11010,7 +13055,7 @@ function checkNeverExfilAfterPrivesc(graph) {
11010
13055
  if (candidates.length > 0) {
11011
13056
  const pre = nodes[candidates[candidates.length - 1]];
11012
13057
  const post = nodes[firstEv];
11013
- const path8 = [
13058
+ const path9 = [
11014
13059
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
11015
13060
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
11016
13061
  ];
@@ -11018,8 +13063,8 @@ function checkNeverExfilAfterPrivesc(graph) {
11018
13063
  propertyId: "no-exfil-after-privesc",
11019
13064
  reason: "\u63D0\u6743\u540E\u51FA\u73B0\u5916\u4F20\uFF1A\u63D0\u6743(\u524D) \u2192 \u5916\u4F20(\u540E)\uFF0C\u8FDD\u53CD \u25A1(PRIVESC\u2192\u25C7EXFIL) \u7A97\u53E3\u7EA6\u675F",
11020
13065
  riskLevel: "critical",
11021
- path: path8,
11022
- graph: graphFromPath(nodes, path8, "next", {
13066
+ path: path9,
13067
+ graph: graphFromPath(nodes, path9, "next", {
11023
13068
  property_id: "no-exfil-after-privesc",
11024
13069
  property_short: "P4",
11025
13070
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -11036,7 +13081,7 @@ function checkNeverExfilAfterPrivesc(graph) {
11036
13081
  for (let j = i + 1; j < nodes.length; j++) {
11037
13082
  if (!isExfilNode(nodes[j])) continue;
11038
13083
  if (privescInWindow(nodes, [i], j, windowSec).length === 0) continue;
11039
- const path8 = [
13084
+ const path9 = [
11040
13085
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
11041
13086
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
11042
13087
  ];
@@ -11044,8 +13089,8 @@ function checkNeverExfilAfterPrivesc(graph) {
11044
13089
  propertyId: "no-exfil-after-privesc",
11045
13090
  reason: "\u63D0\u6743\u540E\u51FA\u73B0\u5916\u4F20\uFF1A\u63D0\u6743(\u524D) \u2192 \u5916\u4F20(\u540E)\uFF0C\u8FDD\u53CD \u25A1(PRIVESC\u2192\u25C7EXFIL) \u7A97\u53E3\u7EA6\u675F",
11046
13091
  riskLevel: "critical",
11047
- path: path8,
11048
- graph: graphFromPath(nodes, path8, "next", {
13092
+ path: path9,
13093
+ graph: graphFromPath(nodes, path9, "next", {
11049
13094
  property_id: "no-exfil-after-privesc",
11050
13095
  property_short: "P4",
11051
13096
  property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
@@ -11077,7 +13122,7 @@ function checkNeverExfilAfterCred(graph) {
11077
13122
  }
11078
13123
  if (pre) {
11079
13124
  const post = nodes[firstEv];
11080
- const path8 = [
13125
+ const path9 = [
11081
13126
  { sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
11082
13127
  { sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
11083
13128
  ];
@@ -11085,8 +13130,8 @@ function checkNeverExfilAfterCred(graph) {
11085
13130
  propertyId: "no-exfil-after-credential",
11086
13131
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
11087
13132
  riskLevel: "critical",
11088
- path: path8,
11089
- graph: graphFromPath(nodes, path8, "data", {
13133
+ path: path9,
13134
+ graph: graphFromPath(nodes, path9, "data", {
11090
13135
  property_id: "no-exfil-after-credential",
11091
13136
  property_short: "P5",
11092
13137
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -11102,7 +13147,7 @@ function checkNeverExfilAfterCred(graph) {
11102
13147
  if (!isCredNode(nodes[i])) continue;
11103
13148
  for (let j = i + 1; j < nodes.length; j++) {
11104
13149
  if (isExfilNode(nodes[j])) {
11105
- const path8 = [
13150
+ const path9 = [
11106
13151
  { sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
11107
13152
  { sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
11108
13153
  ];
@@ -11110,8 +13155,8 @@ function checkNeverExfilAfterCred(graph) {
11110
13155
  propertyId: "no-exfil-after-credential",
11111
13156
  reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
11112
13157
  riskLevel: "critical",
11113
- path: path8,
11114
- graph: graphFromPath(nodes, path8, "data", {
13158
+ path: path9,
13159
+ graph: graphFromPath(nodes, path9, "data", {
11115
13160
  property_id: "no-exfil-after-credential",
11116
13161
  property_short: "P5",
11117
13162
  property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
@@ -11181,13 +13226,13 @@ function checkLowIntegrityCommandExec(graph) {
11181
13226
  for (const i of candidates) {
11182
13227
  const n = nodes[i];
11183
13228
  if (lowAt.has(i) && isComputeNode(n)) {
11184
- const path8 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
13229
+ const path9 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
11185
13230
  violations.push({
11186
13231
  propertyId: "low-integrity-command-exec",
11187
13232
  reason: `\u4F4E\u5B8C\u6574\u6027\u6570\u636E\u63A7\u5236\u547D\u4EE4\u6267\u884C\uFF1A${lowAt.get(i)} \u2192 ${n.sessionId}#${n.seq} \u6267\u884C\u4E0D\u53EF\u4FE1\u5185\u5BB9`,
11188
13233
  riskLevel: "critical",
11189
- path: path8,
11190
- graph: graphFromPath(nodes, path8, "next", {
13234
+ path: path9,
13235
+ graph: graphFromPath(nodes, path9, "next", {
11191
13236
  property_id: "low-integrity-command-exec",
11192
13237
  property_short: "P7",
11193
13238
  property_name: "\u4F4E\u5B8C\u6574\u6027\u547D\u4EE4\u6267\u884C"
@@ -11234,7 +13279,7 @@ function checkCrossSessionReachability(graph) {
11234
13279
  if (reached.has(i)) {
11235
13280
  const srcIdx = Math.min(...sources);
11236
13281
  const srcDesc = nodes[srcIdx].actionDetail.slice(0, 40);
11237
- const path8 = nodes.slice(-3).map((m) => ({
13282
+ const path9 = nodes.slice(-3).map((m) => ({
11238
13283
  sessionId: m.sessionId,
11239
13284
  seq: m.seq,
11240
13285
  detail: m.actionDetail.slice(0, 60)
@@ -11243,8 +13288,8 @@ function checkCrossSessionReachability(graph) {
11243
13288
  propertyId: "low-integrity-reachability",
11244
13289
  reason: `\u4F4E\u5B8C\u6574\u6027\u6E90\u7ECF\u8DE8 session \u6570\u636E\u94FE\u591A\u8DF3\u5230\u8FBE\u5F53\u524D\u6267\u884C\uFF08\u6E90: ${srcDesc} \u2192 ${n.sessionId}#${n.seq}\uFF09`,
11245
13290
  riskLevel: "high",
11246
- path: path8,
11247
- graph: graphFromPath(nodes, path8, "data", {
13291
+ path: path9,
13292
+ graph: graphFromPath(nodes, path9, "data", {
11248
13293
  property_id: "low-integrity-reachability",
11249
13294
  property_short: "P3",
11250
13295
  property_name: "\u4F4E\u5B8C\u6574\u6027\u6570\u636E\u6D41\u53EF\u8FBE"
@@ -11291,13 +13336,13 @@ function checkSensitiveDataAggregation(graph) {
11291
13336
  if (!isExfilNode(n)) continue;
11292
13337
  const srcs = sourcesFor(i);
11293
13338
  if (srcs.size >= 2) {
11294
- const path8 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
13339
+ const path9 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
11295
13340
  violations.push({
11296
13341
  propertyId: "sensitive-data-aggregation",
11297
13342
  reason: `\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20\uFF1Aegress \u805A\u5408 ${srcs.size} \u4E2A\u4E8B\u4EF6\u6E90\u6570\u636E\uFF08Rule 12\uFF09`,
11298
13343
  riskLevel: "critical",
11299
- path: path8,
11300
- graph: graphFromPath(nodes, path8, "next", {
13344
+ path: path9,
13345
+ graph: graphFromPath(nodes, path9, "next", {
11301
13346
  property_id: "sensitive-data-aggregation",
11302
13347
  property_short: "P8",
11303
13348
  property_name: "\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20"
@@ -11384,10 +13429,10 @@ var FormalEngine = class {
11384
13429
  // src/engine/formal-engine/stateful.ts
11385
13430
  init_esm_shims();
11386
13431
  init_rules_loader();
11387
- import { createHash as createHash2 } from "crypto";
13432
+ import { createHash as createHash3 } from "crypto";
11388
13433
  import * as fs5 from "fs";
11389
13434
  import * as os3 from "os";
11390
- import * as path6 from "path";
13435
+ import * as path7 from "path";
11391
13436
  import { gzipSync } from "zlib";
11392
13437
  function resolveMaxNodes() {
11393
13438
  const n = Number.parseInt(process.env.AGENT_MOSS_CHAIN_MAX_NODES || "100000", 10);
@@ -11399,8 +13444,8 @@ var MAX_NODES = resolveMaxNodes();
11399
13444
  init_esm_shims();
11400
13445
  import * as fs6 from "fs";
11401
13446
  import * as os4 from "os";
11402
- import * as path7 from "path";
11403
- import { createHash as createHash3 } from "crypto";
13447
+ import * as path8 from "path";
13448
+ import { createHash as createHash4 } from "crypto";
11404
13449
 
11405
13450
  // src/engine/coordinator.ts
11406
13451
  var TRUSTED_SKILLS_BASE = /* @__PURE__ */ new Set([]);