openfeel 1.6.0 → 1.6.1

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.
Files changed (80) hide show
  1. package/README.en.md +7 -0
  2. package/README.zh-CN.md +7 -0
  3. package/dist/commands/dashboard.d.ts.map +1 -1
  4. package/dist/commands/dashboard.js +10 -1
  5. package/dist/commands/dashboard.js.map +1 -1
  6. package/dist/commands/flow.d.ts.map +1 -1
  7. package/dist/commands/flow.js +19 -12
  8. package/dist/commands/flow.js.map +1 -1
  9. package/dist/commands/lint.d.ts +3 -1
  10. package/dist/commands/lint.d.ts.map +1 -1
  11. package/dist/commands/lint.js +279 -2
  12. package/dist/commands/lint.js.map +1 -1
  13. package/dist/commands/req.d.ts.map +1 -1
  14. package/dist/commands/req.js +470 -95
  15. package/dist/commands/req.js.map +1 -1
  16. package/dist/core/adherence.d.ts +135 -0
  17. package/dist/core/adherence.d.ts.map +1 -0
  18. package/dist/core/adherence.js +221 -0
  19. package/dist/core/adherence.js.map +1 -0
  20. package/dist/core/dashboard/aggregate.d.ts +39 -0
  21. package/dist/core/dashboard/aggregate.d.ts.map +1 -1
  22. package/dist/core/dashboard/aggregate.js +64 -5
  23. package/dist/core/dashboard/aggregate.js.map +1 -1
  24. package/dist/core/dashboard/render.d.ts.map +1 -1
  25. package/dist/core/dashboard/render.js +88 -1
  26. package/dist/core/dashboard/render.js.map +1 -1
  27. package/dist/core/errors.d.ts +27 -2
  28. package/dist/core/errors.d.ts.map +1 -1
  29. package/dist/core/errors.js +15 -2
  30. package/dist/core/errors.js.map +1 -1
  31. package/dist/core/flow/gate-override.d.ts +72 -0
  32. package/dist/core/flow/gate-override.d.ts.map +1 -0
  33. package/dist/core/flow/gate-override.js +71 -0
  34. package/dist/core/flow/gate-override.js.map +1 -0
  35. package/dist/core/flow-manager.d.ts +13 -4
  36. package/dist/core/flow-manager.d.ts.map +1 -1
  37. package/dist/core/flow-manager.js +47 -16
  38. package/dist/core/flow-manager.js.map +1 -1
  39. package/dist/core/i18n-data/en.d.ts.map +1 -1
  40. package/dist/core/i18n-data/en.js +45 -6
  41. package/dist/core/i18n-data/en.js.map +1 -1
  42. package/dist/core/i18n-data/zh-CN.d.ts.map +1 -1
  43. package/dist/core/i18n-data/zh-CN.js +45 -6
  44. package/dist/core/i18n-data/zh-CN.js.map +1 -1
  45. package/dist/core/req/body-file.d.ts +37 -0
  46. package/dist/core/req/body-file.d.ts.map +1 -1
  47. package/dist/core/req/body-file.js +39 -2
  48. package/dist/core/req/body-file.js.map +1 -1
  49. package/dist/core/req/plan-file.d.ts +83 -0
  50. package/dist/core/req/plan-file.d.ts.map +1 -0
  51. package/dist/core/req/plan-file.js +205 -0
  52. package/dist/core/req/plan-file.js.map +1 -0
  53. package/dist/core/req/requirement-ops.d.ts +25 -3
  54. package/dist/core/req/requirement-ops.d.ts.map +1 -1
  55. package/dist/core/req/requirement-ops.js +66 -11
  56. package/dist/core/req/requirement-ops.js.map +1 -1
  57. package/dist/core/req/types.d.ts +8 -2
  58. package/dist/core/req/types.d.ts.map +1 -1
  59. package/dist/core/req/types.js +10 -2
  60. package/dist/core/req/types.js.map +1 -1
  61. package/dist/core/template-loader.d.ts.map +1 -1
  62. package/dist/core/template-loader.js +12 -0
  63. package/dist/core/template-loader.js.map +1 -1
  64. package/dist/core/templates.d.ts +1 -1
  65. package/dist/core/templates.d.ts.map +1 -1
  66. package/dist/core/templates.js +18 -0
  67. package/dist/core/templates.js.map +1 -1
  68. package/dsh/ACTION-GUIDE.md +15 -6
  69. package/dsh/ADAPTER.md +62 -1
  70. package/dsh/README.md +13 -11
  71. package/dsh/docs/compat/persistence.md +13 -0
  72. package/dsh/docs/compat/pipeline.md +12 -0
  73. package/dsh/docs/compat/req.md +15 -0
  74. package/dsh/docs/compat/stage.md +12 -0
  75. package/dsh/lib/adapters/dispatch-ledger.js +149 -10
  76. package/dsh/lib/guard.js +685 -22
  77. package/dsh/lib/surface/prompt.js +4 -0
  78. package/dsh/lib/tools/index.js +113 -22
  79. package/dsh/package.json +2 -2
  80. package/package.json +2 -1
package/dsh/lib/guard.js CHANGED
@@ -29,6 +29,21 @@
29
29
  * `.openfeel/` 之外另有 `PROTECTED_WORKSPACE_PATHS`(`dsh/cordis.patch.yml` 的门禁开关行);
30
30
  * - `.openfeel/` 外的源码/文档要求存在 `exec_running` 阶段(或 general 需求例外);
31
31
  * **代码目录**(`CODE_DIRECTORIES`)内任何扩展名都不享受 doc/asset 豁免(D-126-06);
32
+ * v1.6.1 / REQ-062 A62.1 起 `review_passed` / `test_passed` 只额外放行**文档类**
33
+ * 目标(`isDocAssetWritePath`:`docs/**`、根级 `*.md`、`test/fixtures/**` 与
34
+ * `dsh/test/fixtures/**`),`src/**` 与测试代码仍按源码门禁;
35
+ * - v1.6.1 / REQ-067 A67.1—A67.4(wrapper 静态分类):`pwsh|powershell -File|-f <脚本>`、
36
+ * `cmd /c|/k <脚本>`、`bash|sh <脚本>` 会**读脚本内容**(≤`MAX_SCRIPT_BYTES`)并按
37
+ * 同一套 `classifyShellCommand` 递归分类(`WRAPPER_MAX_DEPTH` 触顶即不可判定):
38
+ * 内容命中 openfeel 写动词 → 1 类拒;内容可解析出写目标(受保护/相位不允许)→ 2 类拒;
39
+ * 审计行带 `detail:{wrapper, scriptPath, class, reason}`(`reason:'wrapper-write'`)。
40
+ * **读不到 / 超限 / 非 UTF 编码 → 第 4 类**(默认 warn + 审计 `detail`),不静默放行;
41
+ * `strict` 档下照样拒。编码口径:只接受 UTF-8(含 BOM)与 UTF-16(BOM 或 NUL 启发式),
42
+ * GBK 等双字节编码**不解码**(同一字节串解错会给出假安全)→ 一律 `undecidable`。
43
+ * `node <脚本>` 只解析路径、不读内容(读 JS 会把 `node test/guard.js` 这类含 openfeel
44
+ * 字面量的测试脚本误杀)→ 恒为第 4 类并留审计;内联 `node -e` / `bash -c` 仍走原递归。
45
+ * - 审计条目(v1.6.1 / R7):`execution.agent.session.header` 提供 `origin` /
46
+ * `delegationDepth` 时原样写入(缺失即省略,**不伪造**),`detail` 仅在包装器判定时出现;
32
47
  * - 判定顺序:受保护路径 → 未初始化/bootstrap → 内部路径早返回 → 研究闸 →
33
48
  * 无阶段/chore/doc-asset → 相位判定;
34
49
  * - 无 `.openfeel/` 时:`always` 拒绝全部写文件,`project`/`off` 放行;
@@ -41,7 +56,7 @@ import { execFileSync } from 'node:child_process';
41
56
  import {
42
57
  appendFileSync, existsSync, mkdirSync, readFileSync, realpathSync, statSync,
43
58
  } from 'node:fs';
44
- import { basename, dirname, extname, join, resolve } from 'node:path';
59
+ import { basename, dirname, extname, join, relative, resolve } from 'node:path';
45
60
 
46
61
  import { globalGuardAuditPath, writeGuardState } from './adapters/guard-state.js';
47
62
  import { lookupSessionCwd } from './adapters/session-cwd-registry.js';
@@ -448,6 +463,69 @@ export function isExemptPath(absolute, cwd) {
448
463
  return isDocPath(absolute, cwd) || isPresentationalAssetPath(absolute);
449
464
  }
450
465
 
