@fantasticit/sumi 0.10.3 → 0.11.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 (170) hide show
  1. package/README.md +5 -1
  2. package/dist/adapters.d.ts +4 -0
  3. package/dist/adapters.js +9 -2
  4. package/dist/adapters.js.map +1 -1
  5. package/dist/agent-hooks.js +32 -4
  6. package/dist/agent-hooks.js.map +1 -1
  7. package/dist/agents.js +38 -1
  8. package/dist/agents.js.map +1 -1
  9. package/dist/bin.js +0 -0
  10. package/dist/cli.js +42 -7
  11. package/dist/cli.js.map +1 -1
  12. package/dist/config-text.d.ts +7 -0
  13. package/dist/config-text.js +54 -0
  14. package/dist/config-text.js.map +1 -0
  15. package/dist/context.js +14 -2
  16. package/dist/context.js.map +1 -1
  17. package/dist/doctor-wiring.d.ts +12 -0
  18. package/dist/doctor-wiring.js +59 -0
  19. package/dist/doctor-wiring.js.map +1 -0
  20. package/dist/hook-routing.d.ts +22 -0
  21. package/dist/hook-routing.js +95 -0
  22. package/dist/hook-routing.js.map +1 -0
  23. package/dist/index.d.ts +1 -0
  24. package/dist/index.js +1 -0
  25. package/dist/index.js.map +1 -1
  26. package/dist/instructions.js +7 -5
  27. package/dist/instructions.js.map +1 -1
  28. package/dist/run-stats.d.ts +52 -0
  29. package/dist/run-stats.js +150 -0
  30. package/dist/run-stats.js.map +1 -0
  31. package/dist/task.js +5 -2
  32. package/dist/task.js.map +1 -1
  33. package/dist/vendor.js +7 -3
  34. package/dist/vendor.js.map +1 -1
  35. package/node_modules/@sumi/create/package.json +2 -2
  36. package/node_modules/@sumi/create/template/control/flows/check.flow.yaml +6 -1
  37. package/node_modules/@sumi/create/template/control/rubrics/behavior.yaml +1 -1
  38. package/node_modules/@sumi/create/template/control/rubrics/domain.yaml +1 -1
  39. package/node_modules/@sumi/create/template/control/rubrics/omission.yaml +1 -1
  40. package/node_modules/@sumi/create/template/control/rules/development.md +7 -0
  41. package/node_modules/@sumi/kernel/README.md +9 -8
  42. package/node_modules/@sumi/kernel/dist/brief.d.ts +1 -0
  43. package/node_modules/@sumi/kernel/dist/brief.js +6 -0
  44. package/node_modules/@sumi/kernel/dist/brief.js.map +1 -1
  45. package/node_modules/@sumi/kernel/dist/engine.d.ts +6 -0
  46. package/node_modules/@sumi/kernel/dist/engine.js +84 -9
  47. package/node_modules/@sumi/kernel/dist/engine.js.map +1 -1
  48. package/node_modules/@sumi/kernel/dist/flow.d.ts +2 -0
  49. package/node_modules/@sumi/kernel/dist/flow.js +3 -0
  50. package/node_modules/@sumi/kernel/dist/flow.js.map +1 -1
  51. package/node_modules/@sumi/kernel/dist/index.d.ts +1 -0
  52. package/node_modules/@sumi/kernel/dist/index.js +1 -0
  53. package/node_modules/@sumi/kernel/dist/index.js.map +1 -1
  54. package/node_modules/@sumi/kernel/dist/record.d.ts +7 -0
  55. package/node_modules/@sumi/kernel/dist/record.js +2 -0
  56. package/node_modules/@sumi/kernel/dist/record.js.map +1 -1
  57. package/node_modules/@sumi/kernel/dist/registry.js +1 -0
  58. package/node_modules/@sumi/kernel/dist/registry.js.map +1 -1
  59. package/node_modules/@sumi/kernel/dist/resume.d.ts +9 -0
  60. package/node_modules/@sumi/kernel/dist/resume.js +171 -0
  61. package/node_modules/@sumi/kernel/dist/resume.js.map +1 -0
  62. package/node_modules/@sumi/kernel/dist/step-cache.d.ts +21 -1
  63. package/node_modules/@sumi/kernel/dist/step-cache.js +151 -15
  64. package/node_modules/@sumi/kernel/dist/step-cache.js.map +1 -1
  65. package/node_modules/@sumi/kernel/package.json +2 -2
  66. package/node_modules/@sumi/plugin-sdk/README.md +4 -0
  67. package/node_modules/@sumi/plugin-sdk/dist/protocol.d.ts +30 -4
  68. package/node_modules/@sumi/plugin-sdk/dist/protocol.js +28 -0
  69. package/node_modules/@sumi/plugin-sdk/dist/protocol.js.map +1 -1
  70. package/node_modules/@sumi/plugin-sdk/dist/session-context.d.ts +16 -0
  71. package/node_modules/@sumi/plugin-sdk/dist/session-context.js +51 -11
  72. package/node_modules/@sumi/plugin-sdk/dist/session-context.js.map +1 -1
  73. package/node_modules/@sumi/plugin-sdk/dist/shell.d.ts +27 -1
  74. package/node_modules/@sumi/plugin-sdk/dist/shell.js +430 -22
  75. package/node_modules/@sumi/plugin-sdk/dist/shell.js.map +1 -1
  76. package/node_modules/@sumi/plugin-sdk/dist/validate.js +14 -4
  77. package/node_modules/@sumi/plugin-sdk/dist/validate.js.map +1 -1
  78. package/node_modules/@sumi/plugin-sdk/package.json +1 -1
  79. package/node_modules/@sumi/plugins-core/README.md +11 -1
  80. package/node_modules/@sumi/plugins-core/dist/plugins/coverage.js +9 -2
  81. package/node_modules/@sumi/plugins-core/dist/plugins/coverage.js.map +1 -1
  82. package/node_modules/@sumi/plugins-core/dist/plugins/lint.js +3 -2
  83. package/node_modules/@sumi/plugins-core/dist/plugins/lint.js.map +1 -1
  84. package/node_modules/@sumi/plugins-core/dist/plugins/test-affected.js +39 -16
  85. package/node_modules/@sumi/plugins-core/dist/plugins/test-affected.js.map +1 -1
  86. package/node_modules/@sumi/plugins-core/instructions/bugfix.md +3 -3
  87. package/node_modules/@sumi/plugins-core/package.json +2 -2
  88. package/node_modules/@sumi/plugins-core/sumi-plugins.yaml +10 -2
  89. package/node_modules/@sumi/plugins-governance/dist/checkout.d.ts +8 -0
  90. package/node_modules/@sumi/plugins-governance/dist/checkout.js +18 -2
  91. package/node_modules/@sumi/plugins-governance/dist/checkout.js.map +1 -1
  92. package/node_modules/@sumi/plugins-governance/dist/commands/gate.js +16 -1
  93. package/node_modules/@sumi/plugins-governance/dist/commands/gate.js.map +1 -1
  94. package/node_modules/@sumi/plugins-governance/dist/commands/pr-report.js +3 -1
  95. package/node_modules/@sumi/plugins-governance/dist/commands/pr-report.js.map +1 -1
  96. package/node_modules/@sumi/plugins-governance/dist/gate-cache.d.ts +3 -1
  97. package/node_modules/@sumi/plugins-governance/dist/gate-cache.js +9 -0
  98. package/node_modules/@sumi/plugins-governance/dist/gate-cache.js.map +1 -1
  99. package/node_modules/@sumi/plugins-governance/dist/guard.js +261 -23
  100. package/node_modules/@sumi/plugins-governance/dist/guard.js.map +1 -1
  101. package/node_modules/@sumi/plugins-governance/dist/pr-report-compose.d.ts +2 -1
  102. package/node_modules/@sumi/plugins-governance/dist/pr-report-compose.js +19 -4
  103. package/node_modules/@sumi/plugins-governance/dist/pr-report-compose.js.map +1 -1
  104. package/node_modules/@sumi/plugins-governance/dist/state.js +8 -2
  105. package/node_modules/@sumi/plugins-governance/dist/state.js.map +1 -1
  106. package/node_modules/@sumi/plugins-governance/dist/workspace-runs.d.ts +21 -0
  107. package/node_modules/@sumi/plugins-governance/dist/workspace-runs.js +68 -0
  108. package/node_modules/@sumi/plugins-governance/dist/workspace-runs.js.map +1 -0
  109. package/node_modules/@sumi/plugins-governance/instructions/push.md +4 -3
  110. package/node_modules/@sumi/plugins-governance/package.json +2 -2
  111. package/node_modules/@sumi/plugins-openspec/package.json +4 -4
  112. package/node_modules/@sumi/plugins-precedent/README.md +11 -6
  113. package/node_modules/@sumi/plugins-precedent/dist/after-edit-context.d.ts +2 -1
  114. package/node_modules/@sumi/plugins-precedent/dist/after-edit-context.js +124 -13
  115. package/node_modules/@sumi/plugins-precedent/dist/after-edit-context.js.map +1 -1
  116. package/node_modules/@sumi/plugins-precedent/dist/commands/before-edit-context.js +4 -2
  117. package/node_modules/@sumi/plugins-precedent/dist/commands/before-edit-context.js.map +1 -1
  118. package/node_modules/@sumi/plugins-precedent/dist/commands/on-prompt-context.js +9 -6
  119. package/node_modules/@sumi/plugins-precedent/dist/commands/on-prompt-context.js.map +1 -1
  120. package/node_modules/@sumi/plugins-precedent/dist/plugins/context-read.d.ts +1 -0
  121. package/node_modules/@sumi/plugins-precedent/dist/plugins/context-read.js +42 -0
  122. package/node_modules/@sumi/plugins-precedent/dist/plugins/context-read.js.map +1 -0
  123. package/node_modules/@sumi/plugins-precedent/package.json +3 -3
  124. package/node_modules/@sumi/plugins-precedent/sumi-plugins.yaml +14 -0
  125. package/node_modules/@sumi/plugins-review/README.md +10 -0
  126. package/node_modules/@sumi/plugins-review/dist/command-hint.d.ts +3 -0
  127. package/node_modules/@sumi/plugins-review/dist/command-hint.js +10 -0
  128. package/node_modules/@sumi/plugins-review/dist/command-hint.js.map +1 -0
  129. package/node_modules/@sumi/plugins-review/dist/commands/context.js +7 -1
  130. package/node_modules/@sumi/plugins-review/dist/commands/context.js.map +1 -1
  131. package/node_modules/@sumi/plugins-review/dist/commands/model-recheck.js +57 -42
  132. package/node_modules/@sumi/plugins-review/dist/commands/model-recheck.js.map +1 -1
  133. package/node_modules/@sumi/plugins-review/dist/commands/submit.js +92 -35
  134. package/node_modules/@sumi/plugins-review/dist/commands/submit.js.map +1 -1
  135. package/node_modules/@sumi/plugins-review/dist/model-execution.d.ts +8 -3
  136. package/node_modules/@sumi/plugins-review/dist/model-execution.js +99 -33
  137. package/node_modules/@sumi/plugins-review/dist/model-execution.js.map +1 -1
  138. package/node_modules/@sumi/plugins-review/dist/plugins/rubric.js +107 -36
  139. package/node_modules/@sumi/plugins-review/dist/plugins/rubric.js.map +1 -1
  140. package/node_modules/@sumi/plugins-review/dist/recheck.js +18 -6
  141. package/node_modules/@sumi/plugins-review/dist/recheck.js.map +1 -1
  142. package/node_modules/@sumi/plugins-review/dist/review-evidence.d.ts +7 -1
  143. package/node_modules/@sumi/plugins-review/dist/review-evidence.js +44 -2
  144. package/node_modules/@sumi/plugins-review/dist/review-evidence.js.map +1 -1
  145. package/node_modules/@sumi/plugins-review/dist/review.d.ts +34 -4
  146. package/node_modules/@sumi/plugins-review/dist/review.js +149 -29
  147. package/node_modules/@sumi/plugins-review/dist/review.js.map +1 -1
  148. package/node_modules/@sumi/plugins-review/dist/submission.d.ts +8 -1
  149. package/node_modules/@sumi/plugins-review/dist/submission.js +58 -7
  150. package/node_modules/@sumi/plugins-review/dist/submission.js.map +1 -1
  151. package/node_modules/@sumi/plugins-review/dist/upgrade-flow-plan.js +9 -0
  152. package/node_modules/@sumi/plugins-review/dist/upgrade-flow-plan.js.map +1 -1
  153. package/node_modules/@sumi/plugins-review/dist/upgrade.js +25 -5
  154. package/node_modules/@sumi/plugins-review/dist/upgrade.js.map +1 -1
  155. package/node_modules/@sumi/plugins-review/dist/validation-receipt.js +3 -0
  156. package/node_modules/@sumi/plugins-review/dist/validation-receipt.js.map +1 -1
  157. package/node_modules/@sumi/plugins-review/package.json +5 -5
  158. package/package.json +10 -10
  159. package/dist/trace.d.ts +0 -16
  160. package/dist/trace.js +0 -30
  161. package/dist/trace.js.map +0 -1
  162. package/node_modules/@sumi/create/dist/bin.d.ts +0 -2
  163. package/node_modules/@sumi/create/dist/bin.js +0 -52
  164. package/node_modules/@sumi/create/dist/bin.js.map +0 -1
  165. package/node_modules/@sumi/plugins-core/dist/tool-batches.d.ts +0 -11
  166. package/node_modules/@sumi/plugins-core/dist/tool-batches.js +0 -41
  167. package/node_modules/@sumi/plugins-core/dist/tool-batches.js.map +0 -1
  168. package/node_modules/@sumi/plugins-governance/dist/hooks.d.ts +0 -2
  169. package/node_modules/@sumi/plugins-governance/dist/hooks.js +0 -4
  170. package/node_modules/@sumi/plugins-governance/dist/hooks.js.map +0 -1
