openfeel 1.5.9 → 1.5.11
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.
- package/README.md +1 -1
- package/dist/cli/index.d.ts.map +1 -1
- package/dist/cli/index.js +2 -0
- package/dist/cli/index.js.map +1 -1
- package/dist/commands/chore.d.ts +7 -0
- package/dist/commands/chore.d.ts.map +1 -1
- package/dist/commands/chore.js +43 -3
- package/dist/commands/chore.js.map +1 -1
- package/dist/commands/dashboard.d.ts +42 -0
- package/dist/commands/dashboard.d.ts.map +1 -0
- package/dist/commands/dashboard.js +170 -0
- package/dist/commands/dashboard.js.map +1 -0
- package/dist/commands/flow.d.ts +8 -0
- package/dist/commands/flow.d.ts.map +1 -1
- package/dist/commands/flow.js +2 -1
- package/dist/commands/flow.js.map +1 -1
- package/dist/commands/shared/json-output.d.ts.map +1 -1
- package/dist/commands/shared/json-output.js +1 -0
- package/dist/commands/shared/json-output.js.map +1 -1
- package/dist/core/dashboard/aggregate.d.ts +146 -0
- package/dist/core/dashboard/aggregate.d.ts.map +1 -0
- package/dist/core/dashboard/aggregate.js +231 -0
- package/dist/core/dashboard/aggregate.js.map +1 -0
- package/dist/core/dashboard/render.d.ts +12 -0
- package/dist/core/dashboard/render.d.ts.map +1 -0
- package/dist/core/dashboard/render.js +506 -0
- package/dist/core/dashboard/render.js.map +1 -0
- package/dist/core/i18n-data/en.d.ts +6 -0
- package/dist/core/i18n-data/en.d.ts.map +1 -1
- package/dist/core/i18n-data/en.js +63 -1
- package/dist/core/i18n-data/en.js.map +1 -1
- package/dist/core/i18n-data/zh-CN.d.ts +6 -0
- package/dist/core/i18n-data/zh-CN.d.ts.map +1 -1
- package/dist/core/i18n-data/zh-CN.js +63 -1
- package/dist/core/i18n-data/zh-CN.js.map +1 -1
- package/dist/core/i18n.js +4 -4
- package/dist/core/i18n.js.map +1 -1
- package/dist/core/template-loader.d.ts.map +1 -1
- package/dist/core/template-loader.js +19 -7
- package/dist/core/template-loader.js.map +1 -1
- package/dist/core/update.d.ts.map +1 -1
- package/dist/core/update.js +19 -7
- package/dist/core/update.js.map +1 -1
- package/dsh/ADAPTER.md +72 -13
- package/dsh/README.md +20 -11
- package/dsh/cordis.patch.yml +23 -3
- package/dsh/lib/adapters/guard-state.js +326 -0
- package/dsh/lib/adapters/session-cwd-registry.js +82 -0
- package/dsh/lib/adapters/workflow-gate.js +52 -2
- package/dsh/lib/adapters/workspace.js +4 -2
- package/dsh/lib/guard.js +2732 -206
- package/dsh/lib/index.js +48 -4
- package/dsh/lib/tools/index.js +54 -1
- package/dsh/package.json +2 -2
- package/package.json +1 -1
package/dsh/lib/guard.js
CHANGED
|
@@ -2,31 +2,122 @@
|
|
|
2
2
|
* OpenFeel × DSH — 写入门禁
|
|
3
3
|
*
|
|
4
4
|
* 用 DSH 的 `ctx.tools.guard()` 在工具执行前做**同步拒绝**。守卫只读
|
|
5
|
-
* `.openfeel/flow.json
|
|
5
|
+
* `.openfeel/flow.json`,不写流程状态;唯一写盘的是自检证据
|
|
6
|
+
* (`guard-state.json` / `guard-audit.jsonl`),所有流程状态变更仍由 OpenFeel CLI 负责。
|
|
6
7
|
*
|
|
7
|
-
* 规则(与 `.openfeel/plan/v1/stage-103/plan.md` 一致):
|
|
8
|
-
* -
|
|
9
|
-
* -
|
|
8
|
+
* 规则(与 `.openfeel/plan/v1/stage-103/plan.md`、`stage-126/plan.md` 一致):
|
|
9
|
+
* - 守文件修改工具(默认 edit/write/apply_patch/str_replace_editor)**与 shell 工具**
|
|
10
|
+
* (`bash` / `pwsh`,v1.5.11 D-126-02:`pwsh -Command 'Set-Content src/x.ts'` 曾是
|
|
11
|
+
* 零守卫绕过面)。shell 命令按「1 类硬拒 / 2 类按目标路径判 / 3 类产物豁免 /
|
|
12
|
+
* 4 类目标不可判定」四类判定,2 类复用与文件工具完全相同的 `decideForTargets`;
|
|
13
|
+
* **op-005:未识别命令不再当 `none` 静默放行**,改判第 4 类 `undecidable`
|
|
14
|
+
* (审计 `kind` 区分 `none` 与 `undecidable`)。注意口径:第 4 类**默认仍是
|
|
15
|
+
* `warn` 放行 + 留痕**,只有 `OPENFEEL_SHELL_GATE=strict` 才拒 —— 是
|
|
16
|
+
* 「不再静默」,不是「默认拒绝」,别把这一行读成默认拒绝;
|
|
17
|
+
* - cwd 解析链(D-126-01):`OPENFEEL_GUARD_CWD` → `agent.session.header.cwd` →
|
|
18
|
+
* `config.cwd` → 会话登记表 `[sessionId]` → `process.cwd()`(**仅当含 `.openfeel/`**)
|
|
19
|
+
* → **fail-closed 拒绝**。**没有** `registry-last` 进程级标量(多项目会串味);
|
|
20
|
+
* - 每次判定都写 `guard-state.json.lastDecision`(D-126-04):cwd 不可解析时固定落
|
|
21
|
+
* `os.tmpdir()/openfeel-guard/`,审计同理 —— 最需要证据的时候绝不静默;
|
|
22
|
+
* **op-005:状态带进程内 HMAC**,缺 `pid` 或验签失败一律 `stale`;
|
|
23
|
+
* - 路径归一化(op-005 / P0-2):尾点 / 尾空格 / ADS(`flow.json::$DATA`)/ 8.3 短名 /
|
|
24
|
+
* 大小写都在比较前归一,双路径(write 与 shell)同名同判;
|
|
25
|
+
* - `.openfeel/**` 是流程产物区,任意阶段可写;但受保护名单
|
|
26
|
+
* (`PROTECTED_OPENFEEL_PATHS`:flow.json / flow.json.bak / pipeline.yaml / config.yaml /
|
|
27
|
+
* metrics.json / status.md / chore.json / dev 账本 / flow-archive / checkpoints /
|
|
28
|
+
* requirements/*.md / log/guard-audit.jsonl)始终拒绝(D-126-05,防 agent 手写状态自提权);
|
|
29
|
+
* `.openfeel/` 之外另有 `PROTECTED_WORKSPACE_PATHS`(`dsh/cordis.patch.yml` 的门禁开关行);
|
|
10
30
|
* - `.openfeel/` 外的源码/文档要求存在 `exec_running` 阶段(或 general 需求例外);
|
|
31
|
+
* **代码目录**(`CODE_DIRECTORIES`)内任何扩展名都不享受 doc/asset 豁免(D-126-06);
|
|
32
|
+
* - 判定顺序:受保护路径 → 未初始化/bootstrap → 内部路径早返回 → 研究闸 →
|
|
33
|
+
* 无阶段/chore/doc-asset → 相位判定;
|
|
11
34
|
* - 无 `.openfeel/` 时:`always` 拒绝全部写文件,`project`/`off` 放行;
|
|
12
35
|
* - `apply_patch` 解析所有 patch 头目标,混合/无头时保守拒绝。
|
|
13
36
|
*
|
|
14
37
|
* @module openfeel-dsh/guard
|
|
15
38
|
*/
|
|
16
39
|
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
40
|
+
import { execFileSync } from 'node:child_process';
|
|
41
|
+
import {
|
|
42
|
+
appendFileSync, existsSync, mkdirSync, readFileSync, realpathSync, statSync,
|
|
43
|
+
} from 'node:fs';
|
|
44
|
+
import { basename, dirname, extname, join, resolve } from 'node:path';
|
|
19
45
|
|
|
46
|
+
import { globalGuardAuditPath, writeGuardState } from './adapters/guard-state.js';
|
|
47
|
+
import { lookupSessionCwd } from './adapters/session-cwd-registry.js';
|
|
20
48
|
import { isProjectWorkspace, OPENFEEL_DIR } from './adapters/workspace.js';
|
|
21
49
|
|
|
22
|
-
/**
|
|
50
|
+
/**
|
|
51
|
+
* 默认受守卫的工具。
|
|
52
|
+
*
|
|
53
|
+
* `bash` / `pwsh` 是 v1.5.11 D-126-02 补上的头号绕过面(本宿主真实存在,
|
|
54
|
+
* 参数为 `command` + `workdir`)。
|
|
55
|
+
*
|
|
56
|
+
* **跨宿主防御条目**:`shell` / `execute_command` / `exec`(以及上面的
|
|
57
|
+
* `apply_patch`)在本宿主**不存在**,保留在默认列表里只是为了让「换到别的
|
|
58
|
+
* DSH 宿主后被注册」时不至于静默放行 —— 不要为它们写实现,也不要以为它们
|
|
59
|
+
* 已经在本宿主生效。真正的 shell 分支只认 `SHELL_TOOLS`。
|
|
60
|
+
*
|
|
61
|
+
* 两处必须同步:本常量与 `dsh/lib/index.js` 的 `normalizeConfig` 默认列表;
|
|
62
|
+
* 只改一处会让 profile 传空数组时回落到旧列表(D-126-02)。
|
|
63
|
+
*/
|
|
23
64
|
export const DEFAULT_MUTATING_TOOLS = Object.freeze([
|
|
24
65
|
'edit',
|
|
25
66
|
'write',
|
|
26
67
|
'apply_patch',
|
|
27
68
|
'str_replace_editor',
|
|
69
|
+
'bash',
|
|
70
|
+
'pwsh',
|
|
71
|
+
'shell',
|
|
72
|
+
'execute_command',
|
|
73
|
+
'exec',
|
|
28
74
|
]);
|
|
29
75
|
|
|
76
|
+
/**
|
|
77
|
+
* 需要解析命令文本的 shell 工具(v1.5.11 D-126-02)。
|
|
78
|
+
*
|
|
79
|
+
* 只列**本宿主真实存在**的工具名:`bash` / `pwsh`。跨宿主防御条目
|
|
80
|
+
* (`shell`/`execute_command`/`exec`)刻意不在这里 —— 它们没有已知的参数形状,
|
|
81
|
+
* 不写实现;若真被注册,会走文件工具分支(无可提取路径 → 拒绝),而不是放行。
|
|
82
|
+
*/
|
|
83
|
+
export const SHELL_TOOLS = Object.freeze(['bash', 'pwsh']);
|
|
84
|
+
const SHELL_TOOL_SET = new Set(SHELL_TOOLS);
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* `OPENFEEL_SHELL_GATE` 的默认组合(D-126-02):用两个常量表达,
|
|
88
|
+
* **不是**单一开关 —— 1/2 类(可判定)默认拒,4 类(目标不可判定)默认告警。
|
|
89
|
+
*/
|
|
90
|
+
export const SHELL_GATE_DECIDABLE = 'deny';
|
|
91
|
+
export const SHELL_GATE_UNDECIDABLE = 'warn';
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* 解析 shell 门禁档位。
|
|
95
|
+
*
|
|
96
|
+
* | 取值 | 第 1 类(受保护 / openfeel 写子命令) | 第 2 类(可解析目标) | 第 4 类(不可判定) |
|
|
97
|
+
* |---|---|---|---|
|
|
98
|
+
* | 默认(未设) | 拒 | 拒(`decideForTargets` 正常判定) | 告警放行(审计 + stderr) |
|
|
99
|
+
* | `strict` | 拒 | 拒 | 拒 |
|
|
100
|
+
* | `warn` | 告警放行 | 告警放行 | 告警放行 |
|
|
101
|
+
* | `off` | 放行 | 放行 | 放行(**shell 完全不解析**) |
|
|
102
|
+
*
|
|
103
|
+
* `off` / `warn` **只作用于 shell 分支**,`write`/`edit` 等文件工具不受影响。
|
|
104
|
+
*
|
|
105
|
+
* @param {unknown} raw
|
|
106
|
+
* @returns {{ mode: 'default'|'strict'|'warn'|'off', decidable: 'deny'|'warn'|'allow', undecidable: 'deny'|'warn'|'allow' }}
|
|
107
|
+
*/
|
|
108
|
+
export function resolveShellGate(raw) {
|
|
109
|
+
const value = typeof raw === 'string' ? raw.trim().toLowerCase() : '';
|
|
110
|
+
if (value === 'strict') return { mode: 'strict', decidable: 'deny', undecidable: 'deny', label: 'strict' };
|
|
111
|
+
if (value === 'warn') return { mode: 'warn', decidable: 'warn', undecidable: 'warn', label: 'warn' };
|
|
112
|
+
if (value === 'off') return { mode: 'off', decidable: 'allow', undecidable: 'allow', label: 'off' };
|
|
113
|
+
return {
|
|
114
|
+
mode: 'default',
|
|
115
|
+
decidable: SHELL_GATE_DECIDABLE,
|
|
116
|
+
undecidable: SHELL_GATE_UNDECIDABLE,
|
|
117
|
+
label: 'default(1/2=deny,4=warn)',
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
30
121
|
/**
|
|
31
122
|
* 大小写不敏感文件系统:Windows + 默认 macOS(APFS/HFS+)。
|
|
32
123
|
* 在这两类平台上把路径统一小写,防止 `.OPENFEEL/FLOW.JSON` 绕过。
|
|
@@ -40,6 +131,81 @@ export function normalizeForComparison(value, platform = process.platform) {
|
|
|
40
131
|
return platform === 'win32' || platform === 'darwin' ? value.toLowerCase() : value;
|
|
41
132
|
}
|
|
42
133
|
|
|
134
|
+
/**
|
|
135
|
+
* 已报警过的降级来源(`source + cwd` 去重)。
|
|
136
|
+
*
|
|
137
|
+
* 计划要求「非 agent-session 来源每次命中都打一行 stderr」;长会话里同一来源
|
|
138
|
+
* 会命中成百上千次,逐次打会把终端刷满,所以按「来源 + 目录」去重一次:
|
|
139
|
+
* 首次即暴露、后续不噪音。`OPENFEEL_GUARD_CWD` / `config` / 登记表 / `process`
|
|
140
|
+
* 都属降级路径,必须让用户看见。
|
|
141
|
+
*/
|
|
142
|
+
const degradedWarned = new Set();
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* cwd 解析链(v1.5.11 D-126-01)。
|
|
146
|
+
*
|
|
147
|
+
* 顺序(取第一个可用值并记下来源):
|
|
148
|
+
* 0. `OPENFEEL_GUARD_CWD` → `env`(**逃生阀**,不是常规路径;宿主升级拿掉
|
|
149
|
+
* `agent.session.header.cwd` 时救急,不必改 profile + 重启)
|
|
150
|
+
* 1. `execution.agent.session.header.cwd` → `agent-session`(实测唯一稳定链路)
|
|
151
|
+
* 2. `config.cwd`(profile 的 `cwd:`)→ `config`
|
|
152
|
+
* 3. 会话登记表 `[sessionId]` → `registry`(**只在 agent 存在但 header.cwd 为空时命中**)
|
|
153
|
+
* 4. `process.cwd()` → `process`,**仅当该目录本身含 `.openfeel/`**
|
|
154
|
+
* (否则就是把宿主启动目录当会话工作区 —— 原 bug 的形态)
|
|
155
|
+
* 5. 全部失败 → `{ cwd: null, source: 'unresolved' }`(调用方 fail-closed 拒绝)
|
|
156
|
+
*
|
|
157
|
+
* **为什么没有 `registry-last`**:进程级「最近一次 cwd」在多窗口/多项目时会
|
|
158
|
+
* 跨项目串味(按别的项目的 flow 放行),比静默放行更危险(plan P1-4)。
|
|
159
|
+
*
|
|
160
|
+
* @param {{ agent?: { session?: { id?: string, header?: { cwd?: string } } } } | undefined} execution
|
|
161
|
+
* @param {{ cwd?: string }} [options]
|
|
162
|
+
* @returns {{ cwd: string | null, source: 'env'|'agent-session'|'config'|'registry'|'process'|'unresolved', degraded: boolean }}
|
|
163
|
+
*/
|
|
164
|
+
export function resolveGuardCwd(execution, options = {}) {
|
|
165
|
+
const envCwd = process.env.OPENFEEL_GUARD_CWD;
|
|
166
|
+
if (typeof envCwd === 'string' && envCwd.trim() !== '') {
|
|
167
|
+
return { cwd: resolve(envCwd.trim()), source: 'env', degraded: true };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const sessionCwd = execution?.agent?.session?.header?.cwd;
|
|
171
|
+
if (typeof sessionCwd === 'string' && sessionCwd.trim() !== '') {
|
|
172
|
+
return { cwd: resolve(sessionCwd.trim()), source: 'agent-session', degraded: false };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const configCwd = options.cwd;
|
|
176
|
+
if (typeof configCwd === 'string' && configCwd.trim() !== '') {
|
|
177
|
+
return { cwd: resolve(configCwd.trim()), source: 'config', degraded: true };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const sessionId = execution?.agent?.session?.id;
|
|
181
|
+
const registryCwd = lookupSessionCwd(sessionId);
|
|
182
|
+
if (typeof registryCwd === 'string' && registryCwd !== '') {
|
|
183
|
+
return { cwd: resolve(registryCwd), source: 'registry', degraded: true };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const processCwd = process.cwd();
|
|
187
|
+
if (typeof processCwd === 'string' && processCwd !== '' && isProjectWorkspace(processCwd)) {
|
|
188
|
+
return { cwd: resolve(processCwd), source: 'process', degraded: true };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
return { cwd: null, source: 'unresolved', degraded: true };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* 降级来源必须出声(P1-4):非 `agent-session` 每次命中打一行 stderr(按来源+目录去重)。
|
|
196
|
+
* @param {{ cwd: string | null, source: string }} resolution
|
|
197
|
+
*/
|
|
198
|
+
function warnDegradedSource(resolution) {
|
|
199
|
+
if (resolution.source === 'agent-session' || resolution.cwd === null) return;
|
|
200
|
+
const key = `${resolution.source}\u0000${resolution.cwd}`;
|
|
201
|
+
if (degradedWarned.has(key)) return;
|
|
202
|
+
degradedWarned.add(key);
|
|
203
|
+
const extra = resolution.source === 'process'
|
|
204
|
+
? '(最弱一环:宿主启动目录,仅因它本身含 .openfeel/ 才采用)'
|
|
205
|
+
: '';
|
|
206
|
+
process.stderr.write(`[openfeel-guard] cwdSource=${resolution.source}(非会话直读,可能是降级路径)${extra}\n`);
|
|
207
|
+
}
|
|
208
|
+
|
|
43
209
|
/** 文档/笔记类扩展名(写门禁按产物类型分层:doc/note 不绑相位)。 */
|
|
44
210
|
export const DOC_EXTENSIONS = Object.freeze(['.md', '.mdx', '.txt', '.rst', '.adoc']);
|
|
45
211
|
|
|
@@ -62,6 +228,22 @@ export const SOURCE_EXTENSIONS = Object.freeze([
|
|
|
62
228
|
'.lua', '.dart', '.ex', '.exs',
|
|
63
229
|
]);
|
|
64
230
|
|
|
231
|
+
/**
|
|
232
|
+
* 代码目录(D-126-06):这些**工作区根级**目录内的任何文件都按源码门禁。
|
|
233
|
+
*
|
|
234
|
+
* 为什么:`src/x.md`、`src/x.css`、`src/assets/logo.svg` 同样是仓库内容
|
|
235
|
+
* (可被 import / 被脚本读取 / 被打包),而且 `src/*.md` 正是上一轮
|
|
236
|
+
* 「门禁失效」假象的来源。豁免只应给「人读产物」(docs/、根级 README 等),
|
|
237
|
+
* **不给代码目录里的任何文件** —— 所以判定顺序必须是「先判目录,再判扩展名」。
|
|
238
|
+
*
|
|
239
|
+
* 只看工作区根级目录段(`docs/src-notes.md`、`docs/src/a.md` 不算代码目录);
|
|
240
|
+
* 判据只用路径段,不做子串匹配,避免 `src-notes.md` 这类误伤。
|
|
241
|
+
*/
|
|
242
|
+
export const CODE_DIRECTORIES = Object.freeze(['src', 'test', 'scripts', 'dsh', 'bin']);
|
|
243
|
+
|
|
244
|
+
/** 工作区**根级**人读文件前缀(D-126-06):README / CHANGELOG / LICENSE(可无扩展名)。 */
|
|
245
|
+
const ROOT_DOC_FILE_PREFIXES = Object.freeze(['readme', 'changelog', 'license']);
|
|
246
|
+
|
|
65
247
|
/**
|
|
66
248
|
* 是否为文档/笔记类目标(P0-4):扩展名命中,或位于**工作区根级 `docs/`** 下。
|
|
67
249
|
* v1.3.3 复核:`docs` 必须直接位于会话工作区下(`src/docs/x.ts` 不算文档,防源码借名绕过相位门)。
|
|
@@ -104,6 +286,92 @@ function isUnderWorkspace(absolute, cwd) {
|
|
|
104
286
|
return absolute === cwd || absolute.startsWith(`${cwd}\\`) || absolute.startsWith(`${cwd}/`);
|
|
105
287
|
}
|
|
106
288
|
|
|
289
|
+
/**
|
|
290
|
+
* 工作区相对路径段(已归一化、已小写)。工作区外返回 null。
|
|
291
|
+
* @param {string} absolute 已归一化绝对路径
|
|
292
|
+
* @param {string} cwd 已归一化工作区
|
|
293
|
+
* @returns {string[] | null}
|
|
294
|
+
*/
|
|
295
|
+
function workspaceRelativeSegments(absolute, cwd) {
|
|
296
|
+
if (absolute === cwd) return [];
|
|
297
|
+
if (!isUnderWorkspace(absolute, cwd)) return null;
|
|
298
|
+
return absolute.slice(cwd.length + 1).split(/[\\/]+/).filter(Boolean);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* 是否位于**代码目录**内(D-126-06)。
|
|
303
|
+
*
|
|
304
|
+
* 工作区根级目录段命中 `CODE_DIRECTORIES` 即 true;工作区外沿用既有扩展名语义
|
|
305
|
+
* (本 op 不扩大改动面)。`src/x.md` / `src/x.css` / `src/assets/logo.svg` → true;
|
|
306
|
+
* `docs/src-notes.md`(文件名不是目录段)→ false。
|
|
307
|
+
* @param {string} absolute 已归一化绝对路径
|
|
308
|
+
* @param {string} cwd 已归一化工作区
|
|
309
|
+
* @returns {boolean}
|
|
310
|
+
*/
|
|
311
|
+
export function isCodeDirectoryPath(absolute, cwd) {
|
|
312
|
+
const segments = workspaceRelativeSegments(absolute, cwd);
|
|
313
|
+
if (segments === null) return false;
|
|
314
|
+
return segments.length > 1 && CODE_DIRECTORIES.includes(segments[0]);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* 构建/测试产物(v1.5.11 D-126-02 第 3 类):写这些目标**不触发拒绝**。
|
|
319
|
+
*
|
|
320
|
+
* 目的:保证 `npx vitest` / `npm run build` / `cargo build` / `tsc -b` /
|
|
321
|
+
* `npm install` 这类日常命令不被误杀(它们会写 `dist/`、`target/`、
|
|
322
|
+
* `node_modules/` 等)。匹配按**工作区根级**路径段(`dist/**` 就是根级 `dist/`),
|
|
323
|
+
* 不做任意层级匹配 —— 否则 `src/build/x.ts` 会借名豁免。
|
|
324
|
+
*
|
|
325
|
+
* 口径:**全部**目标命中豁免才放行,混合目标从严(走 `decideForTargets`)。
|
|
326
|
+
*/
|
|
327
|
+
export const BUILD_ARTIFACT_GLOBS = Object.freeze([
|
|
328
|
+
'dist/**',
|
|
329
|
+
'build/**',
|
|
330
|
+
'out/**',
|
|
331
|
+
'target/**',
|
|
332
|
+
'.next/**',
|
|
333
|
+
'node_modules/**',
|
|
334
|
+
'coverage/**',
|
|
335
|
+
'.openfeel/tmp/**',
|
|
336
|
+
'.cache/**',
|
|
337
|
+
'*.tsbuildinfo',
|
|
338
|
+
'pnpm-lock.yaml',
|
|
339
|
+
'package-lock.json',
|
|
340
|
+
]);
|
|
341
|
+
|
|
342
|
+
const BUILD_ARTIFACT_DIRS = new Set(['dist', 'build', 'out', 'target', '.next', 'node_modules', 'coverage', '.cache']);
|
|
343
|
+
const BUILD_ARTIFACT_FILES = new Set(['pnpm-lock.yaml', 'package-lock.json']);
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* 是否为构建/测试产物目标(第 3 类)。
|
|
347
|
+
* @param {string} absolute 已归一化绝对路径
|
|
348
|
+
* @param {string} cwd 已归一化工作区
|
|
349
|
+
* @returns {boolean}
|
|
350
|
+
*/
|
|
351
|
+
export function isBuildArtifactPath(absolute, cwd) {
|
|
352
|
+
const segments = workspaceRelativeSegments(absolute, cwd);
|
|
353
|
+
if (segments === null || segments.length === 0) return false;
|
|
354
|
+
const base = segments[segments.length - 1].toLowerCase();
|
|
355
|
+
if (BUILD_ARTIFACT_FILES.has(base)) return true;
|
|
356
|
+
if (base.endsWith('.tsbuildinfo')) return true;
|
|
357
|
+
if (segments.length > 1 && segments[0] === '.openfeel' && segments[1] === 'tmp') return true;
|
|
358
|
+
return segments.length > 1 && BUILD_ARTIFACT_DIRS.has(segments[0].toLowerCase());
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* 是否为工作区**根级**人读文件(`README*` / `CHANGELOG*` / `LICENSE*`,D-126-06)。
|
|
363
|
+
* 只认根级:`src/README.md` 仍按源码门禁。
|
|
364
|
+
* @param {string} absolute 已归一化绝对路径
|
|
365
|
+
* @param {string} cwd 已归一化工作区
|
|
366
|
+
* @returns {boolean}
|
|
367
|
+
*/
|
|
368
|
+
function isRootDocFile(absolute, cwd) {
|
|
369
|
+
const segments = workspaceRelativeSegments(absolute, cwd);
|
|
370
|
+
if (segments === null || segments.length !== 1) return false;
|
|
371
|
+
const name = segments[0].toLowerCase();
|
|
372
|
+
return ROOT_DOC_FILE_PREFIXES.some((prefix) => name.startsWith(prefix));
|
|
373
|
+
}
|
|
374
|
+
|
|
107
375
|
/**
|
|
108
376
|
* 是否为**静态展示资源**(v1.4.0;与 doc 同层豁免)。
|
|
109
377
|
*
|
|
@@ -124,34 +392,84 @@ export function isPresentationalAssetPath(absolute) {
|
|
|
124
392
|
return segments.includes('assets') || segments.includes('public');
|
|
125
393
|
}
|
|
126
394
|
|
|
127
|
-
/**
|
|
128
|
-
|
|
395
|
+
/**
|
|
396
|
+
* doc + 静态展示资源合并豁免判据(v1.4.0 / v1.5.11 D-126-06)。
|
|
397
|
+
*
|
|
398
|
+
* 顺序(必须保持):**先判代码目录,再判扩展名**。
|
|
399
|
+
* - 代码目录内任何扩展名一律不豁免(含 `.md`/`.css`/`.png`/`assets/**`);
|
|
400
|
+
* - 工作区根级 `README*`/`CHANGELOG*`/`LICENSE*` 豁免(根级 `LICENSE` 可无扩展名);
|
|
401
|
+
* - 其它位置沿用既有 `isDocPath` / `isPresentationalAssetPath`(`docs/**`、
|
|
402
|
+
* 任意 `assets/` / `public/`、doc/展示资源扩展名),保持既有放行语义。
|
|
403
|
+
*
|
|
404
|
+
* @param {string} absolute 已归一化绝对路径
|
|
405
|
+
* @param {string} cwd 已归一化工作区
|
|
406
|
+
* @returns {boolean}
|
|
407
|
+
*/
|
|
408
|
+
export function isExemptPath(absolute, cwd) {
|
|
409
|
+
if (isCodeDirectoryPath(absolute, cwd)) return false;
|
|
410
|
+
if (isRootDocFile(absolute, cwd)) return true;
|
|
129
411
|
return isDocPath(absolute, cwd) || isPresentationalAssetPath(absolute);
|
|
130
412
|
}
|
|
131
413
|
|
|
132
414
|
/**
|
|
133
|
-
*
|
|
134
|
-
*
|
|
135
|
-
* @param {
|
|
136
|
-
* @
|
|
415
|
+
* 审计里的命令片段(v1.5.11 D-126-02):折叠空白并截断到 200 字符。
|
|
416
|
+
* @param {unknown} command
|
|
417
|
+
* @param {number} [limit]
|
|
418
|
+
* @returns {string | undefined}
|
|
419
|
+
*/
|
|
420
|
+
function truncateCommand(command, limit = 200) {
|
|
421
|
+
if (typeof command !== 'string') return undefined;
|
|
422
|
+
const value = command.replace(/\s+/g, ' ').trim();
|
|
423
|
+
if (value === '') return undefined;
|
|
424
|
+
return value.length <= limit ? value : `${value.slice(0, limit - 1)}…`;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* 写入门禁审计(v1.4.0 / v1.5.2 / v1.5.11):放行、拒绝、告警都追加 JSONL。
|
|
429
|
+
*
|
|
430
|
+
* 落点(D-126-04):工作区 `.openfeel/log/guard-audit.jsonl`;**cwd 为 null 时
|
|
431
|
+
* 固定落全局** `os.tmpdir()/openfeel-guard/guard-audit.jsonl`,**绝不静默丢弃**
|
|
432
|
+
* —— 那恰好是最需要证据的时刻。写失败也出声(stderr)。
|
|
433
|
+
*
|
|
434
|
+
* 每行必须带 `cwdSource`(验收 14)与 `decision`(allow|deny|warn);shell 行
|
|
435
|
+
* 额外带 `command`(截断 ≤200 字符),否则「门禁是否真的拦过」无法自证。
|
|
436
|
+
*
|
|
437
|
+
* @param {string | null} cwd 已归一化工作区(null = 不可解析)
|
|
438
|
+
* @param {{ event?: 'guard_allow'|'guard_deny'|'guard_shell_unresolved'|'guard_shell_downgraded', decision?: 'allow'|'deny'|'warn', tool: string, reason: string, phase: string, paths: string[], cwdSource?: string, command?: string }} event
|
|
137
439
|
*/
|
|
138
440
|
function recordGuardAudit(cwd, event) {
|
|
441
|
+
const entry = {
|
|
442
|
+
time: new Date().toISOString(),
|
|
443
|
+
event: event.event ?? 'guard_allow',
|
|
444
|
+
decision: event.decision ?? 'allow',
|
|
445
|
+
tool: event.tool,
|
|
446
|
+
reason: event.reason,
|
|
447
|
+
phase: event.phase,
|
|
448
|
+
paths: event.paths,
|
|
449
|
+
// 每行都要能回答「用哪个 cwd 判的」(验收 14)。
|
|
450
|
+
cwdSource: typeof event.cwdSource === 'string' && event.cwdSource !== '' ? event.cwdSource : 'agent-session',
|
|
451
|
+
};
|
|
452
|
+
const command = truncateCommand(event.command);
|
|
453
|
+
if (command !== undefined) entry.command = command;
|
|
454
|
+
// op-005 / P0-1:shell 行必须能区分「确认只读(none)」与「无法判定(undecidable)」,
|
|
455
|
+
// 否则审计会把一次静默放行记成「没有写」。
|
|
456
|
+
if (typeof event.kind === 'string' && event.kind !== '') entry.kind = event.kind;
|
|
457
|
+
|
|
458
|
+
const hasWorkspace = typeof cwd === 'string' && cwd !== '';
|
|
459
|
+
const file = hasWorkspace ? join(cwd, '.openfeel', 'log', 'guard-audit.jsonl') : globalGuardAuditPath();
|
|
139
460
|
try {
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
appendFileSync(join(logDir, 'guard-audit.jsonl'), `${JSON.stringify(entry)}\n`, 'utf-8');
|
|
153
|
-
} catch {
|
|
154
|
-
/* 审计写失败不阻塞放行 */
|
|
461
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
462
|
+
appendFileSync(file, `${JSON.stringify(entry)}\n`, 'utf-8');
|
|
463
|
+
if (!hasWorkspace) {
|
|
464
|
+
// 全局落点是兜底:必须让人知道证据换了地方(不能让「证据还在」变成静默)。
|
|
465
|
+
process.stderr.write(`[guard] audit-unavailable:工作区不可解析,审计已落全局 ${file}\n`);
|
|
466
|
+
}
|
|
467
|
+
} catch (error) {
|
|
468
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
469
|
+
process.stderr.write(`[guard] audit-unavailable:${file}(${reason})\n`);
|
|
470
|
+
process.stderr.write(
|
|
471
|
+
`[guard] at=${entry.time} tool=${entry.tool} reason=${entry.reason} cwdSource=${entry.cwdSource}\n`,
|
|
472
|
+
);
|
|
155
473
|
}
|
|
156
474
|
}
|
|
157
475
|
|
|
@@ -179,14 +497,94 @@ function readActiveChore(cwd) {
|
|
|
179
497
|
const flowCache = new Map();
|
|
180
498
|
|
|
181
499
|
/**
|
|
182
|
-
*
|
|
500
|
+
* Win32 文件名字面归一化(op-005 / P0-2)。
|
|
501
|
+
*
|
|
502
|
+
* Windows 上**同一个文件有多种写法**,逐字比较会被一个字符破掉:
|
|
503
|
+
* - 每段尾点 / 尾空格被文件系统忽略:`.openfeel/flow.json.` ≡ `flow.json`;
|
|
504
|
+
* - 备用数据流(ADS):`flow.json::$DATA` / `flow.json:stream` 指向同一个文件;
|
|
505
|
+
* - 8.3 短名:`FLOW~1.JSO` ≡ `flow.json`(字面归一化做不到,只能靠 realpath 反查)。
|
|
506
|
+
*
|
|
507
|
+
* 本函数只做**字面**归一化(去尾点/尾空格、按第一个 `:` 截断 ADS),
|
|
508
|
+
* 短名/大小写由 `tryRealPath` 反查。
|
|
509
|
+
*
|
|
510
|
+
* **盘符冒号不能误截**:只对「非盘符」的 `:` 生效(`C:\x` 的 `C:` 保留)。
|
|
511
|
+
*
|
|
512
|
+
* @param {string} absolute 绝对路径(未归一化)
|
|
513
|
+
* @returns {string}
|
|
514
|
+
*/
|
|
515
|
+
export function canonicalizeWin32Path(absolute) {
|
|
516
|
+
const text = String(absolute);
|
|
517
|
+
// 长路径前缀(\\?\C:\… / \\.\C:\…)原样保留,只归一化剩余部分。
|
|
518
|
+
const longPrefix = /^[\\/]{2}[?.][\\/]/.exec(text);
|
|
519
|
+
const prefix = longPrefix === null ? '' : longPrefix[0];
|
|
520
|
+
const body = prefix === '' ? text : text.slice(prefix.length);
|
|
521
|
+
const drive = /^([A-Za-z]:)(?:[\\/]|$)/.exec(body);
|
|
522
|
+
const root = drive === null ? '' : `${drive[1]}\\`;
|
|
523
|
+
const rest = drive === null ? body.replace(/^[\\/]+/, '') : body.slice(drive[0].length);
|
|
524
|
+
const segments = rest.split(/[\\/]+/).filter((segment) => segment !== '');
|
|
525
|
+
const cleaned = segments
|
|
526
|
+
.map((segment) => {
|
|
527
|
+
// ADS / file:stream → 取第一个 `:` 之前的部分(盘符已在上面剥离)。
|
|
528
|
+
const colon = segment.indexOf(':');
|
|
529
|
+
const cut = colon === -1 ? segment : segment.slice(0, colon);
|
|
530
|
+
// 尾点 / 尾空格被 Win32 忽略(`nul` 之类的设备名不在此处理)。
|
|
531
|
+
return cut.replace(/[. ]+$/, '');
|
|
532
|
+
})
|
|
533
|
+
.filter((segment) => segment !== '');
|
|
534
|
+
return `${prefix}${root}${cleaned.join('\\')}`;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/**
|
|
538
|
+
* 用 `realpathSync.native` 反查真实名(大小写 + 8.3 短名 + 尾点/尾空格 + 链接)。
|
|
539
|
+
* @param {string} absolute
|
|
540
|
+
* @returns {string | null}
|
|
541
|
+
*/
|
|
542
|
+
function tryRealPath(absolute) {
|
|
543
|
+
try {
|
|
544
|
+
return realpathSync.native(absolute);
|
|
545
|
+
} catch {
|
|
546
|
+
return null;
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/**
|
|
551
|
+
* 目标不存在时的反查:父目录 realpath + 自身 basename(写新文件时父目录已存在)。
|
|
552
|
+
* basename 也做 Win32 字面归一(否则 `flow.json.` 会把尾点带进结果)。
|
|
553
|
+
* @param {string} absolute
|
|
554
|
+
* @returns {string | null}
|
|
555
|
+
*/
|
|
556
|
+
function tryRealPathParent(absolute) {
|
|
557
|
+
try {
|
|
558
|
+
const parent = dirname(absolute);
|
|
559
|
+
if (parent === absolute) return null;
|
|
560
|
+
const realParent = realpathSync.native(parent);
|
|
561
|
+
const name = process.platform === 'win32' ? canonicalizeWin32Path(basename(absolute)) : basename(absolute);
|
|
562
|
+
return join(realParent, name);
|
|
563
|
+
} catch {
|
|
564
|
+
return null;
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/**
|
|
569
|
+
* 归一化路径:绝对化 + Win32 文件名字面归一化 + realpath 反查 + 大小写归一化。
|
|
570
|
+
*
|
|
571
|
+
* 为什么三者都要(op-005 / P0-2):受保护名单按**字符串**比对,只要有任意一种
|
|
572
|
+
* 等价写法不被归一,`.openfeel/flow.json.` / `flow.json::$DATA` / `FLOW~1.JSO`
|
|
573
|
+
* 就能在不触碰名单的情况下覆盖 `flow.json`(门禁双路径 ALLOW)。
|
|
574
|
+
*
|
|
575
|
+
* **所有**路径(cwd / baseDir / 写入目标 / patch 目标)都必须走这里,否则两侧
|
|
576
|
+
* 归一化口径不一致,前缀比较(`isUnderWorkspace` 等)会失效。
|
|
577
|
+
*
|
|
183
578
|
* @param {string} cwd
|
|
184
579
|
* @param {string} target
|
|
185
580
|
* @returns {string}
|
|
186
581
|
*/
|
|
187
582
|
function normalizeTarget(cwd, target) {
|
|
188
|
-
const absolute = resolve(cwd, target);
|
|
189
|
-
|
|
583
|
+
const absolute = resolve(cwd, String(target ?? ''));
|
|
584
|
+
const literal = process.platform === 'win32' ? canonicalizeWin32Path(absolute) : absolute;
|
|
585
|
+
// 顺序:原样 realpath → 字面归一后 realpath(去尾点/ADS/短名)→ 父目录 + 归一 basename。
|
|
586
|
+
const real = tryRealPath(absolute) ?? tryRealPath(literal) ?? tryRealPathParent(absolute);
|
|
587
|
+
return normalizeForComparison(real ?? literal);
|
|
190
588
|
}
|
|
191
589
|
|
|
192
590
|
/**
|
|
@@ -214,15 +612,206 @@ function isUnderOpenFeel(absolute, cwd) {
|
|
|
214
612
|
}
|
|
215
613
|
|
|
216
614
|
/**
|
|
217
|
-
*
|
|
218
|
-
*
|
|
219
|
-
*
|
|
220
|
-
*
|
|
615
|
+
* D-126-05 受保护路径(相对 `.openfeel/` 的路径段;比对前已由 `normalizeTarget`
|
|
616
|
+
* 做大小写归一化,防 `.OPENFEEL/CHORE.JSON` 绕过)。
|
|
617
|
+
*
|
|
618
|
+
* 为什么要先于 `allInternal` 早返回判定:早返回让 `.openfeel/**` 任意相位可写,
|
|
619
|
+
* 于是 agent 能手写 `chore.json`(自开写窗口,`expires_at` 填未来)、
|
|
620
|
+
* `.preflight.json`(伪造「10 分钟内读过状态」)、`guard-state.json` / 归档 /
|
|
621
|
+
* 快照 / 需求人读副本(与 flow.json 漂移,要等 health 才发现)。
|
|
622
|
+
*
|
|
623
|
+
* **边界(不要"顺手"加豁免)**:guard **只拦 agent 的工具调用**(write/edit/shell);
|
|
624
|
+
* 适配器与 CLI 自己用 `fs` 直写(`recordGuardAudit` 的 `appendFileSync`、CLI 写
|
|
625
|
+
* `flow.json` / preflight / `chore.json` / 归档、之后的 `guard-state.json` /
|
|
626
|
+
* `sessions.json`)**不经过 guard**,因此不受影响。给它们加豁免开关等于把自提权通道还回去。
|
|
627
|
+
*
|
|
628
|
+
* `.openfeel/log/` **不做整目录保护**(其它日志文件仍可写,避免打断工作流);
|
|
629
|
+
* 只单独保护审计证据 `guard-audit.jsonl` —— 否则 agent 可截断/伪造审计把证据抹掉。
|
|
630
|
+
*
|
|
631
|
+
* `match`:`file` = 精确文件;`dir` = 目录前缀(含自身);`md` = `requirements/*.md`(单层)。
|
|
632
|
+
*/
|
|
633
|
+
export const PROTECTED_OPENFEEL_PATHS = Object.freeze([
|
|
634
|
+
{ match: 'file', segments: Object.freeze(['flow.json']), hint: 'state' },
|
|
635
|
+
{ match: 'file', segments: Object.freeze(['flow.json.bak']), hint: 'state' },
|
|
636
|
+
// op-005 / P0-3:状态机转移表与工作流配置。两者不在名单时,`.openfeel/**` 的
|
|
637
|
+
// `allInternal` 早返回会让**任意相位、任意工具**改写它们 —— 「把转移表改成
|
|
638
|
+
// plan_pending→done 合法」「把 workflow_mode 改成 general」都是自提权通道。
|
|
639
|
+
{ match: 'file', segments: Object.freeze(['pipeline.yaml']), hint: 'pipeline-config' },
|
|
640
|
+
{ match: 'file', segments: Object.freeze(['config.yaml']), hint: 'pipeline-config' },
|
|
641
|
+
// metrics.json 是 CLI 维护的运行期指标;手改会与 flow.json 记账漂移。
|
|
642
|
+
{ match: 'file', segments: Object.freeze(['metrics.json']), hint: 'metrics' },
|
|
643
|
+
{ match: 'file', segments: Object.freeze(['chore.json']), hint: 'chore' },
|
|
644
|
+
{ match: 'file', segments: Object.freeze(['dev', '.preflight.json']), hint: 'preflight' },
|
|
645
|
+
{ match: 'file', segments: Object.freeze(['dev', 'sessions.json']), hint: 'sessions' },
|
|
646
|
+
{ match: 'file', segments: Object.freeze(['dev', 'guard-state.json']), hint: 'guard-state' },
|
|
647
|
+
{ match: 'file', segments: Object.freeze(['log', 'guard-audit.jsonl']), hint: 'audit' },
|
|
648
|
+
{ match: 'dir', segments: Object.freeze(['flow-archive']), hint: 'flow-archive' },
|
|
649
|
+
{ match: 'dir', segments: Object.freeze(['checkpoints']), hint: 'checkpoints' },
|
|
650
|
+
{ match: 'md', segments: Object.freeze(['requirements']), hint: 'requirements' },
|
|
651
|
+
]);
|
|
652
|
+
|
|
653
|
+
/**
|
|
654
|
+
* 受保护的工作区相对路径(`.openfeel/` 之外;op-005 / P2)。
|
|
655
|
+
*
|
|
656
|
+
* `dsh/cordis.patch.yml` 里的 `enforce` / `shellGate` 是**门禁自身的开关**:
|
|
657
|
+
* agent 在 exec 期把它改成 `enforce: off` 或 `shellGate: off`,宿主重启后门禁即失效。
|
|
658
|
+
* 这类「关掉守卫」的配置必须与人开的写窗口同权(只有人类能改)。
|
|
659
|
+
*
|
|
660
|
+
* 取舍:本列表**只收门禁开关文件**,不整目录保护 `dsh/**`(那会把正常开发也锁死)。
|
|
661
|
+
*/
|
|
662
|
+
export const PROTECTED_WORKSPACE_PATHS = Object.freeze([
|
|
663
|
+
{ match: 'file', segments: Object.freeze(['dsh', 'cordis.patch.yml']), hint: 'adapter-config' },
|
|
664
|
+
]);
|
|
665
|
+
|
|
666
|
+
/** 受保护路径的归属与拒绝指引(服务端拒绝文案;文案即修复路径)。 */
|
|
667
|
+
const PROTECTED_HINTS = Object.freeze({
|
|
668
|
+
state: {
|
|
669
|
+
zh: '`.openfeel/flow.json`(含 `.bak`)与 `.openfeel/**/status.md` 是流水线权威状态:请改用 feel_flow / feel_stage 等 CLI 工具。',
|
|
670
|
+
en: '`.openfeel/flow.json` (and `.bak`) plus `.openfeel/**/status.md` are authoritative pipeline state: use feel_flow / feel_stage instead.',
|
|
671
|
+
},
|
|
672
|
+
chore: {
|
|
673
|
+
zh: '`.openfeel/chore.json` 是 chore 写窗口,只能由**人类**在外部终端开启/收口:`openfeel chore "<说明>"` / `openfeel chore --end`;agent 不能自行开窗。',
|
|
674
|
+
en: '`.openfeel/chore.json` is the chore write window and can only be opened/closed by a human from an external terminal: `openfeel chore "<note>"` / `openfeel chore --end`; the agent cannot open it.',
|
|
675
|
+
},
|
|
676
|
+
preflight: {
|
|
677
|
+
zh: '`.openfeel/dev/.preflight.json` 由 feel_status / feel_next 自动记录:请勿手写。',
|
|
678
|
+
en: '`.openfeel/dev/.preflight.json` is recorded automatically by feel_status / feel_next: do not hand-write it.',
|
|
679
|
+
},
|
|
680
|
+
sessions: {
|
|
681
|
+
zh: '`.openfeel/dev/sessions.json` 由 feel_* 自动心跳维护:请勿手写。',
|
|
682
|
+
en: '`.openfeel/dev/sessions.json` is maintained by feel_* heartbeats: do not hand-write it.',
|
|
683
|
+
},
|
|
684
|
+
'guard-state': {
|
|
685
|
+
zh: '`.openfeel/dev/guard-state.json` 是门禁自检状态,由 guard 自动写入;请看 feel_status 的 guard 段。',
|
|
686
|
+
en: '`.openfeel/dev/guard-state.json` is guard self-check state written by the guard itself; read the guard section of feel_status.',
|
|
687
|
+
},
|
|
688
|
+
'pipeline-config': {
|
|
689
|
+
zh: '`.openfeel/pipeline.yaml`(状态机转移表)与 `.openfeel/config.yaml`(workflow_mode / auto_advance / test_enabled)是流程**规则**本身:改它们等于改判定标准(例如把 plan_pending→done 变合法)。请由人类直接修改并在改后重启会话。',
|
|
690
|
+
en: '`.openfeel/pipeline.yaml` (state machine transitions) and `.openfeel/config.yaml` (workflow_mode / auto_advance / test_enabled) are the pipeline rules themselves: editing them rewrites the criteria (e.g. making plan_pending→done legal). Only a human may edit them, then restart the session.',
|
|
691
|
+
},
|
|
692
|
+
metrics: {
|
|
693
|
+
zh: '`.openfeel/metrics.json` 由 CLI 维护(agent 运行指标):请勿手写。',
|
|
694
|
+
en: '`.openfeel/metrics.json` is maintained by the CLI (agent run metrics): do not hand-write it.',
|
|
695
|
+
},
|
|
696
|
+
'adapter-config': {
|
|
697
|
+
zh: '`dsh/cordis.patch.yml` 的 `enforce` / `shellGate` 是**门禁自身的开关**(改成 off 重启即失效):请由人类在外部终端修改。',
|
|
698
|
+
en: 'The `enforce` / `shellGate` rows of `dsh/cordis.patch.yml` are the gate\'s own switches (setting them to off disables the guard after a restart): only a human may edit this file from an external terminal.',
|
|
699
|
+
},
|
|
700
|
+
'flow-archive': {
|
|
701
|
+
zh: '`.openfeel/flow-archive/**` 是版本归档:请用 feel_archive action=create / show。',
|
|
702
|
+
en: '`.openfeel/flow-archive/**` is version archive data: use feel_archive action=create / show.',
|
|
703
|
+
},
|
|
704
|
+
checkpoints: {
|
|
705
|
+
zh: '`.openfeel/checkpoints/**` 是相位快照:请用 feel_checkpoint(读/恢复)。',
|
|
706
|
+
en: '`.openfeel/checkpoints/**` is checkpoint data: use feel_checkpoint.',
|
|
707
|
+
},
|
|
708
|
+
requirements: {
|
|
709
|
+
zh: '`.openfeel/requirements/*.md` 是 CLI 生成的人读副本:请用 feel_req action=add|set|claim 等维护。',
|
|
710
|
+
en: '`.openfeel/requirements/*.md` is a human-readable copy generated by the CLI: use feel_req action=add|set|claim.',
|
|
711
|
+
},
|
|
712
|
+
audit: {
|
|
713
|
+
zh: '`.openfeel/log/guard-audit.jsonl` 是门禁审计证据,由 guard 自动追加:请勿手写或截断。',
|
|
714
|
+
en: '`.openfeel/log/guard-audit.jsonl` is guard audit evidence appended by the guard: do not hand-write or truncate it.',
|
|
715
|
+
},
|
|
716
|
+
});
|
|
717
|
+
|
|
718
|
+
/**
|
|
719
|
+
* 按「路径段 + 匹配模式」比对一组受保护条目。
|
|
720
|
+
* @param {string[]} segments 已归一化(小写)的路径段
|
|
721
|
+
* @param {ReadonlyArray<{ match: string, segments: readonly string[], hint: string }>} entries
|
|
722
|
+
* @returns {{ hint: string } | null}
|
|
723
|
+
*/
|
|
724
|
+
function matchProtectedEntries(segments, entries) {
|
|
725
|
+
for (const entry of entries) {
|
|
726
|
+
const lengthOk = entry.match === 'file'
|
|
727
|
+
? segments.length === entry.segments.length
|
|
728
|
+
: segments.length >= entry.segments.length;
|
|
729
|
+
if (!lengthOk) continue;
|
|
730
|
+
if (!entry.segments.every((segment, index) => segments[index] === segment)) continue;
|
|
731
|
+
if (entry.match === 'md') {
|
|
732
|
+
// `requirements/*.md`:只匹配一层,且扩展名必须是 `.md`。
|
|
733
|
+
if (segments.length !== entry.segments.length + 1) continue;
|
|
734
|
+
if (extname(segments[segments.length - 1]).toLowerCase() !== '.md') continue;
|
|
735
|
+
}
|
|
736
|
+
return { hint: entry.hint };
|
|
737
|
+
}
|
|
738
|
+
return null;
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
/**
|
|
742
|
+
* 匹配受保护路径,命中返回归属 `{ hint }`,否则 null。
|
|
743
|
+
*
|
|
744
|
+
* 比较对象是**归一化后**的绝对路径(`normalizeTarget` 已做尾点/尾空格/ADS/短名/
|
|
745
|
+
* 大小写归一),所以 `.openfeel/flow.json.`、`flow.json::$DATA`、`FLOW~1.JSO`
|
|
746
|
+
* 与 `flow.json` 得到同一结论(op-005 / P0-2)。
|
|
747
|
+
*
|
|
748
|
+
* @param {string} absolute 已归一化绝对路径
|
|
749
|
+
* @param {string} cwd 已归一化工作区
|
|
750
|
+
* @returns {{ hint: string } | null}
|
|
751
|
+
*/
|
|
752
|
+
function matchProtectedPath(absolute, cwd) {
|
|
753
|
+
const root = normalizeTarget(cwd, OPENFEEL_DIR);
|
|
754
|
+
if (absolute === root || absolute.startsWith(`${root}\\`) || absolute.startsWith(`${root}/`)) {
|
|
755
|
+
const segments = absolute === root
|
|
756
|
+
? []
|
|
757
|
+
: absolute.slice(root.length).split(/[\\/]+/).filter(Boolean);
|
|
758
|
+
// 既有语义(v1.4.0 起):`.openfeel/**/status.md` 任意层级始终拒绝。
|
|
759
|
+
if (segments.length > 0 && segments[segments.length - 1] === 'status.md') return { hint: 'state' };
|
|
760
|
+
const hit = matchProtectedEntries(segments, PROTECTED_OPENFEEL_PATHS);
|
|
761
|
+
if (hit !== null) return hit;
|
|
762
|
+
// op-005:目标若是受保护文件的**父目录**(`rm -rf .openfeel`、
|
|
763
|
+
// `robocopy src .openfeel /MIR`、`prettier --write .openfeel`),
|
|
764
|
+
// 目录级写会连受保护文件一起覆盖/删除 → 同样拒绝。
|
|
765
|
+
const contains = matchProtectedAncestor(segments, PROTECTED_OPENFEEL_PATHS);
|
|
766
|
+
if (contains !== null) return contains;
|
|
767
|
+
}
|
|
768
|
+
// `.openfeel/` 之外的门禁开关文件(`dsh/cordis.patch.yml`)。
|
|
769
|
+
const relative = workspaceRelativeSegments(absolute, cwd);
|
|
770
|
+
if (relative !== null && relative.length > 0) {
|
|
771
|
+
return matchProtectedEntries(relative, PROTECTED_WORKSPACE_PATHS)
|
|
772
|
+
?? matchProtectedAncestor(relative, PROTECTED_WORKSPACE_PATHS);
|
|
773
|
+
}
|
|
774
|
+
return null;
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
/**
|
|
778
|
+
* 目标是否为某受保护条目的**祖先目录**(op-005)。
|
|
779
|
+
*
|
|
780
|
+
* 受保护名单是文件名级别的:`rm -rf .openfeel` / `prettier --write .openfeel`
|
|
781
|
+
* 这类「目录级写」不命中任何条目,却会把 flow.json 一起覆盖 —— 所以把
|
|
782
|
+
* 「目标段是受保护条目段的前缀」也算命中(`.openfeel` 自身 = 空前缀)。
|
|
783
|
+
*
|
|
784
|
+
* 注意 `.openfeel/log` 这种「只保护单文件」的目录也会因此被拒:
|
|
785
|
+
* 代价只是 agent 不能 `rm -rf .openfeel/log`(CLI / guard 自己写日志不经过 guard)。
|
|
786
|
+
*
|
|
787
|
+
* @param {string[]} segments
|
|
788
|
+
* @param {ReadonlyArray<{ match: string, segments: readonly string[], hint: string }>} entries
|
|
789
|
+
* @returns {{ hint: string } | null}
|
|
790
|
+
*/
|
|
791
|
+
function matchProtectedAncestor(segments, entries) {
|
|
792
|
+
for (const entry of entries) {
|
|
793
|
+
if (segments.length >= entry.segments.length) continue;
|
|
794
|
+
if (segments.every((segment, index) => entry.segments[index] === segment)) return { hint: entry.hint };
|
|
795
|
+
}
|
|
796
|
+
return null;
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
/**
|
|
800
|
+
* 受保护路径拒绝文案:按归属给出对应 CLI(文案即修复路径)。
|
|
801
|
+
* @param {Array<{ hint: string }>} hits
|
|
802
|
+
* @param {(zh: string, en: string) => string} t
|
|
803
|
+
* @returns {string}
|
|
221
804
|
*/
|
|
222
|
-
function
|
|
223
|
-
const
|
|
224
|
-
|
|
225
|
-
|
|
805
|
+
function protectedDenialMessage(hits, t) {
|
|
806
|
+
const hints = [...new Set(hits.map((hit) => hit.hint))];
|
|
807
|
+
const lines = hints.map((hint) => {
|
|
808
|
+
const entry = PROTECTED_HINTS[hint] ?? PROTECTED_HINTS.state;
|
|
809
|
+
return `- ${t(entry.zh, entry.en)}`;
|
|
810
|
+
});
|
|
811
|
+
return t(
|
|
812
|
+
`OpenFeel 写入门禁:禁止手改 OpenFeel 受保护的流程文件。\n${lines.join('\n')}`,
|
|
813
|
+
`OpenFeel write guard: never hand-edit protected OpenFeel pipeline files.\n${lines.join('\n')}`,
|
|
814
|
+
);
|
|
226
815
|
}
|
|
227
816
|
|
|
228
817
|
/**
|
|
@@ -329,80 +918,1875 @@ export function parsePatchTargets(patch) {
|
|
|
329
918
|
return { ok: true, paths, entries: paths.map((path) => ({ path, kind: kinds.get(path) })) };
|
|
330
919
|
}
|
|
331
920
|
|
|
332
|
-
|
|
333
|
-
*
|
|
334
|
-
*
|
|
335
|
-
*
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
921
|
+
/* ──────────────────────────────────────────────────────────────────────────
|
|
922
|
+
* shell 命令解析(v1.5.11 D-126-02)
|
|
923
|
+
*
|
|
924
|
+
* 目标(可验收):`bash` / `pwsh` 纳入守卫,命令文本按四类判定,且**不误杀**
|
|
925
|
+
* 日常构建/测试命令。判定不复用任何「宽松启发式」:
|
|
926
|
+
* - 第 1 类(任何相位硬拒):受保护路径、shell 跑 openfeel 写子命令、
|
|
927
|
+
* 编码/间接执行形态(`-EncodedCommand` / `iex` / `bash -c` / `node -e` …);
|
|
928
|
+
* - 第 2 类(按目标路径判):重定向、`tee`、PowerShell 写 cmdlet、POSIX
|
|
929
|
+
* `rm/del/mv/cp/touch/mkdir`、`sed -i`、`patch`、以及全部 git 工作区写;
|
|
930
|
+
* 一旦目标可判定,就交给 `decideForTargets()`(与文件工具**同一份**判定);
|
|
931
|
+
* - 第 3 类(产物豁免):`dist|build|out|target|.next|node_modules|coverage|
|
|
932
|
+
* .openfeel/tmp|.cache|*.tsbuildinfo|pnpm-lock.yaml|package-lock.json`;
|
|
933
|
+
* - 第 4 类(目标不可判定):默认 `warn`(审计 + stderr 放行),`strict` 下拒。
|
|
934
|
+
*
|
|
935
|
+
* **第 4 类的书面口径(也要写进 ADAPTER.md)**:第 4 类**只防误写、不防蓄意**。
|
|
936
|
+
* 编码/嵌套执行形态已在第 1 类堵死;能走到第 4 类的只剩「目标来自运行时数据」,
|
|
937
|
+
* 默认告警,要更严就设 `OPENFEEL_SHELL_GATE=strict`。
|
|
938
|
+
*
|
|
939
|
+
* **变量口径**:只有「同一命令内一次字面量赋值得到完整目标路径」才算第 2 类
|
|
940
|
+
* (`$f='src/x.ts'; Set-Content $f`);任何拼接/派生/跨语句取值
|
|
941
|
+
* (`$d='src'; Set-Content "$d/x.ts"`、`Join-Path`、管道/文件/env)一律第 4 类 ——
|
|
942
|
+
* 明确**不做**字符串求值/拼接推导,避免「看起来能算」的半成品解析。
|
|
943
|
+
* ────────────────────────────────────────────────────────────────────────── */
|
|
944
|
+
|
|
945
|
+
/** 重定向里的「不是文件」目标(丢弃,不算写入)。 */
|
|
946
|
+
const SHELL_NULL_TARGETS = new Set(['/dev/null', 'nul', '$null', '/dev/stdout', '/dev/stderr', 'con']);
|
|
947
|
+
|
|
948
|
+
/** 包装命令:跳过它们(与其 flag/`VAR=` 赋值)之后才是真正的命令名。 */
|
|
949
|
+
const SHELL_WRAPPER_COMMANDS = new Set(['sudo', 'env', 'nohup', 'time', 'command', 'exec', 'builtin', 'doas']);
|
|
950
|
+
|
|
951
|
+
/** POSIX 写命令 → 目标位置(bash 分支)。 */
|
|
952
|
+
const POSIX_WRITE_SPECS = new Map([
|
|
953
|
+
['rm', 'all'],
|
|
954
|
+
['del', 'all'],
|
|
955
|
+
['erase', 'all'],
|
|
956
|
+
['rmdir', 'all'],
|
|
957
|
+
['rd', 'all'],
|
|
958
|
+
['mv', 'all'],
|
|
959
|
+
['move', 'all'],
|
|
960
|
+
['cp', 'dest'],
|
|
961
|
+
['copy', 'dest'],
|
|
962
|
+
// op-005 / P0-1:Windows 目录复制命令(Git Bash / cmd 下都可用)。
|
|
963
|
+
// `dest2` = 第二个位置参数是目标(`robocopy src dst /MIR`、`xcopy src dst /E`)。
|
|
964
|
+
['robocopy', 'dest2'],
|
|
965
|
+
['xcopy', 'dest2'],
|
|
966
|
+
['touch', 'all'],
|
|
967
|
+
['mkdir', 'all'],
|
|
968
|
+
['md', 'all'],
|
|
969
|
+
['tee', 'all'],
|
|
970
|
+
['sed', 'sed'],
|
|
971
|
+
['patch', 'patch'],
|
|
972
|
+
]);
|
|
355
973
|
|
|
356
974
|
/**
|
|
357
|
-
*
|
|
358
|
-
*
|
|
359
|
-
*
|
|
975
|
+
* PowerShell 写 cmdlet(含常用别名)→ 目标位置(pwsh 分支)。
|
|
976
|
+
* `dest`:最后一个位置参数是目标(`Copy-Item src dest`);`first`:第一个位置参数;
|
|
977
|
+
* `all`:全部位置参数(`Remove-Item a b`、`mv`/`rm` 的源也是被删改目标)。
|
|
360
978
|
*/
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
979
|
+
const PS_WRITE_SPECS = new Map([
|
|
980
|
+
['set-content', 'first'],
|
|
981
|
+
['sc', 'first'],
|
|
982
|
+
['add-content', 'first'],
|
|
983
|
+
['ac', 'first'],
|
|
984
|
+
['clear-content', 'first'],
|
|
985
|
+
['clc', 'first'],
|
|
986
|
+
['out-file', 'first'],
|
|
987
|
+
['tee-object', 'first'],
|
|
988
|
+
['tee', 'first'],
|
|
989
|
+
['new-item', 'first'],
|
|
990
|
+
['ni', 'first'],
|
|
991
|
+
['set-item', 'first'],
|
|
992
|
+
['si', 'first'],
|
|
993
|
+
['rename-item', 'first'],
|
|
994
|
+
['rni', 'first'],
|
|
995
|
+
['remove-item', 'all'],
|
|
996
|
+
['ri', 'all'],
|
|
997
|
+
['rm', 'all'],
|
|
998
|
+
['del', 'all'],
|
|
999
|
+
['erase', 'all'],
|
|
1000
|
+
['rmdir', 'all'],
|
|
1001
|
+
['rd', 'all'],
|
|
1002
|
+
['copy-item', 'dest'],
|
|
1003
|
+
['cpi', 'dest'],
|
|
1004
|
+
['cp', 'dest'],
|
|
1005
|
+
['copy', 'dest'],
|
|
1006
|
+
['robocopy', 'dest2'],
|
|
1007
|
+
['xcopy', 'dest2'],
|
|
1008
|
+
['move-item', 'all'],
|
|
1009
|
+
['mi', 'all'],
|
|
1010
|
+
['mv', 'all'],
|
|
1011
|
+
['move', 'all'],
|
|
1012
|
+
['mkdir', 'all'],
|
|
1013
|
+
['md', 'all'],
|
|
1014
|
+
// P2:pwsh 下也能跑的 POSIX 写命令(`touch` / `sed -i`),避免换 shell 就绕过去。
|
|
1015
|
+
['touch', 'all'],
|
|
1016
|
+
['sed', 'sed'],
|
|
1017
|
+
]);
|
|
368
1018
|
|
|
369
|
-
/**
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
1019
|
+
/** PowerShell 里表示「目标路径」的具名参数。 */
|
|
1020
|
+
const PS_PATH_PARAMS = new Set(['path', 'filepath', 'literalpath', 'destination', 'target', 'outputfile']);
|
|
1021
|
+
/** PowerShell 里表示「只读源路径」的具名参数(`Copy-Item -Path src -Destination dst`)。 */
|
|
1022
|
+
const PS_SOURCE_PARAMS = new Set(['path', 'filepath', 'literalpath']);
|
|
1023
|
+
/** PowerShell 开关参数(不消费下一个 token)。 */
|
|
1024
|
+
const PS_SWITCH_PARAMS = new Set([
|
|
1025
|
+
'force', 'recurse', 'whatif', 'confirm', 'verbose', 'debug', 'passthru', 'nonewline',
|
|
1026
|
+
'asbytestream', 'append', 'wait', 'usetransaction', 'container', 'hidden', 'readonly',
|
|
1027
|
+
'system', 'update', 'raw', 'noenumerate', 'unique', 'follow', 'preserve', 'stream',
|
|
1028
|
+
]);
|
|
1029
|
+
|
|
1030
|
+
/** shell 跑 openfeel 时的写动词(第 1 类)。 */
|
|
1031
|
+
const OPENFEEL_WRITE_VERBS = new Set(['flow', 'stage', 'req', 'chore']);
|
|
1032
|
+
|
|
1033
|
+
/** 只读白名单(放行)—— D-126-02 逐条列出。 */
|
|
1034
|
+
const OPENFEEL_READONLY_VERBS = new Set([
|
|
1035
|
+
'status', 'next', 'current', 'overview', 'phases', 'mode', 'log', 'metrics',
|
|
1036
|
+
'health', 'recover', 'retry', 'list', 'show', 'board', 'help', 'version',
|
|
1037
|
+
]);
|
|
1038
|
+
|
|
1039
|
+
/* ── op-005 / P0-1:默认 fail-closed 所需的正面证据表 ─────────────────────
|
|
1040
|
+
*
|
|
1041
|
+
* 规则变更:**无法判定「这条命令不写」→ 第 4 类(undecidable,默认 warn)**,
|
|
1042
|
+
* 不再把未识别命令当 `kind='none'` 静默放行(旧口径的审计还会记成「没有写」)。
|
|
1043
|
+
* 于是「确认只读」必须有正面证据 —— 命中下面这些表之一才允许 `no-write`。
|
|
1044
|
+
*
|
|
1045
|
+
* 反例(实测绕过,全部必须落到 undecidable 或写类):
|
|
1046
|
+
* `[IO.File]::WriteAllText(...)`、`iwr -OutFile`、`curl.exe -o`、`certutil -urlcache`、
|
|
1047
|
+
* `robocopy`/`xcopy`、`npx prettier --write src`、`gofmt -w`、`node scripts/gen.js`、
|
|
1048
|
+
* `python -c "pathlib…write_text"`、`$c='Set-Content'; & $c …`。
|
|
1049
|
+
* ─────────────────────────────────────────────────────────────────────── */
|
|
377
1050
|
|
|
378
1051
|
/**
|
|
379
|
-
*
|
|
1052
|
+
* 已知**只读**程序(确认无文件副作用)。
|
|
380
1053
|
*
|
|
381
|
-
*
|
|
382
|
-
*
|
|
383
|
-
*
|
|
384
|
-
* @param {boolean} [options.allowGeneral]
|
|
385
|
-
* @param {'zh-CN'|'en'} [options.language]
|
|
386
|
-
* @param {string} [options.cwd] 无会话时的兜底目录(通常为 config.cwd)
|
|
387
|
-
* @returns {(execution: { name?: string, arguments?: unknown, agent?: { session?: { header?: { cwd?: string } } } }) => string | undefined}
|
|
1054
|
+
* 收录口径:只读文件 / 只向 stdout 输出 / 只查环境。写命令一律走
|
|
1055
|
+
* `POSIX_WRITE_SPECS` / `PS_WRITE_SPECS` / 专门解析器,**别往这里加**。
|
|
1056
|
+
* 拿不准就不要加 —— 落到 undecidable 只是多一条 warning,加错就是放行。
|
|
388
1057
|
*/
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
1058
|
+
const READONLY_PROGRAMS = new Set([
|
|
1059
|
+
// 文件/文本读取
|
|
1060
|
+
'ls', 'dir', 'cat', 'head', 'tail', 'grep', 'egrep', 'fgrep', 'rg', 'wc', 'file', 'stat',
|
|
1061
|
+
'pwd', 'cd', 'pushd', 'popd', 'which', 'where', 'whereis', 'whoami', 'hostname', 'date',
|
|
1062
|
+
'env', 'printenv', 'uname', 'id', 'echo', 'printf', 'true', 'false', 'test', '[', ']',
|
|
1063
|
+
'basename', 'dirname', 'realpath', 'readlink', 'diff', 'cmp', 'md5sum', 'sha1sum',
|
|
1064
|
+
'sha256sum', 'sha512sum', 'xxd', 'od', 'hexdump', 'jq', 'sort', 'uniq', 'nl', 'less',
|
|
1065
|
+
'more', 'clear', 'sleep', 'seq', 'tree', 'du', 'df', 'ps', 'kill', 'nproc', 'arch',
|
|
1066
|
+
'uptime', 'exit', 'export', 'unset', 'shift', 'type', 'alias', 'cd',
|
|
1067
|
+
// PowerShell 只读 cmdlet / 常用别名
|
|
1068
|
+
'get-content', 'gc', 'type', 'get-childitem', 'gci', 'get-item', 'gi',
|
|
1069
|
+
'select-string', 'sls', 'get-command', 'gcm', 'get-help', 'help', 'get-member', 'gm',
|
|
1070
|
+
'get-process', 'gps', 'get-service', 'gsv', 'get-date', 'get-location', 'gl',
|
|
1071
|
+
'get-host', 'get-variable', 'gv', 'get-itemproperty', 'gp', 'test-path',
|
|
1072
|
+
'resolve-path', 'split-path', 'join-path', 'convert-path', 'measure-object',
|
|
1073
|
+
'select-object', 'where-object', 'foreach-object', 'sort-object', 'group-object',
|
|
1074
|
+
'format-table', 'ft', 'format-list', 'fl', 'format-wide', 'fw', 'out-string', 'out-host',
|
|
1075
|
+
'write-host', 'write-output', 'write', 'echo', 'start-sleep', 'compare-object',
|
|
1076
|
+
'convertto-json', 'convertfrom-json', 'get-filehash', 'get-acl', 'select', 'where', '%', '?',
|
|
1077
|
+
// openfeel:写子命令已在上游 `matchOpenFeelWrite` 拦掉,能走到这里的都是只读动词
|
|
1078
|
+
'openfeel',
|
|
1079
|
+
]);
|
|
1080
|
+
|
|
1081
|
+
/**
|
|
1082
|
+
* 已知**构建/测试**工具:只写产物目录(第 3 类),无源码副作用,不解析目标。
|
|
1083
|
+
*
|
|
1084
|
+
* 只收「写的是 dist/build/target/node_modules 这类产物」的构建器与测试器。
|
|
1085
|
+
* 写源码的工具(`cargo fmt`、`gofmt`、`black`、`ruff format`)**不在此列**,
|
|
1086
|
+
* 它们走 formatter 写解析器。
|
|
1087
|
+
*/
|
|
1088
|
+
const BUILD_TOOL_PROGRAMS = new Set([
|
|
1089
|
+
'vitest', 'jest', 'mocha', 'ava', 'tap', 'playwright', 'cypress',
|
|
1090
|
+
'tsc', 'vite', 'webpack', 'rollup', 'esbuild', 'next', 'nuxt', 'turbo', 'nx', 'parcel',
|
|
1091
|
+
'tsup', 'node-gyp', 'msbuild', 'gradle', 'gradlew', 'mvn', 'mvnw', 'make', 'cmake',
|
|
1092
|
+
'ninja', 'meson', 'bazel', 'bazelisk', 'pytest', 'mypy', 'cargo', 'go', 'dotnet',
|
|
1093
|
+
]);
|
|
1094
|
+
|
|
1095
|
+
/** 需要再按子命令收窄的构建工具(`cargo fmt` 会改源码,不能整命令放行)。 */
|
|
1096
|
+
const BUILD_TOOL_SUBCOMMANDS = new Map([
|
|
1097
|
+
['cargo', new Set(['build', 'test', 'check', 'clippy', 'bench', 'doc', 'fetch', 'metadata', 'tree', 'locate-project', 'version'])],
|
|
1098
|
+
['go', new Set(['build', 'test', 'vet', 'version', 'env', 'list', 'doc'])],
|
|
1099
|
+
['dotnet', new Set(['build', 'test', 'restore', 'publish', 'pack'])],
|
|
1100
|
+
]);
|
|
1101
|
+
|
|
1102
|
+
/** 会**就地改源码**的格式化/修复工具:`--write` / `--fix` / `-w` / `-i` 才是写。 */
|
|
1103
|
+
const FORMATTER_TOOLS = new Set([
|
|
1104
|
+
'prettier', 'eslint', 'gofmt', 'goimports', 'rustfmt', 'biome', 'stylelint', 'black',
|
|
1105
|
+
'isort', 'autopep8', 'clang-format', 'golines', 'swiftformat', 'dprint', 'standard',
|
|
1106
|
+
'oxlint', 'oxfmt', 'yapf', 'rubocop', 'php-cs-fixer', 'prettierd', 'markdownlint',
|
|
1107
|
+
]);
|
|
1108
|
+
|
|
1109
|
+
/** 下载器:只有带「输出到文件」参数才算写(`curl url` = 只读)。 */
|
|
1110
|
+
const DOWNLOAD_TOOLS = new Set([
|
|
1111
|
+
'curl', 'wget', 'iwr', 'invoke-webrequest', 'invoke-restmethod', 'irm',
|
|
1112
|
+
'start-bitstransfer', 'aria2c',
|
|
1113
|
+
]);
|
|
1114
|
+
|
|
1115
|
+
/** 会执行**外部脚本/程序**、目标静态不可判的解释器(`node x.js` / `python x.py`)。 */
|
|
1116
|
+
const SCRIPT_INTERPRETER_TOOLS = new Set([
|
|
1117
|
+
'node', 'python', 'python2', 'python3', 'py', 'perl', 'ruby', 'php', 'deno', 'bun',
|
|
1118
|
+
'osascript', 'wscript', 'cscript',
|
|
1119
|
+
]);
|
|
1120
|
+
|
|
1121
|
+
/** npx/dl x 之类「跑一个包」的前置命令。 */
|
|
1122
|
+
const PACKAGE_RUNNERS = new Set(['npx', 'pnpx', 'bunx', 'dlx']);
|
|
1123
|
+
|
|
1124
|
+
/**
|
|
1125
|
+
* **硬拒**的间接执行形态(第 1 类):内容不可见 / 不可可靠判定,一律拒绝。
|
|
1126
|
+
*
|
|
1127
|
+
* - `-EncodedCommand` / `-EncodedArguments`:base64 编码,看得到也读不出;
|
|
1128
|
+
* - `iex` / `Invoke-Expression`:拼接后执行,静态不可判;
|
|
1129
|
+
* - `eval`:同上;
|
|
1130
|
+
* - `cmd /c|/k`:同族形态(`cmd /c "echo x > src/x.ts"` 会让引号内重定向逃过扫描);
|
|
1131
|
+
* - **.NET 静态写方法**(op-005 / P0-1,op-006 改**正面判定**见下);
|
|
1132
|
+
* - **`New-Object` 写对象**:`New-Object System.IO.StreamWriter('src/x.ts')`;
|
|
1133
|
+
* - **`Add-Type` 动态编译**:编译后的代码可任意写盘(`-AssemblyName` 纯加载除外)。
|
|
1134
|
+
*
|
|
1135
|
+
* 检测在「引号内容被掩码」的文本上做,避免 `git commit -m "…bash -c…"` 被消息文本误杀。
|
|
1136
|
+
*/
|
|
1137
|
+
const HARD_INDIRECT_PATTERNS = Object.freeze([
|
|
1138
|
+
[/-EncodedCommand\b/i, '-EncodedCommand'],
|
|
1139
|
+
[/-EncodedArguments\b/i, '-EncodedArguments'],
|
|
1140
|
+
[/(?:^|\s)-(?:enc|ec)\b/i, '-EncodedCommand'],
|
|
1141
|
+
[/\b(?:iex|Invoke-Expression)\b/i, 'Invoke-Expression'],
|
|
1142
|
+
[/(?:^|[|&]\s*)eval\s/i, 'eval'],
|
|
1143
|
+
[/(?:^|[|&]\s*)(?:cmd(?:\.exe)?\s+\/[ck]\b)/i, 'cmd /c'],
|
|
1144
|
+
[/\bNew-Object\s+(?:System\.)?IO\.(?:StreamWriter|FileStream|BinaryWriter|DirectoryInfo|FileInfo)\b/i, 'New-Object 写对象'],
|
|
1145
|
+
[/\bAdd-Type\b/i, 'Add-Type 动态编译'],
|
|
1146
|
+
]);
|
|
1147
|
+
|
|
1148
|
+
/**
|
|
1149
|
+
* 可能写盘的 `.NET` 静态类型(op-006 / P1-2:**正向判定**)。
|
|
1150
|
+
*
|
|
1151
|
+
* 旧实现是**方法名黑名单**(只列 `WriteAllText|Copy|Move|…`),于是
|
|
1152
|
+
* `WriteAllTextAsync` / `AppendAllTextAsync` / `[IO.File]::Open('x','Create')`
|
|
1153
|
+
* 全部漏到第 4 类(默认 warn = 放行)—— 与 P0-1 同形态。
|
|
1154
|
+
*
|
|
1155
|
+
* 现在反过来:**类型可写** 且 **方法不在只读白名单** → 一律第 1 类。
|
|
1156
|
+
* 只列「能写文件」的类型,`[Math]::Floor` / `[IO.Path]::Combine` 这类纯函数
|
|
1157
|
+
* 不在此列,不会被误杀。
|
|
1158
|
+
*/
|
|
1159
|
+
const DOTNET_WRITE_TYPE_RE = /\[\s*(?:System\.)?(?:IO\.(?:File|FileInfo|Directory|DirectoryInfo|StreamWriter|FileStream|BinaryWriter|BinaryReader)|IO\.Compression\.[A-Za-z.]+)\s*\]\s*::\s*([A-Za-z_][A-Za-z0-9_]*)/gi;
|
|
1160
|
+
|
|
1161
|
+
/** 可写类型上的**只读**方法(不在表里 → 按写处理)。 */
|
|
1162
|
+
const DOTNET_READ_METHODS = new Set([
|
|
1163
|
+
'readalltext', 'readalllines', 'readallbytes', 'readlines', 'openread', 'opentext',
|
|
1164
|
+
'exists', 'getfiles', 'getdirectories', 'getlastwritetime', 'getlastwritetimeutc',
|
|
1165
|
+
'getcreationtime', 'getcreationtimeutc', 'getlength', 'getattributes', 'getfullpath',
|
|
1166
|
+
'combine', 'getfilename', 'getdirectoryname', 'getextension', 'gettemppath',
|
|
1167
|
+
'getpathroot', 'ispathrooted', 'enumeratefiles', 'enumeratedirectories',
|
|
1168
|
+
]);
|
|
1169
|
+
|
|
1170
|
+
/**
|
|
1171
|
+
* 解释器内联代码(op-002b):**先扫 payload 里的写 API** —— 纯只读诊断
|
|
1172
|
+
* (`node -e "console.log(1)"`)不该被拦,这也是 agent 日常读 JSON 的常用手段。
|
|
1173
|
+
*/
|
|
1174
|
+
const INLINE_INTERPRETER_PATTERNS = Object.freeze([
|
|
1175
|
+
[/\bnode(?:\.exe)?\s+(?:-e\b|--eval\b|-p\b|--print\b)\s*/i, 'node -e'],
|
|
1176
|
+
[/\bpython[0-9.]*(?:\.exe)?\s+-c\s*/i, 'python -c'],
|
|
1177
|
+
[/\bperl(?:\.exe)?\s+-[a-zA-Z]*e\s*/i, 'perl -e'],
|
|
1178
|
+
[/\bruby(?:\.exe)?\s+-[a-zA-Z]*e\s*/i, 'ruby -e'],
|
|
1179
|
+
[/\bphp(?:\.exe)?\s+-r\s*/i, 'php -r'],
|
|
1180
|
+
]);
|
|
1181
|
+
|
|
1182
|
+
/** 内联 payload 里出现这些写 API → 视为「间接执行含写操作」。 */
|
|
1183
|
+
const INDIRECT_WRITE_PATTERNS = Object.freeze([
|
|
1184
|
+
/\bwriteFileSync\b/, /\bappendFileSync\b/, /\bwriteFile\b/, /\bcreateWriteStream\b/,
|
|
1185
|
+
/\bcopyFileSync\b/, /\brenameSync\b/, /\bunlinkSync\b/, /\brmSync\b/,
|
|
1186
|
+
/\bmkdirSync\b/, /\brmdirSync\b/, /\btruncateSync\b/, /\bchmodSync\b/,
|
|
1187
|
+
/\bopenSync\b[^)]*['"][wa]/, /\bfs\.promises\b[\s\S]{0,80}?\b(?:writeFile|appendFile|rm|mkdir|unlink|rename|copyFile)\b/,
|
|
1188
|
+
/\bSet-Content\b/i, /\bOut-File\b/i, /\bAdd-Content\b/i, /\bNew-Item\b/i,
|
|
1189
|
+
/\bRemove-Item\b/i, /\bCopy-Item\b/i, /\bMove-Item\b/i, /\bSet-Item\b/i,
|
|
1190
|
+
// Python / Ruby / PHP 的同义写法(同一判定口径,别让换语言就绕过去)
|
|
1191
|
+
/\bopen\s*\([^)]{0,120}?['"][wa]/, /\bos\.remove\b/, /\bshutil\b/, /\bFile\.write\b/,
|
|
1192
|
+
// op-005 / P1-5:**间接写 API**。命中即第 1 类 —— 否则
|
|
1193
|
+
// `node -e "child_process.execSync('openfeel chore --source x')"` 会被判只读放行。
|
|
1194
|
+
/\bchild_process\b/i, /\bexecSync\b/, /\bexecFileSync\b/, /\bspawnSync\b/, /\bspawn\s*\(/,
|
|
1195
|
+
/\bexecFile\b/, /\bpathlib\b/, /\bwrite_text\b/, /\bwrite_bytes\b/,
|
|
1196
|
+
/\burlretrieve\b/, /\bos\.system\b/, /\bos\.popen\b/, /\bsubprocess\b/,
|
|
1197
|
+
/\bDeno\.(?:writeTextFile|writeFile|create|mkdir|remove|rename|copyFile)\b/,
|
|
1198
|
+
/\bBun\.(?:write|file)\b/,
|
|
1199
|
+
]);
|
|
1200
|
+
|
|
1201
|
+
/** 递归深度上限(防构造 `bash -c 'bash -c …'` 无限套娃)。 */
|
|
1202
|
+
const WRAPPER_MAX_DEPTH = 4;
|
|
1203
|
+
|
|
1204
|
+
/**
|
|
1205
|
+
* 同一命令内「一次字面量赋值」:`$f='src/x.ts'` / `F=src/x.ts` / `export F=x`。
|
|
1206
|
+
* 值里出现 `$` 或反引号(插值/子表达式)即不算纯字面量。
|
|
1207
|
+
*/
|
|
1208
|
+
const LITERAL_VAR_ASSIGN_RE = /^\s*(?:(?:export|local|set)\s+)?(?:\$([A-Za-z_][A-Za-z0-9_]*)|([A-Za-z_][A-Za-z0-9_]*))\s*=\s*(?:'([^']*)'|"([^"]*)"|([^\s;&|]+))\s*;?\s*$/;
|
|
1209
|
+
|
|
1210
|
+
/**
|
|
1211
|
+
* 把 shell 文本切成句子(引号感知;`;`、换行、`&&`、`||` 都是边界)。
|
|
1212
|
+
* @param {string} command
|
|
1213
|
+
* @returns {string[]}
|
|
1214
|
+
*/
|
|
1215
|
+
function splitShellStatements(command) {
|
|
1216
|
+
const out = [];
|
|
1217
|
+
let current = '';
|
|
1218
|
+
let quote = null;
|
|
1219
|
+
for (let index = 0; index < command.length; index += 1) {
|
|
1220
|
+
const ch = command[index];
|
|
1221
|
+
if (quote !== null) {
|
|
1222
|
+
current += ch;
|
|
1223
|
+
if (ch === quote) quote = null;
|
|
1224
|
+
continue;
|
|
1225
|
+
}
|
|
1226
|
+
if (ch === '`' && command[index + 1] === 'n') { current += '\n'; index += 1; continue; }
|
|
1227
|
+
if (ch === '"' || ch === "'") { quote = ch; current += ch; continue; }
|
|
1228
|
+
if (ch === '\n' || ch === '\r' || ch === ';') { out.push(current); current = ''; continue; }
|
|
1229
|
+
if ((ch === '&' && command[index + 1] === '&') || (ch === '|' && command[index + 1] === '|')) {
|
|
1230
|
+
out.push(current);
|
|
1231
|
+
current = '';
|
|
1232
|
+
index += 1;
|
|
1233
|
+
continue;
|
|
1234
|
+
}
|
|
1235
|
+
current += ch;
|
|
1236
|
+
}
|
|
1237
|
+
out.push(current);
|
|
1238
|
+
return out.map((statement) => statement.replace(/[`^]+\s*$/, '').trim()).filter((statement) => statement !== '');
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
/**
|
|
1242
|
+
* 把引号内容掩码成 `_` / 空格(用于 indirect 检测,避免提交信息等文本误杀)。
|
|
1243
|
+
* **保持长度不变**:调用方可以按同一 offset 回到原文取参数。
|
|
1244
|
+
* @param {string} text
|
|
1245
|
+
* @returns {string}
|
|
1246
|
+
*/
|
|
1247
|
+
function maskQuoted(text) {
|
|
1248
|
+
let out = '';
|
|
1249
|
+
let quote = null;
|
|
1250
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
1251
|
+
const ch = text[index];
|
|
1252
|
+
if (quote !== null) {
|
|
1253
|
+
if (ch === quote) { quote = null; out += '_'; continue; }
|
|
1254
|
+
out += ' ';
|
|
1255
|
+
continue;
|
|
1256
|
+
}
|
|
1257
|
+
if (ch === '"' || ch === "'") { quote = ch; out += '_'; continue; }
|
|
1258
|
+
out += ch;
|
|
1259
|
+
}
|
|
1260
|
+
return out;
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
/**
|
|
1264
|
+
* 还原「命令位置」上的引号程序名(`"bash" -c …` / `x | "bash" -c …`)——
|
|
1265
|
+
* 否则加一对引号就能绕过第 1 类的间接执行检测。
|
|
1266
|
+
* @param {string} text
|
|
1267
|
+
* @returns {string}
|
|
1268
|
+
*/
|
|
1269
|
+
function unquoteProgramNames(text) {
|
|
1270
|
+
// 前缀集合含 `.` / `&`:`& "openfeel" chore …`、`. "script.ps1"` 也算命令位置
|
|
1271
|
+
// (op-005 / P1-1:引号程序名曾是 openfeel 写命令检测的绕过面)。
|
|
1272
|
+
return text.replace(/(^|[|&;(.]\s*)(["'])([^"'\n]+)\2(?=\s)/g, (_all, prefix, _quote, program) => `${prefix}${program}`);
|
|
1273
|
+
}
|
|
1274
|
+
|
|
1275
|
+
/**
|
|
1276
|
+
* 切 token:去引号;`|` 单独成 token(用于识别管道后的命令位置)。
|
|
1277
|
+
* @param {string} text
|
|
1278
|
+
* @returns {string[]}
|
|
1279
|
+
*/
|
|
1280
|
+
function tokenizeShell(text) {
|
|
1281
|
+
const tokens = [];
|
|
1282
|
+
let current = '';
|
|
1283
|
+
let quote = null;
|
|
1284
|
+
let has = false;
|
|
1285
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
1286
|
+
const ch = text[index];
|
|
1287
|
+
if (quote !== null) {
|
|
1288
|
+
if (ch === quote) { quote = null; continue; }
|
|
1289
|
+
current += ch;
|
|
1290
|
+
has = true;
|
|
1291
|
+
continue;
|
|
1292
|
+
}
|
|
1293
|
+
if (ch === '"' || ch === "'") { quote = ch; has = true; continue; }
|
|
1294
|
+
if (ch === '|') {
|
|
1295
|
+
if (has) { tokens.push(current); current = ''; has = false; }
|
|
1296
|
+
tokens.push('|');
|
|
1297
|
+
continue;
|
|
1298
|
+
}
|
|
1299
|
+
if (ch === '`' && text[index + 1] !== undefined && !/\s/.test(text[index + 1])) { continue; }
|
|
1300
|
+
if (/\s/.test(ch)) {
|
|
1301
|
+
if (has) { tokens.push(current); current = ''; has = false; }
|
|
1302
|
+
continue;
|
|
1303
|
+
}
|
|
1304
|
+
current += ch;
|
|
1305
|
+
has = true;
|
|
1306
|
+
}
|
|
1307
|
+
if (has) tokens.push(current);
|
|
1308
|
+
return tokens;
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
/**
|
|
1312
|
+
* 扫重定向(引号感知):`>` `>>` `2>` `&>`;`2>&1` / `>&2` 跳过;返回目标与
|
|
1313
|
+
* 「去掉重定向片段」的文本(供命令识别,避免把 `>` 误当参数)。
|
|
1314
|
+
* @param {string} statement
|
|
1315
|
+
* @returns {{ targets: string[], cleaned: string }}
|
|
1316
|
+
*/
|
|
1317
|
+
function scanShellRedirections(statement) {
|
|
1318
|
+
const targets = [];
|
|
1319
|
+
let cleaned = '';
|
|
1320
|
+
let quote = null;
|
|
1321
|
+
let index = 0;
|
|
1322
|
+
while (index < statement.length) {
|
|
1323
|
+
const ch = statement[index];
|
|
1324
|
+
if (quote !== null) {
|
|
1325
|
+
if (ch === quote) quote = null;
|
|
1326
|
+
cleaned += ch;
|
|
1327
|
+
index += 1;
|
|
1328
|
+
continue;
|
|
1329
|
+
}
|
|
1330
|
+
if (ch === '"' || ch === "'") { quote = ch; cleaned += ch; index += 1; continue; }
|
|
1331
|
+
const digitOp = ch >= '0' && ch <= '9' && statement[index + 1] === '>';
|
|
1332
|
+
const ampOp = ch === '&' && statement[index + 1] === '>';
|
|
1333
|
+
if (ch === '>' || digitOp || ampOp) {
|
|
1334
|
+
let cursor = index;
|
|
1335
|
+
if (digitOp) cursor += 1;
|
|
1336
|
+
if (statement[cursor] === '&') cursor += 1;
|
|
1337
|
+
if (statement[cursor] !== '>') { cleaned += ch; index += 1; continue; }
|
|
1338
|
+
cursor += 1;
|
|
1339
|
+
if (statement[cursor] === '>') cursor += 1;
|
|
1340
|
+
while (cursor < statement.length && /\s/.test(statement[cursor])) cursor += 1;
|
|
1341
|
+
if (cursor >= statement.length) { index = cursor; break; }
|
|
1342
|
+
if (statement[cursor] === '&') { index = cursor + 1; continue; } // 2>&1 / >&2
|
|
1343
|
+
let target = '';
|
|
1344
|
+
if (statement[cursor] === '"' || statement[cursor] === "'") {
|
|
1345
|
+
const opener = statement[cursor];
|
|
1346
|
+
cursor += 1;
|
|
1347
|
+
while (cursor < statement.length && statement[cursor] !== opener) { target += statement[cursor]; cursor += 1; }
|
|
1348
|
+
cursor += 1;
|
|
1349
|
+
} else {
|
|
1350
|
+
while (cursor < statement.length && !/[\s;&|<>]/.test(statement[cursor])) { target += statement[cursor]; cursor += 1; }
|
|
1351
|
+
}
|
|
1352
|
+
if (target !== '' && !SHELL_NULL_TARGETS.has(target.toLowerCase())) targets.push(target);
|
|
1353
|
+
index = cursor;
|
|
1354
|
+
continue;
|
|
1355
|
+
}
|
|
1356
|
+
cleaned += ch;
|
|
1357
|
+
index += 1;
|
|
1358
|
+
}
|
|
1359
|
+
return { targets, cleaned };
|
|
1360
|
+
}
|
|
1361
|
+
|
|
1362
|
+
/**
|
|
1363
|
+
* 命令名归一化(取 basename、去 `.exe`、小写)。
|
|
1364
|
+
* @param {string} token
|
|
1365
|
+
* @returns {string}
|
|
1366
|
+
*/
|
|
1367
|
+
function commandNameOf(token) {
|
|
1368
|
+
const base = String(token).replace(/\\/g, '/').split('/').pop() ?? '';
|
|
1369
|
+
const lower = base.toLowerCase();
|
|
1370
|
+
return lower.endsWith('.exe') ? lower.slice(0, -4) : lower;
|
|
1371
|
+
}
|
|
1372
|
+
|
|
1373
|
+
/**
|
|
1374
|
+
* 收集「同一命令内一次字面量赋值」的变量(第 2 类用)。
|
|
1375
|
+
* @param {string[]} statements
|
|
1376
|
+
* @returns {Map<string, string>}
|
|
1377
|
+
*/
|
|
1378
|
+
function collectLiteralAssignments(statements) {
|
|
1379
|
+
const vars = new Map();
|
|
1380
|
+
for (const statement of statements) {
|
|
1381
|
+
const match = LITERAL_VAR_ASSIGN_RE.exec(statement);
|
|
1382
|
+
if (match === null) continue;
|
|
1383
|
+
const name = (match[1] ?? match[2] ?? '').toLowerCase();
|
|
1384
|
+
const value = match[3] ?? match[4] ?? match[5] ?? '';
|
|
1385
|
+
if (name === '' || value === '') continue;
|
|
1386
|
+
if (/[`$]/.test(value)) continue; // 插值/子表达式 → 不是纯字面量
|
|
1387
|
+
vars.set(name, value);
|
|
1388
|
+
}
|
|
1389
|
+
return vars;
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
/**
|
|
1393
|
+
* 解析一个目标 token:纯字面量 → 可直接判定(第 2 类);
|
|
1394
|
+
* `$var` / `${var}` 且同命令内有字面量赋值 → 解析成字面量;
|
|
1395
|
+
* 其余(拼接、派生、`Join-Path`、管道/文件/env 取值)→ 第 4 类。
|
|
1396
|
+
* @param {string} raw
|
|
1397
|
+
* @param {Map<string, string>} vars
|
|
1398
|
+
* @returns {{ ok: boolean, value: string }}
|
|
1399
|
+
*/
|
|
1400
|
+
function resolveShellToken(raw, vars) {
|
|
1401
|
+
const text = String(raw).trim();
|
|
1402
|
+
if (text === '') return { ok: false, value: text };
|
|
1403
|
+
if (!/[$`]/.test(text)) return { ok: true, value: text };
|
|
1404
|
+
const exact = /^\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))$/.exec(text);
|
|
1405
|
+
if (exact !== null) {
|
|
1406
|
+
const key = (exact[1] ?? exact[2]).toLowerCase();
|
|
1407
|
+
if (vars.has(key)) return { ok: true, value: vars.get(key) };
|
|
1408
|
+
}
|
|
1409
|
+
return { ok: false, value: text };
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
/**
|
|
1413
|
+
* `.NET` 静态写方法(op-006 / P1-2 正面判定):可写类型 + 方法不在只读白名单 → 命中。
|
|
1414
|
+
* @param {string} text 掩码后的命令文本
|
|
1415
|
+
* @returns {string | null}
|
|
1416
|
+
*/
|
|
1417
|
+
function matchDotNetStaticWrite(text) {
|
|
1418
|
+
DOTNET_WRITE_TYPE_RE.lastIndex = 0;
|
|
1419
|
+
let match;
|
|
1420
|
+
while ((match = DOTNET_WRITE_TYPE_RE.exec(text)) !== null) {
|
|
1421
|
+
const method = match[1].toLowerCase();
|
|
1422
|
+
if (DOTNET_READ_METHODS.has(method)) continue;
|
|
1423
|
+
return `.NET 静态写方法 ${match[1]}`;
|
|
1424
|
+
}
|
|
1425
|
+
return null;
|
|
1426
|
+
}
|
|
1427
|
+
|
|
1428
|
+
/**
|
|
1429
|
+
* 匹配编码/间接执行形态(第 1 类)。
|
|
1430
|
+
* @param {string} statement
|
|
1431
|
+
* @returns {string | null} 命中的形态标签
|
|
1432
|
+
*/
|
|
1433
|
+
function matchHardIndirect(statement) {
|
|
1434
|
+
// 原文掩码(无消息文本误杀)+ 程序名去引号后再掩码(防 `"bash" -c …` 绕过)
|
|
1435
|
+
for (const text of [maskQuoted(statement), maskQuoted(unquoteProgramNames(statement))]) {
|
|
1436
|
+
for (const [pattern, tag] of HARD_INDIRECT_PATTERNS) {
|
|
1437
|
+
if (!pattern.test(text)) continue;
|
|
1438
|
+
// `Add-Type -AssemblyName X` 只是加载程序集(不编译、不落盘),放行;
|
|
1439
|
+
// 其余 `Add-Type`(`-TypeDefinition` / `-MemberDefinition` / `-OutputAssembly`)算动态编译。
|
|
1440
|
+
if (tag === 'Add-Type 动态编译' && /^Add-Type\s+-AssemblyName\s+\S+\s*$/i.test(text.trim())) continue;
|
|
1441
|
+
return tag;
|
|
1442
|
+
}
|
|
1443
|
+
// .NET 静态写方法:**正向**判定(可写类型 + 方法不在只读白名单)。
|
|
1444
|
+
const dotnet = matchDotNetStaticWrite(text);
|
|
1445
|
+
if (dotnet !== null) return dotnet;
|
|
1446
|
+
}
|
|
1447
|
+
return null;
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
/**
|
|
1451
|
+
* 匹配内联解释器调用(`node -e …` / `python -c …`),返回标签与 **payload 原文**。
|
|
1452
|
+
*
|
|
1453
|
+
* 用「掩码定位置、原文取 payload」:既不被 `git commit -m "node -e …"` 误杀,
|
|
1454
|
+
* 又能拿到真实代码去扫写 API。
|
|
1455
|
+
* @param {string} statement
|
|
1456
|
+
* @returns {{ tag: string, payload: string } | null}
|
|
1457
|
+
*/
|
|
1458
|
+
function matchInlineInterpreter(statement) {
|
|
1459
|
+
const masked = maskQuoted(statement);
|
|
1460
|
+
for (const [pattern, tag] of INLINE_INTERPRETER_PATTERNS) {
|
|
1461
|
+
const match = pattern.exec(masked);
|
|
1462
|
+
if (match === null) continue;
|
|
1463
|
+
const payload = statement.slice(match.index + match[0].length).trim();
|
|
1464
|
+
return { tag, payload };
|
|
1465
|
+
}
|
|
1466
|
+
return null;
|
|
1467
|
+
}
|
|
1468
|
+
|
|
1469
|
+
/**
|
|
1470
|
+
* payload 里是否出现写 API(op-002b):命中 → 第 1/2 类拒绝;未命中 → 只读诊断放行。
|
|
1471
|
+
* @param {string} payload
|
|
1472
|
+
* @returns {string | null} 命中的写 API 标签
|
|
1473
|
+
*/
|
|
1474
|
+
function findWriteApi(payload) {
|
|
1475
|
+
for (const pattern of INDIRECT_WRITE_PATTERNS) {
|
|
1476
|
+
const match = pattern.exec(payload);
|
|
1477
|
+
if (match !== null) return match[0].slice(0, 40);
|
|
1478
|
+
}
|
|
1479
|
+
return null;
|
|
1480
|
+
}
|
|
1481
|
+
|
|
1482
|
+
/**
|
|
1483
|
+
* 取出 `-c` / `-Command` 包装器的内层命令(op-002b 第 2 条:递归解析)。
|
|
1484
|
+
*
|
|
1485
|
+
* 用 token 而不是原文 offset:tokenizer 已去引号,`"bash" -c "…"`(程序名/命令都加引号)
|
|
1486
|
+
* 同样能识别,且 payload 可重新拼成可解析的命令串。
|
|
1487
|
+
* @param {string} statement
|
|
1488
|
+
* @returns {{ payload: string, shell: 'bash'|'pwsh' } | null}
|
|
1489
|
+
*/
|
|
1490
|
+
function extractWrapperPayload(statement) {
|
|
1491
|
+
const tokens = tokenizeShell(statement);
|
|
1492
|
+
for (let index = 0; index < tokens.length; index += 1) {
|
|
1493
|
+
const name = commandNameOf(tokens[index]);
|
|
1494
|
+
const isPosix = /^(?:bash|sh|zsh|dash|fish|ksh)$/.test(name);
|
|
1495
|
+
const isPowerShell = /^(?:powershell|pwsh)$/.test(name);
|
|
1496
|
+
if (!isPosix && !isPowerShell) continue;
|
|
1497
|
+
for (let cursor = index + 1; cursor < tokens.length && tokens[cursor] !== '|'; cursor += 1) {
|
|
1498
|
+
const flag = tokens[cursor];
|
|
1499
|
+
const matched = isPosix ? /^-[a-zA-Z]*c$/i.test(flag) : /^-(?:c|command|commandwithargs)$/i.test(flag);
|
|
1500
|
+
if (!matched) continue;
|
|
1501
|
+
const payloadTokens = [];
|
|
1502
|
+
for (let rest = cursor + 1; rest < tokens.length && tokens[rest] !== '|'; rest += 1) payloadTokens.push(tokens[rest]);
|
|
1503
|
+
return { payload: payloadTokens.join(' ').trim(), shell: isPosix ? 'bash' : 'pwsh' };
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
return null;
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
/**
|
|
1510
|
+
* 包装器 payload 的首个 token 是变量/子表达式(`bash -c "$CMD"`)→ 内层命令不可判定。
|
|
1511
|
+
* @param {string} payload
|
|
1512
|
+
* @returns {boolean}
|
|
1513
|
+
*/
|
|
1514
|
+
function payloadIsUnresolvable(payload) {
|
|
1515
|
+
const first = String(payload).trim().split(/\s+/)[0] ?? '';
|
|
1516
|
+
return /[$`]/.test(first);
|
|
1517
|
+
}
|
|
1518
|
+
|
|
1519
|
+
/**
|
|
1520
|
+
* 判断 shell 命令里的 `openfeel …` 是否是写子命令(第 1 类)。
|
|
1521
|
+
* @param {string[]} args `openfeel` 之后的 token
|
|
1522
|
+
* @returns {boolean}
|
|
1523
|
+
*/
|
|
1524
|
+
function isOpenFeelWriteInvocation(args) {
|
|
1525
|
+
const value = args.filter((token) => token !== '' && token !== '|');
|
|
1526
|
+
if (value.length === 0) return false;
|
|
1527
|
+
const verbIndex = value.findIndex((token) => !token.startsWith('-'));
|
|
1528
|
+
if (verbIndex === -1) return false;
|
|
1529
|
+
const verb = value[verbIndex].toLowerCase();
|
|
1530
|
+
if (!OPENFEEL_WRITE_VERBS.has(verb)) return false;
|
|
1531
|
+
const rest = value.slice(verbIndex + 1);
|
|
1532
|
+
// chore:`--status` / `--end` 放行(只读 / 收口);带说明或 `--ttl-min` 视为开启 → 拒。
|
|
1533
|
+
if (verb === 'chore') {
|
|
1534
|
+
if (value.some((token) => ['--status', '--end', '--help', '-h'].includes(token))) return false;
|
|
1535
|
+
const hasArgument = rest.some((token) => !token.startsWith('-'));
|
|
1536
|
+
const hasTtl = value.some((token) => token === '--ttl-min' || token.startsWith('--ttl-min='));
|
|
1537
|
+
return hasArgument || hasTtl;
|
|
1538
|
+
}
|
|
1539
|
+
const nonFlags = [];
|
|
1540
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
1541
|
+
if (!value[index].startsWith('-')) nonFlags.push(value[index].toLowerCase());
|
|
1542
|
+
}
|
|
1543
|
+
const sub = nonFlags[1];
|
|
1544
|
+
if (sub === undefined) return false;
|
|
1545
|
+
if (OPENFEEL_READONLY_VERBS.has(sub)) return false;
|
|
1546
|
+
// 只读特例:`checkpoint list` / `plan stage list` / `plan scheme list` / `review list`
|
|
1547
|
+
if (verb === 'flow' && sub === 'checkpoint') return nonFlags[2] !== 'list';
|
|
1548
|
+
if (verb === 'flow' && sub === 'plan') {
|
|
1549
|
+
return !((nonFlags[2] === 'stage' || nonFlags[2] === 'scheme') && nonFlags[3] === 'list');
|
|
1550
|
+
}
|
|
1551
|
+
if (verb === 'flow' && sub === 'review') return nonFlags[2] !== 'list';
|
|
1552
|
+
return true;
|
|
1553
|
+
}
|
|
1554
|
+
|
|
1555
|
+
/**
|
|
1556
|
+
* 找到 shell 命令里的 openfeel 写调用(第 1 类),返回可读片段或 null。
|
|
1557
|
+
*
|
|
1558
|
+
* op-005 / P1-1 加固 —— 旧实现只在「引号未掩码的原文」上找 `openfeel`,于是:
|
|
1559
|
+
* - `& "openfeel" chore --source x`、`'openfeel' chore …`(引号程序名)→ ALLOW;
|
|
1560
|
+
* - `node bin/openfeel.js chore --source x`、`node ./dist/cli.js …` → ALLOW;
|
|
1561
|
+
* - `Start-Process openfeel …` → ALLOW。
|
|
1562
|
+
* 三条都能让 agent 给自己开 `--source` 写窗口。
|
|
1563
|
+
*
|
|
1564
|
+
* 现在:先 `unquoteProgramNames` 把命令位置上的引号程序名还原,再掩码参数文本
|
|
1565
|
+
* (避免 `git commit -m "openfeel chore"` 被消息误杀);并额外识别
|
|
1566
|
+
* `node <cli/index/bin 路径>`、`Start-Process openfeel`、以及
|
|
1567
|
+
* **任何同时含 `chore` 与 `--source` 的命令**(chore 是纯人类通道)。
|
|
1568
|
+
*
|
|
1569
|
+
* @param {string} statement
|
|
1570
|
+
* @returns {string | null}
|
|
1571
|
+
*/
|
|
1572
|
+
function matchOpenFeelWrite(statement) {
|
|
1573
|
+
const unquoted = unquoteProgramNames(statement);
|
|
1574
|
+
const masked = maskQuoted(unquoted);
|
|
1575
|
+
const snippet = truncateCommand(statement, 160) ?? 'openfeel';
|
|
1576
|
+
|
|
1577
|
+
// ① 兜底(chore 纯人类通道):`chore` + `--source` 不论怎么写都拒。
|
|
1578
|
+
const flat = tokenizeShell(masked).map((token) => commandNameOf(token));
|
|
1579
|
+
if (flat.includes('chore') && tokenizeShell(masked).some((token) => token.startsWith('--source'))) return snippet;
|
|
1580
|
+
|
|
1581
|
+
// ② 程序位置上的 openfeel(含 `& "openfeel"` 已由 unquoteProgramNames 还原)
|
|
1582
|
+
const pattern = /\bopenfeel(?:\.cmd|\.exe)?\b/gi;
|
|
1583
|
+
let match;
|
|
1584
|
+
while ((match = pattern.exec(masked)) !== null) {
|
|
1585
|
+
const start = match.index + match[0].length;
|
|
1586
|
+
const pipeAt = masked.indexOf('|', start);
|
|
1587
|
+
const argsText = unquoted.slice(start, pipeAt === -1 ? undefined : pipeAt);
|
|
1588
|
+
if (isOpenFeelWriteInvocation(tokenizeShell(argsText))) return snippet;
|
|
1589
|
+
}
|
|
1590
|
+
|
|
1591
|
+
// ③ `node <cli 路径>` / `Start-Process openfeel`(这里用**去引号**文本取参数:
|
|
1592
|
+
// `-ArgumentList 'chore --source x'` 的实参在引号里,掩码后取不到)。
|
|
1593
|
+
const tokens = tokenizeShell(unquoted);
|
|
1594
|
+
for (let index = 0; index < tokens.length; index += 1) {
|
|
1595
|
+
const name = commandNameOf(tokens[index]);
|
|
1596
|
+
if (name === 'node' && index + 1 < tokens.length) {
|
|
1597
|
+
const script = tokens[index + 1];
|
|
1598
|
+
if (/openfeel|(?:^|[\\/])(?:cli|index)\.(?:js|mjs|cjs|ts)$|[\\/]bin[\\/]/i.test(script)
|
|
1599
|
+
&& isOpenFeelWriteInvocation(tokens.slice(index + 2))) {
|
|
1600
|
+
return snippet;
|
|
1601
|
+
}
|
|
1602
|
+
}
|
|
1603
|
+
if (name === 'start-process') {
|
|
1604
|
+
let cursor = index + 1;
|
|
1605
|
+
while (cursor < tokens.length && tokens[cursor].startsWith('-')) cursor += 1;
|
|
1606
|
+
const program = commandNameOf(tokens[cursor] ?? '');
|
|
1607
|
+
// `-ArgumentList 'chore --source x'` 的实参是一个带空格的 token → 再拆开
|
|
1608
|
+
const startArgs = tokens.slice(cursor + 1).flatMap((token) => token.split(/\s+/).filter(Boolean));
|
|
1609
|
+
if (/openfeel/.test(program) && isOpenFeelWriteInvocation(startArgs)) return snippet;
|
|
1610
|
+
}
|
|
1611
|
+
}
|
|
1612
|
+
return null;
|
|
1613
|
+
}
|
|
1614
|
+
|
|
1615
|
+
/**
|
|
1616
|
+
* 读取 patch 文件里的目标(`patch -i x.diff` / `git apply x.diff` / `patch < x.diff`)。
|
|
1617
|
+
* @param {string | undefined} file
|
|
1618
|
+
* @param {string} baseDir 已归一化命令基准目录
|
|
1619
|
+
* @returns {{ targets: string[], undecidable?: boolean, detail?: string }}
|
|
1620
|
+
*/
|
|
1621
|
+
function readPatchTargets(file, baseDir) {
|
|
1622
|
+
if (typeof file !== 'string' || file === '') {
|
|
1623
|
+
return { targets: [], undecidable: true, detail: '无法确定 patch 文件' };
|
|
1624
|
+
}
|
|
1625
|
+
try {
|
|
1626
|
+
const parsed = parsePatchTargets(readFileSync(resolve(baseDir, file), 'utf8'));
|
|
1627
|
+
if (!parsed.ok) return { targets: [], undecidable: true, detail: parsed.reason };
|
|
1628
|
+
return { targets: parsed.paths };
|
|
1629
|
+
} catch {
|
|
1630
|
+
return { targets: [], undecidable: true, detail: `无法读取 patch 文件 ${file}` };
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
|
|
1634
|
+
/**
|
|
1635
|
+
* 解析 PowerShell 写 cmdlet 的目标(pwsh 分支)。
|
|
1636
|
+
* @param {string} command 已小写的命令名
|
|
1637
|
+
* @param {string[]} tokens
|
|
1638
|
+
* @param {number} start
|
|
1639
|
+
* @returns {{ targets: string[], undecidable?: boolean, detail?: string } | null}
|
|
1640
|
+
*/
|
|
1641
|
+
function parsePowerShellWrite(command, tokens, start) {
|
|
1642
|
+
const spec = PS_WRITE_SPECS.get(command);
|
|
1643
|
+
if (spec === undefined) return null;
|
|
1644
|
+
// P2:`sed -i` 在 pwsh 分支也要按 -i 判定(不是「只有源」的 dest 语义)。
|
|
1645
|
+
if (spec === 'sed') {
|
|
1646
|
+
const sedArgs = [];
|
|
1647
|
+
for (let index = start + 1; index < tokens.length && tokens[index] !== '|'; index += 1) sedArgs.push(tokens[index]);
|
|
1648
|
+
return parseSedTargets(sedArgs);
|
|
1649
|
+
}
|
|
1650
|
+
const namedTargets = [];
|
|
1651
|
+
const positionals = [];
|
|
1652
|
+
let index = start + 1;
|
|
1653
|
+
while (index < tokens.length && tokens[index] !== '|') {
|
|
1654
|
+
const token = tokens[index];
|
|
1655
|
+
if (token.startsWith('-') && token.length > 1) {
|
|
1656
|
+
const colon = token.indexOf(':');
|
|
1657
|
+
const name = (colon === -1 ? token.slice(1) : token.slice(1, colon)).toLowerCase();
|
|
1658
|
+
let value = colon === -1 ? undefined : token.slice(colon + 1);
|
|
1659
|
+
if (PS_PATH_PARAMS.has(name)) {
|
|
1660
|
+
if (value === undefined) {
|
|
1661
|
+
value = tokens[index + 1];
|
|
1662
|
+
index += 1;
|
|
1663
|
+
}
|
|
1664
|
+
const isSource = spec === 'dest' && PS_SOURCE_PARAMS.has(name);
|
|
1665
|
+
if (!isSource && value !== undefined && value !== '|' && value !== '') namedTargets.push(value);
|
|
1666
|
+
} else if (!PS_SWITCH_PARAMS.has(name) && value === undefined) {
|
|
1667
|
+
// 未知参数:保守地当作「带一个值」,避免把参数值误当目标路径
|
|
1668
|
+
index += 1;
|
|
1669
|
+
}
|
|
1670
|
+
index += 1;
|
|
1671
|
+
continue;
|
|
1672
|
+
}
|
|
1673
|
+
positionals.push(token);
|
|
1674
|
+
index += 1;
|
|
1675
|
+
}
|
|
1676
|
+
const targets = [...namedTargets];
|
|
1677
|
+
if (spec === 'first') {
|
|
1678
|
+
if (positionals.length > 0) targets.push(positionals[0]);
|
|
1679
|
+
} else if (spec === 'all') {
|
|
1680
|
+
targets.push(...positionals);
|
|
1681
|
+
} else if (spec === 'dest2') {
|
|
1682
|
+
// `robocopy src dst [files...]` / `xcopy src dst /E`:第二个位置参数才是目标。
|
|
1683
|
+
if (positionals.length >= 2) targets.push(positionals[1]);
|
|
1684
|
+
else return { targets, undecidable: true, detail: `${command} 缺少目标(只有源)` };
|
|
1685
|
+
} else if (positionals.length >= 2) {
|
|
1686
|
+
targets.push(positionals[positionals.length - 1]);
|
|
1687
|
+
} else if (positionals.length === 1) {
|
|
1688
|
+
return { targets, undecidable: true, detail: `${command} 缺少目标(只有源)` };
|
|
1689
|
+
}
|
|
1690
|
+
return { targets };
|
|
1691
|
+
}
|
|
1692
|
+
|
|
1693
|
+
/**
|
|
1694
|
+
* 解析 POSIX 写命令的目标(bash 分支)。
|
|
1695
|
+
* @param {string} command 已小写的命令名
|
|
1696
|
+
* @param {string[]} tokens
|
|
1697
|
+
* @param {number} start
|
|
1698
|
+
* @param {string} baseDir
|
|
1699
|
+
* @returns {{ targets: string[], undecidable?: boolean, detail?: string } | null}
|
|
1700
|
+
*/
|
|
1701
|
+
function parsePosixWrite(command, tokens, start, baseDir) {
|
|
1702
|
+
const spec = POSIX_WRITE_SPECS.get(command);
|
|
1703
|
+
if (spec === undefined) return null;
|
|
1704
|
+
const args = [];
|
|
1705
|
+
for (let index = start + 1; index < tokens.length && tokens[index] !== '|'; index += 1) args.push(tokens[index]);
|
|
1706
|
+
|
|
1707
|
+
if (spec === 'sed') return parseSedTargets(args);
|
|
1708
|
+
if (spec === 'patch') {
|
|
1709
|
+
let patchFile;
|
|
1710
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
1711
|
+
const arg = args[index];
|
|
1712
|
+
if (arg === '<' || arg === '-i' || arg === '--input') { patchFile = args[index + 1]; break; }
|
|
1713
|
+
if (arg.startsWith('-i') && arg.length > 2) { patchFile = arg.slice(2); break; }
|
|
1714
|
+
if (!arg.startsWith('-')) { patchFile = arg; break; }
|
|
1715
|
+
}
|
|
1716
|
+
return readPatchTargets(patchFile, baseDir);
|
|
1717
|
+
}
|
|
1718
|
+
|
|
1719
|
+
const positionals = [];
|
|
1720
|
+
let endOfFlags = false;
|
|
1721
|
+
for (const arg of args) {
|
|
1722
|
+
if (!endOfFlags && arg === '--') { endOfFlags = true; continue; }
|
|
1723
|
+
if (!endOfFlags && arg.startsWith('-') && arg !== '-') continue;
|
|
1724
|
+
positionals.push(arg);
|
|
1725
|
+
}
|
|
1726
|
+
if (spec === 'dest') {
|
|
1727
|
+
if (positionals.length >= 2) return { targets: [positionals[positionals.length - 1]] };
|
|
1728
|
+
if (positionals.length === 1) return { targets: [], undecidable: true, detail: `${command} 缺少目标` };
|
|
1729
|
+
return { targets: [] };
|
|
1730
|
+
}
|
|
1731
|
+
if (spec === 'dest2') {
|
|
1732
|
+
if (positionals.length >= 2) return { targets: [positionals[1]] };
|
|
1733
|
+
return { targets: [], undecidable: true, detail: `${command} 缺少目标(只有源)` };
|
|
1734
|
+
}
|
|
1735
|
+
return { targets: positionals };
|
|
1736
|
+
}
|
|
1737
|
+
|
|
1738
|
+
/**
|
|
1739
|
+
* `sed -i` 的目标(只在 `-i`/`--in-place` 时才算写入)。
|
|
1740
|
+
* @param {string[]} args
|
|
1741
|
+
* @returns {{ targets: string[], undecidable?: boolean, detail?: string }}
|
|
1742
|
+
*/
|
|
1743
|
+
function parseSedTargets(args) {
|
|
1744
|
+
const inPlace = args.some((arg) => arg === '--in-place' || /^-[a-zA-Z]*i/.test(arg));
|
|
1745
|
+
if (!inPlace) return { targets: [] };
|
|
1746
|
+
const rest = [];
|
|
1747
|
+
let scriptSeen = false;
|
|
1748
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
1749
|
+
const arg = args[index];
|
|
1750
|
+
if (arg === '-e' || arg === '--expression' || arg === '-f' || arg === '--file') {
|
|
1751
|
+
index += 1;
|
|
1752
|
+
scriptSeen = true;
|
|
1753
|
+
continue;
|
|
1754
|
+
}
|
|
1755
|
+
if (arg.startsWith('-')) continue;
|
|
1756
|
+
if (!scriptSeen) { scriptSeen = true; continue; }
|
|
1757
|
+
rest.push(arg);
|
|
1758
|
+
}
|
|
1759
|
+
if (rest.length === 0) return { targets: [], undecidable: true, detail: 'sed -i 的目标无法确定' };
|
|
1760
|
+
return { targets: rest };
|
|
1761
|
+
}
|
|
1762
|
+
|
|
1763
|
+
/* ── op-005 / P0-1:未识别命令不再静默放行 ────────────────────────────────
|
|
1764
|
+
*
|
|
1765
|
+
* 下面的解析器承担「写明」与「确认只读」两条正面证据;两条都不成立时由
|
|
1766
|
+
* `analyzeShellStatement` 记入第 4 类(undecidable),**绝不**再返回 no-write。
|
|
1767
|
+
* ─────────────────────────────────────────────────────────────────────── */
|
|
1768
|
+
|
|
1769
|
+
/** 带「输出到文件」语义的下载器参数(值可能是下一个 token 或 `:`/`=` 后粘连)。 */
|
|
1770
|
+
const DOWNLOAD_OUTPUT_FLAGS = new Set(['-o', '-outfile', '--output', '--output-document', '--out']);
|
|
1771
|
+
/** 下载器的「文件名来自 URL」参数 → 目标不可判定(大写 `-O` / `--remote-name`)。 */
|
|
1772
|
+
|
|
1773
|
+
/** certutil 的落盘动作(`-urlcache` 下载、`-decode`/`-encode` 转换)。 */
|
|
1774
|
+
const CERTUTIL_WRITE_FLAGS = new Set(['-urlcache', '-decode', '-decodehex', '-encode']);
|
|
1775
|
+
|
|
1776
|
+
/** 通用的「写」长参数(任何程序带上都代表就地改写)。 */
|
|
1777
|
+
const GENERIC_WRITE_FLAGS = new Set(['--write', '--fix', '--write-changes', '--in-place']);
|
|
1778
|
+
|
|
1779
|
+
/** 取值型 flag:其后的 token 是参数值而不是目标路径。 */
|
|
1780
|
+
const VALUE_FLAGS = new Set([
|
|
1781
|
+
'--config', '-c', '--ignore-path', '--ignore-pattern', '--parser', '--plugin', '--ext',
|
|
1782
|
+
'--rules', '--rule', '--max-warnings', '--stdin-filename', '--cache-location',
|
|
1783
|
+
'--print-width', '--tab-width', '--log-level', '--cache', '--format', '--output',
|
|
1784
|
+
]);
|
|
1785
|
+
|
|
1786
|
+
/** `npm run <script>` 里视为「构建/测试」的脚本名。 */
|
|
1787
|
+
const BUILD_SCRIPTS = new Set([
|
|
1788
|
+
'build', 'test', 'lint', 'typecheck', 'type-check', 'check', 'compile', 'bundle',
|
|
1789
|
+
'package', 'coverage', 'format:check', 'test:unit', 'test:integration', 'ci',
|
|
1790
|
+
]);
|
|
1791
|
+
|
|
1792
|
+
/** .NET 静态**只读**调用(op-006 起由 `DOTNET_READ_METHODS` 正面白名单承担)。 */
|
|
1793
|
+
|
|
1794
|
+
/**
|
|
1795
|
+
* 收集位置参数(跳过 flag 与 `--`),可选跳过取值型 flag 的值。
|
|
1796
|
+
* @param {string[]} args
|
|
1797
|
+
* @param {Set<string>} [valueFlags]
|
|
1798
|
+
* @returns {string[]}
|
|
1799
|
+
*/
|
|
1800
|
+
function positionalArgs(args, valueFlags = new Set()) {
|
|
1801
|
+
const out = [];
|
|
1802
|
+
let endOfFlags = false;
|
|
1803
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
1804
|
+
const arg = args[index];
|
|
1805
|
+
if (!endOfFlags && arg === '--') { endOfFlags = true; continue; }
|
|
1806
|
+
if (!endOfFlags && arg.startsWith('-') && arg !== '-') {
|
|
1807
|
+
if (valueFlags.has(arg.toLowerCase())) index += 1;
|
|
1808
|
+
continue;
|
|
1809
|
+
}
|
|
1810
|
+
out.push(arg);
|
|
1811
|
+
}
|
|
1812
|
+
return out;
|
|
1813
|
+
}
|
|
1814
|
+
|
|
1815
|
+
/**
|
|
1816
|
+
* 格式化/修复工具的写目标(op-005 / P0-1:`prettier --write src`、`eslint --fix`、`gofmt -w`)。
|
|
1817
|
+
*
|
|
1818
|
+
* 只有在**确实要求就地改写**时才返回非 null:`--write` / `--fix` / `--write-changes`
|
|
1819
|
+
* 对任何程序生效;`-w` / `-i` / `--in-place` 只对已知 formatter 生效
|
|
1820
|
+
* (否则 `grep -i` / `-w` 会被误判成写)。
|
|
1821
|
+
*
|
|
1822
|
+
* @param {string} name 程序名(已小写、去 .exe)
|
|
1823
|
+
* @param {string[]} args
|
|
1824
|
+
* @returns {{ targets: string[], undecidable?: boolean, detail?: string } | null}
|
|
1825
|
+
*/
|
|
1826
|
+
function parseFormatterWrite(name, args) {
|
|
1827
|
+
const lower = args.map((arg) => arg.toLowerCase());
|
|
1828
|
+
const genericWrite = lower.some((arg) => GENERIC_WRITE_FLAGS.has(arg));
|
|
1829
|
+
const formatter = FORMATTER_TOOLS.has(name);
|
|
1830
|
+
const shortWrite = formatter && lower.some((arg) => arg === '-w' || arg === '-i'
|
|
1831
|
+
|| (/^-[a-z]*[wi]$/.test(arg) && arg.length <= 4));
|
|
1832
|
+
if (!genericWrite && !shortWrite) return null;
|
|
1833
|
+
const targets = positionalArgs(args, VALUE_FLAGS);
|
|
1834
|
+
if (targets.length === 0) {
|
|
1835
|
+
return { targets: [], undecidable: true, detail: `${name} 的就地改写目标未给出(可能作用于整树)` };
|
|
1836
|
+
}
|
|
1837
|
+
return { targets };
|
|
1838
|
+
}
|
|
1839
|
+
|
|
1840
|
+
/**
|
|
1841
|
+
* 下载器的落盘目标(`curl -o x` / `iwr -OutFile x` / `wget -O x`)。
|
|
1842
|
+
*
|
|
1843
|
+
* 没有输出参数 → null(下载到 stdout,只读)。注意 `-O` 在**两个工具里含义相反**:
|
|
1844
|
+
* curl 的 `-O` 是「文件名来自 URL」(目标不可判定),wget 的 `-O` 是「输出到文件」
|
|
1845
|
+
* (下一个 token 是目标)。
|
|
1846
|
+
*
|
|
1847
|
+
* @param {string} name 程序名(已小写、去 .exe)
|
|
1848
|
+
* @param {string[]} args
|
|
1849
|
+
* @returns {{ targets: string[], undecidable?: boolean, detail?: string } | null}
|
|
1850
|
+
*/
|
|
1851
|
+
function parseDownloadWrite(name, args) {
|
|
1852
|
+
const wgetLike = name === 'wget';
|
|
1853
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
1854
|
+
const raw = args[index];
|
|
1855
|
+
const lower = raw.toLowerCase();
|
|
1856
|
+
const colon = lower.indexOf(':');
|
|
1857
|
+
const head = colon === -1 ? lower : lower.slice(0, colon);
|
|
1858
|
+
// wget 的 -O <file>:输出到文件
|
|
1859
|
+
if (wgetLike && raw === '-O') {
|
|
1860
|
+
const value = args[index + 1];
|
|
1861
|
+
if (typeof value !== 'string' || value === '') return { targets: [], undecidable: true, detail: 'wget -O 缺少输出路径' };
|
|
1862
|
+
return { targets: [value] };
|
|
1863
|
+
}
|
|
1864
|
+
// curl / iwr 的「文件名来自 URL」形态 → 第 4 类
|
|
1865
|
+
if (!wgetLike && (raw === '-O' || lower === '--remote-name' || lower === '--remote-name-all' || /^-[a-z]*O$/.test(raw))) {
|
|
1866
|
+
return { targets: [], undecidable: true, detail: `${raw} 的文件名来自 URL` };
|
|
1867
|
+
}
|
|
1868
|
+
if (DOWNLOAD_OUTPUT_FLAGS.has(head)) {
|
|
1869
|
+
const attachedValue = colon === -1 ? (lower !== head ? raw.slice(head.length) : '') : raw.slice(colon + 1);
|
|
1870
|
+
const value = attachedValue !== '' ? attachedValue : args[index + 1];
|
|
1871
|
+
if (typeof value !== 'string' || value === '' || value.startsWith('-')) {
|
|
1872
|
+
return { targets: [], undecidable: true, detail: `${raw} 缺少输出路径` };
|
|
1873
|
+
}
|
|
1874
|
+
return { targets: [value] };
|
|
1875
|
+
}
|
|
1876
|
+
// 短参数粘连:`-sSLo out.txt` / `-oout.txt`
|
|
1877
|
+
const combined = /^-([a-zA-Z]*)o$/.exec(raw);
|
|
1878
|
+
if (combined !== null && raw.length > 2) {
|
|
1879
|
+
const value = args[index + 1];
|
|
1880
|
+
if (typeof value !== 'string' || value === '') return { targets: [], undecidable: true, detail: `${raw} 缺少输出路径` };
|
|
1881
|
+
return { targets: [value] };
|
|
1882
|
+
}
|
|
1883
|
+
const attachedShort = /^-([a-zA-Z]*)o(.+)$/.exec(raw);
|
|
1884
|
+
if (attachedShort !== null) return { targets: [attachedShort[2]] };
|
|
1885
|
+
}
|
|
1886
|
+
return null;
|
|
1887
|
+
}
|
|
1888
|
+
|
|
1889
|
+
/**
|
|
1890
|
+
* certutil 的落盘目标(`certutil -urlcache -split -f <url> <out>`)。
|
|
1891
|
+
* @param {string[]} args
|
|
1892
|
+
* @returns {{ targets: string[], undecidable?: boolean, detail?: string } | null}
|
|
1893
|
+
*/
|
|
1894
|
+
function parseCertutilWrite(args) {
|
|
1895
|
+
const lower = args.map((arg) => arg.toLowerCase());
|
|
1896
|
+
if (!lower.some((arg) => CERTUTIL_WRITE_FLAGS.has(arg))) return null;
|
|
1897
|
+
const positionals = positionalArgs(args);
|
|
1898
|
+
if (positionals.length === 0) {
|
|
1899
|
+
return { targets: [], undecidable: true, detail: 'certutil 的落盘目标不可判定' };
|
|
1900
|
+
}
|
|
1901
|
+
return { targets: [positionals[positionals.length - 1]] };
|
|
1902
|
+
}
|
|
1903
|
+
|
|
1904
|
+
/**
|
|
1905
|
+
* 包管理器 / 包运行器(`npx` / `npm` / `pnpm` / `yarn`)分类。
|
|
1906
|
+
*
|
|
1907
|
+
* 放行口径(op-005 / P0-1):**只**放行「已知构建/测试工具」与已知构建脚本;
|
|
1908
|
+
* `npx <任意>` 一律第 4 类(可执行任意包,静态不可判)。
|
|
1909
|
+
*
|
|
1910
|
+
* @param {string} name 已小写程序名
|
|
1911
|
+
* @param {string[]} args
|
|
1912
|
+
* @returns {{ kind: 'readonly'|'build'|'unknown', detail?: string }}
|
|
1913
|
+
*/
|
|
1914
|
+
function classifyPackageRunner(name, args) {
|
|
1915
|
+
const tokens = args.filter((token) => token !== '');
|
|
1916
|
+
let index = 0;
|
|
1917
|
+
while (index < tokens.length && tokens[index].startsWith('-')) {
|
|
1918
|
+
if (tokens[index] === '-p' || tokens[index] === '--package') index += 2;
|
|
1919
|
+
else index += 1;
|
|
1920
|
+
}
|
|
1921
|
+
const sub = (tokens[index] ?? '').toLowerCase();
|
|
1922
|
+
const rest = tokens.slice(index + 1);
|
|
1923
|
+
if (PACKAGE_RUNNERS.has(name)) {
|
|
1924
|
+
if (sub === '') return { kind: 'unknown', detail: `${name} 未指定要运行的程序` };
|
|
1925
|
+
if (BUILD_TOOL_PROGRAMS.has(sub) || FORMATTER_TOOLS.has(sub) || READONLY_PROGRAMS.has(sub)) return { kind: 'build' };
|
|
1926
|
+
return { kind: 'unknown', detail: `${name} ${sub} 会执行任意包,目标不可判定` };
|
|
1927
|
+
}
|
|
1928
|
+
if (sub === '' || sub === '--version' || sub === '-v' || sub === '-h' || sub === '--help') return { kind: 'readonly' };
|
|
1929
|
+
if (['install', 'i', 'ci', 'add', 'update', 'up', 'prune', 'dedupe'].includes(sub)) return { kind: 'build' };
|
|
1930
|
+
if (sub === 'test' || sub === 't') return { kind: 'build' };
|
|
1931
|
+
if (sub === 'run' || sub === 'run-script' || sub === 'rum') {
|
|
1932
|
+
const script = (rest.find((token) => !token.startsWith('-')) ?? '').toLowerCase();
|
|
1933
|
+
if (BUILD_SCRIPTS.has(script)) return { kind: 'build' };
|
|
1934
|
+
return { kind: 'unknown', detail: `${name} run ${script || '?'} 的脚本内容静态不可判` };
|
|
1935
|
+
}
|
|
1936
|
+
if (sub === 'exec' || sub === 'x' || sub === 'dlx') {
|
|
1937
|
+
const tool = (rest.find((token) => !token.startsWith('-')) ?? '').toLowerCase();
|
|
1938
|
+
if (tool !== '' && (BUILD_TOOL_PROGRAMS.has(tool) || FORMATTER_TOOLS.has(tool))) return { kind: 'build' };
|
|
1939
|
+
return { kind: 'unknown', detail: `${name} ${sub} ${tool || '?'} 会执行任意程序` };
|
|
1940
|
+
}
|
|
1941
|
+
return { kind: 'unknown', detail: `${name} ${sub} 无法确证` };
|
|
1942
|
+
}
|
|
1943
|
+
|
|
1944
|
+
/**
|
|
1945
|
+
* 脚本解释器(`node x.js` / `python x.py` / `bun x`)分类。
|
|
1946
|
+
*
|
|
1947
|
+
* `-e` / `-c` 的内联形态已由 `matchInlineInterpreter` 处理;到这里只可能是
|
|
1948
|
+
* 「跑一个脚本文件」——脚本内容不可见 → 默认第 4 类(**不**一刀切放行)。
|
|
1949
|
+
*
|
|
1950
|
+
* @param {string} name
|
|
1951
|
+
* @param {string[]} args
|
|
1952
|
+
* @returns {{ kind: 'readonly'|'unknown', detail?: string }}
|
|
1953
|
+
*/
|
|
1954
|
+
function classifyScriptInterpreter(name, args) {
|
|
1955
|
+
const tokens = args.filter((token) => token !== '');
|
|
1956
|
+
const positionals = tokens.filter((token) => !token.startsWith('-'));
|
|
1957
|
+
if (positionals.length > 0) {
|
|
1958
|
+
return { kind: 'unknown', detail: `${name} 执行的脚本 ${positionals[0]} 内容不可见` };
|
|
1959
|
+
}
|
|
1960
|
+
const versionOnly = tokens.every((token) => ['--version', '-v', '-V', '--help', '-h'].includes(token));
|
|
1961
|
+
if (tokens.length > 0 && versionOnly) return { kind: 'readonly' };
|
|
1962
|
+
return { kind: 'unknown', detail: `${name} 参数无法判定` };
|
|
1963
|
+
}
|
|
1964
|
+
|
|
1965
|
+
/**
|
|
1966
|
+
* 构建/测试工具的子命令收窄(`cargo fmt` 会改源码,不能整命令放行)。
|
|
1967
|
+
* @param {string} name
|
|
1968
|
+
* @param {string[]} args
|
|
1969
|
+
* @returns {{ kind: 'build'|'unknown', detail?: string }}
|
|
1970
|
+
*/
|
|
1971
|
+
function classifyBuildTool(name, args) {
|
|
1972
|
+
if (name === 'tsc') {
|
|
1973
|
+
// `tsc file.ts` 会就地生成 `file.js`;只有 `-b`/`-p`/`--noEmit` 才是纯产物。
|
|
1974
|
+
const safe = args.some((arg) => ['-b', '--build', '-p', '--project', '--noEmit', '--version', '-v', '--help', '-h'].includes(arg));
|
|
1975
|
+
const positional = args.some((arg) => !arg.startsWith('-'));
|
|
1976
|
+
if (!positional || safe) return { kind: 'build' };
|
|
1977
|
+
return { kind: 'unknown', detail: 'tsc <文件> 会就地生成 .js' };
|
|
1978
|
+
}
|
|
1979
|
+
const subs = BUILD_TOOL_SUBCOMMANDS.get(name);
|
|
1980
|
+
if (subs === undefined) return { kind: 'build' };
|
|
1981
|
+
const first = args.find((arg) => !arg.startsWith('-'));
|
|
1982
|
+
if (first === undefined) return { kind: 'build' };
|
|
1983
|
+
if (subs.has(first.toLowerCase())) return { kind: 'build' };
|
|
1984
|
+
return { kind: 'unknown', detail: `${name} ${first} 不确认只写产物` };
|
|
1985
|
+
}
|
|
1986
|
+
|
|
1987
|
+
/** git 里表示「整个工作树」的路径参数(`.` / `:/` / `*` 等)。 */
|
|
1988
|
+
const WHOLE_TREE_GIT_TARGETS = new Set(['.', './', './*', ':/', ':(top)', '*', '**', '.\\']);
|
|
1989
|
+
|
|
1990
|
+
/**
|
|
1991
|
+
* 该 git 路径参数是否覆盖整个工作树(op-005 / P1-2)。
|
|
1992
|
+
* @param {string} token
|
|
1993
|
+
* @returns {boolean}
|
|
1994
|
+
*/
|
|
1995
|
+
function coversWholeTree(token) {
|
|
1996
|
+
return WHOLE_TREE_GIT_TARGETS.has(String(token).toLowerCase());
|
|
1997
|
+
}
|
|
1998
|
+
|
|
1999
|
+
/**
|
|
2000
|
+
* git 子命令分类(第 2 类;`status|log|diff|branch|fetch` 等永远放行)。
|
|
2001
|
+
*
|
|
2002
|
+
* 整树写(`reset --hard`/`--merge`、`stash`(含 `push`)、`clean`、`commit`、
|
|
2003
|
+
* `checkout/switch 分支`、`merge/rebase/pull/…`)需要特定相位:
|
|
2004
|
+
* - 默认要求 `exec_running`(否则「非 exec 相位用 git 还原/丢弃源码」绕过一切文件门禁);
|
|
2005
|
+
* - `commit` 额外允许 `archiving`(op-005 / P1-4:发版提交发生在 archiving);
|
|
2006
|
+
* - 进入整树写前还有一道 `.openfeel/**` 无差异检查(op-005 / P1-2),见 `openfeelTreeDirty`。
|
|
2007
|
+
* @param {string[]} tokens
|
|
2008
|
+
* @param {number} start
|
|
2009
|
+
* @param {string} baseDir
|
|
2010
|
+
* @returns {{ kind: 'readonly' } | { kind: 'targets', targets: string[] } | { kind: 'whole-tree', detail: string, phases?: string[] } | { kind: 'undecidable', detail: string }}
|
|
2011
|
+
*/
|
|
2012
|
+
function classifyGitCommand(tokens, start, baseDir) {
|
|
2013
|
+
let index = start + 1;
|
|
2014
|
+
let subcommand;
|
|
2015
|
+
while (index < tokens.length && tokens[index] !== '|') {
|
|
2016
|
+
const token = tokens[index];
|
|
2017
|
+
if (token === '-C' || token === '--git-dir' || token === '--work-tree') { index += 2; continue; }
|
|
2018
|
+
if (token.startsWith('-')) { index += 1; continue; }
|
|
2019
|
+
subcommand = token.toLowerCase();
|
|
2020
|
+
break;
|
|
2021
|
+
}
|
|
2022
|
+
if (subcommand === undefined) return { kind: 'readonly' };
|
|
2023
|
+
const rest = [];
|
|
2024
|
+
for (let cursor = index + 1; cursor < tokens.length && tokens[cursor] !== '|'; cursor += 1) rest.push(tokens[cursor]);
|
|
2025
|
+
const positionals = rest.filter((token) => !token.startsWith('-') && token !== '--');
|
|
2026
|
+
const dashdash = rest.indexOf('--');
|
|
2027
|
+
const pathsAfterDashDash = dashdash === -1 ? [] : rest.slice(dashdash + 1).filter((token) => !token.startsWith('-'));
|
|
2028
|
+
|
|
2029
|
+
switch (subcommand) {
|
|
2030
|
+
case 'checkout':
|
|
2031
|
+
case 'switch': {
|
|
2032
|
+
if (rest.some((token) => ['-b', '-B', '--orphan', '-c', '--create'].includes(token))) return { kind: 'readonly' };
|
|
2033
|
+
if (dashdash !== -1) {
|
|
2034
|
+
// op-005 / P1-2:`git checkout -- .` 是**整树**写(旧实现按「目标 = 当前目录」
|
|
2035
|
+
// 处理 → exec_running 下放行,连 `.openfeel/**` 一起覆盖)。
|
|
2036
|
+
if (pathsAfterDashDash.length === 0 || pathsAfterDashDash.some(coversWholeTree)) {
|
|
2037
|
+
return { kind: 'whole-tree', detail: `git ${subcommand} --` };
|
|
2038
|
+
}
|
|
2039
|
+
return { kind: 'targets', targets: pathsAfterDashDash };
|
|
2040
|
+
}
|
|
2041
|
+
if (positionals.length === 0) return { kind: 'readonly' };
|
|
2042
|
+
if (positionals.some(coversWholeTree)) return { kind: 'whole-tree', detail: `git ${subcommand} .` };
|
|
2043
|
+
// `git checkout <path>`(无 `--`)= 还原该路径;分支名 → 整树切换
|
|
2044
|
+
if (positionals.length === 1 && /[\\/.]/.test(positionals[0])) {
|
|
2045
|
+
return { kind: 'targets', targets: [positionals[0]] };
|
|
2046
|
+
}
|
|
2047
|
+
return { kind: 'whole-tree', detail: `git ${subcommand} ${positionals[0]}` };
|
|
2048
|
+
}
|
|
2049
|
+
case 'restore': {
|
|
2050
|
+
if (positionals.length === 0 || positionals.some(coversWholeTree)) return { kind: 'whole-tree', detail: 'git restore' };
|
|
2051
|
+
return { kind: 'targets', targets: positionals };
|
|
2052
|
+
}
|
|
2053
|
+
case 'reset': {
|
|
2054
|
+
if (rest.includes('--hard') || rest.includes('--merge')) return { kind: 'whole-tree', detail: 'git reset --hard / --merge' };
|
|
2055
|
+
return { kind: 'readonly' };
|
|
2056
|
+
}
|
|
2057
|
+
case 'stash': {
|
|
2058
|
+
// op-005 / P1-3:`git stash`(无 action)/ `push` 会**丢弃工作区改动**,
|
|
2059
|
+
// 旧的 `readonly` 判定等于给了一条整树覆盖后门;只有 list/show 是真只读。
|
|
2060
|
+
const action = (positionals[0] ?? '').toLowerCase();
|
|
2061
|
+
if (action === 'list' || action === 'show') return { kind: 'readonly' };
|
|
2062
|
+
// op-006 / P1-1:`stash -u` 会把未跟踪文件也收走 → 需要未跟踪检查。
|
|
2063
|
+
const destroysUntracked = rest.some((token) => ['-u', '--include-untracked', '-a', '--all'].includes(token));
|
|
2064
|
+
return { kind: 'whole-tree', detail: `git stash ${action || 'push'}`, destroysUntracked };
|
|
2065
|
+
}
|
|
2066
|
+
case 'clean':
|
|
2067
|
+
// op-006 / P1-1:`git clean` 删的是未跟踪文件(`-x` 连 ignored 一起删),
|
|
2068
|
+
// 而 `.openfeel/**` 的证据大多是未跟踪 / 被忽略的 → 必须把这些也当「差异」。
|
|
2069
|
+
return {
|
|
2070
|
+
kind: 'whole-tree',
|
|
2071
|
+
detail: 'git clean',
|
|
2072
|
+
destroysUntracked: true,
|
|
2073
|
+
// `-fdx` / `-fdX` / 组合短参数:连 .gitignore 忽略的文件一起删。
|
|
2074
|
+
purgesIgnored: rest.some((token) => /^-[a-zA-Z]*[xX]/.test(token)),
|
|
2075
|
+
};
|
|
2076
|
+
case 'apply': {
|
|
2077
|
+
if (rest.some((token) => ['--check', '--stat', '--numstat', '--summary', '--name-only', '--name-status', '--verbose', '-v'].includes(token))) {
|
|
2078
|
+
return { kind: 'readonly' };
|
|
2079
|
+
}
|
|
2080
|
+
const parsed = readPatchTargets(positionals[0], baseDir);
|
|
2081
|
+
if (parsed.undecidable === true) return { kind: 'undecidable', detail: parsed.detail ?? 'git apply' };
|
|
2082
|
+
return { kind: 'targets', targets: parsed.targets };
|
|
2083
|
+
}
|
|
2084
|
+
case 'commit':
|
|
2085
|
+
// op-005 / P1-4:发版提交发生在 `archiving`,只认 exec_running 会误杀。
|
|
2086
|
+
// `commit` **不覆盖工作区**(它是把当前状态记进版本库),所以 P1-2 的
|
|
2087
|
+
// 「`.openfeel/**` 必须干净」不能套在它身上 —— 否则「先提交 .openfeel」
|
|
2088
|
+
// 的修复动作本身会被拒(死锁)。
|
|
2089
|
+
return {
|
|
2090
|
+
kind: 'whole-tree',
|
|
2091
|
+
detail: 'git commit',
|
|
2092
|
+
phases: ['exec_running', 'archiving'],
|
|
2093
|
+
preservesWorktree: true,
|
|
2094
|
+
};
|
|
2095
|
+
case 'merge':
|
|
2096
|
+
case 'rebase':
|
|
2097
|
+
case 'pull':
|
|
2098
|
+
case 'cherry-pick':
|
|
2099
|
+
case 'revert':
|
|
2100
|
+
case 'am':
|
|
2101
|
+
return { kind: 'whole-tree', detail: `git ${subcommand}` };
|
|
2102
|
+
case 'rm':
|
|
2103
|
+
case 'mv':
|
|
2104
|
+
return positionals.length > 0
|
|
2105
|
+
? { kind: 'targets', targets: positionals }
|
|
2106
|
+
: { kind: 'undecidable', detail: `git ${subcommand}` };
|
|
2107
|
+
default:
|
|
2108
|
+
// `status|log|diff|show|branch|fetch|remote|rev-parse|…` 与其它非工作区写命令
|
|
2109
|
+
return { kind: 'readonly' };
|
|
2110
|
+
}
|
|
2111
|
+
}
|
|
2112
|
+
|
|
2113
|
+
/**
|
|
2114
|
+
* 分析一句命令:抽出写入目标 / 整树写标记 / 「未识别命令」。
|
|
2115
|
+
*
|
|
2116
|
+
* op-005 / P0-1 核心改动:**每个命令位置上的程序都必须拿到正面证据** ——
|
|
2117
|
+
* 命中写解析器(产出目标)或命中只读/构建/包管理器白名单。两者都不成立时记
|
|
2118
|
+
* `undecidable = true`(第 4 类),**不再**静默按「没有写」放行。
|
|
2119
|
+
*
|
|
2120
|
+
* @param {string} statement
|
|
2121
|
+
* @param {'bash'|'pwsh'} shell
|
|
2122
|
+
* @param {string} baseDir
|
|
2123
|
+
* @returns {{ targets: string[], wholeTree?: string, wholeTreePhases?: string[], undecidable: boolean, detail: string }}
|
|
2124
|
+
*/
|
|
2125
|
+
function analyzeShellStatement(statement, shell, baseDir, vars = new Map()) {
|
|
2126
|
+
const redirections = scanShellRedirections(statement);
|
|
2127
|
+
const tokens = tokenizeShell(redirections.cleaned).filter((token) => token !== '');
|
|
2128
|
+
const targets = [...redirections.targets];
|
|
2129
|
+
let undecidable = false;
|
|
2130
|
+
let detail = '';
|
|
2131
|
+
|
|
2132
|
+
/** 记一条「无法确证不写」的证据(第 4 类)。 */
|
|
2133
|
+
const noteUnknown = (descriptor) => {
|
|
2134
|
+
undecidable = true;
|
|
2135
|
+
if (detail === '') detail = descriptor;
|
|
2136
|
+
};
|
|
2137
|
+
|
|
2138
|
+
// 命令替换(`echo $(touch x)` / 反引号)的内层命令不进入解析器 → 第 4 类。
|
|
2139
|
+
// 叠加在正常分析之上(不提前返回):`git commit -m "…$(…)"` 仍按整树写判。
|
|
2140
|
+
// 反引号用掩码文本判断,避免提交信息里的反引号被误当命令替换。
|
|
2141
|
+
if (/\$\(/.test(statement) || maskQuoted(statement).includes('`')) {
|
|
2142
|
+
noteUnknown('命令替换($() / 反引号)的内层命令无法解析');
|
|
2143
|
+
}
|
|
2144
|
+
|
|
2145
|
+
for (let index = 0; index < tokens.length; index += 1) {
|
|
2146
|
+
// 纯变量赋值语句(`$c='Set-Content'` / `F=src/x.ts`)本身不写盘,跳过;
|
|
2147
|
+
// 后续 `& $c …` 会单独落到第 4 类(不静默放行)。
|
|
2148
|
+
if (LITERAL_VAR_ASSIGN_RE.test(tokens.join(' '))) continue;
|
|
2149
|
+
const isCommandStart = index === 0 || tokens[index - 1] === '|' || tokens[index - 1] === '&';
|
|
2150
|
+
if (!isCommandStart) continue;
|
|
2151
|
+
let cursor = index;
|
|
2152
|
+
while (cursor < tokens.length && SHELL_WRAPPER_COMMANDS.has(commandNameOf(tokens[cursor]))) {
|
|
2153
|
+
cursor += 1;
|
|
2154
|
+
while (cursor < tokens.length && (tokens[cursor].startsWith('-') || /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[cursor]))) cursor += 1;
|
|
2155
|
+
}
|
|
2156
|
+
if (cursor >= tokens.length || tokens[cursor] === '|') continue;
|
|
2157
|
+
let name = commandNameOf(tokens[cursor]);
|
|
2158
|
+
// `&` / `.` 调用运算符(op-005 / P0-1):被调用者是字面量就按它判,
|
|
2159
|
+
// 是**同命令内一次字面量赋值**(`$c='Set-Content'; & $c …`)→ 解析成该程序再判
|
|
2160
|
+
// (与「目标变量」同一口径);其余变量/子表达式 → 第 4 类
|
|
2161
|
+
// (旧实现直接 continue = 静默放行)。
|
|
2162
|
+
if (name === '&' || name === '.') {
|
|
2163
|
+
const callee = tokens[cursor + 1];
|
|
2164
|
+
let resolvedCallee = null;
|
|
2165
|
+
if (callee !== undefined && callee !== '|') {
|
|
2166
|
+
const resolved = resolveShellToken(callee, vars);
|
|
2167
|
+
if (resolved.ok) resolvedCallee = resolved.value;
|
|
2168
|
+
}
|
|
2169
|
+
if (resolvedCallee === null) {
|
|
2170
|
+
noteUnknown(`${name} 调用运算符的被调用者不可判定`);
|
|
2171
|
+
continue;
|
|
2172
|
+
}
|
|
2173
|
+
cursor += 1;
|
|
2174
|
+
name = commandNameOf(resolvedCallee);
|
|
2175
|
+
}
|
|
2176
|
+
const args = [];
|
|
2177
|
+
for (let rest = cursor + 1; rest < tokens.length && tokens[rest] !== '|'; rest += 1) args.push(tokens[rest]);
|
|
2178
|
+
|
|
2179
|
+
if (name === 'git') {
|
|
2180
|
+
const git = classifyGitCommand(tokens, cursor, baseDir);
|
|
2181
|
+
if (git.kind === 'whole-tree') {
|
|
2182
|
+
return {
|
|
2183
|
+
targets,
|
|
2184
|
+
wholeTree: git.detail,
|
|
2185
|
+
wholeTreePhases: git.phases,
|
|
2186
|
+
wholeTreePreservesWorktree: git.preservesWorktree,
|
|
2187
|
+
wholeTreeDestroysUntracked: git.destroysUntracked === true,
|
|
2188
|
+
wholeTreePurgesIgnored: git.purgesIgnored === true,
|
|
2189
|
+
undecidable,
|
|
2190
|
+
detail,
|
|
2191
|
+
};
|
|
2192
|
+
}
|
|
2193
|
+
if (git.kind === 'targets') targets.push(...git.targets);
|
|
2194
|
+
else if (git.kind === 'undecidable') noteUnknown(git.detail ?? 'git');
|
|
2195
|
+
continue;
|
|
2196
|
+
}
|
|
2197
|
+
|
|
2198
|
+
// `Start-Process <程序> …`:被启动的程序本身不可判 → 第 4 类。
|
|
2199
|
+
if (name === 'start-process') {
|
|
2200
|
+
const started = positionalArgs(args).find((token) => !token.startsWith('-'));
|
|
2201
|
+
if (started === undefined) noteUnknown('Start-Process 未给出要启动的程序');
|
|
2202
|
+
else noteUnknown(`Start-Process ${commandNameOf(started)} 的目标不可判定`);
|
|
2203
|
+
continue;
|
|
2204
|
+
}
|
|
2205
|
+
|
|
2206
|
+
if (DOWNLOAD_TOOLS.has(name)) {
|
|
2207
|
+
const download = parseDownloadWrite(name, args);
|
|
2208
|
+
if (download === null) continue; // 无输出参数 = 下载到 stdout
|
|
2209
|
+
targets.push(...download.targets);
|
|
2210
|
+
if (download.undecidable === true) noteUnknown(download.detail ?? name);
|
|
2211
|
+
continue;
|
|
2212
|
+
}
|
|
2213
|
+
|
|
2214
|
+
if (name === 'certutil') {
|
|
2215
|
+
const cert = parseCertutilWrite(args);
|
|
2216
|
+
if (cert === null) continue; // `certutil -hashfile` 等只读用法
|
|
2217
|
+
targets.push(...cert.targets);
|
|
2218
|
+
if (cert.undecidable === true) noteUnknown(cert.detail ?? name);
|
|
2219
|
+
continue;
|
|
2220
|
+
}
|
|
2221
|
+
|
|
2222
|
+
const formatter = parseFormatterWrite(name, args);
|
|
2223
|
+
if (formatter !== null) {
|
|
2224
|
+
targets.push(...formatter.targets);
|
|
2225
|
+
if (formatter.undecidable === true) noteUnknown(formatter.detail ?? name);
|
|
2226
|
+
continue;
|
|
2227
|
+
}
|
|
2228
|
+
// op-006 / P2:formatter 没带写标志(`prettier --check` / `eslint src` / `gofmt -l`)
|
|
2229
|
+
// = 纯检查,确认只读;否则 strict 档会把这类日常命令当第 4 类误拒。
|
|
2230
|
+
if (FORMATTER_TOOLS.has(name)) continue;
|
|
2231
|
+
|
|
2232
|
+
// 写命令解析:**两个分支都跑并合并**(op-005)。
|
|
2233
|
+
// 只看本 shell 的 spec 会漏:pwsh 分支把 `rm -rf .openfeel` 里的 `-rf` 当
|
|
2234
|
+
// 「未知具名参数」消费掉下一个 token(保守规则),结果 targets 为空 →
|
|
2235
|
+
// 误判成「没有写」。合并 POSIX spec 后目标仍能取到;两类 spec 是保守并集
|
|
2236
|
+
// (多出来的目标只会更严,不会更松)。
|
|
2237
|
+
const parsed = [];
|
|
2238
|
+
if (shell === 'pwsh') {
|
|
2239
|
+
parsed.push(parsePowerShellWrite(name, tokens, cursor), parsePosixWrite(name, tokens, cursor, baseDir));
|
|
2240
|
+
} else {
|
|
2241
|
+
parsed.push(parsePosixWrite(name, tokens, cursor, baseDir), parsePowerShellWrite(name, tokens, cursor));
|
|
2242
|
+
}
|
|
2243
|
+
const writes = parsed.filter((entry) => entry !== null);
|
|
2244
|
+
if (writes.length > 0) {
|
|
2245
|
+
for (const write of writes) {
|
|
2246
|
+
targets.push(...write.targets);
|
|
2247
|
+
if (write.undecidable === true) noteUnknown(write.detail ?? name);
|
|
2248
|
+
}
|
|
2249
|
+
continue;
|
|
2250
|
+
}
|
|
2251
|
+
|
|
2252
|
+
if (PACKAGE_RUNNERS.has(name) || ['npm', 'pnpm', 'yarn'].includes(name)) {
|
|
2253
|
+
const runner = classifyPackageRunner(name, args);
|
|
2254
|
+
if (runner.kind === 'unknown') noteUnknown(runner.detail ?? name);
|
|
2255
|
+
continue;
|
|
2256
|
+
}
|
|
2257
|
+
|
|
2258
|
+
if (SCRIPT_INTERPRETER_TOOLS.has(name) || /^python[0-9.]*$/.test(name)) {
|
|
2259
|
+
const interpreter = classifyScriptInterpreter(name, args);
|
|
2260
|
+
if (interpreter.kind === 'unknown') noteUnknown(interpreter.detail ?? name);
|
|
2261
|
+
continue;
|
|
2262
|
+
}
|
|
2263
|
+
|
|
2264
|
+
// `.NET` 静态调用:**写方法已在 `matchDotNetStaticWrite` 里正面硬拒**;
|
|
2265
|
+
// 走到这里的只剩非可写类型 / 只读方法(`[Math]::Floor`、`[IO.Path]::Combine`、
|
|
2266
|
+
// `[IO.File]::ReadAllText`)→ 只读,不制造第 4 类噪音。
|
|
2267
|
+
if (/^\[[^\]]*\]\s*::/.test(tokens[cursor])) continue;
|
|
2268
|
+
|
|
2269
|
+
if (READONLY_PROGRAMS.has(name)) continue;
|
|
2270
|
+
|
|
2271
|
+
if (BUILD_TOOL_PROGRAMS.has(name)) {
|
|
2272
|
+
const build = classifyBuildTool(name, args);
|
|
2273
|
+
if (build.kind === 'unknown') noteUnknown(build.detail ?? name);
|
|
2274
|
+
continue;
|
|
2275
|
+
}
|
|
2276
|
+
|
|
2277
|
+
// 未识别命令:**默认 fail-closed**(第 4 类),不再当作「没有写」静默放行。
|
|
2278
|
+
noteUnknown(`未识别的命令 ${name}`);
|
|
2279
|
+
}
|
|
2280
|
+
return { targets, undecidable, detail };
|
|
2281
|
+
}
|
|
2282
|
+
|
|
2283
|
+
/**
|
|
2284
|
+
* 分类一条 shell 命令(四类判定;不读 flow,不判定相位)。
|
|
2285
|
+
*
|
|
2286
|
+
* op-002b 精化:
|
|
2287
|
+
* - `-EncodedCommand` / `iex` / `Invoke-Expression` / `eval` / `cmd /c` → 第 1 类硬拒(内容不可见);
|
|
2288
|
+
* - `node -e` / `python -c` / `perl -e` / `ruby -e` / `php -r` → **先扫 payload**:
|
|
2289
|
+
* 含写 API 才拒,纯只读诊断(`node -e "console.log(…)"`)放行且不审计(`readonly-interpreter`);
|
|
2290
|
+
* - `bash|sh -c` / `powershell|pwsh -Command` → **递归解析内层命令**(同一判定器),
|
|
2291
|
+
* 内层可判定按内层判;内层为空/不可判定 → 第 4 类(`undecidable`)。
|
|
2292
|
+
*
|
|
2293
|
+
* @param {{ command: string, baseDir: string, shell: 'bash'|'pwsh', depth?: number }} input
|
|
2294
|
+
* @returns {{ kind: 'indirect'|'openfeel-write'|'whole-tree'|'targets'|'undecidable'|'none'|'readonly-interpreter', detail: string, targets: string[], undecidable: boolean, phases?: string[] }}
|
|
2295
|
+
*/
|
|
2296
|
+
export function classifyShellCommand({ command, baseDir, shell, depth = 0 }) {
|
|
2297
|
+
const statements = splitShellStatements(command);
|
|
2298
|
+
// 同一命令内的字面量赋值(变量间接:只有「一次字面量赋值得到完整路径」才算第 2 类)
|
|
2299
|
+
const vars = collectLiteralAssignments(statements);
|
|
2300
|
+
|
|
2301
|
+
const targets = [];
|
|
2302
|
+
let undecidable = false;
|
|
2303
|
+
let detail = '';
|
|
2304
|
+
let readonlyInterpreter = false;
|
|
2305
|
+
|
|
2306
|
+
/** 记录一个目标(字面量 → 绝对路径;变量/派生 → 第 4 类)。 */
|
|
2307
|
+
const pushTarget = (raw) => {
|
|
2308
|
+
const resolved = resolveShellToken(raw, vars);
|
|
2309
|
+
if (!resolved.ok) {
|
|
2310
|
+
// ADS 形态(`.openfeel/flow.json::$DATA`):`$` 是流名,不是变量插值。
|
|
2311
|
+
// 截断到第一个非盘符 `:` 后路径是确定的 → 按第 2 类判(不再告警放行)。
|
|
2312
|
+
const prefix = adsPathPrefix(resolved.value);
|
|
2313
|
+
const retry = prefix === null ? null : resolveShellToken(prefix, vars);
|
|
2314
|
+
if (retry !== null && retry.ok) {
|
|
2315
|
+
targets.push(normalizeTarget(baseDir, retry.value));
|
|
2316
|
+
return;
|
|
2317
|
+
}
|
|
2318
|
+
undecidable = true;
|
|
2319
|
+
detail = detail || raw;
|
|
2320
|
+
return;
|
|
2321
|
+
}
|
|
2322
|
+
targets.push(normalizeTarget(baseDir, resolved.value));
|
|
2323
|
+
};
|
|
2324
|
+
|
|
2325
|
+
for (const statement of statements) {
|
|
2326
|
+
// 第 1 类:内容不可见的形态 → 硬拒
|
|
2327
|
+
const hard = matchHardIndirect(statement);
|
|
2328
|
+
if (hard !== null) return { kind: 'indirect', detail: hard, targets: [], undecidable: false };
|
|
2329
|
+
|
|
2330
|
+
// 第 1 类:shell 跑 openfeel 写子命令
|
|
2331
|
+
const openfeel = matchOpenFeelWrite(statement);
|
|
2332
|
+
if (openfeel !== null) return { kind: 'openfeel-write', detail: openfeel, targets: [], undecidable: false };
|
|
2333
|
+
|
|
2334
|
+
// 解释器内联:先扫 payload 写 API(只读诊断放行)
|
|
2335
|
+
const inline = matchInlineInterpreter(statement);
|
|
2336
|
+
if (inline !== null) {
|
|
2337
|
+
const writeApi = findWriteApi(inline.payload);
|
|
2338
|
+
if (writeApi !== null) {
|
|
2339
|
+
return { kind: 'indirect', detail: `${inline.tag} 含写操作 ${writeApi}`, targets: [], undecidable: false };
|
|
2340
|
+
}
|
|
2341
|
+
// payload 只读,但**重定向**仍是写入形态(`node -e "console.log(1)" > src/x.ts`)
|
|
2342
|
+
for (const raw of scanShellRedirections(statement).targets) pushTarget(raw);
|
|
2343
|
+
readonlyInterpreter = true;
|
|
2344
|
+
continue;
|
|
2345
|
+
}
|
|
2346
|
+
|
|
2347
|
+
// `-c` / `-Command` 包装器:递归解析内层命令
|
|
2348
|
+
if (depth < WRAPPER_MAX_DEPTH) {
|
|
2349
|
+
const wrapper = extractWrapperPayload(statement);
|
|
2350
|
+
if (wrapper !== null) {
|
|
2351
|
+
// 外层重定向同样算写入(`bash -c 'git status' > src/x.ts`)
|
|
2352
|
+
for (const raw of scanShellRedirections(statement).targets) pushTarget(raw);
|
|
2353
|
+
if (wrapper.payload === '' || payloadIsUnresolvable(wrapper.payload)) {
|
|
2354
|
+
undecidable = true;
|
|
2355
|
+
detail = detail || '`-c` / `-Command` 的内层命令为空或来自变量';
|
|
2356
|
+
continue;
|
|
2357
|
+
}
|
|
2358
|
+
const nested = classifyShellCommand({
|
|
2359
|
+
command: wrapper.payload,
|
|
2360
|
+
baseDir,
|
|
2361
|
+
shell: wrapper.shell,
|
|
2362
|
+
depth: depth + 1,
|
|
2363
|
+
});
|
|
2364
|
+
if (nested.kind === 'indirect' || nested.kind === 'openfeel-write' || nested.kind === 'whole-tree') return nested;
|
|
2365
|
+
targets.push(...nested.targets);
|
|
2366
|
+
if (nested.undecidable) {
|
|
2367
|
+
undecidable = true;
|
|
2368
|
+
detail = detail || nested.detail || '内层命令目标不可判定';
|
|
2369
|
+
}
|
|
2370
|
+
continue;
|
|
2371
|
+
}
|
|
2372
|
+
}
|
|
2373
|
+
|
|
2374
|
+
// 命令替换 / 反引号的内层命令在 `analyzeShellStatement` 里**叠加**判定为第 4 类
|
|
2375
|
+
// (不和 git 整树写等更强结论二选一)。
|
|
2376
|
+
const analysis = analyzeShellStatement(statement, shell, baseDir, vars);
|
|
2377
|
+
if (analysis.wholeTree !== undefined) {
|
|
2378
|
+
return {
|
|
2379
|
+
kind: 'whole-tree',
|
|
2380
|
+
detail: analysis.wholeTree,
|
|
2381
|
+
phases: analysis.wholeTreePhases,
|
|
2382
|
+
preservesWorktree: analysis.wholeTreePreservesWorktree === true,
|
|
2383
|
+
destroysUntracked: analysis.wholeTreeDestroysUntracked === true,
|
|
2384
|
+
purgesIgnored: analysis.wholeTreePurgesIgnored === true,
|
|
2385
|
+
targets: [],
|
|
2386
|
+
undecidable: false,
|
|
2387
|
+
};
|
|
2388
|
+
}
|
|
2389
|
+
for (const raw of analysis.targets) pushTarget(raw);
|
|
2390
|
+
if (analysis.undecidable) {
|
|
2391
|
+
undecidable = true;
|
|
2392
|
+
detail = detail || analysis.detail;
|
|
2393
|
+
}
|
|
2394
|
+
}
|
|
2395
|
+
|
|
2396
|
+
if (targets.length === 0) {
|
|
2397
|
+
// 只有只读解释器调用 → 放行且不审计(日常诊断噪音为零)
|
|
2398
|
+
if (readonlyInterpreter && !undecidable) {
|
|
2399
|
+
return { kind: 'readonly-interpreter', detail, targets, undecidable };
|
|
2400
|
+
}
|
|
2401
|
+
// 第 4 类(op-005 / P0-1):**没有正面证据**证明「这条命令不写」→ undecidable,
|
|
2402
|
+
// 不再返回 `none` 静默放行。审计的 `kind` 因此能区分 no-write 与 undecidable。
|
|
2403
|
+
if (undecidable) return { kind: 'undecidable', detail: detail || '命令写入意图无法判定', targets, undecidable };
|
|
2404
|
+
return { kind: 'none', detail, targets, undecidable };
|
|
2405
|
+
}
|
|
2406
|
+
return { kind: 'targets', targets, undecidable, detail };
|
|
2407
|
+
}
|
|
2408
|
+
|
|
2409
|
+
/**
|
|
2410
|
+
* Win32 备用数据流(ADS)形态的路径前缀(op-005 / P0-2 配套)。
|
|
2411
|
+
*
|
|
2412
|
+
* `flow.json::$DATA` / `flow.json:stream` 里的 `$` 是**流名**而不是变量插值,
|
|
2413
|
+
* 但 `resolveShellToken` 看到 `$` 就判不可判定 → 会落到第 4 类告警放行。
|
|
2414
|
+
* 截断到第一个「非盘符」`:` 之后,路径部分是确定的字面量,可按第 2 类判。
|
|
2415
|
+
*
|
|
2416
|
+
* @param {string} raw
|
|
2417
|
+
* @returns {string | null}
|
|
2418
|
+
*/
|
|
2419
|
+
function adsPathPrefix(raw) {
|
|
2420
|
+
const text = String(raw);
|
|
2421
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
2422
|
+
if (text[index] !== ':') continue;
|
|
2423
|
+
// 盘符(`C:\…`)不算 ADS 分隔符。
|
|
2424
|
+
if (index === 1 && /[A-Za-z]/.test(text[0]) && /[\\/]/.test(text[2] ?? '')) continue;
|
|
2425
|
+
const prefix = text.slice(0, index);
|
|
2426
|
+
if (prefix === '' || /[$`]/.test(prefix)) return null;
|
|
2427
|
+
return prefix;
|
|
2428
|
+
}
|
|
2429
|
+
return null;
|
|
2430
|
+
}
|
|
2431
|
+
|
|
2432
|
+
/**
|
|
2433
|
+
* 从 shell 工具参数提取命令与工作目录。
|
|
2434
|
+
*
|
|
2435
|
+
* 真机 `bash` / `pwsh` 的参数是 `command` + `workdir`;`script` / `cmd` 兼容其它宿主。
|
|
2436
|
+
* 相对路径的基准是 **`workdir ?? guard cwd`**(`baseDir = resolve(guardCwd, workdir ?? '.')`),
|
|
2437
|
+
* 否则在子目录里跑 shell 会把目标解析到错误的项目根(误放/误拒)。
|
|
2438
|
+
* @param {unknown} args
|
|
2439
|
+
* @returns {{ command: string | undefined, workdir: string | undefined }}
|
|
2440
|
+
*/
|
|
2441
|
+
export function extractShellCommand(args) {
|
|
2442
|
+
if (typeof args !== 'object' || args === null) return { command: undefined, workdir: undefined };
|
|
2443
|
+
const record = /** @type {Record<string, unknown>} */ (args);
|
|
2444
|
+
let command;
|
|
2445
|
+
for (const key of ['command', 'script', 'cmd']) {
|
|
2446
|
+
const value = record[key];
|
|
2447
|
+
if (typeof value === 'string' && value.trim() !== '') { command = value; break; }
|
|
2448
|
+
}
|
|
2449
|
+
const rawWorkdir = record.workdir;
|
|
2450
|
+
const workdir = typeof rawWorkdir === 'string' && rawWorkdir.trim() !== '' ? rawWorkdir.trim() : undefined;
|
|
2451
|
+
return { command, workdir };
|
|
2452
|
+
}
|
|
2453
|
+
|
|
2454
|
+
/**
|
|
2455
|
+
* 读取 flow.json(同步、按 mtime/size 缓存)。
|
|
2456
|
+
* @param {string} cwd
|
|
2457
|
+
* @returns {{ ok: true, value: any } | { ok: false, reason: string }}
|
|
2458
|
+
*/
|
|
2459
|
+
function readFlow(cwd) {
|
|
2460
|
+
const path = join(cwd, OPENFEEL_DIR, 'flow.json');
|
|
2461
|
+
try {
|
|
2462
|
+
const stat = statSync(path);
|
|
2463
|
+
const cached = flowCache.get(path);
|
|
2464
|
+
if (cached !== undefined && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) {
|
|
2465
|
+
return { ok: true, value: cached.value };
|
|
2466
|
+
}
|
|
2467
|
+
const value = JSON.parse(readFileSync(path, 'utf8'));
|
|
2468
|
+
flowCache.set(path, { mtimeMs: stat.mtimeMs, size: stat.size, value });
|
|
2469
|
+
return { ok: true, value };
|
|
2470
|
+
} catch (error) {
|
|
2471
|
+
return {
|
|
2472
|
+
ok: false,
|
|
2473
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
2474
|
+
};
|
|
2475
|
+
}
|
|
2476
|
+
}
|
|
2477
|
+
|
|
2478
|
+
/**
|
|
2479
|
+
* 是否存在 general 模式的 in_progress 需求(允许无阶段直接改)。
|
|
2480
|
+
* @param {any} flow
|
|
2481
|
+
* @returns {boolean}
|
|
2482
|
+
*/
|
|
2483
|
+
function hasGeneralRequirement(flow) {
|
|
2484
|
+
const requirements = flow?.requirements;
|
|
2485
|
+
if (!Array.isArray(requirements)) return false;
|
|
2486
|
+
return requirements.some((requirement) => requirement
|
|
2487
|
+
&& requirement.status === 'in_progress'
|
|
2488
|
+
&& requirement.workflow_mode === 'general');
|
|
2489
|
+
}
|
|
2490
|
+
|
|
2491
|
+
/** 活跃阶段(phase !== done)。 */
|
|
2492
|
+
function activeStages(flow) {
|
|
2493
|
+
const stages = flow?.stages;
|
|
2494
|
+
if (typeof stages !== 'object' || stages === null) return [];
|
|
2495
|
+
return Object.entries(stages)
|
|
2496
|
+
.filter(([, stage]) => stage && stage.phase !== 'done')
|
|
2497
|
+
.map(([id, stage]) => ({ ...stage, id }));
|
|
2498
|
+
}
|
|
2499
|
+
|
|
2500
|
+
/**
|
|
2501
|
+
* 活跃阶段相位摘要(审计/拒绝文案用):`v1-stage=plan_review, v2-stage=exec_running`。
|
|
2502
|
+
* @param {Array<{ id?: string, phase?: string }>} active
|
|
2503
|
+
* @returns {string}
|
|
2504
|
+
*/
|
|
2505
|
+
function formatActivePhases(active) {
|
|
2506
|
+
return active
|
|
2507
|
+
.map((stage) => `${stage.id ?? '(unknown)'}=${stage.phase ?? '(unknown)'}`)
|
|
2508
|
+
.join(', ');
|
|
2509
|
+
}
|
|
2510
|
+
|
|
2511
|
+
/**
|
|
2512
|
+
* 统一的目标判定(v1.5.11 D-126-02;plan §3.1⑤ 的纯重构)。
|
|
2513
|
+
*
|
|
2514
|
+
* 文件工具分支(`write`/`edit`/`str_replace_editor`/`apply_patch`)与 shell 分支
|
|
2515
|
+
* 共用**这一份**判定,保证「经 shell 绕道」与「直接写文件」得到完全相同的结论:
|
|
2516
|
+
* 受保护路径 → 未初始化/bootstrap → 内部路径早返回 → 研究闸 → 无阶段/chore/
|
|
2517
|
+
* doc-asset → 相位判定,逐行语义与重构前一致(零复制、零漂移)。
|
|
2518
|
+
*
|
|
2519
|
+
* 判定顺序里「受保护路径」必须在 `allInternal` 早返回与相位判定之前 —— 否则
|
|
2520
|
+
* `.openfeel/**` 任意相位可写会让 agent 手写 `chore.json` / `.preflight.json` 自提权。
|
|
2521
|
+
*
|
|
2522
|
+
* @param {{ t: (zh: string, en: string) => string, enforce: 'off'|'project'|'always', allowGeneral: boolean, bootstrapHinted: Set<string> }} context
|
|
2523
|
+
* @param {{ name: string, targets: string[], patchEntries?: Array<{ path: string, kind: string }> | null, resolvedCwd: string, normalizedCwd: string, cwdSource: string, audit?: boolean }} request
|
|
2524
|
+
* @returns {{ decision: 'allow'|'deny', reason: string, message?: string }}
|
|
2525
|
+
*/
|
|
2526
|
+
function decideForTargets(context, request) {
|
|
2527
|
+
const { t, enforce, allowGeneral, bootstrapHinted } = context;
|
|
2528
|
+
const { name, targets, resolvedCwd, normalizedCwd, cwdSource } = request;
|
|
2529
|
+
const patchEntries = request.patchEntries ?? null;
|
|
2530
|
+
const recordAudit = (event) => {
|
|
2531
|
+
if (request.audit === false) return;
|
|
2532
|
+
recordGuardAudit(normalizedCwd, {
|
|
2533
|
+
tool: name,
|
|
2534
|
+
cwdSource,
|
|
2535
|
+
paths: targets,
|
|
2536
|
+
...event,
|
|
2537
|
+
});
|
|
2538
|
+
};
|
|
2539
|
+
|
|
2540
|
+
// 受保护路径(D-126-05):guard 启用时始终拒绝(enforce=off 已提前返回)。
|
|
2541
|
+
// 位置要求见函数注释;这里是唯一入口,文件工具与 shell 都经过它。
|
|
2542
|
+
const protectedHits = targets
|
|
2543
|
+
.map((target) => matchProtectedPath(target, normalizedCwd))
|
|
2544
|
+
.filter((hit) => hit !== null);
|
|
2545
|
+
if (protectedHits.length > 0) {
|
|
2546
|
+
return { decision: 'deny', reason: 'protected', message: protectedDenialMessage(protectedHits, t) };
|
|
2547
|
+
}
|
|
2548
|
+
|
|
2549
|
+
const initialized = isProjectWorkspace(resolvedCwd);
|
|
2550
|
+
if (!initialized) {
|
|
2551
|
+
if (enforce === 'always') {
|
|
2552
|
+
// P0-1 bootstrap 例外:空工作区 + 全部为「新增文件」→ 放行(最高风险等级不成立)。
|
|
2553
|
+
// apply_patch 额外要求全部 block 为 `*** Add File:`(Update/Delete/Move/混合一律从严)。
|
|
2554
|
+
// `.openfeel/**` 不适用:流程产物仍要求先 init(B8)。
|
|
2555
|
+
const allNew = targets.every((target) => !existsSync(target));
|
|
2556
|
+
const anyInternal = targets.some((target) => isUnderOpenFeel(target, normalizedCwd));
|
|
2557
|
+
const allInside = targets.every((target) => isUnderWorkspace(target, normalizedCwd));
|
|
2558
|
+
const addOnly = patchEntries === null || patchEntries.every((entry) => entry.kind === 'add');
|
|
2559
|
+
if (allNew && addOnly && !anyInternal && allInside) {
|
|
2560
|
+
if (!bootstrapHinted.has(normalizedCwd)) {
|
|
2561
|
+
bootstrapHinted.add(normalizedCwd);
|
|
2562
|
+
process.stderr.write(
|
|
2563
|
+
`${t(
|
|
2564
|
+
'OpenFeel 写入门禁:[bootstrap] 工作区尚未初始化,已放行本次新增文件;建议稍后运行 `openfeel init` 补账本。',
|
|
2565
|
+
'OpenFeel write guard: [bootstrap] workspace not initialized; this new-file write was allowed. Run `openfeel init` later to record it.',
|
|
2566
|
+
)}\n`,
|
|
2567
|
+
);
|
|
2568
|
+
}
|
|
2569
|
+
return { decision: 'allow', reason: 'bootstrap' };
|
|
2570
|
+
}
|
|
2571
|
+
return {
|
|
2572
|
+
decision: 'deny',
|
|
2573
|
+
reason: 'not-initialized',
|
|
2574
|
+
message: t(
|
|
2575
|
+
'OpenFeel 写入门禁:当前工作区尚未初始化 OpenFeel(无 `.openfeel/`)。请先运行 `openfeel init` 并建立需求/阶段;或让用户把 profile 的 `enforce` 改为 `project` / `off`。',
|
|
2576
|
+
'OpenFeel write guard: this workspace is not OpenFeel-initialized (no `.openfeel/`). Run `openfeel init` and create a requirement/stage first; or ask the user to set `enforce` to `project` / `off`.',
|
|
2577
|
+
),
|
|
2578
|
+
};
|
|
2579
|
+
}
|
|
2580
|
+
return { decision: 'allow', reason: 'not-initialized' };
|
|
2581
|
+
}
|
|
2582
|
+
|
|
2583
|
+
const allInternal = targets.every((target) => isUnderOpenFeel(target, normalizedCwd));
|
|
2584
|
+
if (allInternal) return { decision: 'allow', reason: 'internal' };
|
|
2585
|
+
|
|
2586
|
+
const flow = readFlow(resolvedCwd);
|
|
2587
|
+
if (!flow.ok) {
|
|
2588
|
+
return {
|
|
2589
|
+
decision: 'deny',
|
|
2590
|
+
reason: 'flow-unreadable',
|
|
2591
|
+
message: t(
|
|
2592
|
+
`OpenFeel 写入门禁:无法读取 .openfeel/flow.json(${flow.reason})。请运行 feel_verify action=health。`,
|
|
2593
|
+
`OpenFeel write guard: cannot read .openfeel/flow.json (${flow.reason}). Run feel_verify action=health.`,
|
|
2594
|
+
),
|
|
2595
|
+
};
|
|
2596
|
+
}
|
|
2597
|
+
|
|
2598
|
+
const active = activeStages(flow.value);
|
|
2599
|
+
// v1.5.2 入口闸:研究/方案产物(docs/research/**)是阶段交付物,无活跃阶段时不得写入;
|
|
2600
|
+
// chore 也不能绕过(在下方 chore 放行之前判定)。
|
|
2601
|
+
if (active.length === 0 && targets.some((target) => isResearchArtifactPath(target, normalizedCwd))) {
|
|
2602
|
+
recordAudit({ event: 'guard_deny', reason: 'research-needs-stage', phase: 'done' });
|
|
2603
|
+
return {
|
|
2604
|
+
decision: 'deny',
|
|
2605
|
+
reason: 'research-needs-stage',
|
|
2606
|
+
message: t(
|
|
2607
|
+
'OpenFeel 写入门禁:研究/方案产物(docs/research/**)要求有开启的阶段。请先按当前小版本开一个阶段(保持 exec_running),再 feel_req add → claim 建需求并写调研/方案。纯只读问答无需落盘。',
|
|
2608
|
+
'OpenFeel write guard: research/proposal artifacts (docs/research/**) require an open stage. Open a stage for the current minor version (keep it in exec_running), then feel_req add → claim before writing. Pure read-only Q&A needs no file.',
|
|
2609
|
+
),
|
|
2610
|
+
};
|
|
2611
|
+
}
|
|
2612
|
+
if (active.length === 0) {
|
|
2613
|
+
if (allowGeneral && hasGeneralRequirement(flow.value)) return { decision: 'allow', reason: 'general' };
|
|
2614
|
+
// v1.4.0 chore 通道:仅在**无活跃阶段**时生效;受保护路径已在上方拒绝。
|
|
2615
|
+
// v1.5.11 / D-126-03 收窄:chore 窗口**默认不放行源码**(doc/asset 本来就不需要
|
|
2616
|
+
// chore)。只有人类以 `openfeel chore --source "<说明>"` 开启、且 chore.json 写了
|
|
2617
|
+
// `source_allowed: true` 时才放行源码;旧记录缺该字段一律视为未授权。
|
|
2618
|
+
const activeChore = readActiveChore(normalizedCwd);
|
|
2619
|
+
if (activeChore !== null) {
|
|
2620
|
+
const sourceAllowed = activeChore.source_allowed === true;
|
|
2621
|
+
if (sourceAllowed || targets.every((target) => isExemptPath(target, normalizedCwd))) {
|
|
2622
|
+
recordAudit({ reason: 'chore', phase: 'done' });
|
|
2623
|
+
return { decision: 'allow', reason: 'chore' };
|
|
2624
|
+
}
|
|
2625
|
+
recordAudit({ event: 'guard_deny', reason: 'chore-source', phase: 'done' });
|
|
2626
|
+
return {
|
|
2627
|
+
decision: 'deny',
|
|
2628
|
+
reason: 'chore-source',
|
|
2629
|
+
message: t(
|
|
2630
|
+
'OpenFeel 写入门禁:当前 chore 窗口未授予源码写入(默认只放行 doc/静态资源)。需要改源码时,请由人类在外部终端执行 `openfeel chore --source "<说明>"` 开启窗口;或按当前小版本开一个阶段并保持 exec_running。',
|
|
2631
|
+
'OpenFeel write guard: this chore window does not allow source writes (the default window covers docs/static assets only). To change source, ask the human to run `openfeel chore --source "<note>"` from an external terminal, or open a stage for the current minor version and keep it in exec_running.',
|
|
2632
|
+
),
|
|
2633
|
+
};
|
|
2634
|
+
}
|
|
2635
|
+
// P0-4/v1.4.0:doc/note 与静态展示资源不要求活跃阶段(收口后仍可写);混合目标从严。
|
|
2636
|
+
if (targets.every((target) => isExemptPath(target, normalizedCwd))) {
|
|
2637
|
+
recordAudit({ reason: 'doc-asset', phase: 'done' });
|
|
2638
|
+
return { decision: 'allow', reason: 'doc-asset' };
|
|
2639
|
+
}
|
|
2640
|
+
return {
|
|
2641
|
+
decision: 'deny',
|
|
2642
|
+
reason: 'no-stage',
|
|
2643
|
+
message: t(
|
|
2644
|
+
'OpenFeel 写入门禁:无活跃阶段,不能修改源码/文档(当前没有开启的阶段)。默认按当前小版本开一个阶段并保持 exec_running(feel_stage add stage=<vX.Y.Z-stage-N>),再在该版本下建需求推进;需求完成不要求关闭阶段。只改 doc/静态资源的微变更可由人类在外部终端 `openfeel chore "<说明>"` 开启;改源码必须由人类用 `openfeel chore --source "<说明>"`。',
|
|
2645
|
+
'OpenFeel write guard: no active stage (no open stage), so source/docs are read-only. Open a stage for the current minor version and keep it in exec_running (feel_stage add stage=<vX.Y.Z-stage-N>), then add requirements under that version; requirement completion does not require closing the stage. For docs/static-asset-only micro-changes the human can run `openfeel chore "<note>"` from an external terminal; source changes require `openfeel chore --source "<note>"`.',
|
|
2646
|
+
),
|
|
2647
|
+
};
|
|
2648
|
+
}
|
|
2649
|
+
|
|
2650
|
+
if (active.some((stage) => stage.phase === 'exec_running')) return { decision: 'allow', reason: 'exec-running' };
|
|
2651
|
+
// P0-4/v1.4.0:非 exec 相位仍允许 doc/note 与静态展示资源(研究记录、设计文档、UI 资源等);源码仍严格。
|
|
2652
|
+
if (targets.every((target) => isExemptPath(target, normalizedCwd))) {
|
|
2653
|
+
recordAudit({ reason: 'doc-asset', phase: formatActivePhases(active) });
|
|
2654
|
+
return { decision: 'allow', reason: 'doc-asset' };
|
|
2655
|
+
}
|
|
2656
|
+
|
|
2657
|
+
return {
|
|
2658
|
+
decision: 'deny',
|
|
2659
|
+
reason: 'phase',
|
|
2660
|
+
message: t(
|
|
2661
|
+
`OpenFeel 写入门禁:活跃阶段当前不在 exec_running(${formatActivePhases(active)}),不能修改源码/文档。请先 feel_flow action=advance 推进到 exec_running。`,
|
|
2662
|
+
`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.`,
|
|
2663
|
+
),
|
|
2664
|
+
};
|
|
2665
|
+
}
|
|
2666
|
+
|
|
2667
|
+
/**
|
|
2668
|
+
* 整树写(git `reset --hard` / `stash pop` / `clean` / `commit` …)是否被允许:
|
|
2669
|
+
* **必须**存在 `exec_running` 阶段(与文件工具的源码写门槛一致)。
|
|
2670
|
+
* 未初始化工作区沿用 `enforce` 语义(`always` 下 fail-closed)。
|
|
2671
|
+
* @param {string} resolvedCwd
|
|
2672
|
+
* @param {'off'|'project'|'always'} enforce
|
|
2673
|
+
* @param {string[]} [phases] 放行的相位(缺省 `['exec_running']`;`git commit` 额外允许 `archiving`)
|
|
2674
|
+
* @returns {boolean}
|
|
2675
|
+
*/
|
|
2676
|
+
function allowsWholeTreeWrite(resolvedCwd, enforce, phases = ['exec_running']) {
|
|
2677
|
+
if (!isProjectWorkspace(resolvedCwd)) return enforce !== 'always';
|
|
2678
|
+
const flow = readFlow(resolvedCwd);
|
|
2679
|
+
if (!flow.ok) return false;
|
|
2680
|
+
const allowed = new Set(phases);
|
|
2681
|
+
return activeStages(flow.value).some((stage) => allowed.has(stage.phase));
|
|
2682
|
+
}
|
|
2683
|
+
|
|
2684
|
+
/**
|
|
2685
|
+
* `.openfeel/**` 是否有未提交差异(op-005 / P1-2;op-006 / P1-1 补未跟踪)。
|
|
2686
|
+
*
|
|
2687
|
+
* 整树 git 写(`checkout -- .` / `reset --hard` / `stash pop` / `clean -fdx`)
|
|
2688
|
+
* 会把 `.openfeel/flow.json`、`chore.json`、`guard-audit.jsonl` 一起覆盖,
|
|
2689
|
+
* 「受保护路径任意相位硬拒」就形同虚设。执行整树写前要求该目录干净。
|
|
2690
|
+
*
|
|
2691
|
+
* **未跟踪文件**(op-006):`git diff` 系列看不到它们,而 `checkpoints/`、
|
|
2692
|
+
* 新 plan 目录、`chore.json` 恰恰常常是未跟踪的 —— `git clean -fdx` 会直接删掉。
|
|
2693
|
+
* 所以对**会删未跟踪文件**的整树写(`git clean`、`stash -u`)追加
|
|
2694
|
+
* `git ls-files --others --exclude-standard -- .openfeel`:非空即 dirty。
|
|
2695
|
+
* 带了 `-x`/`-X`(连 ignored 一起删)时还要看**证据文件是否存在**:
|
|
2696
|
+
* `log/guard-audit.jsonl` 与 `chore.json` 本身被 .gitignore 忽略,
|
|
2697
|
+
* `git ls-files --exclude-standard` 看不见它们,但 `clean -fdx` 会删掉。
|
|
2698
|
+
* `checkout`/`reset` **不动**未跟踪文件,不套这两条(否则会把正常工作流误拒)。
|
|
2699
|
+
*
|
|
2700
|
+
* 返回 `true` = 有差异(拒绝);`false` = 干净;`null` = 无法判定
|
|
2701
|
+
* (不是 git 仓库 / 无 HEAD / git 不可用 → 按「无证据」放行,保持旧行为)。
|
|
2702
|
+
*
|
|
2703
|
+
* @param {string} resolvedCwd
|
|
2704
|
+
* @param {{ includeUntracked?: boolean, includeIgnoredEvidence?: boolean }} [options]
|
|
2705
|
+
* @returns {boolean | null}
|
|
2706
|
+
*/
|
|
2707
|
+
function openfeelTreeDirty(resolvedCwd, options = {}) {
|
|
2708
|
+
const run = (args, capture = false) => {
|
|
2709
|
+
try {
|
|
2710
|
+
const stdout = execFileSync('git', args, {
|
|
2711
|
+
cwd: resolvedCwd,
|
|
2712
|
+
stdio: capture ? ['ignore', 'pipe', 'ignore'] : 'ignore',
|
|
2713
|
+
encoding: 'utf8',
|
|
2714
|
+
timeout: 5000,
|
|
2715
|
+
windowsHide: true,
|
|
2716
|
+
});
|
|
2717
|
+
return { status: 0, stdout: typeof stdout === 'string' ? stdout : '' };
|
|
2718
|
+
} catch (error) {
|
|
2719
|
+
const status = error !== null && typeof error === 'object' && Number.isInteger(error.status)
|
|
2720
|
+
? error.status
|
|
2721
|
+
: null;
|
|
2722
|
+
return { status, stdout: '' };
|
|
2723
|
+
}
|
|
2724
|
+
};
|
|
2725
|
+
// 先确认「是 git 仓库且有 HEAD」:非仓库目录里 `git diff` 会退化成
|
|
2726
|
+
// `--no-index` 模式并以 1 退出(会被误读成「有差异」)。
|
|
2727
|
+
if (run(['rev-parse', '--git-dir']).status !== 0) return null;
|
|
2728
|
+
if (run(['rev-parse', '--verify', '--quiet', 'HEAD']).status !== 0) return null;
|
|
2729
|
+
const head = run(['diff', '--quiet', 'HEAD', '--', OPENFEEL_DIR]).status;
|
|
2730
|
+
if (head === 1) return true;
|
|
2731
|
+
if (head !== 0) return null;
|
|
2732
|
+
const cached = run(['diff', '--cached', '--quiet', '--', OPENFEEL_DIR]).status;
|
|
2733
|
+
if (cached === 1) return true;
|
|
2734
|
+
if (cached !== 0) return null;
|
|
2735
|
+
if (options.includeUntracked === true) {
|
|
2736
|
+
// 未跟踪且**未被 .gitignore 忽略**的 `.openfeel/**`(checkpoints / 新 plan /
|
|
2737
|
+
// 手写 chore.json 等)会被 `git clean` 删掉 → 同样算 dirty。
|
|
2738
|
+
const others = run(['ls-files', '--others', '--exclude-standard', '--', OPENFEEL_DIR], true);
|
|
2739
|
+
if (others.status !== 0) return null;
|
|
2740
|
+
if (others.stdout.trim() !== '') return true;
|
|
2741
|
+
}
|
|
2742
|
+
if (options.includeIgnoredEvidence === true) {
|
|
2743
|
+
// `clean -x` 连 ignored 一起删:审计证据与 chore 窗口是「被忽略但绝不能删」的
|
|
2744
|
+
// 两类文件,直接看存在性(`git ls-files` 默认看不见它们)。
|
|
2745
|
+
for (const relative of [join('log', 'guard-audit.jsonl'), 'chore.json']) {
|
|
2746
|
+
if (existsSync(join(resolvedCwd, OPENFEEL_DIR, relative))) return true;
|
|
2747
|
+
}
|
|
2748
|
+
}
|
|
2749
|
+
return false;
|
|
2750
|
+
}
|
|
2751
|
+
|
|
2752
|
+
/**
|
|
2753
|
+
* 生成守卫。
|
|
2754
|
+
*
|
|
2755
|
+
* @param {object} options
|
|
2756
|
+
* @param {'off'|'project'|'always'} [options.enforce]
|
|
2757
|
+
* @param {string[]} [options.mutatingTools]
|
|
2758
|
+
* @param {boolean} [options.allowGeneral]
|
|
2759
|
+
* @param {'zh-CN'|'en'} [options.language]
|
|
2760
|
+
* @param {string} [options.cwd] 无会话时的兜底目录(通常为 config.cwd)
|
|
2761
|
+
* @param {'strict'|'warn'|'off'} [options.shellGate]
|
|
2762
|
+
* shell 门禁档位。缺省读 `OPENFEEL_SHELL_GATE`(环境变量优先,作逃生阀);两者都没有 =
|
|
2763
|
+
* 默认组合(1/2 类拒、4 类告警)。**只影响 shell 分支**,不影响文件工具。
|
|
2764
|
+
* @returns {(execution: { name?: string, arguments?: unknown, agent?: { session?: { header?: { cwd?: string } } } }) => string | undefined}
|
|
2765
|
+
*/
|
|
2766
|
+
export function createOpenFeelGuard(options = {}) {
|
|
2767
|
+
const enforce = options.enforce === 'off' || options.enforce === 'project' || options.enforce === 'always'
|
|
2768
|
+
? options.enforce
|
|
2769
|
+
: 'always';
|
|
2770
|
+
const mutating = new Set(Array.isArray(options.mutatingTools) && options.mutatingTools.length > 0
|
|
2771
|
+
? options.mutatingTools
|
|
2772
|
+
: DEFAULT_MUTATING_TOOLS);
|
|
2773
|
+
const allowGeneral = options.allowGeneral !== false;
|
|
2774
|
+
const english = options.language === 'en';
|
|
2775
|
+
const fallbackCwd = typeof options.cwd === 'string' && options.cwd !== '' ? options.cwd : undefined;
|
|
2776
|
+
// shell 门禁档位在**创建时**读一次(换档需要重建 guard / 重启宿主)。
|
|
2777
|
+
const shellGate = resolveShellGate(
|
|
2778
|
+
typeof process.env.OPENFEEL_SHELL_GATE === 'string' && process.env.OPENFEEL_SHELL_GATE.trim() !== ''
|
|
2779
|
+
? process.env.OPENFEEL_SHELL_GATE
|
|
2780
|
+
: options.shellGate,
|
|
2781
|
+
);
|
|
399
2782
|
|
|
400
2783
|
const t = (zh, en) => (english ? en : zh);
|
|
401
2784
|
/** bootstrap 例外提示去重(按工作区路径)。 */
|
|
402
2785
|
const bootstrapHinted = new Set();
|
|
2786
|
+
const guardContext = { t, enforce, allowGeneral, bootstrapHinted };
|
|
403
2787
|
|
|
404
2788
|
if (enforce === 'off') {
|
|
405
|
-
// 完全关闭:连 flow.json/status.md
|
|
2789
|
+
// 完全关闭:连 flow.json/status.md 也不拦(D-126-01 的 cwd 链同样不启用)。
|
|
406
2790
|
return () => undefined;
|
|
407
2791
|
}
|
|
408
2792
|
|
|
@@ -410,11 +2794,240 @@ export function createOpenFeelGuard(options = {}) {
|
|
|
410
2794
|
const name = execution?.name;
|
|
411
2795
|
if (typeof name !== 'string' || !mutating.has(name)) return undefined;
|
|
412
2796
|
|
|
413
|
-
const
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
2797
|
+
const isShell = SHELL_TOOL_SET.has(name);
|
|
2798
|
+
// `OPENFEEL_SHELL_GATE=off` **只关 shell 分支**:完全不解析命令;
|
|
2799
|
+
// `write` / `edit` / `str_replace_editor` 仍然走完整门禁。
|
|
2800
|
+
if (isShell && shellGate.mode === 'off') return undefined;
|
|
2801
|
+
|
|
2802
|
+
// ── cwd 解析链(D-126-01):env → agent-session → config → registry → process → fail-closed
|
|
2803
|
+
const resolution = resolveGuardCwd(execution, { cwd: fallbackCwd });
|
|
2804
|
+
const cwdSource = resolution.source;
|
|
2805
|
+
const resolvedCwd = resolution.cwd;
|
|
2806
|
+
// 与写入目标**同一套**归一化(P0-2):短名/尾点/ADS 归一后再做前缀比较。
|
|
2807
|
+
const normalizedCwd = resolvedCwd === null ? null : normalizeTarget(resolvedCwd, '.');
|
|
2808
|
+
const degraded = resolution.degraded;
|
|
2809
|
+
const shellCommand = isShell ? extractShellCommand(execution?.arguments).command : undefined;
|
|
2810
|
+
|
|
2811
|
+
/** 判定结论落盘(D-126-04):每次放行/拒绝/告警都更新 lastDecision。 */
|
|
2812
|
+
const recordDecision = (decision, { reason, paths = [], command = shellCommand }) => {
|
|
2813
|
+
const at = new Date().toISOString();
|
|
2814
|
+
const lastDecision = {
|
|
2815
|
+
at,
|
|
2816
|
+
tool: name,
|
|
2817
|
+
decision,
|
|
2818
|
+
reason,
|
|
2819
|
+
paths,
|
|
2820
|
+
cwd: resolvedCwd,
|
|
2821
|
+
cwdSource,
|
|
2822
|
+
...(truncateCommand(command) !== undefined ? { command: truncateCommand(command) } : {}),
|
|
2823
|
+
};
|
|
2824
|
+
writeGuardState(resolvedCwd, {
|
|
2825
|
+
registered: true,
|
|
2826
|
+
enforce,
|
|
2827
|
+
shellGate: shellGate.label,
|
|
2828
|
+
cwd: resolvedCwd,
|
|
2829
|
+
cwdSource,
|
|
2830
|
+
degraded,
|
|
2831
|
+
resolvedAt: at,
|
|
2832
|
+
pid: process.pid,
|
|
2833
|
+
lastDecision,
|
|
2834
|
+
}, { at, tool: name, reason, decision, cwdSource });
|
|
2835
|
+
};
|
|
2836
|
+
|
|
2837
|
+
// 全链失败 → fail-closed:证据固定落全局目录(绝不用 process.cwd(),绝不静默)
|
|
2838
|
+
if (resolvedCwd === null || normalizedCwd === null) {
|
|
2839
|
+
const message = t(
|
|
2840
|
+
'OpenFeel 写入门禁:无法确定会话工作区(cwd 解析失败),已按 fail-closed 拒绝本次写入。修复(任一):① profile 的 cordis.patch.yml 给 openfeel-feel 配 cwd: "<项目绝对路径>";② 设环境变量 OPENFEEL_GUARD_CWD 后重启;③ 重启会话让提示装配登记 cwd。诊断:feel_status 的 guard 段(.openfeel/dev/guard-state.json)。',
|
|
2841
|
+
'OpenFeel write guard: cannot resolve the session workspace (cwd resolution failed); refusing this write (fail-closed). Fix one of: (1) set cwd: "<absolute project path>" for openfeel-feel in cordis.patch.yml; (2) set OPENFEEL_GUARD_CWD and restart; (3) restart the session so the prompt assembly records the cwd. Diagnose: the guard section of feel_status.',
|
|
2842
|
+
);
|
|
2843
|
+
writeGuardState(null, {
|
|
2844
|
+
registered: true,
|
|
2845
|
+
enforce,
|
|
2846
|
+
shellGate: shellGate.label,
|
|
2847
|
+
cwd: null,
|
|
2848
|
+
cwdSource: 'unresolved',
|
|
2849
|
+
degraded: true,
|
|
2850
|
+
hostCwd: process.cwd(),
|
|
2851
|
+
resolvedAt: new Date().toISOString(),
|
|
2852
|
+
pid: process.pid,
|
|
2853
|
+
lastDecision: {
|
|
2854
|
+
at: new Date().toISOString(),
|
|
2855
|
+
tool: name,
|
|
2856
|
+
decision: 'deny',
|
|
2857
|
+
reason: 'cwd-unresolved',
|
|
2858
|
+
paths: [],
|
|
2859
|
+
cwd: null,
|
|
2860
|
+
cwdSource: 'unresolved',
|
|
2861
|
+
...(truncateCommand(shellCommand) !== undefined ? { command: truncateCommand(shellCommand) } : {}),
|
|
2862
|
+
},
|
|
2863
|
+
}, { at: new Date().toISOString(), tool: name, reason: 'cwd-unresolved', decision: 'deny', cwdSource: 'unresolved' });
|
|
2864
|
+
recordGuardAudit(null, {
|
|
2865
|
+
event: 'guard_deny',
|
|
2866
|
+
decision: 'deny',
|
|
2867
|
+
tool: name,
|
|
2868
|
+
reason: 'cwd-unresolved',
|
|
2869
|
+
phase: '',
|
|
2870
|
+
paths: [],
|
|
2871
|
+
cwdSource: 'unresolved',
|
|
2872
|
+
command: shellCommand,
|
|
2873
|
+
});
|
|
2874
|
+
return message;
|
|
2875
|
+
}
|
|
2876
|
+
|
|
2877
|
+
warnDegradedSource(resolution);
|
|
2878
|
+
|
|
2879
|
+
/* ── shell 分支(v1.5.11 D-126-02) ────────────────────────────────── */
|
|
2880
|
+
|
|
2881
|
+
if (isShell) {
|
|
2882
|
+
const { command, workdir } = extractShellCommand(execution?.arguments);
|
|
2883
|
+
if (command === undefined) {
|
|
2884
|
+
recordDecision('deny', { reason: 'shell-no-command' });
|
|
2885
|
+
return t(
|
|
2886
|
+
'OpenFeel 写入门禁:shell 工具缺少 `command` 文本,无法判断是否会写文件;请提供 command(不要用其它字段绕过门禁)。',
|
|
2887
|
+
'OpenFeel write guard: the shell tool has no `command` text, so the write intent cannot be judged. Provide command; do not use other fields to bypass the gate.',
|
|
2888
|
+
);
|
|
2889
|
+
}
|
|
2890
|
+
// 相对路径基准:`baseDir = resolve(guardCwd, workdir ?? '.')`(验收 17);
|
|
2891
|
+
// 与目标同样走 normalizeTarget(否则两侧口径不同会让前缀比较失效)。
|
|
2892
|
+
const baseDir = normalizeTarget(resolvedCwd, workdir ?? '.');
|
|
2893
|
+
|
|
2894
|
+
const phaseSummary = () => {
|
|
2895
|
+
const flow = readFlow(resolvedCwd);
|
|
2896
|
+
if (!flow.ok) return '';
|
|
2897
|
+
const active = activeStages(flow.value);
|
|
2898
|
+
return active.length === 0 ? 'done' : formatActivePhases(active);
|
|
2899
|
+
};
|
|
2900
|
+
// 先分类:审计的 `kind` 要能区分 `no-write`(确认只读)与 `undecidable`
|
|
2901
|
+
// (无法判定,op-005 / P0-1)。
|
|
2902
|
+
const classification = classifyShellCommand({ command, baseDir, shell: name });
|
|
2903
|
+
const recordShellAudit = (event) => recordGuardAudit(normalizedCwd, {
|
|
2904
|
+
tool: name,
|
|
2905
|
+
cwdSource,
|
|
2906
|
+
command,
|
|
2907
|
+
phase: phaseSummary(),
|
|
2908
|
+
kind: classification.kind,
|
|
2909
|
+
...event,
|
|
2910
|
+
});
|
|
2911
|
+
const warnLine = (zh, en) => process.stderr.write(`${t(zh, en)}\n`);
|
|
2912
|
+
const allowShell = (reason, paths) => {
|
|
2913
|
+
recordShellAudit({ event: 'guard_allow', decision: 'allow', reason, paths });
|
|
2914
|
+
recordDecision('allow', { reason, paths });
|
|
2915
|
+
return undefined;
|
|
2916
|
+
};
|
|
2917
|
+
/** 第 1/2 类统一出口:默认拒;`OPENFEEL_SHELL_GATE=warn` 时降级为告警放行。 */
|
|
2918
|
+
const denyDecidable = (reason, message, paths) => {
|
|
2919
|
+
if (shellGate.decidable === 'deny') {
|
|
2920
|
+
recordShellAudit({ event: 'guard_deny', decision: 'deny', reason, paths });
|
|
2921
|
+
recordDecision('deny', { reason, paths });
|
|
2922
|
+
return message;
|
|
2923
|
+
}
|
|
2924
|
+
recordShellAudit({ event: 'guard_shell_downgraded', decision: 'warn', reason, paths });
|
|
2925
|
+
recordDecision('warn', { reason, paths });
|
|
2926
|
+
warnLine(
|
|
2927
|
+
`[guard] OpenFeel 写入门禁:OPENFEEL_SHELL_GATE=warn,shell 判定「${reason}」已降级为告警放行。`,
|
|
2928
|
+
`[guard] OpenFeel write guard: OPENFEEL_SHELL_GATE=warn; shell decision "${reason}" was downgraded to a warning.`,
|
|
2929
|
+
);
|
|
2930
|
+
return undefined;
|
|
2931
|
+
};
|
|
2932
|
+
/** 第 4 类:默认告警放行 + 审计 + stderr 一行;`strict` 下拒绝。 */
|
|
2933
|
+
const undecidableShell = (detail, paths) => {
|
|
2934
|
+
const reason = 'shell-undecidable';
|
|
2935
|
+
if (shellGate.undecidable === 'deny') {
|
|
2936
|
+
recordShellAudit({ event: 'guard_deny', decision: 'deny', reason, paths });
|
|
2937
|
+
recordDecision('deny', { reason, paths });
|
|
2938
|
+
return t(
|
|
2939
|
+
`OpenFeel 写入门禁:无法静态判定 shell 命令的写入目标(${detail})。OPENFEEL_SHELL_GATE=strict 下第 4 类也拒绝 —— 请改用 write/edit,或把目标写成字面量路径。`,
|
|
2940
|
+
`OpenFeel write guard: cannot statically resolve the write target of this shell command (${detail}). Under OPENFEEL_SHELL_GATE=strict class 4 is denied too: use write/edit, or spell the target as a literal path.`,
|
|
2941
|
+
);
|
|
2942
|
+
}
|
|
2943
|
+
recordShellAudit({ event: 'guard_shell_unresolved', decision: 'warn', reason, paths });
|
|
2944
|
+
recordDecision('warn', { reason, paths });
|
|
2945
|
+
warnLine(
|
|
2946
|
+
`[guard] OpenFeel 写入门禁:无法静态判定 shell 命令的写入目标(${detail}),已按默认策略告警放行(第 4 类只防误写、不防蓄意)。`,
|
|
2947
|
+
`[guard] OpenFeel write guard: cannot statically resolve the shell write target (${detail}); allowed with a warning (class 4 guards mistakes, not intent).`,
|
|
2948
|
+
);
|
|
2949
|
+
return undefined;
|
|
2950
|
+
};
|
|
2951
|
+
|
|
2952
|
+
// 第 1 类:编码/间接执行形态(含「内联解释器 payload 里有写 API」)
|
|
2953
|
+
if (classification.kind === 'indirect') {
|
|
2954
|
+
return denyDecidable('shell-indirect-exec', t(
|
|
2955
|
+
`OpenFeel 写入门禁:禁止用 shell 嵌套解释器或编码执行(${classification.detail})。这类形态无法静态判定写入目标,一律拒绝 —— 请直接把命令写在 shell 工具里;若只是只读诊断(如 node -e "console.log(...)"),去掉写操作即放行。`,
|
|
2956
|
+
`OpenFeel write guard: nested interpreters / encoded execution (${classification.detail}) are not allowed from the shell — their write target cannot be judged. Put the command directly in the shell tool; a read-only one-liner (e.g. node -e "console.log(...)") is allowed once the write call is removed.`,
|
|
2957
|
+
), []);
|
|
2958
|
+
}
|
|
2959
|
+
// 第 1 类:shell 跑 openfeel 写子命令
|
|
2960
|
+
if (classification.kind === 'openfeel-write') {
|
|
2961
|
+
return denyDecidable('shell-openfeel-write', t(
|
|
2962
|
+
`OpenFeel 写入门禁:禁止用 shell 跑 openfeel 写命令(${classification.detail})。请改用 feel_flow / feel_stage / feel_req 等工具;chore 写窗口是纯人类通道,只能由用户在外部终端执行 \`openfeel chore "<说明>"\` 开启。`,
|
|
2963
|
+
`OpenFeel write guard: running openfeel write commands via the shell is not allowed (${classification.detail}). Use feel_flow / feel_stage / feel_req instead; the chore write window is human-only and must be opened by the user in an external terminal with \`openfeel chore "<note>"\`.`,
|
|
2964
|
+
), []);
|
|
2965
|
+
}
|
|
2966
|
+
// 第 2 类:git 整树工作区写(需要相位 + `.openfeel/**` 无差异,见 P1-2 / P1-4)
|
|
2967
|
+
if (classification.kind === 'whole-tree') {
|
|
2968
|
+
if (!allowsWholeTreeWrite(resolvedCwd, enforce, classification.phases)) {
|
|
2969
|
+
return denyDecidable('shell-git-whole-tree', t(
|
|
2970
|
+
`OpenFeel 写入门禁:禁止在没有 exec_running 阶段时用 shell 做 git 工作区写(${classification.detail})—— 它会整树覆盖/丢弃源码或把状态直接写进仓库,等同绕过文件门禁。请先 feel_flow action=advance 推进到 exec_running;只读查询(git status / log / diff)不受影响。`,
|
|
2971
|
+
`OpenFeel write guard: git worktree writes via the shell (${classification.detail}) are blocked without an exec_running stage — they overwrite/discard sources across the whole tree or write repo state, bypassing the file gate. Advance to exec_running with feel_flow action=advance; read-only git status / log / diff are unaffected.`,
|
|
2972
|
+
), []);
|
|
2973
|
+
}
|
|
2974
|
+
// op-005 / P1-2:整树写会覆盖受保护路径所在的 `.openfeel/**`(flow.json /
|
|
2975
|
+
// chore.json / guard-audit…),「受保护路径任意相位硬拒」在主相位会被它绕过。
|
|
2976
|
+
// 要求工作区的 `.openfeel/**` 无未提交差异;有差异先让人提交/还原。
|
|
2977
|
+
// `git commit` 例外(它不覆盖工作区,见 classifyGitCommand)。
|
|
2978
|
+
if (classification.preservesWorktree !== true
|
|
2979
|
+
&& openfeelTreeDirty(resolvedCwd, {
|
|
2980
|
+
includeUntracked: classification.destroysUntracked === true,
|
|
2981
|
+
includeIgnoredEvidence: classification.purgesIgnored === true,
|
|
2982
|
+
}) === true) {
|
|
2983
|
+
return denyDecidable('shell-git-whole-tree-dirty', t(
|
|
2984
|
+
`OpenFeel 写入门禁:\`.openfeel/**\` 还有未提交的改动(或会被本条命令删掉的未跟踪/被忽略文件,如审计 \`log/guard-audit.jsonl\` 与 \`chore.json\`),整树 git 写(${classification.detail})会连流程状态/证据一起覆盖或删除。请先 \`git add -A .openfeel && git commit\`(或还原这些改动、删掉多余未跟踪文件)再执行。`,
|
|
2985
|
+
`OpenFeel write guard: \`.openfeel/**\` has uncommitted changes (or untracked/ignored files this command would delete, e.g. the audit log \`log/guard-audit.jsonl\` and \`chore.json\`), so this whole-tree git write (${classification.detail}) would overwrite/delete pipeline state or evidence. Commit or restore those changes first (\`git add -A .openfeel && git commit\`).`,
|
|
2986
|
+
), []);
|
|
2987
|
+
}
|
|
2988
|
+
return allowShell('git-worktree-write', []);
|
|
2989
|
+
}
|
|
2990
|
+
// 没有任何写入形态:不误杀构建/测试命令(`npx vitest` / `npm run build` / `cargo build` / `tsc -b`)
|
|
2991
|
+
if (classification.kind === 'none') return allowShell('shell-no-write', []);
|
|
2992
|
+
// 第 4 类(op-005 / P0-1):**无法判定「不写」**—— 未识别命令、`& $var`、
|
|
2993
|
+
// 目标不可判等都落这里;默认告警放行 + 审计(`kind: undecidable`),strict 拒。
|
|
2994
|
+
if (classification.kind === 'undecidable') return undecidableShell(classification.detail, []);
|
|
2995
|
+
// 只读解释器(`node -e "console.log(…)"`):放行且**不写审计**(op-002b:
|
|
2996
|
+
// 日常诊断零噪音);lastDecision 仍更新,便于确认「门禁跑过了」。
|
|
2997
|
+
if (classification.kind === 'readonly-interpreter') {
|
|
2998
|
+
recordDecision('allow', { reason: 'shell-readonly-interpreter' });
|
|
2999
|
+
return undefined;
|
|
3000
|
+
}
|
|
3001
|
+
|
|
3002
|
+
const shellPaths = classification.targets;
|
|
3003
|
+
// 第 1 类(写入目标维度):受保护路径,文案与文件工具完全一致
|
|
3004
|
+
const protectedHits = shellPaths
|
|
3005
|
+
.map((target) => matchProtectedPath(target, normalizedCwd))
|
|
3006
|
+
.filter((hit) => hit !== null);
|
|
3007
|
+
if (protectedHits.length > 0) {
|
|
3008
|
+
return denyDecidable('shell-protected', protectedDenialMessage(protectedHits, t), shellPaths);
|
|
3009
|
+
}
|
|
3010
|
+
// 第 3 类:构建/测试产物豁免;必须**全部**命中才放行,混合目标从严
|
|
3011
|
+
const decidableTargets = shellPaths.filter((target) => !isBuildArtifactPath(target, normalizedCwd));
|
|
3012
|
+
if (decidableTargets.length === 0) {
|
|
3013
|
+
if (classification.undecidable) return undecidableShell(classification.detail, shellPaths);
|
|
3014
|
+
return allowShell('shell-build-artifact', shellPaths);
|
|
3015
|
+
}
|
|
3016
|
+
// 第 2 类:复用与文件工具完全相同的判定(相位 / doc-asset / 研究闸 / chore)
|
|
3017
|
+
const decided = decideForTargets(guardContext, {
|
|
3018
|
+
name,
|
|
3019
|
+
targets: decidableTargets,
|
|
3020
|
+
resolvedCwd,
|
|
3021
|
+
normalizedCwd,
|
|
3022
|
+
cwdSource,
|
|
3023
|
+
audit: false,
|
|
3024
|
+
});
|
|
3025
|
+
if (decided.decision === 'deny') return denyDecidable(decided.reason, decided.message, decidableTargets);
|
|
3026
|
+
if (classification.undecidable) return undecidableShell(classification.detail, shellPaths);
|
|
3027
|
+
return allowShell(decided.reason, decidableTargets);
|
|
3028
|
+
}
|
|
3029
|
+
|
|
3030
|
+
/* ── 文件工具分支(write / edit / str_replace_editor / apply_patch) ── */
|
|
418
3031
|
|
|
419
3032
|
let rawTargets;
|
|
420
3033
|
let patchEntries = null;
|
|
@@ -446,110 +3059,23 @@ export function createOpenFeelGuard(options = {}) {
|
|
|
446
3059
|
}
|
|
447
3060
|
|
|
448
3061
|
const targets = rawTargets.map((target) => normalizeTarget(resolvedCwd, target));
|
|
449
|
-
//
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
if (enforce === 'always') {
|
|
463
|
-
// P0-1 bootstrap 例外:空工作区 + 全部为「新增文件」→ 放行(最高风险等级不成立)。
|
|
464
|
-
// apply_patch 额外要求全部 block 为 `*** Add File:`(Update/Delete/Move/混合一律从严)。
|
|
465
|
-
// `.openfeel/**` 不适用:流程产物仍要求先 init(B8)。
|
|
466
|
-
const allNew = targets.every((target) => !existsSync(target));
|
|
467
|
-
const anyInternal = targets.some((target) => isUnderOpenFeel(target, normalizedCwd));
|
|
468
|
-
const allInside = targets.every((target) => isUnderWorkspace(target, normalizedCwd));
|
|
469
|
-
const addOnly = patchEntries === null || patchEntries.every((entry) => entry.kind === 'add');
|
|
470
|
-
if (allNew && addOnly && !anyInternal && allInside) {
|
|
471
|
-
if (!bootstrapHinted.has(normalizedCwd)) {
|
|
472
|
-
bootstrapHinted.add(normalizedCwd);
|
|
473
|
-
process.stderr.write(
|
|
474
|
-
`${t(
|
|
475
|
-
'OpenFeel 写入门禁:[bootstrap] 工作区尚未初始化,已放行本次新增文件;建议稍后运行 `openfeel init` 补账本。',
|
|
476
|
-
'OpenFeel write guard: [bootstrap] workspace not initialized; this new-file write was allowed. Run `openfeel init` later to record it.',
|
|
477
|
-
)}\n`,
|
|
478
|
-
);
|
|
479
|
-
}
|
|
480
|
-
return undefined;
|
|
481
|
-
}
|
|
482
|
-
return t(
|
|
483
|
-
'OpenFeel 写入门禁:当前工作区尚未初始化 OpenFeel(无 `.openfeel/`)。请先运行 `openfeel init` 并建立需求/阶段;或让用户把 profile 的 `enforce` 改为 `project` / `off`。',
|
|
484
|
-
'OpenFeel write guard: this workspace is not OpenFeel-initialized (no `.openfeel/`). Run `openfeel init` and create a requirement/stage first; or ask the user to set `enforce` to `project` / `off`.',
|
|
485
|
-
);
|
|
486
|
-
}
|
|
487
|
-
return undefined;
|
|
488
|
-
}
|
|
489
|
-
|
|
490
|
-
const allInternal = targets.every((target) => isUnderOpenFeel(target, normalizedCwd));
|
|
491
|
-
if (allInternal) return undefined;
|
|
492
|
-
|
|
493
|
-
const flow = readFlow(resolvedCwd);
|
|
494
|
-
if (!flow.ok) {
|
|
495
|
-
return t(
|
|
496
|
-
`OpenFeel 写入门禁:无法读取 .openfeel/flow.json(${flow.reason})。请运行 feel_verify action=health。`,
|
|
497
|
-
`OpenFeel write guard: cannot read .openfeel/flow.json (${flow.reason}). Run feel_verify action=health.`,
|
|
498
|
-
);
|
|
499
|
-
}
|
|
500
|
-
|
|
501
|
-
const active = activeStages(flow.value);
|
|
502
|
-
// v1.5.2 入口闸:研究/方案产物(docs/research/**)是阶段交付物,无活跃阶段时不得写入;
|
|
503
|
-
// chore 也不能绕过(在下方 chore 放行之前判定)。
|
|
504
|
-
if (active.length === 0 && targets.some((target) => isResearchArtifactPath(target, normalizedCwd))) {
|
|
505
|
-
recordGuardAudit(normalizedCwd, {
|
|
506
|
-
event: 'guard_deny',
|
|
507
|
-
tool: name,
|
|
508
|
-
reason: 'research-needs-stage',
|
|
509
|
-
phase: 'done',
|
|
510
|
-
paths: targets,
|
|
511
|
-
});
|
|
512
|
-
return t(
|
|
513
|
-
'OpenFeel 写入门禁:研究/方案产物(docs/research/**)要求有开启的阶段。请先按当前小版本开一个阶段(保持 exec_running),再 feel_req add → claim 建需求并写调研/方案。纯只读问答无需落盘。',
|
|
514
|
-
'OpenFeel write guard: research/proposal artifacts (docs/research/**) require an open stage. Open a stage for the current minor version (keep it in exec_running), then feel_req add → claim before writing. Pure read-only Q&A needs no file.',
|
|
515
|
-
);
|
|
516
|
-
}
|
|
517
|
-
if (active.length === 0) {
|
|
518
|
-
if (allowGeneral && hasGeneralRequirement(flow.value)) return undefined;
|
|
519
|
-
// v1.4.0 chore 通道:仅在**无活跃阶段**时生效;受保护路径已在上方拒绝。
|
|
520
|
-
const chore = readActiveChore(normalizedCwd);
|
|
521
|
-
if (chore !== null) {
|
|
522
|
-
recordGuardAudit(normalizedCwd, { tool: name, reason: 'chore', phase: 'done', paths: targets });
|
|
523
|
-
return undefined;
|
|
524
|
-
}
|
|
525
|
-
// P0-4/v1.4.0:doc/note 与静态展示资源不要求活跃阶段(收口后仍可写);混合目标从严。
|
|
526
|
-
if (allExempt) {
|
|
527
|
-
recordGuardAudit(normalizedCwd, { tool: name, reason: 'doc-asset', phase: 'done', paths: targets });
|
|
528
|
-
return undefined;
|
|
529
|
-
}
|
|
530
|
-
return t(
|
|
531
|
-
'OpenFeel 写入门禁:无活跃阶段,不能修改源码/文档(当前没有开启的阶段)。默认按当前小版本开一个阶段并保持 exec_running(feel_stage add stage=<vX.Y.Z-stage-N>),再在该版本下建需求推进;需求完成不要求关闭阶段。',
|
|
532
|
-
'OpenFeel write guard: no active stage (no open stage), so source/docs are read-only. Open a stage for the current minor version and keep it in exec_running (feel_stage add stage=<vX.Y.Z-stage-N>), then add requirements under that version; requirement completion does not require closing the stage.',
|
|
533
|
-
);
|
|
534
|
-
}
|
|
535
|
-
|
|
536
|
-
if (active.some((stage) => stage.phase === 'exec_running')) return undefined;
|
|
537
|
-
// P0-4/v1.4.0:非 exec 相位仍允许 doc/note 与静态展示资源(研究记录、设计文档、UI 资源等);源码仍严格。
|
|
538
|
-
if (allExempt) {
|
|
539
|
-
const phases = active
|
|
540
|
-
.map((stage) => `${stage.id ?? '(unknown)'}=${stage.phase ?? '(unknown)'}`)
|
|
541
|
-
.join(', ');
|
|
542
|
-
recordGuardAudit(normalizedCwd, { tool: name, reason: 'doc-asset', phase: phases, paths: targets });
|
|
3062
|
+
// 判定体已抽成 `decideForTargets()`(plan §3.1⑤ 的纯重构):文件分支与 shell 分支
|
|
3063
|
+
// 共用同一份 —— 受保护路径 → bootstrap → 内部早返回 → 研究闸 → 无阶段/chore/
|
|
3064
|
+
// doc-asset → 相位判定,逐行语义不变。
|
|
3065
|
+
const decision = decideForTargets(guardContext, {
|
|
3066
|
+
name,
|
|
3067
|
+
targets,
|
|
3068
|
+
patchEntries,
|
|
3069
|
+
resolvedCwd,
|
|
3070
|
+
normalizedCwd,
|
|
3071
|
+
cwdSource,
|
|
3072
|
+
});
|
|
3073
|
+
if (decision.decision === 'allow') {
|
|
3074
|
+
recordDecision('allow', { reason: decision.reason, paths: targets });
|
|
543
3075
|
return undefined;
|
|
544
3076
|
}
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
.map((stage) => `${stage.id ?? '(unknown)'}=${stage.phase ?? '(unknown)'}`)
|
|
548
|
-
.join(', ');
|
|
549
|
-
return t(
|
|
550
|
-
`OpenFeel 写入门禁:活跃阶段当前不在 exec_running(${summary}),不能修改源码/文档。请先 feel_flow action=advance 推进到 exec_running。`,
|
|
551
|
-
`OpenFeel write guard: active stage(s) are not in exec_running (${summary}), so source/docs are read-only. Advance to exec_running with feel_flow action=advance.`,
|
|
552
|
-
);
|
|
3077
|
+
recordDecision('deny', { reason: decision.reason, paths: targets });
|
|
3078
|
+
return decision.message;
|
|
553
3079
|
};
|
|
554
3080
|
}
|
|
555
3081
|
|