466
+ /**
467
+ * 审后相位可写「文档/夹具」的相位集(v1.6.1 / REQ-062 A62.1)。
468
+ *
469
+ * 语义:`review_passed` / `test_passed` 不再要求为改一句文档/测试夹具而 `--force` 回退
470
+ * `exec_running`;**源码(`src/**` 及代码目录内任何文件)仍拒** —— 相位层只放开
471
+ * {@link isDocAssetWritePath} 命中的目标,不改 `exec_running` 才可写源码的规则。
472
+ *
473
+ * 说明:`exec_running` 已在相位判定里**全量**放行(含源码),不需要出现在本表;
474
+ * 单独列出它只会让「哪些相位需要白名单」的语义变含糊。
475
+ */
476
+ export const DOC_WRITE_PHASES = Object.freeze(['review_passed', 'test_passed']);
477
+
478
+ /**
479
+ * 是否为**测试夹具**路径(v1.6.1 / REQ-062 A62.1):只认工作区根级
480
+ * `test/fixtures/**` 与 `dsh/test/fixtures/**`。
481
+ *
482
+ * 刻意**不含** `test/core/**`、`test/commands/**` —— 夹具 ≠ 测试代码:
483
+ * 把 `test/**` 整体当夹具等于在审后放开测试代码改写(A62.1 负例)。
484
+ * @param {string} absolute 已归一化绝对路径
485
+ * @param {string} cwd 已归一化工作区
486
+ * @returns {boolean}
487
+ */
488
+ export function isFixturePath(absolute, cwd) {
489
+ const segments = workspaceRelativeSegments(absolute, cwd);
490
+ if (segments === null) return false;
491
+ const lower = segments.map((segment) => segment.toLowerCase());
492
+ if (lower[0] === 'test' && lower[1] === 'fixtures') return true;
493
+ if (lower[0] === 'dsh' && lower[1] === 'test' && lower[2] === 'fixtures') return true;
494
+ return false;
495
+ }
496
+
497
+ /**
498
+ * 是否为工作区**根级** Markdown(`README*.md` / `CHANGELOG.md` / 其它根 `*.md`)。
499
+ * @param {string} absolute 已归一化绝对路径
500
+ * @param {string} cwd 已归一化工作区
501
+ * @returns {boolean}
502
+ */
503
+ function isRootMarkdownFile(absolute, cwd) {
504
+ const segments = workspaceRelativeSegments(absolute, cwd);
505
+ if (segments === null || segments.length !== 1) return false;
506
+ return segments[0].toLowerCase().endsWith('.md');
507
+ }
508
+
509
+ /**
510
+ * **单一判据**:审后相位可写的「文档类」目标(v1.6.1 / REQ-062 A62.1)。
511
+ *
512
+ * 命中(任一):
513
+ * - 测试夹具({@link isFixturePath},代码目录内唯一例外);
514
+ * - 工作区根级 `*.md`(`README*` / `CHANGELOG` / 其它根 md);
515
+ * - 非代码目录下的文档(`docs/**`、doc 扩展名)与根级人读文件(`LICENSE` 等)。
516
+ *
517
+ * 代码目录内(`src/**`、`test/core/**` …)除夹具外一律 false —— 判据顺序保持
518
+ * 「先判代码目录,再判扩展名」,与 {@link isExemptPath} 同一纪律。
519
+ * @param {string} absolute 已归一化绝对路径
520
+ * @param {string} cwd 已归一化工作区
521
+ * @returns {boolean}
522
+ */
523
+ export function isDocAssetWritePath(absolute, cwd) {
524
+ if (isFixturePath(absolute, cwd)) return true;
525
+ if (isCodeDirectoryPath(absolute, cwd)) return false;
526
+ return isRootMarkdownFile(absolute, cwd) || isRootDocFile(absolute, cwd) || isDocPath(absolute, cwd);
527
+ }
528
+
451
529
  /**
452
530
  * 审计里的命令片段(v1.5.11 D-126-02):折叠空白并截断到 500 字符。
453
531
  *
@@ -475,8 +553,14 @@ function truncateCommand(command, limit = 500) {
475
553
  * 每行必须带 `cwdSource`(验收 14)与 `decision`(allow|deny|warn);shell 行
476
554
  * 额外带 `command`(截断 ≤500 字符,v1.5.14 / stage-129 OF-08.1),否则「门禁是否真的拦过」无法自证。
477
555
  *
556
+ * v1.6.1 / REQ-067(R7):
557
+ * - `detail`:包装器(wrapper 脚本)判定的结构化证据,如
558
+ * `{wrapper:'pwsh -File', scriptPath:'<绝对路径>', class:'class1', reason:'wrapper-write'}`;
559
+ * - `origin` / `delegationDepth`:来自 `execution.agent.session.header`,**有则写、无则省略**,
560
+ * 绝不伪造默认值(伪造会让「谁写的」审计失真)。
561
+ *
478
562
  * @param {string | null} cwd 已归一化工作区(null = 不可解析)
479
- * @param {{ event?: 'guard_allow'|'guard_deny'|'guard_shell_unresolved'|'guard_shell_downgraded'|'guard_shell_allowlisted', decision?: 'allow'|'deny'|'warn', tool: string, reason: string, phase: string, paths: string[], cwdSource?: string, command?: string }} event
563
+ * @param {{ event?: 'guard_allow'|'guard_deny'|'guard_shell_unresolved'|'guard_shell_downgraded'|'guard_shell_allowlisted', decision?: 'allow'|'deny'|'warn', tool: string, reason: string, phase: string, paths: string[], cwdSource?: string, command?: string, kind?: string, detail?: Record<string, unknown>, origin?: string, delegationDepth?: number }} event
480
564
  */