@@ -1,3 +1,26 @@
1
+ /** git config 的只读查询选项,供写入目标分析与治理守卫共用。 */
2
+ export declare const gitConfigReadOption: (option: string) => boolean;
3
+ /** 按 shell 的引号规则切分参数:引号内的空白不切分,去掉引号;提交说明等引号内的单词不会被当成命令。 */
4
+ export declare const shellWords: (segment: string) => string[];
5
+ /** env -S/--split-string 中会作为新命令行解析的字符串。 */
6
+ export declare function envSplitStrings(command: string): string[];
7
+ /** 各包装命令中带一个值的选项,跳过时连同值一起跳过(`--opt=value` 是单个参数,不在此列)。 */
8
+ export declare const WRAPPER_VALUE_OPTIONS: Record<string, Set<string>>;
9
+ /** 一段命令实际执行的命令词及其参数:跳过开头的子 shell 括号、复合命令保留字、环境变量赋值与包装命令(含包装命令的选项)。 */
10
+ export declare function commandWords(segment: string): string[];
11
+ /**
12
+ * 按 shell 控制符(; & |)切成命令段。守卫口径不按换行切分:引号内的多行提交说明与续行写法仍属同一段,
13
+ * 守卫在段内任意位置识别写文件命令,不会丢掉续行上的写入目标。lines 用于只看命令词的送达口径:
14
+ * 先把行尾 `\` 或 PowerShell 的 `` ` `` 续行并成一行,再按换行切分,多行命令第二行起的命令词也能识别
15
+ * (引号内多行说明的行首单词可能被当成命令,误判只多送达一次)。
16
+ */
17
+ export declare function shellSegments(command: string, lines?: boolean): string[];
18
+ /** 带引号的 here-doc 不执行正文,将正文从待分析的 shell 代码中移除。 */
19
+ export declare function withoutQuotedHereDocs(command: string): string;
20
+ /** shell 注释从未加引号且位于词首的 # 起,到本行结束。 */
21
+ export declare function withoutShellComments(command: string): string;
22
+ /** 提取会执行的 shell 命令替换;单引号内的 `$(` 只是文本。 */
23
+ export declare function shellSubstitutions(command: string): string[];
1
24
  /**
2
25
  * 从 shell 命令中粗略提取写入目标:重定向、写文件命令与 sed -i 的参数。
3
26
  * 默认在一段命令的任意位置识别写文件命令(守卫宁可多拦);commandWordOnly 时只看实际执行的命令词,
@@ -5,6 +28,7 @@
5
28
  */
