carlos-flow 2.12.0 → 2.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/card.js CHANGED
@@ -1,288 +1,296 @@
1
- // Carlos Flow - FLOW_CARD parser / repair / validator.
2
- // Node ESM. Self-contained: no imports.
3
-
4
- export const CARD_MARKER = 'FLOW_CARD:';
5
-
6
- const SENSITIVE_NAMES = new Set([
7
- '.env', '.env.local', '.env.development', '.env.production', '.env.test',
8
- 'settings.json', 'settings.local.json',
9
- 'package.json', 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml',
10
- 'poetry.lock', 'requirements.txt',
11
- 'dockerfile', 'docker-compose.yml', 'docker-compose.yaml', 'makefile',
12
- ]);
13
-
14
- const SENSITIVE_SEGMENTS = new Set([
15
- 'migrations', 'deploy', 'deployment', 'k8s', 'kube',
16
- '.github', '.gitlab', 'secrets', 'certs', 'terraform',
17
- ]);
18
-
19
- const SENSITIVE_EXTENSIONS = new Set([
20
- '.pem', '.key', '.p12', '.pfx', '.env',
21
- ]);
22
-
23
- export function isSensitive(rel) {
24
- if (typeof rel !== 'string' || rel.length === 0) return false;
25
- const normalized = rel.replace(/\\/g, '/').toLowerCase();
26
- const segments = normalized.split('/').filter((s) => s.length > 0);
27
- const base = segments.length ? segments[segments.length - 1] : normalized;
28
- if (SENSITIVE_NAMES.has(base)) return true;
29
- // 只检查目录段(不含最后一段文件名):参考实现 flow-gate.py 用 parts[:-1]
30
- for (const seg of segments.slice(0, -1)) {
31
- if (SENSITIVE_SEGMENTS.has(seg)) return true;
32
- }
33
- for (const ext of SENSITIVE_EXTENSIONS) {
34
- if (base.endsWith(ext)) return true;
35
- }
36
- return false;
37
- }
38
-
39
- export function riskTier(scope) {
40
- if (!Array.isArray(scope) || scope.length === 0) return 'read_only';
41
- if (scope.some((p) => isSensitive(p))) return 'sensitive';
42
- if (scope.length === 1) return 'single_file';
43
- return 'cross_module';
44
- }
45
-
46
- export function extractJsonObject(text) {
47
- if (typeof text !== 'string') return null;
48
- const start = text.indexOf('{');
49
- if (start === -1) return null;
50
- let depth = 0;
51
- let inString = false;
52
- let escaped = false;
53
- for (let i = start; i < text.length; i++) {
54
- const ch = text[i];
55
- if (escaped) { escaped = false; continue; }
56
- if (inString) {
57
- if (ch === '\\') { escaped = true; }
58
- else if (ch === '"') { inString = false; }
59
- continue;
60
- }
61
- if (ch === '"') { inString = true; }
62
- else if (ch === '{') { depth++; }
63
- else if (ch === '}') {
64
- depth--;
65
- if (depth === 0) return text.slice(start, i + 1);
66
- }
67
- }
68
- return null;
69
- }
70
-
71
- export function repairJson(raw) {
72
- if (typeof raw !== 'string') return raw;
73
- let s = raw;
74
- s = s.replace(/\u201C/g, '\\"').replace(/\u201D/g, '\\"');
75
- s = s.replace(/\u2018/g, "'").replace(/\u2019/g, "'");
76
- s = s.replace(/,\s*([}\]])/g, '$1');
77
- s = s.replace(/'([^']*)'/g, '"$1"');
78
- s = s.replace(/([{,]\s*)([A-Za-z_][A-Za-z0-9_]*)(\s*:)/g, '$1"$2"$3');
79
- return s;
80
- }
81
-
82
- export function parseCard(description) {
83
- if (typeof description !== 'string' || description.indexOf(CARD_MARKER) === -1) {
84
- return { card: null, error: null };
85
- }
86
- let marker = -1;
87
- let idx = 0;
88
- while (true) {
89
- const found = description.indexOf(CARD_MARKER, idx);
90
- if (found === -1) break;
91
- marker = found;
92
- idx = found + CARD_MARKER.length;
93
- }
94
- const markerPositions = [];
95
- {
96
- let p = 0;
97
- while (true) {
98
- const found = description.indexOf(CARD_MARKER, p);
99
- if (found === -1) break;
100
- markerPositions.push(found);
101
- p = found + CARD_MARKER.length;
102
- }
103
- }
104
- for (let mi = markerPositions.length - 1; mi >= 0; mi--) {
105
- const i = markerPositions[mi];
106
- const after = description.slice(i + CARD_MARKER.length).trim();
107
- const rawJson = extractJsonObject(after);
108
- if (!rawJson) continue;
109
- const candidates = [rawJson, repairJson(rawJson)];
110
- for (const c of candidates) {
111
- try {
112
- const result = JSON.parse(c);
113
- if (result && typeof result === 'object' && !Array.isArray(result)) {
114
- return { card: sanitizeCard(result), error: null };
115
- }
116
- } catch (_) {}
117
- }
118
- }
119
- return { card: null, error: 'FLOW_CARD 解析失败,请按模板重写(单行、英文双引号、值里不要出现双引号):FLOW_CARD:{"goal":"一句话目标","quote":"用户原话摘录","scope":["只准改的文件"],"acceptance":["可判定的验收标准"],"unknowns":[],"assumptions":[],"files":[{"path":"a/b.py","line":1}],"verify":{"cmd":"pytest -q tests/x.py"},"confirmed":false}' };
120
- }
121
-
122
-
123
- const BOUNDARY_TAG_RE = /<\/?\s*(record|scope|goal|quote|acceptance|unknowns|assumptions|files|structure|env|verify)\s*>/gi;
124
-
125
- function stripBoundaryTags(str) {
126
- if (typeof str !== 'string') return str;
127
- // 剥离所有 HTML 标签,不仅仅是白名单标签
128
- return str.replace(/<[^>]*>/g, '').trim();
129
- }
130
-
131
- export function sanitizeCard(card) {
132
- if (!card || typeof card !== 'object') return card;
133
- const out = { ...card };
134
- if (typeof out.goal === 'string') out.goal = stripBoundaryTags(out.goal);
135
- if (typeof out.quote === 'string') out.quote = stripBoundaryTags(out.quote);
136
- for (const key of ['acceptance', 'unknowns', 'assumptions']) {
137
- if (Array.isArray(out[key])) {
138
- out[key] = out[key].map((v) => (typeof v === 'string' ? stripBoundaryTags(v) : v));
139
- }
140
- }
141
- if (Array.isArray(out.scope)) {
142
- out.scope = out.scope.map((v) => (typeof v === 'string' ? stripBoundaryTags(v) : v));
143
- }
144
- if (Array.isArray(out.files)) {
145
- out.files = out.files.map((entry) => {
146
- if (entry && typeof entry === 'object' && typeof entry.path === 'string') {
147
- return { ...entry, path: stripBoundaryTags(entry.path) };
148
- }
149
- return entry;
150
- });
151
- }
152
- if (out.verify && typeof out.verify === 'object' && !Array.isArray(out.verify)) {
153
- const v = { ...out.verify };
154
- if (typeof v.cmd === 'string') v.cmd = stripBoundaryTags(v.cmd);
155
- out.verify = v;
156
- }
157
- for (const key of ['structure', 'env']) {
158
- const v = out[key];
159
- if (v && typeof v === 'object' && !Array.isArray(v)) {
160
- const nv = { ...v };
161
- for (const k of Object.keys(nv)) {
162
- if (typeof nv[k] === 'string') nv[k] = stripBoundaryTags(nv[k]);
163
- }
164
- out[key] = nv;
165
- }
166
- }
167
- return out;
168
- }
169
-
170
- export function validateCard(card, options) {
171
- const opts = options || {};
172
- const findings = [];
173
- const scopeRaw = card ? card.scope : undefined;
174
- if (scopeRaw !== undefined && scopeRaw !== null && !Array.isArray(scopeRaw)) {
175
- return {
176
- ok: false,
177
- reason: 'scope 必须是文件路径数组',
178
- findings: ['scope 必须是文件路径数组(不能是单个字符串)'],
179
- tier: riskTier([]),
180
- };
181
- }
182
- const scope = Array.isArray(scopeRaw) ? scopeRaw : [];
183
- const tier = riskTier(scope);
184
-
185
- for (const p of scope) {
186
- if (typeof p !== 'string' || p.trim() === '') {
187
- findings.push('scope 里有空路径');
188
- return { ok: false, reason: 'scope 中有无效路径,拒绝派发(锚点 veto)', findings, tier };
189
- }
190
- // 拒绝「整个目录」作为改动范围:scope=["."] 等价于授权修改整个 cwd,
191
- // 会把合同边界放大到仓库全量;而 enforceScope(".") 又会把任意改动判越界。
192
- // 这里直接拒绝 "." / ".." 及其路径形式。
193
- const normPath = p.trim().replace(/\\/g, '/').replace(/\/+$/, '') || p.trim();
194
- if (normPath === '.' || normPath === '..' || normPath.endsWith('/.') || normPath.endsWith('/..')) {
195
- findings.push('scope 不能包含整个目录("." / "..")—— 必须精确到文件');
196
- return { ok: false, reason: 'scope 中有指向整个目录的路径,拒绝派发(合同边界 veto)', findings, tier };
197
- }
198
- }
199
-
200
- if (typeof opts.scopeExists === 'function') {
201
- for (const p of scope) {
202
- if (!opts.scopeExists(p)) {
203
- findings.push('scope 路径不存在:' + p);
204
- return { ok: false, reason: 'scope 中有路径在磁盘上不存在,拒绝派发(锚点 veto)', findings, tier };
205
- }
206
- }
207
- }
208
-
209
- const quote = card && typeof card.quote === 'string' ? card.quote : null;
210
- const norm = (s) => (typeof s === 'string' ? s.replace(/\s+/g, ' ').trim() : '');
211
- const qNorm = norm(quote);
212
- if (qNorm) {
213
- const msgs = Array.isArray(opts.userMessages) ? opts.userMessages : [];
214
- let anchored = false;
215
- for (const m of msgs) {
216
- if (norm(m).indexOf(qNorm) !== -1) { anchored = true; break; }
217
- }
218
- if (!anchored) {
219
- // 永不降级:数据源不可用时直接拒绝
220
- findings.push('quote 无法在用户原话中定位(防替用户编需求)');
221
- return { ok: false, reason: 'quote 锚点校验失败:数据源不可用或 quote 不是用户原话的子串,拒绝派发', findings, tier };
222
- }
223
- }
224
-
225
- // 文本类数组字段:元素必须是可读文本。
226
- // 这些字段「长度>0」不等于「已填」——acceptance=[""] / [null] / [0] / [{}]
227
- // 都是「长度>0 但内容无效」的伪填充,必须判为「未填」。
228
- const TEXT_ARRAY_FIELDS = new Set(['acceptance', 'unknowns', 'assumptions', 'scope']);
229
-
230
- const required = {
231
- read_only: ['goal', 'quote'],
232
- single_file: ['goal', 'quote', 'scope'],
233
- cross_module: ['goal', 'quote', 'scope', 'acceptance', 'files'],
234
- sensitive: ['goal', 'quote', 'scope', 'acceptance'],
235
- }[tier] || ['goal', 'quote'];
236
- for (const f of required) {
237
- const v = card ? card[f] : undefined;
238
- let missing;
239
- if (v === undefined || v === null) {
240
- missing = true;
241
- } else if (Array.isArray(v)) {
242
- if (v.length === 0) {
243
- missing = true;
244
- } else if (TEXT_ARRAY_FIELDS.has(f)) {
245
- // 文本类数组:**每一个**元素都必须是有效的非空字符串才算「已填」。
246
- // 严格口径(every 而非 some):验收标准里混入 null / 数字 / 空串是笔误,
247
- // 只会污染落盘的卡片并原样进入 executor 的合同文本 —— 应该报错让作者改,
248
- // 而不是「有一条真条目就算填了」。
249
- missing = !v.every((x) => typeof x === 'string' && x.trim() !== '');
250
- } else {
251
- // 其他数组(如 files):元素结构另有校验,这里只看长度。
252
- missing = false;
253
- }
254
- } else if (typeof v === 'string') {
255
- missing = v.trim() === '';
256
- } else {
257
- missing = false;
258
- }
259
- if (missing) findings.push('缺少必填字段:' + f + '(风险档 ' + tier + ')');
260
- }
261
-
262
- if (tier === 'cross_module' || tier === 'sensitive') {
263
- const files = card && Array.isArray(card.files) ? card.files : [];
264
- for (const entry of files) {
265
- if (!entry || typeof entry.path !== 'string' || typeof entry.line !== 'number') {
266
- findings.push('files 每一项都必须带 path 与 line');
267
- break;
268
- }
269
- }
270
- }
271
-
272
- const unknowns = card && Array.isArray(card.unknowns) ? card.unknowns : [];
273
- const assumptions = card && Array.isArray(card.assumptions) ? card.assumptions : [];
274
- if ((tier === 'cross_module' || tier === 'sensitive') && unknowns.length > 0 && assumptions.length === 0) {
275
- findings.push('WARN: unknowns 非空但无 assumptions(只提醒,不阻断)');
276
- }
277
-
278
- if (tier === 'sensitive' && opts.confirmed !== true) {
279
- return { ok: false, reason: '敏感路径未确认,需先向用户确认后再提交卡片', findings, tier };
280
- }
281
-
282
- const hard = findings.filter((f) => !f.startsWith('WARN:'));
283
- if (hard.length > 0) {
284
- return { ok: false, reason: '卡片不合规:' + hard.join(';'), findings, tier };
285
- }
286
-
287
- return { ok: true, reason: 'ok', findings, tier };
288
- }
1
+ // Carlos Flow - FLOW_CARD parser / repair / validator.
2
+ // Node ESM. Self-contained: no imports.
3
+
4
+ export const CARD_MARKER = 'FLOW_CARD:';
5
+
6
+ const SENSITIVE_NAMES = new Set([
7
+ '.env', '.env.local', '.env.development', '.env.production', '.env.test',
8
+ 'settings.json', 'settings.local.json',
9
+ 'package.json', 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml',
10
+ 'poetry.lock', 'requirements.txt',
11
+ 'dockerfile', 'docker-compose.yml', 'docker-compose.yaml', 'makefile',
12
+ // 凭证与私钥(2026-11-14 补):与 protocol.js 保持同一份口径。
13
+ // 此前 .ssh/id_rsa、.npmrc、.aws/credentials 一律放行,属安全漏洞。
14
+ 'id_rsa', 'id_dsa', 'id_ecdsa', 'id_ed25519', 'id_ed448',
15
+ '.npmrc', '.netrc', '.pgpass', 'credentials', 'known_hosts', 'authorized_keys',
16
+ ]);
17
+
18
+ const SENSITIVE_SEGMENTS = new Set([
19
+ 'migrations', 'deploy', 'deployment', 'k8s', 'kube',
20
+ '.github', '.gitlab', 'secrets', 'certs', 'terraform',
21
+ // 凭证目录(2026-11-14 补):只检查目录段,'.ssh' 能拦住 .ssh/id_rsa。
22
+ '.ssh', '.aws', '.gnupg', '.docker', '.azure', '.gcloud',
23
+ ]);
24
+
25
+ const SENSITIVE_EXTENSIONS = new Set([
26
+ '.pem', '.key', '.p12', '.pfx', '.env',
27
+ // 密码库与签名材料(2026-11-14 补):与 protocol.js 保持一致。
28
+ '.kdbx', '.kdb', '.gpg', '.asc', '.crt', '.cer', '.der',
29
+ ]);
30
+
31
+ export function isSensitive(rel) {
32
+ if (typeof rel !== 'string' || rel.length === 0) return false;
33
+ const normalized = rel.replace(/\\/g, '/').toLowerCase();
34
+ const segments = normalized.split('/').filter((s) => s.length > 0);
35
+ const base = segments.length ? segments[segments.length - 1] : normalized;
36
+ if (SENSITIVE_NAMES.has(base)) return true;
37
+ // 只检查目录段(不含最后一段文件名):参考实现 flow-gate.py 用 parts[:-1]
38
+ for (const seg of segments.slice(0, -1)) {
39
+ if (SENSITIVE_SEGMENTS.has(seg)) return true;
40
+ }
41
+ for (const ext of SENSITIVE_EXTENSIONS) {
42
+ if (base.endsWith(ext)) return true;
43
+ }
44
+ return false;
45
+ }
46
+
47
+ export function riskTier(scope) {
48
+ if (!Array.isArray(scope) || scope.length === 0) return 'read_only';
49
+ if (scope.some((p) => isSensitive(p))) return 'sensitive';
50
+ if (scope.length === 1) return 'single_file';
51
+ return 'cross_module';
52
+ }
53
+
54
+ export function extractJsonObject(text) {
55
+ if (typeof text !== 'string') return null;
56
+ const start = text.indexOf('{');
57
+ if (start === -1) return null;
58
+ let depth = 0;
59
+ let inString = false;
60
+ let escaped = false;
61
+ for (let i = start; i < text.length; i++) {
62
+ const ch = text[i];
63
+ if (escaped) { escaped = false; continue; }
64
+ if (inString) {
65
+ if (ch === '\\') { escaped = true; }
66
+ else if (ch === '"') { inString = false; }
67
+ continue;
68
+ }
69
+ if (ch === '"') { inString = true; }
70
+ else if (ch === '{') { depth++; }
71
+ else if (ch === '}') {
72
+ depth--;
73
+ if (depth === 0) return text.slice(start, i + 1);
74
+ }
75
+ }
76
+ return null;
77
+ }
78
+
79
+ export function repairJson(raw) {
80
+ if (typeof raw !== 'string') return raw;
81
+ let s = raw;
82
+ s = s.replace(/\u201C/g, '\\"').replace(/\u201D/g, '\\"');
83
+ s = s.replace(/\u2018/g, "'").replace(/\u2019/g, "'");
84
+ s = s.replace(/,\s*([}\]])/g, '$1');
85
+ s = s.replace(/'([^']*)'/g, '"$1"');
86
+ s = s.replace(/([{,]\s*)([A-Za-z_][A-Za-z0-9_]*)(\s*:)/g, '$1"$2"$3');
87
+ return s;
88
+ }
89
+
90
+ export function parseCard(description) {
91
+ if (typeof description !== 'string' || description.indexOf(CARD_MARKER) === -1) {
92
+ return { card: null, error: null };
93
+ }
94
+ let marker = -1;
95
+ let idx = 0;
96
+ while (true) {
97
+ const found = description.indexOf(CARD_MARKER, idx);
98
+ if (found === -1) break;
99
+ marker = found;
100
+ idx = found + CARD_MARKER.length;
101
+ }
102
+ const markerPositions = [];
103
+ {
104
+ let p = 0;
105
+ while (true) {
106
+ const found = description.indexOf(CARD_MARKER, p);
107
+ if (found === -1) break;
108
+ markerPositions.push(found);
109
+ p = found + CARD_MARKER.length;
110
+ }
111
+ }
112
+ for (let mi = markerPositions.length - 1; mi >= 0; mi--) {
113
+ const i = markerPositions[mi];
114
+ const after = description.slice(i + CARD_MARKER.length).trim();
115
+ const rawJson = extractJsonObject(after);
116
+ if (!rawJson) continue;
117
+ const candidates = [rawJson, repairJson(rawJson)];
118
+ for (const c of candidates) {
119
+ try {
120
+ const result = JSON.parse(c);
121
+ if (result && typeof result === 'object' && !Array.isArray(result)) {
122
+ return { card: sanitizeCard(result), error: null };
123
+ }
124
+ } catch (_) {}
125
+ }
126
+ }
127
+ return { card: null, error: 'FLOW_CARD 解析失败,请按模板重写(单行、英文双引号、值里不要出现双引号):FLOW_CARD:{"goal":"一句话目标","quote":"用户原话摘录","scope":["只准改的文件"],"acceptance":["可判定的验收标准"],"unknowns":[],"assumptions":[],"files":[{"path":"a/b.py","line":1}],"verify":{"cmd":"pytest -q tests/x.py"},"confirmed":false}' };
128
+ }
129
+
130
+
131
+ const BOUNDARY_TAG_RE = /<\/?\s*(record|scope|goal|quote|acceptance|unknowns|assumptions|files|structure|env|verify)\s*>/gi;
132
+
133
+ function stripBoundaryTags(str) {
134
+ if (typeof str !== 'string') return str;
135
+ // 剥离所有 HTML 标签,不仅仅是白名单标签
136
+ return str.replace(/<[^>]*>/g, '').trim();
137
+ }
138
+
139
+ export function sanitizeCard(card) {
140
+ if (!card || typeof card !== 'object') return card;
141
+ const out = { ...card };
142
+ if (typeof out.goal === 'string') out.goal = stripBoundaryTags(out.goal);
143
+ if (typeof out.quote === 'string') out.quote = stripBoundaryTags(out.quote);
144
+ for (const key of ['acceptance', 'unknowns', 'assumptions']) {
145
+ if (Array.isArray(out[key])) {
146
+ out[key] = out[key].map((v) => (typeof v === 'string' ? stripBoundaryTags(v) : v));
147
+ }
148
+ }
149
+ if (Array.isArray(out.scope)) {
150
+ out.scope = out.scope.map((v) => (typeof v === 'string' ? stripBoundaryTags(v) : v));
151
+ }
152
+ if (Array.isArray(out.files)) {
153
+ out.files = out.files.map((entry) => {
154
+ if (entry && typeof entry === 'object' && typeof entry.path === 'string') {
155
+ return { ...entry, path: stripBoundaryTags(entry.path) };
156
+ }
157
+ return entry;
158
+ });
159
+ }
160
+ if (out.verify && typeof out.verify === 'object' && !Array.isArray(out.verify)) {
161
+ const v = { ...out.verify };
162
+ if (typeof v.cmd === 'string') v.cmd = stripBoundaryTags(v.cmd);
163
+ out.verify = v;
164
+ }
165
+ for (const key of ['structure', 'env']) {
166
+ const v = out[key];
167
+ if (v && typeof v === 'object' && !Array.isArray(v)) {
168
+ const nv = { ...v };
169
+ for (const k of Object.keys(nv)) {
170
+ if (typeof nv[k] === 'string') nv[k] = stripBoundaryTags(nv[k]);
171
+ }
172
+ out[key] = nv;
173
+ }
174
+ }
175
+ return out;
176
+ }
177
+
178
+ export function validateCard(card, options) {
179
+ const opts = options || {};
180
+ const findings = [];
181
+ const scopeRaw = card ? card.scope : undefined;
182
+ if (scopeRaw !== undefined && scopeRaw !== null && !Array.isArray(scopeRaw)) {
183
+ return {
184
+ ok: false,
185
+ reason: 'scope 必须是文件路径数组',
186
+ findings: ['scope 必须是文件路径数组(不能是单个字符串)'],
187
+ tier: riskTier([]),
188
+ };
189
+ }
190
+ const scope = Array.isArray(scopeRaw) ? scopeRaw : [];
191
+ const tier = riskTier(scope);
192
+
193
+ for (const p of scope) {
194
+ if (typeof p !== 'string' || p.trim() === '') {
195
+ findings.push('scope 里有空路径');
196
+ return { ok: false, reason: 'scope 中有无效路径,拒绝派发(锚点 veto)', findings, tier };
197
+ }
198
+ // 拒绝「整个目录」作为改动范围:scope=["."] 等价于授权修改整个 cwd,
199
+ // 会把合同边界放大到仓库全量;而 enforceScope(".") 又会把任意改动判越界。
200
+ // 这里直接拒绝 "." / ".." 及其路径形式。
201
+ const normPath = p.trim().replace(/\\/g, '/').replace(/\/+$/, '') || p.trim();
202
+ if (normPath === '.' || normPath === '..' || normPath.endsWith('/.') || normPath.endsWith('/..')) {
203
+ findings.push('scope 不能包含整个目录("." / "..")—— 必须精确到文件');
204
+ return { ok: false, reason: 'scope 中有指向整个目录的路径,拒绝派发(合同边界 veto)', findings, tier };
205
+ }
206
+ }
207
+
208
+ if (typeof opts.scopeExists === 'function') {
209
+ for (const p of scope) {
210
+ if (!opts.scopeExists(p)) {
211
+ findings.push('scope 路径不存在:' + p);
212
+ return { ok: false, reason: 'scope 中有路径在磁盘上不存在,拒绝派发(锚点 veto)', findings, tier };
213
+ }
214
+ }
215
+ }
216
+
217
+ const quote = card && typeof card.quote === 'string' ? card.quote : null;
218
+ const norm = (s) => (typeof s === 'string' ? s.replace(/\s+/g, ' ').trim() : '');
219
+ const qNorm = norm(quote);
220
+ if (qNorm) {
221
+ const msgs = Array.isArray(opts.userMessages) ? opts.userMessages : [];
222
+ let anchored = false;
223
+ for (const m of msgs) {
224
+ if (norm(m).indexOf(qNorm) !== -1) { anchored = true; break; }
225
+ }
226
+ if (!anchored) {
227
+ // 永不降级:数据源不可用时直接拒绝
228
+ findings.push('quote 无法在用户原话中定位(防替用户编需求)');
229
+ return { ok: false, reason: 'quote 锚点校验失败:数据源不可用或 quote 不是用户原话的子串,拒绝派发', findings, tier };
230
+ }
231
+ }
232
+
233
+ // 文本类数组字段:元素必须是可读文本。
234
+ // 这些字段「长度>0」不等于「已填」——acceptance=[""] / [null] / [0] / [{}]
235
+ // 都是「长度>0 但内容无效」的伪填充,必须判为「未填」。
236
+ const TEXT_ARRAY_FIELDS = new Set(['acceptance', 'unknowns', 'assumptions', 'scope']);
237
+
238
+ const required = {
239
+ read_only: ['goal', 'quote'],
240
+ single_file: ['goal', 'quote', 'scope'],
241
+ cross_module: ['goal', 'quote', 'scope', 'acceptance', 'files'],
242
+ sensitive: ['goal', 'quote', 'scope', 'acceptance'],
243
+ }[tier] || ['goal', 'quote'];
244
+ for (const f of required) {
245
+ const v = card ? card[f] : undefined;
246
+ let missing;
247
+ if (v === undefined || v === null) {
248
+ missing = true;
249
+ } else if (Array.isArray(v)) {
250
+ if (v.length === 0) {
251
+ missing = true;
252
+ } else if (TEXT_ARRAY_FIELDS.has(f)) {
253
+ // 文本类数组:**每一个**元素都必须是有效的非空字符串才算「已填」。
254
+ // 严格口径(every 而非 some):验收标准里混入 null / 数字 / 空串是笔误,
255
+ // 只会污染落盘的卡片并原样进入 executor 的合同文本 —— 应该报错让作者改,
256
+ // 而不是「有一条真条目就算填了」。
257
+ missing = !v.every((x) => typeof x === 'string' && x.trim() !== '');
258
+ } else {
259
+ // 其他数组(如 files):元素结构另有校验,这里只看长度。
260
+ missing = false;
261
+ }
262
+ } else if (typeof v === 'string') {
263
+ missing = v.trim() === '';
264
+ } else {
265
+ missing = false;
266
+ }
267
+ if (missing) findings.push('缺少必填字段:' + f + '(风险档 ' + tier + ')');
268
+ }
269
+
270
+ if (tier === 'cross_module' || tier === 'sensitive') {
271
+ const files = card && Array.isArray(card.files) ? card.files : [];
272
+ for (const entry of files) {
273
+ if (!entry || typeof entry.path !== 'string' || typeof entry.line !== 'number') {
274
+ findings.push('files 每一项都必须带 path 与 line');
275
+ break;
276
+ }
277
+ }
278
+ }
279
+
280
+ const unknowns = card && Array.isArray(card.unknowns) ? card.unknowns : [];
281
+ const assumptions = card && Array.isArray(card.assumptions) ? card.assumptions : [];
282
+ if ((tier === 'cross_module' || tier === 'sensitive') && unknowns.length > 0 && assumptions.length === 0) {
283
+ findings.push('WARN: unknowns 非空但无 assumptions(只提醒,不阻断)');
284
+ }
285
+
286
+ if (tier === 'sensitive' && opts.confirmed !== true) {
287
+ return { ok: false, reason: '敏感路径未确认,需先向用户确认后再提交卡片', findings, tier };
288
+ }
289
+
290
+ const hard = findings.filter((f) => !f.startsWith('WARN:'));
291
+ if (hard.length > 0) {
292
+ return { ok: false, reason: '卡片不合规:' + hard.join(';'), findings, tier };
293
+ }
294
+
295
+ return { ok: true, reason: 'ok', findings, tier };
296
+ }