481
565
  function recordGuardAudit(cwd, event) {
482
566
  const entry = {
@@ -495,6 +579,14 @@ function recordGuardAudit(cwd, event) {
495
579
  // op-005 / P0-1:shell 行必须能区分「确认只读(none)」与「无法判定(undecidable)」,
496
580
  // 否则审计会把一次静默放行记成「没有写」。
497
581
  if (typeof event.kind === 'string' && event.kind !== '') entry.kind = event.kind;
582
+ // v1.6.1 / R7:包装器脚本证据(字段由分类结果给出,不在这里编造)。
583
+ if (event.detail !== undefined && event.detail !== null && typeof event.detail === 'object') {
584
+ const detail = /** @type {Record<string, unknown>} */ (event.detail);
585
+ if (Object.keys(detail).length > 0) entry.detail = detail;
586
+ }
587
+ // v1.6.1 / R7:会话来源与委派深度 —— 只有 header 真的给了才写(缺省省略)。
588
+ if (typeof event.origin === 'string' && event.origin !== '') entry.origin = event.origin;
589
+ if (Number.isInteger(event.delegationDepth)) entry.delegationDepth = event.delegationDepth;
498
590
 
499
591
  const hasWorkspace = typeof cwd === 'string' && cwd !== '';
500
592
  const file = hasWorkspace ? join(cwd, '.openfeel', 'log', 'guard-audit.jsonl') : globalGuardAuditPath();
@@ -1064,8 +1156,36 @@ const PS_WRITE_SPECS = new Map([
1064
1156
  ['sed', 'sed'],
1065
1157
  ]);
1066
1158
 
1067
- /** PowerShell 里表示「目标路径」的具名参数。 */
1068
- const PS_PATH_PARAMS = new Set(['path', 'filepath', 'literalpath', 'destination', 'target', 'outputfile']);
1159
+ /**
1160
+ * **cmd 语义**的写命令表(v1.6.1 fix 3;只用于 `.cmd` / `.bat` 的正文分类)。
1161
+ *
1162
+ * 与 PowerShell 表的差异是**刻意**的(cmd 的 `copy`/`move` 源不是被写对象):
1163
+ * - `copy` / `move`:只有**目标**(最后一个位置参数)算写 —— 把源算进去会误杀
1164
+ * `copy src\a.ts dist\`(源在 `src/**` 里,但它只被读);
1165
+ * - `del` / `erase` / `ren` / `rename` / `rd` / `rmdir` / `rm`:全部位置参数都算写;
1166
+ * - `xcopy` / `robocopy`:第二个位置参数是目标;
1167
+ * - `mkdir` / `md`:创建目录,全部算写。
1168
+ *
1169
+ * `.cmd` 正文里的 `>` / `>>` 重定向由 `scanShellRedirections` 统一收集(与分析器无关),
1170
+ * 所以 `echo x > src\generated.ts` 在 cmd 语义下同样命中第 2 类。
1171
+ */
1172
+ const CMD_WRITE_SPECS = new Map([
1173
+ ['copy', 'dest'],
1174
+ ['move', 'dest'],
1175
+ ['xcopy', 'dest2'],
1176
+ ['robocopy', 'dest2'],
1177
+ ['del', 'all'],
1178
+ ['erase', 'all'],
1179
+ ['ren', 'all'],
1180
+ ['rename', 'all'],
1181
+ ['rm', 'all'],
1182
+ ['rd', 'all'],
1183
+ ['rmdir', 'all'],
1184
+ ['mkdir', 'all'],
1185
+ ['md', 'all'],
1186
+ ]);
1187
+
1188
+ /** PowerShell 里表示「目标路径」的具名参数。 */const PS_PATH_PARAMS = new Set(['path', 'filepath', 'literalpath', 'destination', 'target', 'outputfile']);
1069
1189
  /** PowerShell 里表示「只读源路径」的具名参数(`Copy-Item -Path src -Destination dst`)。 */
1070
1190
  const PS_SOURCE_PARAMS = new Set(['path', 'filepath', 'literalpath']);
1071
1191
  /** PowerShell 开关参数(不消费下一个 token)。 */
@@ -1188,7 +1308,7 @@ const HARD_INDIRECT_PATTERNS = Object.freeze([
1188
1308
  [/(?:^|\s)-(?:enc|ec)\b/i, '-EncodedCommand'],
1189
1309
  [/\b(?:iex|Invoke-Expression)\b/i, 'Invoke-Expression'],
1190
1310
  [/(?:^|[|&]\s*)eval\s/i, 'eval'],
1191
- [/(?:^|[|&]\s*)(?:cmd(?:\.exe)?\s+\/[ck]\b)/i, 'cmd /c'],
1311
+ [/(?:^|[|&]\s*)(?:cmd(?:\.exe)?\s+(?:\/[a-z]+(?::[a-z]+)?\s+)*\/[ck]\b)/i, 'cmd /c'],
1192
1312
  [/\bNew-Object\s+(?:System\.)?IO\.(?:StreamWriter|FileStream|BinaryWriter|DirectoryInfo|FileInfo)\b/i, 'New-Object 写对象'],
1193
1313
  [/\bAdd-Type\b/i, 'Add-Type 动态编译'],
1194
1314
  ]);
@@ -1249,6 +1369,44 @@ const INDIRECT_WRITE_PATTERNS = Object.freeze([
1249
1369
  /** 递归深度上限(防构造 `bash -c 'bash -c …'` 无限套娃)。 */
1250
1370
  const WRAPPER_MAX_DEPTH = 4;
1251
1371
 
1372
+ /**
1373
+ * v1.6.1 / REQ-067 A67:脚本文件读取上限(64KB)。
1374
+ * 超限不做部分读取 —— 半截内容分类会给出假的「只读」结论,一律 undecidable。
1375
+ */
1376
+ const MAX_SCRIPT_BYTES = 64 * 1024;
1377
+
1378
+ /**
1379
+ * 可读内容分类的脚本载体扩展名 → 内容按哪种 shell 解析。
1380
+ *
1381
+ * v1.6.1 fix 3:`.cmd` / `.bat` 的内容是 **cmd** 语义(`copy`/`move` 只把目标算写,
1382
+ * `del`/`ren` 全部算写,`>` 重定向算写),不再拿 PowerShell 语义硬套 ——
1383
+ * 否则 `move src\x.ts dist\` 会把源也算成写目标(误杀),而 `ren` 完全识别不出。
1384
+ */
1385
+ const WRAPPER_SCRIPT_EXTENSIONS = new Map([
1386
+ ['.ps1', 'pwsh'], ['.psm1', 'pwsh'], ['.cmd', 'cmd'], ['.bat', 'cmd'],
1387
+ ['.sh', 'bash'], ['.bash', 'bash'],
1388
+ ]);
1389
+
1390
+ /** PowerShell 读文件执行的旗标(`-File` 及其别名 `-f`)。 */
1391
+ const PS_FILE_FLAGS = new Set(['file', 'f']);
1392
+
1393
+ /** PowerShell 内联执行旗标:命中即交给 `extractWrapperPayload` / 内联解释器分支。 */
1394
+ const PS_INLINE_FLAGS = new Set(['command', 'c', 'commandwithargs', 'encodedcommand', 'e', 'ec']);
1395
+
1396
+ /** cmd 读文件执行的旗标(`/c` / `/k`)。 */
1397
+ const CMD_SCRIPT_FLAGS = new Set(['c', 'k']);
1398
+
1399
+ /**
1400
+ * cmd 的**前置开关**(出现在 `/c` 之前,不改变「读文件执行」语义):
1401
+ * `cmd /d /c x.cmd`、`cmd /q /d /c x.cmd`、`cmd /e:on /c x.cmd`。
1402
+ * 旧实现遇到第一个 `/` 开关就 `break`,于是 `cmd /d /c 脚本` 整条落到第 4 类
1403
+ * (warn 放行)—— 这是 v1.6.1 fix 1 要封的绕过面。
1404
+ */
1405
+ const CMD_PRE_SWITCHES = new Set(['a', 'd', 'e', 'f', 'q', 's', 'u', 'v']);
1406
+
1407
+ /** 解释器内联旗标(`node -e` / `--eval` / `-p` / `-i`)。 */
1408
+ const INTERPRETER_INLINE_FLAGS = /^(?:-e|--eval|-p|--print|-i|--interactive|-c|--check)$/i;
1409
+
1252
1410
  /**
1253
1411
  * 同一命令内「一次字面量赋值」:`$f='src/x.ts'` / `F=src/x.ts` / `export F=x`。
1254
1412
  * 值里出现 `$` 或反引号(插值/子表达式)即不算纯字面量。
@@ -1564,6 +1722,314 @@ function payloadIsUnresolvable(payload) {
1564
1722
  return /[$`]/.test(first);
1565
1723
  }
1566
1724
 
1725
+ /**
1726
+ * 位置参数形式的脚本载体判定(v1.6.1 fix 1):已知脚本扩展名,或带路径分隔符。
1727
+ *
1728
+ * `pwsh build` / `pwsh foo` 这种「一个裸词」不猜是文件(可能只是开关值/参数),
1729
+ * 保持第 4 类;`pwsh ./x.ps1` / `pwsh scripts/x.ps1` 才算载体。
1730
+ * @param {string} token
1731
+ * @returns {boolean}
1732
+ */
1733
+ function looksLikeScriptPath(token) {
1734
+ const text = String(token);
1735
+ if (text === '') return false;
1736
+ if (WRAPPER_SCRIPT_EXTENSIONS.has(extname(text).toLowerCase())) return true;
1737
+ return /[\\/]/.test(text);
1738
+ }
1739
+
1740
+ /**
1741
+ * 识别「读脚本文件执行」的包装器(v1.6.1 / REQ-067 A67.1—A67.3)。
1742
+ *
1743
+ * 覆盖形态(都是**内容在文件里、命令文本只看得见路径**):
1744
+ * - `pwsh|powershell -File|-f <脚本>`,以及 `-File:<脚本>`(同 token 冒号写法);
1745
+ * - `pwsh|powershell <脚本>`(**位置参数**,无 `-File`;fix 1);
1746
+ * - `cmd [/d|/q|/e:on 等前置开关] [/c|/k] <脚本>`(fix 1:前置开关不丢载体);
1747
+ * - `bash|sh|zsh|dash|fish|ksh <脚本>`(第一个非旗标参数;`-c` 形态不在此列);
1748
+ * - `source <脚本>` / `. <脚本>`(命令位;fix 1);
1749
+ * - `node <脚本>`:**只解析路径不读内容**(`inspect:false`)—— 是否强制读取内容
1750
+ * 由 `resolveWrapperScript` 按路径判定(`scripts/**` 或名字含 release/publish/commit)。
1751
+ *
1752
+ * 用 token 而非原文 offset:`"pwsh" -File "x.ps1"` 同样识别。
1753
+ *
1754
+ * @param {string} statement
1755
+ * @returns {{ wrapper: string, scriptPath: string, shell: 'bash'|'pwsh'|'cmd', inspect?: boolean } | null}
1756
+ */
1757
+ function matchWrapperScriptTarget(statement) {
1758
+ const tokens = tokenizeShell(statement);
1759
+ for (let index = 0; index < tokens.length; index += 1) {
1760
+ const name = commandNameOf(tokens[index]);
1761
+ const args = [];
1762
+ for (let cursor = index + 1; cursor < tokens.length && tokens[cursor] !== '|'; cursor += 1) args.push(tokens[cursor]);
1763
+ if (args.length === 0) continue;
1764
+
1765
+ if (/^(?:bash|sh|zsh|dash|fish|ksh)$/.test(name)) {
1766
+ const flags = [];
1767
+ let candidate = null;
1768
+ for (const token of args) {
1769
+ if (token.startsWith('-') && token.length > 1) { flags.push(token); continue; }
1770
+ candidate = token;
1771
+ break;
1772
+ }
1773
+ // `-c` / `-lc` 是内联形态,由 extractWrapperPayload 递归处理,不在这里读文件。
1774
+ if (candidate === null || flags.some((flag) => /^-[a-zA-Z]*c$/i.test(flag))) continue;
1775
+ return { wrapper: name === 'sh' ? 'sh' : 'bash', scriptPath: candidate, shell: 'bash' };
1776
+ }
1777
+
1778
+ // v1.6.1 fix 1:`source x.sh` / `. x.sh` —— 被 source 的脚本正文同样是执行面。
1779
+ // 只认**命令位**(句首 / 管道后):否则 `rg source x.sh` 的参数会被误当载体。
1780
+ if ((name === 'source' || name === '.')
1781
+ && (index === 0 || tokens[index - 1] === '|')) {
1782
+ const candidate = args.find((token) => !token.startsWith('-'));
1783
+ if (candidate === undefined || candidate === '') continue;
1784
+ const extShell = WRAPPER_SCRIPT_EXTENSIONS.get(extname(candidate).toLowerCase());
1785
+ // 只认已知脚本扩展名:`source /etc/os-release` 这类配置文件不读(保持第 4 类)。
1786
+ if (extShell === undefined) continue;
1787
+ return { wrapper: name, scriptPath: candidate, shell: extShell };
1788
+ }
1789
+
1790
+ if (/^(?:powershell|pwsh)$/.test(name)) {
1791
+ let file = null;
1792
+ let fileFlag = false;
1793
+ let inline = false;
1794
+ let positional = null;
1795
+ for (let cursor = 0; cursor < args.length; cursor += 1) {
1796
+ const token = args[cursor];
1797
+ // 位置参数形式(v1.6.1 fix 1):`pwsh ./x.ps1` / `powershell build.ps1`。
1798
+ // **不 break**:`pwsh -ExecutionPolicy Bypass -File x.ps1` 中间夹着开关值,
1799
+ // 提前 break 会漏掉后面的 `-File`(比旧实现更松)。只收「像脚本」的位置参数,
1800
+ // 开关值(`Bypass` / `Text`)不会被当成载体。
1801
+ if (!token.startsWith('-') && !token.startsWith('/')) {
1802
+ if (positional === null && looksLikeScriptPath(token)) positional = token;
1803
+ continue;
1804
+ }
1805
+ const raw = token.replace(/^[-/]+/, '');
1806
+ const colon = raw.indexOf(':');
1807
+ const flag = (colon === -1 ? raw : raw.slice(0, colon)).toLowerCase();
1808
+ if (PS_INLINE_FLAGS.has(flag)) { inline = true; break; }
1809
+ if (PS_FILE_FLAGS.has(flag)) {
1810
+ // 同 token 里的 `-File:x.ps1`(fix 1)与分离写法 `-File x.ps1` 都要认。
1811
+ file = colon === -1 ? (args[cursor + 1] ?? null) : raw.slice(colon + 1);
1812
+ fileFlag = true;
1813
+ break;
1814
+ }
1815
+ }
1816
+ // `-Command` / `-EncodedCommand` 是内联形态,不在这里读文件。
1817
+ if (inline) continue;
1818
+ if (!fileFlag) {
1819
+ if (positional === null) continue;
1820
+ file = positional;
1821
+ }
1822
+ if (file === null || file === '') continue;
1823
+ return { wrapper: fileFlag ? 'pwsh -File' : 'pwsh', scriptPath: file, shell: 'pwsh' };
1824
+ }
1825
+
1826
+ if (/^cmd(?:\.exe)?$/.test(name)) {
1827
+ let candidate = null;
1828
+ let sawFlag = false;
1829
+ for (let cursor = 0; cursor < args.length; cursor += 1) {
1830
+ const token = args[cursor];
1831
+ if (token.startsWith('-')) continue;
1832
+ if (!token.startsWith('/')) break;
1833
+ const raw = token.slice(1);
1834
+ const colon = raw.indexOf(':');
1835
+ const flag = (colon === -1 ? raw : raw.slice(0, colon)).toLowerCase();
1836
+ if (CMD_SCRIPT_FLAGS.has(flag)) {
1837
+ // `/c:x.cmd` 这种同 token 写法也认(fix 1)。
1838
+ candidate = colon === -1 ? (args[cursor + 1] ?? null) : raw.slice(colon + 1);
1839
+ sawFlag = true;
1840
+ break;
1841
+ }
1842
+ // v1.6.1 fix 1:`/d` `/q` `/e:on` 等前置开关不改变「读文件执行」语义,
1843
+ // 继续往后找 `/c`;旧实现遇到它们就 break → `cmd /d /c 脚本` 落到第 4 类。
1844
+ if (CMD_PRE_SWITCHES.has(flag)) continue;
1845
+ break;
1846
+ }
1847
+ if (!sawFlag || candidate === null || candidate === '') continue;
1848
+ // 只把「像脚本文件」的目标当载体:否则 `cmd /c "echo 1 > src/x.ts"` 会被误当脚本,
1849
+ // 丢掉既有的「cmd /c 内容不可见 → 1 类硬拒」判定。带空白/重定向/元字符的一律不是路径。
1850
+ if (/[\s<>&|;$`'"]/.test(candidate)) continue;
1851
+ const ext = extname(candidate).toLowerCase();
1852
+ if (!WRAPPER_SCRIPT_EXTENSIONS.has(ext) && !/[\\/]/.test(candidate)) continue;
1853
+ return { wrapper: 'cmd /c', scriptPath: candidate, shell: 'pwsh' };
1854
+ }
1855
+
1856
+ if (name === 'node') {
1857
+ if (args.some((token) => INTERPRETER_INLINE_FLAGS.test(token))) continue;
1858
+ let candidate = null;
1859
+ for (const token of args) {
1860
+ if (token.startsWith('-')) continue;
1861
+ candidate = token;
1862
+ break;
1863
+ }
1864
+ if (candidate === null) continue;
1865
+ // 默认**不读**内容(`node test/guard.js` 正文里带 openfeel 字面量,读内容会误杀);
1866
+ // 是否强制读取由 `resolveWrapperScript` 按路径判定(scripts/** / release|publish|commit)。
1867
+ return { wrapper: 'node', scriptPath: candidate, shell: 'bash', inspect: false };
1868
+ }
1869
+ }
1870
+ return null;
1871
+ }
1872
+
1873
+ /**
1874
+ * UTF-16 字节序互换(BE → LE 视图)。
1875
+ * @param {Buffer} buffer
1876
+ * @returns {Buffer}
1877
+ */
1878
+ function swapUtf16Bytes(buffer) {
1879
+ const copy = Buffer.from(buffer);
1880
+ for (let index = 0; index + 1 < copy.length; index += 2) {
1881
+ const high = copy[index];
1882
+ copy[index] = copy[index + 1];
1883
+ copy[index + 1] = high;
1884
+ }
1885
+ return copy;
1886
+ }
1887
+
1888
+ /**
1889
+ * 无 BOM 的 UTF-16 粗判:UTF-16 文本在奇/偶字节位置有大量 0x00,GBK/UTF-8 没有。
1890
+ * 只在「一侧近半数为 0、另一侧几乎没有 0」时成立,避免把二进制误当文本。
1891
+ * @param {Buffer} buffer
1892
+ * @returns {{ text: string, charset: string } | null}
1893
+ */
1894
+ function sniffUtf16(buffer) {
1895
+ if (buffer.length < 4 || buffer.length % 2 !== 0) return null;
1896
+ const pairs = Math.min(Math.floor(buffer.length / 2), 1024);
1897
+ let evenZero = 0;
1898
+ let oddZero = 0;
1899
+ for (let index = 0; index < pairs; index += 1) {
1900
+ if (buffer[index * 2] === 0) evenZero += 1;
1901
+ if (buffer[index * 2 + 1] === 0) oddZero += 1;
1902
+ }
1903
+ if (oddZero / pairs > 0.5 && evenZero / pairs < 0.1) {
1904
+ return { text: buffer.toString('utf16le'), charset: 'utf-16le' };
1905
+ }
1906
+ if (evenZero / pairs > 0.5 && oddZero / pairs < 0.1) {
1907
+ return { text: swapUtf16Bytes(buffer).toString('utf16le'), charset: 'utf-16be' };
1908
+ }
1909
+ return null;
1910
+ }
1911
+
1912
+ /**
1913
+ * 脚本正文的「可执行语句视图」(v1.6.1 / R7,仅用于分类,不改写文件)。
1914
+ *
1915
+ * 脚本里的整行注释(`#` / shebang)、cmd 的 `rem` / `::` 不是命令;cmd 行首 `@`
1916
+ * (`@echo off`)也不是命令名。不清洗的话每条带注释的普通脚本都会被打成
1917
+ * 「未识别的命令 #」→ 第 4 类,A67.2 的「普通脚本 allow」就不成立了。
1918
+ *
1919
+ * @param {string} content
1920
+ * @returns {string}
1921
+ */
1922
+ function normalizeScriptStatements(content) {
1923
+ const lines = [];
1924
+ for (const raw of String(content).split(/\r?\n/)) {
1925
+ const line = raw.trim().replace(/^@+/, '').trim();
1926
+ if (line === '') continue;
1927
+ if (line.startsWith('#') || line.startsWith('::')) continue;
1928
+ if (/^rem(?:\s|$)/i.test(line)) continue;
1929
+ lines.push(line);
1930
+ }
1931
+ return lines.join('\n');
1932
+ }
1933
+
1934
+ /**
1935
+ * 解码脚本内容(v1.6.1 / REQ-067 A67.3 编码口径,零外部依赖)。
1936
+ *
1937
+ * 只接受 **UTF-8**(含 BOM,严格校验)与 **UTF-16**(BOM 或 NUL 启发式)。
1938
+ * **GBK 等双字节编码刻意不解码**:同一串字节按 GBK 解很可能得到「看起来只读」的
1939
+ * 乱码文本 → 假安全;保守判 `null`(undecidable),默认 warn + 审计。
1940
+ *
1941
+ * @param {Buffer} buffer
1942
+ * @returns {{ text: string, charset: string } | null}
1943
+ */
1944
+ function decodeScriptText(buffer) {
1945
+ if (buffer.length === 0) return { text: '', charset: 'utf-8' };
1946
+ if (buffer.length >= 3 && buffer[0] === 0xef && buffer[1] === 0xbb && buffer[2] === 0xbf) {
1947
+ try {
1948
+ return { text: new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(3)), charset: 'utf-8-bom' };
1949
+ } catch {
1950
+ return null;
1951
+ }
1952
+ }
1953
+ if (buffer.length >= 2 && buffer[0] === 0xff && buffer[1] === 0xfe) {
1954
+ return { text: buffer.subarray(2).toString('utf16le'), charset: 'utf-16le-bom' };
1955
+ }
1956
+ if (buffer.length >= 2 && buffer[0] === 0xfe && buffer[1] === 0xff) {
1957
+ return { text: swapUtf16Bytes(buffer.subarray(2)).toString('utf16le'), charset: 'utf-16be-bom' };
1958
+ }
1959
+ const sniffed = sniffUtf16(buffer);
1960
+ if (sniffed !== null) return sniffed;
1961
+ try {
1962
+ return { text: new TextDecoder('utf-8', { fatal: true }).decode(buffer), charset: 'utf-8' };
1963
+ } catch {
1964
+ return null;
1965
+ }
1966
+ }
1967
+
1968
+ /**
1969
+ * `node <脚本>` 是否**必须**读内容分类(v1.6.1 fix 2)。
1970
+ *
1971
+ * 默认不读:`node test/guard.js` 这类测试脚本正文里本来就带 openfeel 命令字面量,
1972
+ * 一律读内容会误杀日常测试(A67.2「不误杀」)。
1973
+ * 但下面两类是「命令文本只看得见路径、真实动作在正文里」的高风险载体,必须读:
1974
+ * - 路径落在 `scripts/**`(发布/构建脚本的惯例目录);
1975
+ * - 文件名含 `release` / `publish` / `commit`(`scripts` 之外的同类脚本)。
1976
+ *
1977
+ * @param {string} scriptPath 已解析的绝对路径
1978
+ * @param {string} baseDir 命令基准目录
1979
+ * @returns {boolean}
1980
+ */
1981
+ function nodeScriptNeedsInspection(scriptPath, baseDir) {
1982
+ const rel = relative(baseDir, scriptPath).replace(/\\/g, '/');
1983
+ if (/(?:^|\/)scripts\//i.test(rel)) return true;
1984
+ return /release|publish|commit/i.test(basename(scriptPath));
1985
+ }
1986
+
1987
+ /**
1988
+ * 解析包装器背后的脚本文件并读取内容(v1.6.1 / REQ-067 A67)。
1989
+ *
1990
+ * 返回值三态(调用方据此判 1/2 类或第 4 类):
1991
+ * - `null`:不是「读文件执行」形态(含内联 `-c` / `-e`、`cmd /c` 内联 payload);
1992
+ * - `{ scriptPath, content, shell, charset, wrapper }`:可读取,交给内容分类;
1993
+ * - `{ scriptPath, undecidable: true, reason, wrapper }`:不存在 / 非文件 / 超限 /
1994
+ * 编码非 UTF / node 默认不读 → **不可判定**(绝不当作安全)。
1995
+ *
1996
+ * `highRisk:true`(仅 node 且命中 `nodeScriptNeedsInspection`):内容已读取,
1997
+ * 若正文不可判定,调用方按第 1 类拒绝(发布类脚本不允许「未知 → warn 放行」)。
1998
+ *
1999
+ * @param {string} statement
2000
+ * @param {string} baseDir 已归一化的命令基准目录
2001
+ * @returns {{ wrapper: string, scriptPath: string, content?: string, charset?: string, shell?: 'bash'|'pwsh'|'cmd', highRisk?: boolean, undecidable?: boolean, reason?: string } | null}
2002
+ */
2003
+ function resolveWrapperScript(statement, baseDir) {
2004
+ const candidate = matchWrapperScriptTarget(statement);
2005
+ if (candidate === null) return null;
2006
+ const scriptPath = resolve(baseDir, candidate.scriptPath);
2007
+ const base = { wrapper: candidate.wrapper, scriptPath };
2008
+ if (candidate.inspect === false && !nodeScriptNeedsInspection(scriptPath, baseDir)) {
2009
+ return { ...base, undecidable: true, reason: 'node-script-content-not-inspected' };
2010
+ }
2011
+ try {
2012
+ const stat = statSync(scriptPath);
2013
+ if (!stat.isFile()) return { ...base, undecidable: true, reason: 'script-not-a-file' };
2014
+ if (stat.size > MAX_SCRIPT_BYTES) {
2015
+ return { ...base, undecidable: true, reason: `script-too-large(>${MAX_SCRIPT_BYTES} bytes)` };
2016
+ }
2017
+ const decoded = decodeScriptText(readFileSync(scriptPath));
2018
+ if (decoded === null) return { ...base, undecidable: true, reason: 'unknown-encoding(非 UTF-8/UTF-16)' };
2019
+ const ext = extname(scriptPath).toLowerCase();
2020
+ return {
2021
+ ...base,
2022
+ content: normalizeScriptStatements(decoded.text),
2023
+ charset: decoded.charset,
2024
+ // 内容语义按**扩展名**判定(`.cmd` 用 cmd 语义),扩展名未知时才回落到启动器。
2025
+ shell: WRAPPER_SCRIPT_EXTENSIONS.get(ext) ?? candidate.shell ?? 'bash',
2026
+ ...(candidate.inspect === false ? { highRisk: true } : {}),
2027
+ };
2028
+ } catch {
2029
+ return { ...base, undecidable: true, reason: 'script-unreadable(不存在或不可读)' };
2030
+ }
2031
+ }
2032
+
1567
2033
  /**
1568
2034
  * 判断 shell 命令里的 `openfeel …` 是否是写子命令(第 1 类)。
1569
2035
  * @param {string[]} args `openfeel` 之后的 token
@@ -1738,6 +2204,41 @@ function parsePowerShellWrite(command, tokens, start) {
1738
2204
  return { targets };
1739
2205
  }
1740
2206
 
2207
+ /**
2208
+ * 解析 **cmd 语义**写命令的目标(v1.6.1 fix 3;只用于 `.cmd` / `.bat` 正文)。
2209
+ *
2210
+ * `copy a b` / `move a b`:只有目标(最后一个位置参数)算写 —— 源是读;
2211
+ * `del` / `ren` / `rmdir` 等:全部位置参数都算写。
2212
+ * `/y`、`/q`、`-y`、`/f` 之类的开关不消费下一个 token(cmd 开关不带值),
2213
+ * 所以这里只按「非开关位置参数」取目标。
2214
+ *
2215
+ * @param {string} command 已小写的命令名
2216
+ * @param {string[]} tokens
2217
+ * @param {number} start
2218
+ * @returns {{ targets: string[], undecidable?: boolean, detail?: string } | null}
2219
+ */
2220
+ function parseCmdWrite(command, tokens, start) {
2221
+ const spec = CMD_WRITE_SPECS.get(command);
2222
+ if (spec === undefined) return null;
2223
+ const positionals = [];
2224
+ for (let index = start + 1; index < tokens.length && tokens[index] !== '|'; index += 1) {
2225
+ const token = tokens[index];
2226
+ if (token.startsWith('/') || token.startsWith('-')) continue;
2227
+ if (token === '') continue;
2228
+ positionals.push(token);
2229
+ }
2230
+ if (spec === 'dest') {
2231
+ if (positionals.length >= 2) return { targets: [positionals[positionals.length - 1]] };
2232
+ if (positionals.length === 1) return { targets: [], undecidable: true, detail: `${command} 缺少目标(只有源)` };
2233
+ return { targets: [] };
2234
+ }
2235
+ if (spec === 'dest2') {
2236
+ if (positionals.length >= 2) return { targets: [positionals[1]] };
2237
+ return { targets: [], undecidable: true, detail: `${command} 缺少目标(只有源)` };
2238
+ }
2239
+ return { targets: positionals };
2240
+ }
2241
+
1741
2242
  /**
1742
2243
  * 解析 POSIX 写命令的目标(bash 分支)。
1743
2244
  * @param {string} command 已小写的命令名
@@ -2354,7 +2855,7 @@ function classifyGitCommand(tokens, start, baseDir) {
2354
2855
  * `undecidable = true`(第 4 类),**不再**静默按「没有写」放行。
2355
2856
  *
2356
2857
  * @param {string} statement
2357
- * @param {'bash'|'pwsh'} shell
2858
+ * @param {'bash'|'pwsh'|'cmd'} shell `cmd` 只用于 `.cmd` / `.bat` 正文(v1.6.1 fix 3)
2358
2859
  * @param {string} baseDir
2359
2860
  * @returns {{ targets: string[], wholeTree?: string, wholeTreePhases?: string[], wholeTreeGitSubcommand?: string, wholeTreeRepoOverride?: boolean, wholeTreeGitConfig?: boolean, blockedGit?: string, undecidable: boolean, detail: string }}
2360
2861
  */
@@ -2499,7 +3000,11 @@ function analyzeShellStatement(statement, shell, baseDir, vars = new Map()) {
2499
3000
  // 误判成「没有写」。合并 POSIX spec 后目标仍能取到;两类 spec 是保守并集
2500
3001
  // (多出来的目标只会更严,不会更松)。
2501
3002
  const parsed = [];
2502
- if (shell === 'pwsh') {
3003
+ if (shell === 'cmd') {
3004
+ // v1.6.1 fix 3:`.cmd` / `.bat` 正文按 **cmd 语义**判定,不并入 PowerShell/POSIX 表
3005
+ // (`move` 在 PS 表里是 `all`,会把只被读的源也算成写目标 → 误杀 `copy/move src …`)。
3006
+ parsed.push(parseCmdWrite(name, tokens, cursor));
3007
+ } else if (shell === 'pwsh') {
2503
3008
  parsed.push(parsePowerShellWrite(name, tokens, cursor), parsePosixWrite(name, tokens, cursor, baseDir));
2504
3009
  } else {
2505
3010
  parsed.push(parsePosixWrite(name, tokens, cursor, baseDir), parsePowerShellWrite(name, tokens, cursor));
@@ -2548,14 +3053,21 @@ function analyzeShellStatement(statement, shell, baseDir, vars = new Map()) {
2548
3053
  * 分类一条 shell 命令(四类判定;不读 flow,不判定相位)。
2549
3054
  *
2550
3055
  * op-002b 精化:
2551
- * - `-EncodedCommand` / `iex` / `Invoke-Expression` / `eval` / `cmd /c` → 第 1 类硬拒(内容不可见);
3056
+ * - `-EncodedCommand` / `iex` / `Invoke-Expression` / `eval` → 第 1 类硬拒(内容不可见);
3057
+ * `cmd /c` 若解析得出脚本文件则改走「读内容分类」(R7),解析不出(内联 payload)仍硬拒;
2552
3058
  * - `node -e` / `python -c` / `perl -e` / `ruby -e` / `php -r` → **先扫 payload**:
2553
3059
  * 含写 API 才拒,纯只读诊断(`node -e "console.log(…)"`)放行且不审计(`readonly-interpreter`);
2554
3060
  * - `bash|sh -c` / `powershell|pwsh -Command` → **递归解析内层命令**(同一判定器),
2555
3061
  * 内层可判定按内层判;内层为空/不可判定 → 第 4 类(`undecidable`)。
3062
+ * - v1.6.1 / REQ-067 A67:`pwsh -File` / `cmd /c` / `bash <脚本>` / `source <脚本>` /
3063
+ * `pwsh <脚本>` → **读脚本内容递归分类**;`.cmd`/`.bat` 用 cmd 语义(fix 3);
3064
+ * `node <scripts/**>` 或名字含 release|publish|commit 的脚本也读内容,
3065
+ * 正文判不了按第 1 类拒绝(fix 2);
3066
+ * 结果带 `wrapper:{wrapper, scriptPath, class:'class1'|'class2'|'undecidable'|'none', reason}`
3067
+ * (1/2 类命中时 class 为 1/2;不可判定时 class 为 `undecidable`;确认只读为 `none`)。
2556
3068
  *
2557
- * @param {{ command: string, baseDir: string, shell: 'bash'|'pwsh', depth?: number }} input
2558
- * @returns {{ kind: 'indirect'|'openfeel-write'|'whole-tree'|'targets'|'undecidable'|'none'|'readonly-interpreter', detail: string, targets: string[], undecidable: boolean, phases?: string[], gitSubcommand?: string, repoOverride?: boolean, gitConfig?: boolean }}
3069
+ * @param {{ command: string, baseDir: string, shell: 'bash'|'pwsh'|'cmd', depth?: number }} input
3070
+ * @returns {{ kind: 'indirect'|'openfeel-write'|'whole-tree'|'targets'|'undecidable'|'none'|'readonly-interpreter', detail: string, targets: string[], undecidable: boolean, phases?: string[], gitSubcommand?: string, repoOverride?: boolean, gitConfig?: boolean, wrapper?: { wrapper: string, scriptPath: string, class: string, reason: string } }}
2559
3071
  */
2560
3072
  export function classifyShellCommand({ command, baseDir, shell, depth = 0 }) {
2561
3073
  const statements = splitShellStatements(command);
@@ -2566,6 +3078,8 @@ export function classifyShellCommand({ command, baseDir, shell, depth = 0 }) {
2566
3078
  let undecidable = false;
2567
3079
  let detail = '';
2568
3080
  let readonlyInterpreter = false;
3081
+ /** 包装器脚本证据(R7):{wrapper, scriptPath, class, reason};无则为 null。 */
3082
+ let wrapper = null;
2569
3083
 
2570
3084
  /** 记录一个目标(字面量 → 绝对路径;变量/派生 → 第 4 类)。 */
2571
3085
  const pushTarget = (raw) => {
@@ -2587,9 +3101,21 @@ export function classifyShellCommand({ command, baseDir, shell, depth = 0 }) {
2587
3101
  };
2588
3102
 
2589
3103
  for (const statement of statements) {
2590
- // 第 1 类:内容不可见的形态 → 硬拒
3104
+ // 第 1 类:内容不可见的形态 → 硬拒。
3105
+ // v1.6.1 / R7 例外:`cmd /c <脚本文件>` 以前一律硬拒;现在能解析出脚本文件时改走
3106
+ // 「读内容分类」(否则普通 `cmd /c build.cmd` 会被一并误杀,A67.2)。解析不出
3107
+ // 脚本文件(内联 payload,如 `cmd /c "echo 1 > src/x.ts"`)仍保持硬拒。
3108
+ const scriptInvocation = depth < WRAPPER_MAX_DEPTH ? resolveWrapperScript(statement, baseDir) : null;
2591
3109
  const hard = matchHardIndirect(statement);
2592
- if (hard !== null) return { kind: 'indirect', detail: hard, targets: [], undecidable: false };
3110
+ if (hard !== null) {
3111
+ // `cmd /c <脚本>` 只要解析出脚本路径就走「读内容分类」:可读 → 1/2 类判定;
3112
+ // 不可读/超限/编码不明 → 第 4 类 warn + 审计(A67.3 对 `.cmd` 的 GBK 用例同样是
3113
+ // undecidable,不能因为 `cmd /c` 的旧硬拒把它变成「内容不可见」的假通过)。
3114
+ const scriptCarrier = hard === 'cmd /c' && scriptInvocation !== null;
3115
+ if (!scriptCarrier) {
3116
+ return { kind: 'indirect', detail: hard, targets: [], undecidable: false };
3117
+ }
3118
+ }
2593
3119
 
2594
3120
  // 第 1 类:shell 跑 openfeel 写子命令
2595
3121
  const openfeel = matchOpenFeelWrite(statement);
@@ -2635,6 +3161,94 @@ export function classifyShellCommand({ command, baseDir, shell, depth = 0 }) {
2635
3161
  }
2636
3162
  }
2637
3163
 
3164
+ // v1.6.1 / REQ-067 A67(R7):`pwsh -File` / `cmd /c` / `bash <脚本>` 读文件执行 ——
3165
+ // 命令文本里只有路径,写操作在文件正文里,旧实现整条落到第 4 类(warn 放行)。
3166
+ // 这里静态读取脚本内容,交给**同一份** `classifyShellCommand` 递归分类:
3167
+ // 内容命中 openfeel 写动词/间接执行 → 1 类;内容解析出写目标 → 2 类(交给相位判定);
3168
+ // 内容不可判定 → 第 4 类(把 wrapper/scriptPath 放进 detail,审计可见)。
3169
+ if (scriptInvocation !== null) {
3170
+ // 外层重定向(`pwsh -File x.ps1 > src/x.ts`)同样算写入。
3171
+ for (const raw of scanShellRedirections(statement).targets) pushTarget(raw);
3172
+ if (scriptInvocation.undecidable === true) {
3173
+ undecidable = true;
3174
+ detail = detail || `wrapper ${scriptInvocation.wrapper}(${scriptInvocation.scriptPath}):${scriptInvocation.reason}`;
3175
+ wrapper = {
3176
+ wrapper: scriptInvocation.wrapper,
3177
+ scriptPath: scriptInvocation.scriptPath,
3178
+ class: 'undecidable',
3179
+ reason: scriptInvocation.reason ?? 'script-undecidable',
3180
+ };
3181
+ continue;
3182
+ }
3183
+ const nested = classifyShellCommand({
3184
+ command: scriptInvocation.content ?? '',
3185
+ baseDir,
3186
+ shell: scriptInvocation.shell ?? 'bash',
3187
+ depth: depth + 1,
3188
+ });
3189
+ if (nested.kind === 'indirect' || nested.kind === 'openfeel-write' || nested.kind === 'whole-tree') {
3190
+ wrapper = {
3191
+ wrapper: scriptInvocation.wrapper,
3192
+ scriptPath: scriptInvocation.scriptPath,
3193
+ class: 'class1',
3194
+ reason: 'wrapper-write',
3195
+ };
3196
+ return { ...nested, wrapper };
3197
+ }
3198
+ if (nested.targets.length > 0) {
3199
+ targets.push(...nested.targets);
3200
+ if (nested.undecidable) {
3201
+ undecidable = true;
3202
+ detail = detail || nested.detail || '脚本内写目标不可判定';
3203
+ }
3204
+ wrapper = {
3205
+ wrapper: scriptInvocation.wrapper,
3206
+ scriptPath: scriptInvocation.scriptPath,
3207
+ class: 'class2',
3208
+ reason: 'wrapper-write',
3209
+ };
3210
+ continue;
3211
+ }
3212
+ // v1.6.1 fix 2:`node <scripts/**>` / 名字含 release|publish|commit 的脚本(highRisk)。
3213
+ // 这类脚本的真实动作(npm publish / git commit)只在正文里;正文按 shell 语义拿不到
3214
+ // 确定结论时**不能**继续 warn 放行 —— 那等于发布通道敞开。按第 1 类拒绝。
3215
+ if (scriptInvocation.highRisk === true
3216
+ && (nested.undecidable || nested.kind === 'undecidable')) {
3217
+ wrapper = {
3218
+ wrapper: scriptInvocation.wrapper,
3219
+ scriptPath: scriptInvocation.scriptPath,
3220
+ class: 'class1',
3221
+ reason: 'node-script-high-risk-undecidable',
3222
+ };
3223
+ return {
3224
+ kind: 'indirect',
3225
+ detail: `node 高风险脚本(${scriptInvocation.scriptPath})内容不可判定:${nested.detail || '未知'};按第 1 类拒绝(发布/提交类脚本要求人工在外部终端执行)`,
3226
+ targets: [],
3227
+ undecidable: false,
3228
+ wrapper,
3229
+ };
3230
+ }
3231
+ if (nested.undecidable || nested.kind === 'undecidable') {
3232
+ undecidable = true;
3233
+ detail = detail || nested.detail || `wrapper ${scriptInvocation.wrapper}(${scriptInvocation.scriptPath})内容不可判定`;
3234
+ wrapper = {
3235
+ wrapper: scriptInvocation.wrapper,
3236
+ scriptPath: scriptInvocation.scriptPath,
3237
+ class: 'undecidable',
3238
+ reason: 'wrapper-content-undecidable',
3239
+ };
3240
+ continue;
3241
+ }
3242
+ // 内容确认只读(`readonly.ps1` / `build.ps1`):放行,但审计留下 wrapper 证据。
3243
+ wrapper = {
3244
+ wrapper: scriptInvocation.wrapper,
3245
+ scriptPath: scriptInvocation.scriptPath,
3246
+ class: 'none',
3247
+ reason: 'wrapper-readonly',
3248
+ };
3249
+ continue;
3250
+ }
3251
+
2638
3252
  // 命令替换 / 反引号的内层命令在 `analyzeShellStatement` 里**叠加**判定为第 4 类
2639
3253
  // (不和 git 整树写等更强结论二选一)。
2640
3254
  const analysis = analyzeShellStatement(statement, shell, baseDir, vars);
@@ -2679,10 +3293,12 @@ export function classifyShellCommand({ command, baseDir, shell, depth = 0 }) {
2679
3293
  }
2680
3294
  // 第 4 类(op-005 / P0-1):**没有正面证据**证明「这条命令不写」→ undecidable,
2681
3295
  // 不再返回 `none` 静默放行。审计的 `kind` 因此能区分 no-write 与 undecidable。
2682
- if (undecidable) return { kind: 'undecidable', detail: detail || '命令写入意图无法判定', targets, undecidable };
2683
- return { kind: 'none', detail, targets, undecidable };
3296
+ if (undecidable) {
3297
+ return { kind: 'undecidable', detail: detail || '命令写入意图无法判定', targets, undecidable, ...(wrapper === null ? {} : { wrapper }) };
3298
+ }
3299
+ return { kind: 'none', detail, targets, undecidable, ...(wrapper === null ? {} : { wrapper }) };
2684
3300
  }
2685
- return { kind: 'targets', targets, undecidable, detail };
3301
+ return { kind: 'targets', targets, undecidable, detail, ...(wrapper === null ? {} : { wrapper }) };
2686
3302
  }
2687
3303
 
2688
3304
  /**
@@ -2799,7 +3415,7 @@ function formatActivePhases(active) {
2799
3415
  * `.openfeel/**` 任意相位可写会让 agent 手写 `chore.json` / `.preflight.json` 自提权。
2800
3416
  *
2801
3417
  * @param {{ t: (zh: string, en: string) => string, enforce: 'off'|'project'|'always', allowGeneral: boolean, bootstrapHinted: Set<string> }} context
2802
- * @param {{ name: string, targets: string[], patchEntries?: Array<{ path: string, kind: string }> | null, resolvedCwd: string, normalizedCwd: string, cwdSource: string, audit?: boolean }} request
3418
+ * @param {{ name: string, targets: string[], patchEntries?: Array<{ path: string, kind: string }> | null, resolvedCwd: string, normalizedCwd: string, cwdSource: string, audit?: boolean, auditExtra?: Record<string, unknown> }} request
2803
3419
  * @returns {{ decision: 'allow'|'deny', reason: string, message?: string }}
2804
3420
  */
2805
3421
  function decideForTargets(context, request) {
@@ -2812,6 +3428,8 @@ function decideForTargets(context, request) {
2812
3428
  tool: name,
2813
3429
  cwdSource,
2814
3430
  paths: targets,
3431
+ // v1.6.1 / R7:origin / delegationDepth 由调用方按 header 传入(无则空对象)。
3432
+ ...(request.auditExtra ?? {}),
2815
3433
  ...event,
2816
3434
  });
2817
3435
  };
@@ -2927,7 +3545,14 @@ function decideForTargets(context, request) {
2927
3545
  }
2928
3546
 
2929
3547
  if (active.some((stage) => stage.phase === 'exec_running')) return { decision: 'allow', reason: 'exec-running' };
2930
- // P0-4/v1.4.0:非 exec 相位仍允许 doc/note 与静态展示资源(研究记录、设计文档、UI 资源等);源码仍严格。
3548
+ // v1.6.1 / REQ-062 A62.1:审后相位(review_passed / test_passed)允许写文档与测试夹具,
3549
+ // **源码仍拒**。判据单点 = isDocAssetWritePath(夹具/根 md/docs/**),不在这里散落名单。
3550
+ const docWritePhase = active.some((stage) => DOC_WRITE_PHASES.includes(stage.phase));
3551
+ if (docWritePhase && targets.every((target) => isDocAssetWritePath(target, normalizedCwd))) {
3552
+ recordAudit({ reason: 'doc-asset-phase', phase: formatActivePhases(active) });
3553
+ return { decision: 'allow', reason: 'doc-asset-phase' };
3554
+ }
3555
+ // P0-4/v1.4.0:其余非 exec 相位仍允许 doc/note 与静态展示资源(研究记录、设计文档、UI 资源等);源码仍严格。
2931
3556
  if (targets.every((target) => isExemptPath(target, normalizedCwd))) {
2932
3557
  recordAudit({ reason: 'doc-asset', phase: formatActivePhases(active) });
2933
3558
  return { decision: 'allow', reason: 'doc-asset' };
@@ -2937,8 +3562,8 @@ function decideForTargets(context, request) {
2937
3562
  decision: 'deny',
2938
3563
  reason: 'phase',
2939
3564
  message: t(
2940
- `OpenFeel 写入门禁:活跃阶段当前不在 exec_running(${formatActivePhases(active)}),不能修改源码/文档。请先 feel_flow action=advance 推进到 exec_running。`,
2941
- `OpenFeel write guard: active stage(s) are not in exec_running (${formatActivePhases(active)}), so source/docs are read-only. Advance to exec_running with feel_flow action=advance.`,
3565
+ `OpenFeel 写入门禁:活跃阶段当前不在 exec_running(${formatActivePhases(active)}),且目标不是文档/测试夹具,不能修改源码/文档。文档与测试夹具可在 review_passed / test_passed 写;改源码请先 feel_flow action=advance 推进到 exec_running。`,
3566
+ `OpenFeel write guard: active stage(s) are not in exec_running (${formatActivePhases(active)}) and the targets are not docs/test fixtures, so source is read-only. Docs and test fixtures may be written in review_passed / test_passed; advance to exec_running with feel_flow action=advance to change source.`,
2942
3567
  ),
2943
3568
  };
2944
3569
  }
@@ -3241,6 +3866,17 @@ export function createOpenFeelGuard(options = {}) {
3241
3866
  const normalizedCwd = resolvedCwd === null ? null : normalizeTarget(resolvedCwd, '.');
3242
3867
  const degraded = resolution.degraded;
3243
3868
  const shellCommand = isShell ? extractShellCommand(execution?.arguments).command : undefined;
3869
+ // v1.6.1 / REQ-067(R7):审计补 `origin` / `delegationDepth` —— **header 提供了才写**,
3870
+ // 缺失即省略(伪造会让「谁写的」审计失真)。
3871
+ const sessionHeader = execution?.agent?.session?.header ?? {};
3872
+ const auditOrigin = {
3873
+ ...(typeof sessionHeader.origin === 'string' && sessionHeader.origin.trim() !== ''
3874
+ ? { origin: sessionHeader.origin.trim() }
3875
+ : {}),
3876
+ ...(Number.isInteger(sessionHeader.delegationDepth)
3877
+ ? { delegationDepth: sessionHeader.delegationDepth }
3878
+ : {}),
3879
+ };
3244
3880
 
3245
3881
  /** 判定结论落盘(D-126-04):每次放行/拒绝/告警都更新 lastDecision。 */
3246
3882
  const recordDecision = (decision, { reason, paths = [], command = shellCommand }) => {
@@ -3304,6 +3940,7 @@ export function createOpenFeelGuard(options = {}) {
3304
3940
  paths: [],
3305
3941
  cwdSource: 'unresolved',
3306
3942
  command: shellCommand,
3943
+ ...auditOrigin,
3307
3944
  });
3308
3945
  return message;
3309
3946
  }
@@ -3334,12 +3971,21 @@ export function createOpenFeelGuard(options = {}) {
3334
3971
  // 先分类:审计的 `kind` 要能区分 `no-write`(确认只读)与 `undecidable`
3335
3972
  // (无法判定,op-005 / P0-1)。
3336
3973
  const classification = classifyShellCommand({ command, baseDir, shell: name });
3974
+ // v1.6.1 / REQ-067 A67.1—A67.3:包装器脚本证据。命中 1/2 类时审计 `kind` 用
3975
+ // `class1`/`class2`(A67.1 的取证口径),其余仍用原分类 kind(none/undecidable/…)。
3976
+ const wrapperDetail = classification.wrapper ?? null;
3977
+ const auditKind = wrapperDetail !== null
3978
+ && (wrapperDetail.class === 'class1' || wrapperDetail.class === 'class2')
3979
+ ? wrapperDetail.class
3980
+ : classification.kind;
3337
3981
  const recordShellAudit = (event) => recordGuardAudit(normalizedCwd, {
3338
3982
  tool: name,
3339
3983
  cwdSource,
3340
3984
  command,
3341
3985
  phase: phaseSummary(),
3342
- kind: classification.kind,
3986
+ kind: auditKind,
3987
+ ...(wrapperDetail === null ? {} : { detail: wrapperDetail }),
3988
+ ...auditOrigin,
3343
3989
  ...event,
3344
3990
  });
3345
3991
  const warnLine = (zh, en) => process.stderr.write(`${t(zh, en)}\n`);
@@ -3392,6 +4038,15 @@ export function createOpenFeelGuard(options = {}) {
3392
4038
  return undefined;
3393
4039
  };
3394
4040
 
4041
+ // v1.6.1 / REQ-067 A67.1(class 1):包装器脚本**正文**命中 openfeel 写动词 /
4042
+ // 嵌套解释器 / 间接执行 → 拒绝。审计 `kind:'class1'` + `detail:{wrapper,scriptPath,…}`。
4043
+ if (wrapperDetail !== null && wrapperDetail.class === 'class1') {
4044
+ const target = `${wrapperDetail.wrapper} ${wrapperDetail.scriptPath}`;
4045
+ return denyDecidable('wrapper-write', t(
4046
+ `OpenFeel 写入门禁:禁止用包装脚本执行写操作(${target};脚本内容命中「${classification.detail}」)。脚本正文里的 openfeel 写命令/嵌套解释器与直接写在 shell 工具里同等对待 —— 请改用 feel_flow / feel_stage / feel_req 等工具;只读脚本不受影响。`,
4047
+ `OpenFeel write guard: executing write operations through a wrapper script is not allowed (${target}; script content matched "${classification.detail}"). openfeel write commands / nested interpreters inside the script are treated the same as typing them in the shell tool: use feel_flow / feel_stage / feel_req; read-only scripts are unaffected.`,
4048
+ ), []);
4049
+ }
3395
4050
  // 第 1 类:编码/间接执行形态(含「内联解释器 payload 里有写 API」)
3396
4051
  if (classification.kind === 'indirect') {
3397
4052
  return denyDecidable('shell-indirect-exec', t(
@@ -3525,12 +4180,16 @@ export function createOpenFeelGuard(options = {}) {
3525
4180
  }
3526
4181
 
3527
4182
  const shellPaths = classification.targets;
4183
+ // v1.6.1 / REQ-067 A67.1(class 2):包装器脚本内容可解析出写目标时,拒绝原因统一
4184
+ // 记为 `wrapper-write`(`detail` 已带 wrapper/scriptPath),但判定仍走同一套目标逻辑
4185
+ // (受保护路径 / 相位 / doc-asset),不另立一份表达式。
4186
+ const wrapperClass2 = wrapperDetail !== null && wrapperDetail.class === 'class2';
3528
4187
  // 第 1 类(写入目标维度):受保护路径,文案与文件工具完全一致
3529
4188
  const protectedHits = shellPaths
3530
4189
  .map((target) => matchProtectedPath(target, normalizedCwd))
3531
4190
  .filter((hit) => hit !== null);
3532
4191
  if (protectedHits.length > 0) {
3533
- return denyDecidable('shell-protected', protectedDenialMessage(protectedHits, t), shellPaths);
4192
+ return denyDecidable(wrapperClass2 ? 'wrapper-write' : 'shell-protected', protectedDenialMessage(protectedHits, t), shellPaths);
3534
4193
  }
3535
4194
  // 第 3 类:构建/测试产物豁免;必须**全部**命中才放行,混合目标从严
3536
4195
  const decidableTargets = shellPaths.filter((target) => !isBuildArtifactPath(target, normalizedCwd));
@@ -3546,8 +4205,11 @@ export function createOpenFeelGuard(options = {}) {
3546
4205
  normalizedCwd,
3547
4206
  cwdSource,
3548
4207
  audit: false,
4208
+ auditExtra: auditOrigin,
3549
4209
  });
3550
- if (decided.decision === 'deny') return denyDecidable(decided.reason, decided.message, decidableTargets);
4210
+ if (decided.decision === 'deny') {
4211
+ return denyDecidable(wrapperClass2 ? 'wrapper-write' : decided.reason, decided.message, decidableTargets);
4212
+ }
3551
4213
  if (classification.undecidable) return undecidableShell(classification.detail, shellPaths);
3552
4214
  return allowShell(decided.reason, decidableTargets);
3553
4215
  }
@@ -3594,6 +4256,7 @@ export function createOpenFeelGuard(options = {}) {
3594
4256
  resolvedCwd,
3595
4257
  normalizedCwd,
3596
4258
  cwdSource,
4259
+ auditExtra: auditOrigin,
3597
4260
  });
3598
4261
  if (decision.decision === 'allow') {
3599
4262
  recordDecision('allow', { reason: decision.reason, paths: targets });