6
29
  export declare function writeTargets(command: string, options?: {
7
30
  commandWordOnly?: boolean;
31
+ destinationsOnly?: boolean;
8
32
  }): string[];
9
33
  /**
10
34
  * shell 命令的写入意图:识别出的写入目标;script 表示经解释器执行了脚本或内联代码、或写文件命令的目标无法从命令文本确定,
@@ -12,7 +36,9 @@ export declare function writeTargets(command: string, options?: {
12
36
  * 命令内切换了目录(cd、pushd 等,含子 shell、`bash -c` 与多行写法)且有相对路径的写入目标时,目标的实际位置无法可靠解析:
13
37
  * 不给出路径,按无法识别写入目标处理(script),由调用方保守送达。
14
38
  */
15
- export declare function shellWriteIntent(command: string): {
39
+ export declare function shellWriteIntent(command: string, options?: {
40
+ destinationsOnly?: boolean;
41
+ }): {
16
42
  paths: string[];
17
43
  script: boolean;
18
44
  };
@@ -16,9 +16,18 @@ const realpathOr = (path) => {
16
16
  const WRITE_COMMANDS = new Set([
17
17
  'tee',
18
18
  'cp',
19
+ 'rsync',
20
+ 'dd',
21
+ 'tar',
22
+ 'unzip',
19
23
  'mv',
20
24
  'rm',
21
25
  'touch',
26
+ 'mkdir',
27
+ 'chmod',
28
+ 'chown',
29
+ 'chgrp',
30
+ 'truncate',
22
31
  'install',
23
32
  'ln',
24
33
  'set-content',
@@ -48,19 +57,65 @@ const WRITE_COMMANDS = new Set([
48
57
  'xcopy',
49
58
  'robocopy',
50
59
  ]);
51
- const unquote = (t) => t.replace(/^['"]|['"]$/g, '');
60
+ const unquote = (t) => t
61
+ .replace(/\$'([^']*)'/g, '$1')
62
+ .replace(/\$"([^"]*)"/g, '$1')
63
+ .replace(/\\([ .$"'\\])/g, '$1')
64
+ .replace(/^['"]|['"]$/g, '');
65
+ /** git config 的只读查询选项,供写入目标分析与治理守卫共用。 */
66
+ export const gitConfigReadOption = (option) => /^(?:--get(?:-all|-regexp|-urlmatch|-color|-colorbool)?|--list|-l)$/.test(option);
52
67
  /** 解释器中需要带一个值的选项。 */
53
68
  const VALUE_OPTIONS = /^(-executionpolicy|-ep|-windowstyle|-version|-inputformat|-outputformat|-configurationname|-workingdirectory|-o|\+o|-O|\+O)$/i;
54
69
  /** 把参数当作脚本执行的解释器。 */
55
70
  const SCRIPT_RUNNERS = /^(?:.*[\\/])?(?:sh|bash|zsh|dash|powershell|pwsh|cmd)(?:\.exe)?$/i;
56
71
  /** 按 shell 的引号规则切分参数:引号内的空白不切分,去掉引号;提交说明等引号内的单词不会被当成命令。 */
57
- const shellWords = (segment) => [...segment.matchAll(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g)].map((m) => m[0].replace(/["']/g, ''));
72
+ export const shellWords = (segment) => [...segment.matchAll(/(?:[^\s"'\\]|\\.|"[^"]*"|'[^']*')+/g)].map((m) => unquote(m[0]).replace(/["']/g, ''));
73
+ /** env -S/--split-string 中会作为新命令行解析的字符串。 */
74
+ export function envSplitStrings(command) {
75
+ const values = [];
76
+ for (const segment of shellSegments(command, true)) {
77
+ const words = shellWords(segment);
78
+ let at = 0;
79
+ while (at < words.length) {
80
+ if (/^[A-Za-z_]\w*=/.test(words[at])) {
81
+ at++;
82
+ continue;
83
+ }
84
+ const wrapper = words[at];
85
+ if (!WRAPPERS.has(wrapper))
86
+ break;
87
+ at++;
88
+ let splitFound = false;
89
+ while (words[at]?.startsWith('-')) {
90
+ const option = words[at];
91
+ if (wrapper === 'env') {
92
+ if (option === '-S' || option === '--split-string') {
93
+ if (words[at + 1])
94
+ values.push(words[at + 1]);
95
+ splitFound = true;
96
+ break;
97
+ }
98
+ if (option.startsWith('--split-string=') || /^-S./.test(option)) {
99
+ values.push(option.replace(/^(?:-S|--split-string=)/, ''));
100
+ splitFound = true;
101
+ break;
102
+ }
103
+ }
104
+ at += WRAPPER_VALUE_OPTIONS[wrapper]?.has(option) ? 2 : 1;
105
+ }
106
+ if (splitFound)
107
+ break;
108
+ }
109
+ }
110
+ return values;
111
+ }
58
112
  /** 命令词前可跳过的包装:环境变量赋值之外,这些命令把其余参数作为要执行的命令。 */
59
- const WRAPPERS = new Set(['env', 'time', 'exec', 'nice', 'nohup', 'sudo', 'npx', 'bunx', 'xargs']);
113
+ const WRAPPERS = new Set(['env', 'time', 'exec', 'command', 'nice', 'nohup', 'sudo', 'npx', 'bunx', 'xargs']);
60
114
  /** 复合命令的保留字:其后才是实际执行的命令词(for … do touch a; done、if …; then …、{ …; }、! …)。 */
61
115
  const RESERVED = new Set(['do', 'then', 'else', 'elif', 'if', 'while', 'until', '{', '!']);
62
116
  /** 各包装命令中带一个值的选项,跳过时连同值一起跳过(`--opt=value` 是单个参数,不在此列)。 */
63
- const WRAPPER_VALUE_OPTIONS = {
117
+ export const WRAPPER_VALUE_OPTIONS = {
118
+ exec: new Set(['-a']),
64
119
  env: new Set(['-u', '-C', '-S', '--unset', '--chdir', '--split-string']),
65
120
  sudo: new Set(['-u', '-g', '-h', '-p', '-C', '-D', '-r', '-t', '-U', '--user', '--group', '--host', '--prompt', '--chdir']),
66
121
  nice: new Set(['-n', '--adjustment']),
@@ -70,7 +125,7 @@ const WRAPPER_VALUE_OPTIONS = {
70
125
  xargs: new Set(['-n', '-I', '-P', '-L', '-d', '-E', '-s', '-a', '--max-args', '--max-procs', '--delimiter', '--arg-file']),
71
126
  };
72
127
  /** 一段命令实际执行的命令词及其参数:跳过开头的子 shell 括号、复合命令保留字、环境变量赋值与包装命令(含包装命令的选项)。 */
73
- function commandWords(segment) {
128
+ export function commandWords(segment) {
74
129
  const tokens = shellWords(segment);
75
130
  let at = 0;
76
131
  while (at < tokens.length) {
@@ -81,9 +136,19 @@ function commandWords(segment) {
81
136
  else if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[at]))
82
137
  at++;
83
138
  else if (WRAPPERS.has(tokens[at])) {
84
- const valued = WRAPPER_VALUE_OPTIONS[tokens[at++]];
85
- while (at < tokens.length && tokens[at].startsWith('-'))
86
- at += valued?.has(tokens[at]) ? 2 : 1;
139
+ const wrapper = tokens[at++];
140
+ const valued = WRAPPER_VALUE_OPTIONS[wrapper];
141
+ while (at < tokens.length && tokens[at].startsWith('-')) {
142
+ const option = tokens[at];
143
+ if (wrapper === 'env' &&
144
+ (option === '-S' || option === '--split-string' || option.startsWith('--split-string=') || /^-S./.test(option))) {
145
+ const separate = option === '-S' || option === '--split-string';
146
+ const value = separate ? tokens[at + 1] : option.replace(/^(?:-S|--split-string=)/, '');
147
+ tokens.splice(at, separate ? 2 : 1, ...shellWords(value ?? ''));
148
+ continue;
149
+ }
150
+ at += valued?.has(option) ? 2 : 1;
151
+ }
87
152
  }
88
153
  else
89
154
  break;
@@ -96,7 +161,146 @@ function commandWords(segment) {
96
161
  * 先把行尾 `\` 或 PowerShell 的 `` ` `` 续行并成一行,再按换行切分,多行命令第二行起的命令词也能识别
97
162
  * (引号内多行说明的行首单词可能被当成命令,误判只多送达一次)。
98
163
  */
99
- const segments = (command, lines = false) => lines ? command.replace(/[\\`]\r?\n/g, ' ').split(/[;&|\r\n]+/) : command.split(/[;&|]+/);
164
+ export function shellSegments(command, lines = false) {
165
+ const source = lines ? command.replace(/[\\`]\r?\n/g, ' ') : command;
166
+ const parts = [];
167
+ let quote = '';
168
+ let escaped = false;
169
+ let start = 0;
170
+ for (let i = 0; i < source.length; i++) {
171
+ const char = source[i];
172
+ if (escaped)
173
+ escaped = false;
174
+ else if (char === '\\' && quote !== "'")
175
+ escaped = true;
176
+ else if (quote) {
177
+ if (char === quote)
178
+ quote = '';
179
+ }
180
+ else if (char === "'" || char === '"')
181
+ quote = char;
182
+ else if (/[;&|]/.test(char) || (lines && /[\r\n]/.test(char))) {
183
+ parts.push(source.slice(start, i));
184
+ start = i + 1;
185
+ }
186
+ }
187
+ parts.push(source.slice(start));
188
+ return parts;
189
+ }
190
+ const segments = shellSegments;
191
+ /** 带引号的 here-doc 不执行正文,将正文从待分析的 shell 代码中移除。 */
192
+ export function withoutQuotedHereDocs(command) {
193
+ let delimiter = null;
194
+ return command
195
+ .split('\n')
196
+ .map((line) => {
197
+ if (delimiter !== null) {
198
+ if (line.trim() === delimiter)
199
+ delimiter = null;
200
+ return '';
201
+ }
202
+ // 仅在明确的只读 cat 形式下移除正文;交给 bash/sh 的标准输入是待执行脚本。
203
+ const opener = /^\s*cat\s+<<-?\s*(['"])([A-Za-z_]\w*)\1\s*$/.exec(line);
204
+ if (opener)
205
+ delimiter = opener[2];
206
+ return line;
207
+ })
208
+ .join('\n');
209
+ }
210
+ /** shell 注释从未加引号且位于词首的 # 起,到本行结束。 */
211
+ export function withoutShellComments(command) {
212
+ let quote = '';
213
+ return command
214
+ .split('\n')
215
+ .map((line) => {
216
+ let escaped = false;
217
+ for (let i = 0; i < line.length; i++) {
218
+ const char = line[i];
219
+ if (escaped)
220
+ escaped = false;
221
+ else if (char === '\\' && quote !== "'")
222
+ escaped = true;
223
+ else if (char === quote)
224
+ quote = '';
225
+ else if (char === "'" || char === '"') {
226
+ if (!quote)
227
+ quote = char;
228
+ }
229
+ else if (!quote && char === '#' && (i === 0 || /[\s;&|]/.test(line[i - 1])))
230
+ return line.slice(0, i);
231
+ }
232
+ return line;
233
+ })
234
+ .join('\n');
235
+ }
236
+ /** 提取会执行的 shell 命令替换;单引号内的 `$(` 只是文本。 */
237
+ export function shellSubstitutions(command) {
238
+ const scripts = [];
239
+ let quote = '';
240
+ let escaped = false;
241
+ for (let i = 0; i < command.length; i++) {
242
+ const char = command[i];
243
+ if (escaped) {
244
+ escaped = false;
245
+ continue;
246
+ }
247
+ if (char === '\\' && quote !== "'") {
248
+ escaped = true;
249
+ continue;
250
+ }
251
+ if (char === '`' && quote !== "'") {
252
+ let end = i + 1;
253
+ for (; end < command.length; end++) {
254
+ if (command[end] === '\\')
255
+ end++;
256
+ else if (command[end] === '`')
257
+ break;
258
+ }
259
+ if (end < command.length) {
260
+ scripts.push(command.slice(i + 1, end));
261
+ i = end;
262
+ }
263
+ continue;
264
+ }
265
+ if (char === quote) {
266
+ quote = '';
267
+ continue;
268
+ }
269
+ if (char === "'" || char === '"') {
270
+ if (!quote)
271
+ quote = char;
272
+ continue;
273
+ }
274
+ if (quote === "'" || command[i + 1] !== '(' || !(char === '$' || (!quote && (char === '<' || char === '>'))))
275
+ continue;
276
+ let depth = 1;
277
+ let innerQuote = '';
278
+ let innerEscaped = false;
279
+ let end = i + 2;
280
+ for (; end < command.length; end++) {
281
+ const inner = command[end];
282
+ if (innerEscaped)
283
+ innerEscaped = false;
284
+ else if (inner === '\\' && innerQuote !== "'")
285
+ innerEscaped = true;
286
+ else if (inner === innerQuote)
287
+ innerQuote = '';
288
+ else if (inner === "'" || inner === '"') {
289
+ if (!innerQuote)
290
+ innerQuote = inner;
291
+ }
292
+ else if (!innerQuote && inner === '(')
293
+ depth++;
294
+ else if (!innerQuote && inner === ')' && --depth === 0)
295
+ break;
296
+ }
297
+ if (depth === 0) {
298
+ scripts.push(command.slice(i + 2, end));
299
+ i = end;
300
+ }
301
+ }
302
+ return scripts;
303
+ }
100
304
  /** 前 limit 个参数中第一个带脚本选项(-c、-Command、/c、/k)的解释器所执行的脚本;没有时为 null。 */
101
305
  function scriptArgument(tokens, limit) {
102
306
  for (let runner = 0; runner < Math.min(limit, tokens.length); runner++) {
@@ -119,16 +323,50 @@ function scriptArgument(tokens, limit) {
119
323
  * 用于送达约束等不应把 `grep -rn copy src` 之类只读命令当成写入的场景。
120
324
  */
121
325
  export function writeTargets(command, options = {}) {
326
+ command = withoutShellComments(withoutQuotedHereDocs(command));
122
327
  const targets = [];
328
+ for (const script of shellSubstitutions(command))
329
+ targets.push(...writeTargets(script, options));
123
330
  // 子 shell 或命令组的收尾括号可能贴在重定向目标上:(echo x > a.ts)
124
- for (const m of command.matchAll(/>{1,2}\s*("[^"]*"|'[^']*'|[^\s;&|<>]+)/g)) {
125
- const target = unquote(m[1]).replace(/[)}]+$/, '');
331
+ let quote = '';
332
+ let escaped = false;
333
+ for (let i = 0; i < command.length; i++) {
334
+ const char = command[i];
335
+ if (escaped) {
336
+ escaped = false;
337
+ continue;
338
+ }
339
+ if (char === '\\' && quote !== "'") {
340
+ escaped = true;
341
+ continue;
342
+ }
343
+ if (quote) {
344
+ if (char === quote)
345
+ quote = '';
346
+ continue;
347
+ }
348
+ if (char === "'" || char === '"') {
349
+ quote = char;
350
+ continue;
351
+ }
352
+ if (char !== '>')
353
+ continue;
354
+ const match = /^>{1,2}[&|]?\s*("[^"]*"|'[^']*'|[^\s;&|<>]+)/.exec(command.slice(i));
355
+ if (!match)
356
+ continue;
357
+ const target = unquote(match[1]).replace(/[)}]+$/, '');
126
358
  if (target)
127
359
  targets.push(target);
360
+ i += match[0].length - 1;
128
361
  }
129
362
  for (const segment of segments(command, options.commandWordOnly)) {
130
363
  // 守卫口径去掉贴在参数前的子 shell 或命令组括号:(rm a.ts)、(bash -c "…") 中的 rm、bash 仍被识别;单独的括号参数保留
131
- const tokens = options.commandWordOnly ? commandWords(segment) : shellWords(segment).map((t) => t.replace(/^[({]+(?=.)/, ''));
364
+ const raw = shellWords(segment).map((t) => t.replace(/^[({]+(?=.)/, ''));
365
+ const executed = commandWords(segment);
366
+ const executedWrites = WRITE_COMMANDS.has(executed[0]?.toLowerCase() ?? '') ||
367
+ (executed[0] === 'sed' && sedInPlace(executed)) ||
368
+ (executed[0] === 'git' && executed.includes('config'));
369
+ const tokens = options.commandWordOnly || executedWrites ? executed : raw;
132
370
  const found = (match) => options.commandWordOnly ? (tokens[0] && match(tokens[0]) ? 0 : -1) : tokens.findIndex(match);
133
371
  // 交给另一个解释器执行的脚本(sh/bash -c、powershell -Command、cmd /c):脚本整体是一个参数,递归提取其中的写入目标。
134
372
  // 只在第一个带脚本选项的解释器处递归:后面的解释器都包含在递归输入里,逐个递归会指数增长并让守卫超时(超时被当作放行);
@@ -136,13 +374,180 @@ export function writeTargets(command, options = {}) {
136
374
  const script = scriptArgument(tokens, options.commandWordOnly ? 1 : tokens.length);
137
375
  if (script)
138
376
  targets.push(...writeTargets(script, options));
139
- const at = found((t) => WRITE_COMMANDS.has(t.toLowerCase()) || (t === 'sed' && tokens.includes('-i')));
377
+ if (tokens[0] === 'eval' && tokens[1])
378
+ targets.push(...writeTargets(tokens.slice(1).join(' '), options));
379
+ const configAt = tokens[0] === 'git' ? tokens.indexOf('config') : -1;
380
+ if (configAt > 0) {
381
+ const args = tokens.slice(configAt + 1);
382
+ const fileAt = args.findIndex((t) => t === '--file' || t.startsWith('--file=') || t === '-f' || (t.startsWith('-f') && t.length > 2));
383
+ if (fileAt >= 0) {
384
+ const fileValueAt = args[fileAt] === '--file' || args[fileAt] === '-f' ? fileAt + 1 : -1;
385
+ const file = fileValueAt >= 0 ? args[fileValueAt] : args[fileAt].replace(/^(?:--file=|-f)/, '');
386
+ const reads = args.some(gitConfigReadOption);
387
+ const writes = args.some((t) => /^(?:--add|--replace-all|--unset(?:-all)?|--rename-section|--remove-section)$/.test(t));
388
+ const operands = args.filter((t, i) => i !== fileAt && i !== fileValueAt && !t.startsWith('-'));
389
+ if (file && !reads && (writes || args.includes('--edit') || operands.includes('edit') || operands.length >= 2))
390
+ targets.push(file);
391
+ }
392
+ }
393
+ const at = found((t) => WRITE_COMMANDS.has(t.toLowerCase()) || (t === 'sed' && sedInPlace(tokens)));
140
394
  if (at < 0)
141
395
  continue;
396
+ if (options.destinationsOnly && /^(?:tar|unzip)$/i.test(tokens[at])) {
397
+ const args = tokens.slice(at + 1);
398
+ const optionValue = (...flags) => {
399
+ for (const [index, arg] of args.entries()) {
400
+ for (const flag of flags) {
401
+ if (arg === flag)
402
+ return args[index + 1];
403
+ if (arg.startsWith(`${flag}=`))
404
+ return arg.slice(flag.length + 1);
405
+ if (flag.length === 2 && arg.startsWith(flag) && arg.length > 2)
406
+ return arg.slice(flag.length);
407
+ }
408
+ }
409
+ return undefined;
410
+ };
411
+ if (tokens[at].toLowerCase() === 'unzip') {
412
+ if (!args.some((t) => /^-[A-Za-z0-9]*[ltZpcvzh][A-Za-z0-9]*$/.test(t))) {
413
+ const dir = optionValue('-d') ?? '.';
414
+ targets.push(dir);
415
+ const archiveAt = args.findIndex((t, i) => !t.startsWith('-') && args[i - 1] !== '-d');
416
+ const excludeAt = args.indexOf('-x');
417
+ for (const [index, member] of args.entries()) {
418
+ if (index > archiveAt && (excludeAt < 0 || index < excludeAt) && !member.startsWith('-') && args[index - 1] !== '-d')
419
+ targets.push(`${dir}/${member}`);
420
+ }
421
+ }
422
+ }
423
+ else {
424
+ const shortFlags = args.flatMap((t, i) => {
425
+ if (t.startsWith('--') || !(t.startsWith('-') || i === 0))
426
+ return [];
427
+ const word = t.replace(/^-/, '');
428
+ const fileFlag = word.indexOf('f');
429
+ return /^[a-z]/i.test(word) ? [fileFlag >= 0 ? word.slice(0, fileFlag + 1) : (/^[a-z]+/i.exec(word)?.[0] ?? '')] : [];
430
+ });
431
+ const hasMode = (mode, long) => args.includes(long) || shortFlags.some((flags) => flags.includes(mode));
432
+ const toStdout = args.includes('--to-stdout') ||
433
+ args.some((t, i) => (t.startsWith('-') || i === 0) && /^[a-zA-Z]+$/.test(t.replace(/^-/, '')) && t.includes('O'));
434
+ const fileAt = args.findIndex((t, i) => (t.startsWith('-') && !t.startsWith('--')) || (i === 0 && /^[a-z]+$/i.test(t)) ? /f/.test(t) : false);
435
+ const attached = fileAt < 0 ? undefined : args[fileAt].slice(args[fileAt].indexOf('f') + 1);
436
+ const archive = optionValue('--file') ?? (attached || (fileAt >= 0 ? args[fileAt + 1] : undefined));
437
+ if (hasMode('x', '--extract') && !toStdout) {
438
+ const dir = optionValue('-C', '--directory') ?? '.';
439
+ targets.push(dir);
440
+ const archiveAt = archive ? args.indexOf(archive) : -1;
441
+ for (const [index, member] of args.entries()) {
442
+ if (index <= archiveAt || member.startsWith('-') || (index === 0 && /^[a-z]+$/i.test(member)))
443
+ continue;
444
+ if (['-C', '--directory', '-f', '--file', '--exclude', '--exclude-from', '-X'].includes(args[index - 1] ?? ''))
445
+ continue;
446
+ targets.push(`${dir}/${member}`);
447
+ }
448
+ }
449
+ if (['c', 'r', 'u', 'A'].some((mode) => shortFlags.some((flags) => flags.includes(mode))) ||
450
+ ['--create', '--append', '--update', '--concatenate', '--delete'].some((mode) => args.includes(mode))) {
451
+ if (archive && archive !== '-')
452
+ targets.push(archive);
453
+ }
454
+ }
455
+ continue;
456
+ }
457
+ if (tokens[at].toLowerCase() === 'dd') {
458
+ targets.push(...tokens
459
+ .slice(at + 1)
460
+ .filter((t) => t.startsWith('of='))
461
+ .map((t) => t.slice(3))
462
+ .filter(Boolean));
463
+ continue;
464
+ }
465
+ if (tokens[at].toLowerCase() === 'rsync' && options.destinationsOnly) {
466
+ const operands = [];
467
+ const sideEffects = [];
468
+ const dryRun = tokens.slice(at + 1).some((t) => t === '--dry-run' || /^-[a-z]*n[a-z]*$/i.test(t));
469
+ const optionsWithWritePaths = new Set([
470
+ '--log-file',
471
+ '--backup-dir',
472
+ '--partial-dir',
473
+ '--temp-dir',
474
+ '--write-batch',
475
+ '--only-write-batch',
476
+ ]);
477
+ const optionsWithReadValues = new Set([
478
+ '--exclude',
479
+ '--include',
480
+ '--filter',
481
+ '--exclude-from',
482
+ '--include-from',
483
+ '--files-from',
484
+ '--copy-dest',
485
+ '--link-dest',
486
+ '--compare-dest',
487
+ '--rsh',
488
+ '--out-format',
489
+ '--chmod',
490
+ '--iconv',
491
+ '-e',
492
+ ]);
493
+ for (const [index, token] of tokens.slice(at + 1).entries()) {
494
+ const equalAt = token.indexOf('=');
495
+ const name = equalAt < 0 ? token : token.slice(0, equalAt);
496
+ const value = equalAt < 0 ? null : token.slice(equalAt + 1);
497
+ if (optionsWithWritePaths.has(name)) {
498
+ sideEffects.push(value ?? tokens[at + index + 2] ?? '');
499
+ continue;
500
+ }
501
+ // --link-dest 从参考目录建立硬链接,目标文件可通过该 inode 回写参考目录中的内容。
502
+ if (name === '--link-dest') {
503
+ sideEffects.push(value ?? tokens[at + index + 2] ?? '');
504
+ continue;
505
+ }
506
+ if (optionsWithReadValues.has(name))
507
+ continue;
508
+ if (index > 0 && (optionsWithWritePaths.has(tokens[at + index]) || optionsWithReadValues.has(tokens[at + index])))
509
+ continue;
510
+ if (!token.startsWith('-'))
511
+ operands.push(token);
512
+ }
513
+ targets.push(...[
514
+ ...sideEffects,
515
+ ...(!dryRun && !tokens.includes('--list-only') && operands.length > 1
516
+ ? [operands.at(-1), ...(tokens.includes('--remove-source-files') ? operands.slice(0, -1) : [])]
517
+ : []),
518
+ ].filter((t) => !!t));
519
+ continue;
520
+ }
142
521
  // 子 shell 或命令组的收尾括号贴在最后一个参数上:(touch a.ts)
143
- targets.push(...writeArgs(tokens.slice(at))
144
- .map((t) => t.replace(/[)}]+$/, ''))
145
- .filter(Boolean));
522
+ const writeTokens = tokens.slice(at);
523
+ const referenceFlags = tokens[at].toLowerCase() === 'touch'
524
+ ? ['-r', '--reference']
525
+ : ['chmod', 'chown', 'chgrp'].includes(tokens[at].toLowerCase())
526
+ ? ['--reference']
527
+ : [];
528
+ const args = writeArgs(writeTokens.filter((_, index) => index === 0 || !referenceFlags.includes(writeTokens[index - 1] ?? '')));
529
+ // 复制与链接命令只写目标,不写源文件。GNU cp/ln 的 -t 与 --target-directory 可独立或附着指定目标。
530
+ const copyArgs = tokens.slice(at + 1);
531
+ const targetAt = /^(?:cp|ln)$/i.test(tokens[at])
532
+ ? copyArgs.findIndex((t) => t === '-t' || t === '--target-directory' || /^-t.+$|^--target-directory=.+$/.test(t))
533
+ : -1;
534
+ const targetOption = copyArgs[targetAt];
535
+ const copyTarget = targetAt < 0
536
+ ? args.at(-1)
537
+ : targetOption === '-t' || targetOption === '--target-directory'
538
+ ? copyArgs[targetAt + 1]
539
+ : targetOption?.replace(/^(?:-t|--target-directory=)/, '');
540
+ const destinationsOnly = options.destinationsOnly && /^(?:cp|copy|xcopy|ln|install)$/i.test(tokens[at]);
541
+ // 链接保留对源 inode/路径的写入能力;即使目标在外部,源也属于守卫需要审查的目标。
542
+ const linkedSource = tokens[at].toLowerCase() === 'ln';
543
+ const linkedCopy = tokens[at].toLowerCase() === 'cp' &&
544
+ copyArgs.some((t) => t === '--link' || t === '--symbolic-link' || /^-[A-Za-z]*[ls][A-Za-z]*$/.test(t));
545
+ const writes = destinationsOnly && !linkedSource && !linkedCopy && !(tokens[at].toLowerCase() === 'install' && copyArgs.includes('-d'))
546
+ ? copyTarget
547
+ ? [copyTarget]
548
+ : args
549
+ : args;
550
+ targets.push(...writes.map((t) => t.replace(/[)}]+$/, '')).filter(Boolean));
146
551
  }
147
552
  return targets;
148
553
  }
@@ -155,10 +560,11 @@ const INTERPRETERS = /^(?:.*[\\/])?(?:python[0-9.]*|node|deno|bun|perl|ruby|php|
155
560
  */
156
561
  const DIRECTORY_CHANGE = /(?:^|[\s;&|(){}"'`])(?:cd|pushd|popd|chdir|set-location|push-location|pop-location|sl)(?=$|[\s;&|)}"'`\\]|\.\.)/i;
157
562
  /** 在其他目录执行命令的选项(区分大小写:`bash -c`、`rm -d` 不算)。 */
158
- const CHDIR_OPTION = /(?:^|\s)(?:-C|--chdir)(?=$|[\s=])/;
563
+ const CHDIR_OPTION = /(?:^|\s)(?:-C\S*|--chdir(?:=\S+)?)(?=$|\s)/;
159
564
  /** 写文件命令的目标参数(去掉选项与 sed 表达式)。 */
160
565
  const writeArgs = (tokens) => tokens.slice(1).filter((t) => t && !t.startsWith('-') && !/^s[/|#]/.test(t));
161
- const isWriteCommand = (tokens) => !!tokens[0] && (WRITE_COMMANDS.has(tokens[0].toLowerCase()) || (tokens[0] === 'sed' && tokens.includes('-i')));
566
+ const sedInPlace = (tokens) => tokens.some((t) => /^-i|^--in-place(?:=|$)/i.test(t));
567
+ const isWriteCommand = (tokens) => !!tokens[0] && (WRITE_COMMANDS.has(tokens[0].toLowerCase()) || (tokens[0] === 'sed' && sedInPlace(tokens)));
162
568
  /**
163
569
  * 写入目标无法从命令文本确定的写入:写文件命令没有目标参数(如 `xargs sed -i …` 由标准输入给出文件),
164
570
  * 或 `find` 的 `-delete` 与 `-exec` 写文件命令(目标是 `{}` 占位)。
@@ -178,9 +584,11 @@ function unresolvedWrite(words) {
178
584
  * 命令内切换了目录(cd、pushd 等,含子 shell、`bash -c` 与多行写法)且有相对路径的写入目标时,目标的实际位置无法可靠解析:
179
585
  * 不给出路径,按无法识别写入目标处理(script),由调用方保守送达。
180
586
  */
181
- export function shellWriteIntent(command) {
182
- const paths = [...new Set(writeTargets(command, { commandWordOnly: true }))];
183
- if ((DIRECTORY_CHANGE.test(command) || CHDIR_OPTION.test(command)) && paths.some((path) => !isAbsolute(path)))
587
+ export function shellWriteIntent(command, options = {}) {
588
+ command = withoutShellComments(withoutQuotedHereDocs(command));
589
+ const paths = [...new Set(writeTargets(command, { commandWordOnly: true, ...options }))];
590
+ if ((DIRECTORY_CHANGE.test(command) || CHDIR_OPTION.test(command) || envSplitStrings(command).some((split) => CHDIR_OPTION.test(split))) &&
591
+ paths.some((path) => !isAbsolute(path)))
184
592
  return { paths: [], script: true };
185
593
  const script = segments(command, true).some((segment) => {
186
594
  // 只看命令词:grep -rn node src 这类把解释器名当参数的只读命令不算执行脚本
@@ -203,7 +611,7 @@ export function shellPayloadIntent(root, raw) {
203
611
  const value = JSON.parse(raw);
204
612
  if (value.tool_name !== 'Bash' || typeof value.tool_input?.command !== 'string')
205
613
  return null;
206
- const intent = shellWriteIntent(value.tool_input.command);
614
+ const intent = shellWriteIntent(value.tool_input.command, { destinationsOnly: true });
207
615
  const base = resolve(root, typeof value.cwd === 'string' ? value.cwd : '.');
208
616
  // 项目根可能经符号链接表示(如 macOS 的 /var 与 /private/var),两种写法都算项目内
209
617
  const roots = [root, realpathOr(root)];