dsh-task-card 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +112 -3
  3. package/cordis.patch.yml +9 -0
  4. package/lib/client.js +3214 -0
  5. package/lib/index.js +1591 -0
  6. package/lib/skill/task-card/SKILL.md +106 -0
  7. package/lib/skill/task-card/bin/instantiate-skeleton.mjs +2618 -0
  8. package/lib/skill/task-card/config.example.md +35 -0
  9. package/lib/skill/task-card/integrations/state-patch.md +173 -0
  10. package/lib/skill/task-card/references/delegation.md +121 -0
  11. package/lib/skill/task-card/references/dependency.md +128 -0
  12. package/lib/skill/task-card/references/gate-rules.md +176 -0
  13. package/lib/skill/task-card/references/recovery.md +106 -0
  14. package/lib/skill/task-card/references/task-format.md +613 -0
  15. package/lib/skill/task-card/references/workflows.md +109 -0
  16. package/lib/skill/task-card/templates/TASKFINISH-row.md +14 -0
  17. package/lib/skill/task-card/templates/TASKS-row.md +16 -0
  18. package/lib/skill/task-card/templates/delegation-brief.md +27 -0
  19. package/lib/skill/task-card/templates/integration-brief.md +32 -0
  20. package/lib/skill/task-card/templates/integration-map.yaml +32 -0
  21. package/lib/skill/task-card/templates/project-doc.md +25 -0
  22. package/lib/skill/task-card/templates/receipt.md +37 -0
  23. package/lib/skill/task-card/templates/skeleton.md +38 -0
  24. package/lib/skill/task-card/templates/skill-eval-report.md +82 -0
  25. package/lib/skill/task-card/templates/skill-eval-request.md +52 -0
  26. package/lib/skill/task-card/templates/skill-eval.md +40 -0
  27. package/lib/skill/task-card/templates/task.md +69 -0
  28. package/package.json +61 -3
@@ -0,0 +1,2618 @@
1
+ #!/usr/bin/env node
2
+ // Skeleton tooling for the task-card skill (zero third-party dependencies).
3
+ //
4
+ // Commands:
5
+ // hash <skillDir> print skillHash (references/task-format.md §3.8)
6
+ // verify <skeleton.md> <skillDir> compare skeleton source.hash with current skillHash
7
+ // test reproduce the contract's T1-T3 vectors
8
+ // fingerprint <task.md> print the card's 12-hex steps fingerprint (task-format.md §4.7)
9
+ // instantiate <skeleton.md> --skill <dir> [--params p.json] [--decisions d.json] [--out file]
10
+ // pure function: skeleton + params + decisions -> instance fragment
11
+ //
12
+ // Instantiate output = normalized `steps:` YAML + checkbox list (the agent merges it into the card
13
+ // and appends the execution-history receipt line with the real date).
14
+ // Params/decisions are JSON files (JSON is a YAML subset), so the parser stays tiny.
15
+
16
+ import { createHash } from 'node:crypto';
17
+ import { existsSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
18
+ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
19
+ import { fileURLToPath } from 'node:url';
20
+
21
+ const INCLUDED_ROOTS = ['SKILL.md', 'references', 'templates'];
22
+
23
+ /* ------------------------------ hashing ------------------------------ */
24
+
25
+ function collectFiles(skillDir) {
26
+ if (!existsSync(skillDir) || !statSync(skillDir).isDirectory()) {
27
+ throw new Error(`skill dir does not exist or is not a directory: ${skillDir}`);
28
+ }
29
+ if (!existsSync(join(skillDir, 'SKILL.md'))) {
30
+ throw new Error(`skill dir has no SKILL.md: ${skillDir}`);
31
+ }
32
+ const out = [];
33
+ const walk = (absDir, relDir) => {
34
+ for (const name of readdirSync(absDir).sort()) {
35
+ const abs = join(absDir, name);
36
+ const rel = relDir ? `${relDir}/${name}` : name;
37
+ const st = statSync(abs);
38
+ if (st.isDirectory()) walk(abs, rel);
39
+ else if (st.isFile() && rel.endsWith('.md')) out.push({ abs, rel });
40
+ }
41
+ };
42
+ for (const root of INCLUDED_ROOTS) {
43
+ const abs = join(skillDir, root);
44
+ if (!existsSync(abs)) continue;
45
+ if (statSync(abs).isFile()) {
46
+ if (root.endsWith('.md')) out.push({ abs, rel: root });
47
+ } else walk(abs, root);
48
+ }
49
+ return out.sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));
50
+ }
51
+
52
+ const normalizeLineEndings = (bytes) =>
53
+ bytes.includes(0x0d) ? Buffer.from(bytes.toString('utf8').replace(/\r\n/g, '\n'), 'utf8') : bytes;
54
+
55
+ function skillHashFromEntries(entries) {
56
+ const sorted = [...entries].sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));
57
+ const chunks = [];
58
+ for (const { rel, bytes } of sorted) {
59
+ // 跨平台一致性:Git 在 core.autocrlf=true(Windows 默认)下会把工作树转成 CRLF,
60
+ // 直接哈希工作树字节会让同一份 skill 在不同平台算出不同哈希。契约要求哈希跨平台一致,
61
+ // 因此先做唯一的归一化:CRLF→LF;其余字节原样(不改编码、不裁剪)。
62
+ // LF 内容的归一化结果与自身相同,存量 12 位钉版继续有效。
63
+ const body = normalizeLineEndings(Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes));
64
+ chunks.push(Buffer.from(rel, 'utf8'), Buffer.from([0]));
65
+ chunks.push(Buffer.from(String(body.length), 'utf8'), Buffer.from([0]));
66
+ chunks.push(body);
67
+ }
68
+ const h = createHash('sha256');
69
+ for (const c of chunks) h.update(c);
70
+ return h.digest('hex');
71
+ }
72
+
73
+ function skillHashDir(skillDir) {
74
+ return skillHashFromEntries(
75
+ collectFiles(skillDir).map(({ abs, rel }) => ({ rel, bytes: readFileSync(abs) })),
76
+ );
77
+ }
78
+
79
+ /* --------------------------- tiny YAML subset ------------------------- */
80
+ // Supports: nested block maps, inline flow maps/lists ({a: b, c: [..]}), quoted/bare scalars,
81
+ // booleans, numbers, null, comments (# outside quotes), and flow values wrapped over lines.
82
+
83
+ function stripComment(line) {
84
+ let inS = false;
85
+ let inD = false;
86
+ for (let i = 0; i < line.length; i += 1) {
87
+ const c = line[i];
88
+ if (c === "'" && !inD) inS = !inS;
89
+ else if (c === '"' && !inS) inD = !inD;
90
+ else if (c === '#' && !inS && !inD && (i === 0 || /\s/.test(line[i - 1]))) {
91
+ return line.slice(0, i).replace(/\s+$/, '');
92
+ }
93
+ }
94
+ return line.replace(/\s+$/, '');
95
+ }
96
+
97
+ function bracketBalance(text) {
98
+ let depth = 0;
99
+ let inS = false;
100
+ let inD = false;
101
+ for (const c of text) {
102
+ if (c === "'" && !inD) inS = !inS;
103
+ else if (c === '"' && !inS) inD = !inD;
104
+ else if (!inS && !inD && (c === '{' || c === '[')) depth += 1;
105
+ else if (!inS && !inD && (c === '}' || c === ']')) depth -= 1;
106
+ }
107
+ return depth;
108
+ }
109
+
110
+ function parseFlow(text) {
111
+ let i = 0;
112
+ const ws = () => {
113
+ while (i < text.length && /\s/.test(text[i])) i += 1;
114
+ };
115
+ const scalar = () => {
116
+ ws();
117
+ if (text[i] === '"' || text[i] === "'") {
118
+ const q = text[i];
119
+ i += 1;
120
+ let s = '';
121
+ while (i < text.length && text[i] !== q) {
122
+ if (q === '"' && text[i] === '\\') {
123
+ i += 1;
124
+ s += text[i];
125
+ } else s += text[i];
126
+ i += 1;
127
+ }
128
+ i += 1;
129
+ return s;
130
+ }
131
+ let s = '';
132
+ while (i < text.length && !',}]'.includes(text[i])) {
133
+ s += text[i];
134
+ i += 1;
135
+ }
136
+ s = s.trim();
137
+ if (s === 'true') return true;
138
+ if (s === 'false') return false;
139
+ if (s === 'null' || s === '') return null;
140
+ if (/^-?\d+(\.\d+)?$/.test(s)) return Number(s);
141
+ return s;
142
+ };
143
+ const value = () => {
144
+ ws();
145
+ if (text[i] === '{') return map();
146
+ if (text[i] === '[') return list();
147
+ return scalar();
148
+ };
149
+ const map = () => {
150
+ i += 1;
151
+ const out = {};
152
+ ws();
153
+ if (text[i] === '}') {
154
+ i += 1;
155
+ return out;
156
+ }
157
+ for (;;) {
158
+ ws();
159
+ let key = '';
160
+ if (text[i] === '"' || text[i] === "'") key = scalar();
161
+ else {
162
+ while (i < text.length && text[i] !== ':') key += text[i++];
163
+ key = key.trim();
164
+ }
165
+ ws();
166
+ if (text[i] !== ':') throw new Error(`flow map: expected ":" near "${text.slice(i)}"`);
167
+ i += 1;
168
+ out[key] = value();
169
+ ws();
170
+ if (text[i] === ',') {
171
+ i += 1;
172
+ continue;
173
+ }
174
+ if (text[i] === '}') {
175
+ i += 1;
176
+ return out;
177
+ }
178
+ throw new Error(`flow map: expected "," or "}" near "${text.slice(i)}"`);
179
+ }
180
+ };
181
+ const list = () => {
182
+ i += 1;
183
+ const out = [];
184
+ ws();
185
+ if (text[i] === ']') {
186
+ i += 1;
187
+ return out;
188
+ }
189
+ for (;;) {
190
+ out.push(value());
191
+ ws();
192
+ if (text[i] === ',') {
193
+ i += 1;
194
+ continue;
195
+ }
196
+ if (text[i] === ']') {
197
+ i += 1;
198
+ return out;
199
+ }
200
+ throw new Error(`flow list: expected "," or "]" near "${text.slice(i)}"`);
201
+ }
202
+ };
203
+ const result = value();
204
+ ws();
205
+ if (i !== text.length) throw new Error(`flow: trailing input "${text.slice(i)}"`);
206
+ return result;
207
+ }
208
+
209
+ function parseYaml(text) {
210
+ const raw = text.split(/\r?\n/);
211
+ const lines = [];
212
+ for (let n = 0; n < raw.length; n += 1) {
213
+ const line = stripComment(raw[n]);
214
+ if (!line.trim()) continue;
215
+ lines.push({ indent: line.match(/^\s*/)[0].length, text: line.trim(), n });
216
+ }
217
+ let idx = 0;
218
+ const parseList = (indent) => {
219
+ const out = [];
220
+ while (idx < lines.length && lines[idx].indent === indent && lines[idx].text.startsWith('- ')) {
221
+ const item = lines[idx].text.slice(2).trim();
222
+ idx += 1;
223
+ const m = /^([A-Za-z0-9_.@-]+):\s*(.*)$/.exec(item);
224
+ if (!m) {
225
+ out.push(parseFlow(item));
226
+ continue;
227
+ }
228
+ const obj = {};
229
+ let [key, rest] = [m[1], m[2]];
230
+ if (rest.startsWith('{') || rest.startsWith('[')) {
231
+ while (idx < lines.length && bracketBalance(rest) > 0) {
232
+ rest += ` ${lines[idx].text}`;
233
+ idx += 1;
234
+ }
235
+ obj[key] = parseFlow(rest);
236
+ } else if (rest === '') {
237
+ if (idx < lines.length && lines[idx].indent > indent) {
238
+ obj[key] = lines[idx].text.startsWith('- ') ? parseList(lines[idx].indent) : parseBlock(lines[idx].indent);
239
+ } else obj[key] = null;
240
+ } else {
241
+ obj[key] = parseFlow(rest);
242
+ }
243
+ // Continuation keys of the same list item (e.g. "- name: x\n status: passed").
244
+ if (idx < lines.length && lines[idx].indent > indent && !lines[idx].text.startsWith('- ')) {
245
+ Object.assign(obj, parseBlock(lines[idx].indent));
246
+ }
247
+ out.push(obj);
248
+ }
249
+ return out;
250
+ };
251
+ const parseBlock = (indent) => {
252
+ const out = {};
253
+ while (idx < lines.length && lines[idx].indent === indent) {
254
+ const m = /^([A-Za-z0-9_.@-]+):\s*(.*)$/.exec(lines[idx].text);
255
+ if (!m) throw new Error(`yaml: cannot parse line ${lines[idx].n + 1}: ${lines[idx].text}`);
256
+ const [, key, restRaw] = m;
257
+ idx += 1;
258
+ let rest = restRaw;
259
+ // Flow value spanning multiple lines.
260
+ if (rest && bracketBalance(rest) > 0) {
261
+ while (idx < lines.length && bracketBalance(rest) > 0) {
262
+ rest += ` ${lines[idx].text}`;
263
+ idx += 1;
264
+ }
265
+ }
266
+ if (rest === '') {
267
+ if (idx < lines.length && lines[idx].indent > indent) {
268
+ out[key] = lines[idx].text.startsWith('- ') ? parseList(lines[idx].indent) : parseBlock(lines[idx].indent);
269
+ } else out[key] = null;
270
+ } else if (rest.startsWith('{') || rest.startsWith('[')) {
271
+ out[key] = parseFlow(rest);
272
+ } else {
273
+ out[key] = parseFlow(rest);
274
+ }
275
+ }
276
+ return out;
277
+ };
278
+ const result = parseBlock(0);
279
+ if (idx !== lines.length) throw new Error(`yaml: unexpected indentation at line ${lines[idx].n + 1}`);
280
+ return result;
281
+ }
282
+
283
+ /* ------------------------------ skeleton ------------------------------ */
284
+
285
+ function splitFrontMatter(text) {
286
+ const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/.exec(text);
287
+ if (!m) throw new Error('no front-matter block (--- ... ---)');
288
+ return { front: m[1], body: m[2] };
289
+ }
290
+
291
+ function loadSkeleton(path) {
292
+ const { front, body } = splitFrontMatter(readFileSync(path, 'utf8'));
293
+ const fm = parseYaml(front);
294
+ if (fm.kind !== 'skeleton') throw new Error('front-matter kind must be "skeleton"');
295
+ if (!fm.source || fm.source.hash === undefined || fm.source.hash === null) throw new Error('skeleton requires source.hash');
296
+ if (typeof fm.source.hash === 'number') {
297
+ throw new Error('source.hash must be quoted (a pure-number pin loses leading zeros / length)');
298
+ }
299
+ const pinned = String(fm.source.hash).toLowerCase();
300
+ if (!/^[0-9a-f]{12,64}$/.test(pinned)) throw new Error(`invalid pinned hash "${pinned}": source.hash must be 12-64 hex chars`);
301
+ if (!fm.workflow) throw new Error('skeleton requires workflow');
302
+ if (!fm.steps || typeof fm.steps !== 'object') throw new Error('skeleton requires steps block');
303
+ if (!fm.steps.entry) throw new Error('skeleton steps requires entry');
304
+ const nodes = {};
305
+ for (const [k, v] of Object.entries(fm.steps)) {
306
+ if (k === 'entry' || k === 'current' || k === 'source') continue;
307
+ if (typeof v !== 'object' || v === null) throw new Error(`step ${k} must be a map`);
308
+ nodes[k] = v;
309
+ }
310
+ return { fm, body, nodes };
311
+ }
312
+
313
+ const PINNED = (v) => {
314
+ if (v === undefined || v === null) return null;
315
+ if (typeof v === 'number') return String(v);
316
+ return String(v).toLowerCase();
317
+ };
318
+
319
+ /** Single source of truth for pin comparison: 12-64 hex; full 64 => exact, shorter => prefix. */
320
+ export function verifySkeleton(skeletonPath, skillDir) {
321
+ const sk = loadSkeleton(skeletonPath);
322
+ const current = skillHashDir(skillDir);
323
+ const pinned = PINNED(sk.fm.source.hash);
324
+ const ok = pinned.length === 64 ? current === pinned : current.startsWith(pinned);
325
+ return { ok, pinned, current, skeleton: sk };
326
+ }
327
+
328
+ /* ---------------------------- instantiate ----------------------------- */
329
+
330
+ function deepClone(v) {
331
+ return JSON.parse(JSON.stringify(v));
332
+ }
333
+
334
+ function replacePlaceholders(value, params, used, where) {
335
+ if (typeof value === 'string') {
336
+ const exact = /^\{\{([A-Za-z0-9_]+)\}\}$/.exec(value);
337
+ if (exact) {
338
+ if (!(exact[1] in params)) throw new Error(`missing param "${exact[1]}" (used by ${where})`);
339
+ used.add(exact[1]);
340
+ return params[exact[1]];
341
+ }
342
+ return value.replace(/\{\{([A-Za-z0-9_]+)\}\}/g, (_, name) => {
343
+ if (!(name in params)) throw new Error(`missing param "${name}" (used by ${where})`);
344
+ used.add(name);
345
+ const v = params[name];
346
+ return Array.isArray(v) ? v.join(', ') : String(v);
347
+ });
348
+ }
349
+ if (Array.isArray(value)) return value.map((x, i) => replacePlaceholders(x, params, used, `${where}[${i}]`));
350
+ if (value && typeof value === 'object') {
351
+ const out = {};
352
+ for (const [k, v] of Object.entries(value)) out[k] = replacePlaceholders(v, params, used, `${where}.${k}`);
353
+ return out;
354
+ }
355
+ return value;
356
+ }
357
+
358
+ function collectPlaceholderNames(value, out = new Set()) {
359
+ if (typeof value === 'string') {
360
+ for (const m of value.matchAll(/\{\{([A-Za-z0-9_]+)\}\}/g)) out.add(m[1]);
361
+ } else if (Array.isArray(value)) value.forEach((v) => collectPlaceholderNames(v, out));
362
+ else if (value && typeof value === 'object') Object.values(value).forEach((v) => collectPlaceholderNames(v, out));
363
+ return out;
364
+ }
365
+
366
+ const isSafeBare = (s) => /^[A-Za-z0-9_./@:+()\u4e00-\u9fa5-]+$/.test(s) && !/^(true|false|null)$/.test(s);
367
+
368
+ function renderScalar(v) {
369
+ if (v === true || v === false) return String(v);
370
+ if (v === null) return 'null';
371
+ if (typeof v === 'number') return String(v);
372
+ if (Array.isArray(v)) return `[${v.map(renderScalar).join(', ')}]`;
373
+ if (typeof v === 'object') return renderFlowMap(v);
374
+ return isSafeBare(v) ? v : JSON.stringify(v);
375
+ }
376
+
377
+ function renderFlowMap(obj) {
378
+ const keys = Object.keys(obj).sort();
379
+ return `{${keys.map((k) => `${k}: ${renderScalar(obj[k])}`).join(', ')}}`;
380
+ }
381
+
382
+ /** Natural order for step ids: S1 < S1.2 < S1.10 < S1.10.1 (dot segments compared numerically). */
383
+ function naturalCompare(a, b) {
384
+ const pa = a.split('.');
385
+ const pb = b.split('.');
386
+ for (let i = 0; i < Math.max(pa.length, pb.length); i += 1) {
387
+ if (pa[i] === undefined) return -1;
388
+ if (pb[i] === undefined) return 1;
389
+ const na = /^\d+$/.test(pa[i]);
390
+ const nb = /^\d+$/.test(pb[i]);
391
+ if (na && nb) {
392
+ const diff = Number(pa[i]) - Number(pb[i]);
393
+ if (diff !== 0) return diff;
394
+ } else {
395
+ const diff = pa[i] < pb[i] ? -1 : pa[i] > pb[i] ? 1 : 0;
396
+ if (diff !== 0) return diff;
397
+ }
398
+ }
399
+ return 0;
400
+ }
401
+
402
+ function renderSteps(steps) {
403
+ const lines = ['steps:'];
404
+ for (const key of ['source', 'entry', 'current']) {
405
+ if (steps[key] !== undefined) lines.push(` ${key}: ${renderScalar(steps[key])}`);
406
+ }
407
+ for (const id of Object.keys(steps).sort(naturalCompare)) {
408
+ if (['source', 'entry', 'current'].includes(id)) continue;
409
+ lines.push(` ${id}: ${renderFlowMap(steps[id])}`);
410
+ }
411
+ return lines.join('\n');
412
+ }
413
+
414
+ function checkboxFromBody(body) {
415
+ const lines = [];
416
+ for (const line of body.split(/\r?\n/)) {
417
+ const m = /^(\s*)-\s*\[\s*\]\s+(S[0-9A-Za-z_.]*)\s+(.*)$/.exec(line);
418
+ if (!m) continue;
419
+ // 保留实际缩进;层级是否匹配由覆盖检查负责(支持 S1.1.1 这类多层 id)。
420
+ lines.push(`${m[1]}- [ ] ${m[2]} ${m[3]}`.replace(/\s+$/, ''));
421
+ }
422
+ return lines;
423
+ }
424
+
425
+ function instantiate({ skeletonPath, skillDir, paramsPath, decisionsPath }) {
426
+ const { ok: pinOk, pinned, current: currentHash, skeleton: sk } = verifySkeleton(skeletonPath, skillDir);
427
+ if (!pinOk) {
428
+ throw new Error(
429
+ `stale skeleton: pinned ${pinned}, current ${currentHash.slice(0, 12)} — update skeleton and re-pin before instantiating`,
430
+ );
431
+ }
432
+ const readJson = (p, label) => {
433
+ if (!p) return {};
434
+ const text = readFileSync(p, 'utf8');
435
+ try {
436
+ return JSON.parse(text);
437
+ } catch (e) {
438
+ throw new Error(`${label} must be JSON (YAML subset): ${e.message}`);
439
+ }
440
+ };
441
+ const params = readJson(paramsPath, 'params');
442
+ const decisions = readJson(decisionsPath, 'decisions');
443
+
444
+ const nodes = deepClone(sk.nodes);
445
+ const used = new Set();
446
+ for (const [id, node] of Object.entries(nodes)) {
447
+ nodes[id] = replacePlaceholders(node, params, used, id);
448
+ }
449
+ for (const name of Object.keys(params)) {
450
+ if (!used.has(name)) throw new Error(`unused param "${name}"`);
451
+ }
452
+ // Source marker: skeleton-derived nodes carry from=<workflow>; task-added steps may use `task`.
453
+ for (const node of Object.values(nodes)) {
454
+ if (node.from === undefined) node.from = sk.fm.workflow;
455
+ }
456
+
457
+ // Decisions: pin decided, mark the targets of unselected branches as skipped.
458
+ const decisionNodes = Object.entries(nodes).filter(([, n]) => n.type === 'decision').map(([id]) => id);
459
+ const usedDecisionNodes = new Set();
460
+ for (const [id, node] of Object.entries(nodes)) {
461
+ if (node.type !== 'decision') continue;
462
+ const chosen = Object.entries(decisions).find(([, d]) => d && d.node === id);
463
+ if (!chosen) throw new Error(`decision node ${id} has no entry in decisions file`);
464
+ const [dId, d] = chosen;
465
+ if (usedDecisionNodes.has(id)) throw new Error(`decision node ${id} has more than one entry in decisions file`);
466
+ usedDecisionNodes.add(id);
467
+ if (!d.reason || !String(d.reason).trim()) throw new Error(`decision ${dId}: reason is required`);
468
+ const choices = (node.branches || []).map((b) => b.if);
469
+ if (!choices.includes(d.choice)) {
470
+ throw new Error(`decision ${dId}: choice "${d.choice}" is not one of ${JSON.stringify(choices)}`);
471
+ }
472
+ node.decided = dId;
473
+ for (const br of node.branches || []) {
474
+ if (br.go === 'end') throw new Error(`decision ${dId}: branch target must be a node, not end`);
475
+ if (!nodes[br.go]) throw new Error(`decision ${dId}: branch target ${br.go} does not exist`);
476
+ if (br.if === d.choice) continue;
477
+ // required + skip is allowed: skip wins (task-format.md §3.5 rule 8).
478
+ nodes[br.go].skip = dId;
479
+ }
480
+ const live = liveBranches(nodes, node);
481
+ if (live.length !== 1) throw new Error(`decision ${dId}: ${live.length} live branches after applying the decision (need exactly 1)`);
482
+ }
483
+ // Reverse direction: every decisions-file entry must target a real decision node, once.
484
+ for (const [dId, d] of Object.entries(decisions)) {
485
+ if (!d || !d.node) throw new Error(`decision ${dId}: node is required`);
486
+ if (!nodes[d.node]) throw new Error(`decision ${dId}: node ${d.node} does not exist`);
487
+ if (nodes[d.node].type !== 'decision') throw new Error(`decision ${dId}: node ${d.node} is not a decision node`);
488
+ if (Object.values(decisions).filter((x) => x && x.node === d.node).length > 1) {
489
+ throw new Error(`decision node ${d.node} has more than one entry in decisions file`);
490
+ }
491
+ }
492
+
493
+ // Counters: retry max comes from the skeleton; loop iter length from the `over` list.
494
+ for (const [id, node] of Object.entries(nodes)) {
495
+ if (node.retry !== undefined && typeof node.retry !== 'object') {
496
+ const max = Number(node.retry);
497
+ if (!Number.isInteger(max) || max < 1) throw new Error(`step ${id}: retry must be a positive integer`);
498
+ node.retry = `0/${max}`;
499
+ }
500
+ if (node.type === 'loop') {
501
+ const over = node.over;
502
+ if (!Array.isArray(over)) throw new Error(`loop ${id}: over must resolve to a list`);
503
+ node.iter = `0/${over.length}`;
504
+ }
505
+ }
506
+
507
+ // Structural coverage: entry exists; every node ↔ checkbox; indent matches depth.
508
+ // (Required nodes cannot be "missing" here because instantiation never drops nodes;
509
+ // the contract documents this honestly instead of pretending it is a real check.)
510
+ if (!nodes[sk.fm.steps.entry]) throw new Error(`coverage: entry node ${sk.fm.steps.entry} does not exist`);
511
+ const boxes = checkboxFromBody(sk.body);
512
+ const boxIds = boxes.map((line) => /^(\s*)- \[ \] (S[0-9A-Za-z_.]*)/.exec(line)).filter(Boolean);
513
+ const boxIdList = boxIds.map((m) => m[2]);
514
+ for (const id of Object.keys(nodes)) {
515
+ if (!boxIdList.includes(id)) throw new Error(`coverage: node ${id} has no checkbox in the skeleton body`);
516
+ }
517
+ for (const m of boxIds) {
518
+ const indent = m[1];
519
+ const id = m[2];
520
+ if (!nodes[id]) throw new Error(`coverage: checkbox ${id} has no node in the skeleton steps`);
521
+ const depth = id.split('.').length;
522
+ if (indent.length !== (depth - 1) * 2) {
523
+ throw new Error(`coverage: checkbox ${id} indent ${indent.length} should be ${(depth - 1) * 2}`);
524
+ }
525
+ }
526
+
527
+ const instanceSteps = { source: `${sk.fm.workflow}@${pinned}`, entry: sk.fm.steps.entry, current: sk.fm.steps.entry, ...nodes };
528
+ const yaml = renderSteps(instanceSteps);
529
+ return { yaml, boxes, hash: currentHash, workflow: sk.fm.workflow };
530
+ }
531
+
532
+ /* ------------------------------ check card ---------------------------- */
533
+
534
+ const REQUIRED_CARD_KEYS = ['id', 'title', 'status', 'created', 'updated'];
535
+ const BUDGET_KEYS = new Set(['retries', 'tool_calls', 'dispatches']);
536
+ // v4 compatibility only; v5 removes this read-only legacy counter.
537
+ const DEPRECATED_BUDGET_KEYS = new Set(['wall_clock_min']);
538
+ const STATUSES = new Set(['active', 'paused', 'blocked', 'done', 'cancelled']);
539
+ /** 步骤清单的文案前缀(契约 §4.3):以 `skill:<名字> ` 开头的步骤是从那个 skill 的正文里提取出来的。
540
+ * 前缀与 from 是否一致(checkCard)、执行史里有没有它的收据(missingReceipts)都按这一个正则认,口径不分叉。 */
541
+ const SKILL_TEXT_PREFIX = /^skill:([a-z0-9][a-z0-9-]*)\s+/;
542
+
543
+ /** Routing/state diagnostics for a steps block — SINGLE SOURCE shared with advance().
544
+ * Exported so tests can differential-test it against advance() (对拍). */
545
+ export function diagnoseSteps(steps, status, checkedSet = new Set()) {
546
+ const issues = [];
547
+ const nodes = {};
548
+ for (const [k, v] of Object.entries(steps)) {
549
+ if (['source', 'entry', 'current'].includes(k)) continue;
550
+ if (v !== null && typeof v !== 'object') {
551
+ issues.push(`step ${k}: must be a map`);
552
+ nodes[k] = {};
553
+ continue;
554
+ }
555
+ nodes[k] = v || {};
556
+ }
557
+ const ids = Object.keys(nodes);
558
+ if (!ids.length) issues.push('steps block has no nodes');
559
+ if (steps.source && !steps.entry) issues.push('steps.entry missing (required for instantiated cards)');
560
+ if (!steps.current) issues.push('steps.current missing');
561
+ const currentIsEnd = steps.current === 'end';
562
+ if (steps.current && !currentIsEnd && !nodes[steps.current]) issues.push(`current points to unknown node: ${steps.current}`);
563
+ if (steps.entry && !nodes[steps.entry]) issues.push(`entry points to unknown node: ${steps.entry}`);
564
+
565
+ const NODE_KEYS = new Set(['from', 'required', 'decided', 'skip', 'waive', 'block', 'next', 'type', 'branches', 'over', 'body', 'exit', 'iter', 'retry', 'pass', 'exhausted']);
566
+ const loopBodyLast = new Set();
567
+ for (const node of Object.values(nodes)) {
568
+ if (node.type === 'loop' && Array.isArray(node.body) && node.body.length) {
569
+ loopBodyLast.add(node.body[node.body.length - 1]);
570
+ }
571
+ }
572
+ const targetExists = (t) => t === 'end' || Boolean(nodes[t]);
573
+
574
+ for (const id of ids) {
575
+ const node = nodes[id];
576
+ const depth = id.split('.').length;
577
+ if (depth > 5) issues.push(`node ${id}: more than 5 levels`);
578
+ if (depth > 1) {
579
+ const parent = id.split('.').slice(0, -1).join('.');
580
+ if (!nodes[parent]) issues.push(`node ${id}: parent ${parent} missing`);
581
+ }
582
+ for (const k of Object.keys(node)) if (!NODE_KEYS.has(k)) issues.push(`node ${id}: unknown key "${k}"`);
583
+ if (node.from !== undefined && !/^(task|[a-z0-9][a-z0-9-]*)$/.test(String(node.from))) {
584
+ issues.push(`node ${id}: from must be <workflow-name> or task`);
585
+ }
586
+ if (node.type === 'decision') {
587
+ if (!Array.isArray(node.branches) || node.branches.length < 2) issues.push(`node ${id}: decision requires >=2 branches`);
588
+ for (const br of node.branches || []) {
589
+ if (br.if === undefined || br.if === '') issues.push(`node ${id}: branch missing if`);
590
+ if (br.go === 'end') issues.push(`node ${id}: branch target must be a node, not end`);
591
+ else if (!nodes[br.go]) issues.push(`node ${id}: branch target ${br.go} does not exist`);
592
+ }
593
+ const live = liveBranches(nodes, node);
594
+ if (node.branches && live.length !== 1) issues.push(`node ${id}: decision must have exactly 1 live branch (got ${live.length})`);
595
+ if (!node.decided) issues.push(`node ${id}: decision requires decided pointer`);
596
+ } else if (node.type === 'loop') {
597
+ if (!Array.isArray(node.body) || !node.body.length) issues.push(`node ${id}: loop requires non-empty body`);
598
+ for (const b of node.body || []) if (!nodes[b]) issues.push(`node ${id}: body node ${b} missing`);
599
+ if (node.over === undefined) issues.push(`node ${id}: loop requires over`);
600
+ if (!targetExists(node.exit)) issues.push(`node ${id}: loop requires exit target`);
601
+ } else if (node.type !== undefined) {
602
+ issues.push(`node ${id}: unknown type "${node.type}"`);
603
+ }
604
+ if (node.next !== undefined) {
605
+ if (!targetExists(node.next)) issues.push(`node ${id}: next target ${node.next} does not exist`);
606
+ } else if (!node.type && !loopBodyLast.has(id) && !node.pass) {
607
+ const kind = isSkipped(node) ? 'skip/waive node' : 'normal node';
608
+ issues.push(`node ${id}: missing next (${kind} requires next; only last loop-body node may omit)`);
609
+ }
610
+ for (const outKey of ['pass', 'exhausted']) {
611
+ if (node[outKey] !== undefined && !targetExists(node[outKey])) issues.push(`node ${id}: ${outKey} target ${node[outKey]} does not exist`);
612
+ }
613
+ if (node.branches !== undefined && node.type !== 'decision') issues.push(`node ${id}: branches only allowed on decision nodes`);
614
+ if (node.skip !== undefined && !/^D[0-9]+$/.test(String(node.skip))) issues.push(`node ${id}: skip must be a decision pointer D#`);
615
+ if (node.waive !== undefined && !/^D[0-9]+$/.test(String(node.waive))) issues.push(`node ${id}: waive must be a decision pointer D#`);
616
+ if (node.retry !== undefined && !/^\d+\/\d+$/.test(String(node.retry))) issues.push(`node ${id}: retry must be <used>/<max>`);
617
+ if (node.iter !== undefined && !/^\d+\/\d+$/.test(String(node.iter))) issues.push(`node ${id}: iter must be <used>/<max>`);
618
+ }
619
+
620
+ if (steps.current && !currentIsEnd && nodes[steps.current] && isSkipped(nodes[steps.current])) {
621
+ issues.push(`current points to a skip/waive node: ${steps.current}`);
622
+ }
623
+
624
+ for (const id of ids) {
625
+ if (!checkedSet.has(id)) continue;
626
+ // 直接子节点即可递归保证「父勾 ⇒ 所有后代已勾」;避免多层重复报同一问题。
627
+ const children = ids.filter((c) => c.split('.').slice(0, -1).join('.') === id);
628
+ for (const c of children) {
629
+ if (!checkedSet.has(c) && !isSkipped(nodes[c])) issues.push(`node ${id} is checked but child ${c} is not`);
630
+ }
631
+ }
632
+
633
+ const unfinished = ids.filter((id) => !checkedSet.has(id) && !isSkipped(nodes[id]));
634
+ if (currentIsEnd && !['done', 'cancelled'].includes(status) && unfinished.length) {
635
+ issues.push(`current=end but steps unfinished: ${unfinished.join(', ')}`);
636
+ }
637
+ return { issues, nodes, ids };
638
+ }
639
+
640
+ const FLOW_KINDS = new Set(['defined', 'skill', 'ad-hoc']);
641
+
642
+ function checkFlowYaml(path, steps, warnings, issues) {
643
+ const flowPath = join(dirname(path), 'flow.yaml');
644
+ if (!existsSync(flowPath)) return false;
645
+ let flow;
646
+ try {
647
+ flow = parseYaml(readFileSync(flowPath, 'utf8'));
648
+ } catch (e) {
649
+ issues.push(`flow.yaml parse error: ${e.message}`);
650
+ return false;
651
+ }
652
+ if (!flow || typeof flow !== 'object' || Array.isArray(flow)) {
653
+ issues.push('flow.yaml must be a map');
654
+ return false;
655
+ }
656
+ for (const key of ['workflow', 'kind', 'ref']) {
657
+ if (typeof flow[key] !== 'string' || !flow[key].trim()) issues.push(`flow.yaml missing ${key}`);
658
+ }
659
+ if (typeof flow.kind === 'string' && !FLOW_KINDS.has(flow.kind)) {
660
+ issues.push(`flow.yaml invalid kind: ${flow.kind} (defined | skill | ad-hoc)`);
661
+ }
662
+ const current = flow.current_stage;
663
+ if (current !== undefined && current !== null && String(current).trim()) {
664
+ const value = String(current).trim();
665
+ if (/^S[0-9A-Za-z_.]*$/.test(value)) {
666
+ if (!steps[value]) issues.push(`flow.yaml current_stage ${value} is not a step in steps`);
667
+ } else {
668
+ warnings.push(`flow.yaml current_stage "${value}" is a legacy label (not a step id); migrate to a step id when convenient`);
669
+ }
670
+ }
671
+ return true;
672
+ }
673
+
674
+ function checkStageEvidence(path, nodes, boxes, body, warnings, issues, strict) {
675
+ const checked = boxes.filter((b) => b.checked);
676
+ if (!checked.length) return;
677
+ const sections = sectionMap(body);
678
+ const evidenceText = [sections.get('验证记录'), sections.get('执行史')].filter(Boolean).join('\n');
679
+ const lines = evidenceText.split(/\r?\n/);
680
+ const markers = /产物|文件|命令|exit|用户|验证人|证据|回执|evidence/i;
681
+ const escape = (s) => String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
682
+ const mentions = (line, id) => new RegExp(`(?:^|[^0-9A-Za-z_.])${escape(id)}(?:[^0-9A-Za-z_.]|$)`).test(line);
683
+ for (const box of checked) {
684
+ const node = nodes[box.id];
685
+ if (!node) continue;
686
+ const from = node.from === undefined || node.from === null ? '' : String(node.from);
687
+ if (!from || from === 'task') continue;
688
+ const relevant = lines.filter((line) => {
689
+ if (!line.trim() || /<[^>]+>/.test(line)) return false;
690
+ return mentions(line, box.id) && markers.test(line);
691
+ });
692
+ if (!relevant.length) {
693
+ const msg = `阶段步骤 ${box.id}(from: ${from})已勾选,但「验证记录」/「执行史」没有可核对证据(产物/命令/exit/用户点头)`;
694
+ if (strict) issues.push(msg);
695
+ else warnings.push(msg);
696
+ continue;
697
+ }
698
+ for (const line of relevant) {
699
+ // 「产物:」「文件:」只有落在一个字段的开头才算:行首(可带 `- [..]` 标记),或竖线、分号、逗号之后。
700
+ // 写在括号等说明里的(例如 `exit=0(含「打开文件:某个断言名」一组)`)不是在声称产物,不当成路径去核对。
701
+ // 判断错了的症状:写在别处的真产物不被核对(漏报)——存量证据行已用新旧两版逐条对比,取到的产物完全一致。
702
+ const m = /(?:^-\s*(?:\[[^\]]*\]\s*)?|[|;;,,]\s*)(?:产物|文件)\s*[::]\s*([^\s|,,;;()、]+)/.exec(line);
703
+ if (!m) continue;
704
+ const artifact = m[1].trim();
705
+ if (!artifact || artifact.startsWith('<') || /^https?:/i.test(artifact) || /[*?]/.test(artifact)) continue;
706
+ const candidates = [
707
+ resolve(dirname(path), artifact),
708
+ resolve(projectRootForCard(path), artifact),
709
+ ];
710
+ if (candidates.some((p) => existsSync(p))) continue;
711
+ const msg = `阶段步骤 ${box.id} 的证据产物不存在:${artifact}(按卡目录/项目根解析)`;
712
+ if (strict) issues.push(msg);
713
+ else warnings.push(msg);
714
+ }
715
+ }
716
+ }
717
+
718
+ function checkCard(path, options = {}) {
719
+ const strict = Boolean(options && options.strict);
720
+ const warnings = [];
721
+ let front;
722
+ let body;
723
+ try {
724
+ const parts = splitFrontMatter(readFileSync(path, 'utf8'));
725
+ front = parts.front;
726
+ body = parts.body;
727
+ } catch (e) {
728
+ return { legacy: false, issues: [`front-matter error: ${e.message}`], warnings };
729
+ }
730
+ let fm;
731
+ try {
732
+ fm = parseYaml(front);
733
+ } catch (e) {
734
+ return { legacy: false, issues: [`yaml parse error: ${e.message}`], warnings };
735
+ }
736
+ const issues = [];
737
+ for (const k of REQUIRED_CARD_KEYS) if (fm[k] === undefined || fm[k] === null) issues.push(`missing key: ${k}`);
738
+ if (fm.status && !STATUSES.has(fm.status)) issues.push(`invalid status: ${fm.status}`);
739
+ if (fm.id && !/^[a-z0-9]+(-[a-z0-9]+)*$/.test(fm.id)) issues.push(`invalid id: ${fm.id}`);
740
+ if (fm.id && fm.id !== basename(dirname(path))) issues.push(`id (${fm.id}) must equal directory name (${basename(dirname(path))})`);
741
+ if (fm.title !== undefined && (typeof fm.title !== 'string' || !fm.title.trim())) issues.push('title must be a non-empty string');
742
+ for (const k of ['created', 'updated']) {
743
+ if (fm[k] !== undefined && !/^\d{4}-\d{2}-\d{2}$/.test(String(fm[k]))) issues.push(`${k} must be YYYY-MM-DD`);
744
+ }
745
+ if (fm.created && fm.updated && String(fm.updated) < String(fm.created)) issues.push('updated must not be earlier than created');
746
+ if (fm.status === 'blocked' && !(fm['blocked-by']?.length || fm['blocked-reason'])) {
747
+ issues.push('status=blocked requires blocked-by or blocked-reason');
748
+ }
749
+ if (fm.budget !== undefined && fm.budget !== null) {
750
+ if (!fm.budget || typeof fm.budget !== 'object' || Array.isArray(fm.budget)) {
751
+ issues.push('budget must be a map');
752
+ } else {
753
+ for (const key of Object.keys(fm.budget)) {
754
+ if (DEPRECATED_BUDGET_KEYS.has(key)) {
755
+ warnings.push(`budget.${key} is deprecated since v4; read-only compatibility through v4, removed in v5`);
756
+ } else if (!BUDGET_KEYS.has(key)) {
757
+ issues.push(`budget has unknown counter: ${key}`);
758
+ }
759
+ const counter = fm.budget[key];
760
+ if (!counter || typeof counter !== 'object' || Array.isArray(counter)) {
761
+ issues.push(`budget.${key} must be a map with used and limit`);
762
+ continue;
763
+ }
764
+ for (const field of ['used', 'limit']) {
765
+ if (!Number.isInteger(counter[field]) || counter[field] < 0) {
766
+ issues.push(`budget.${key}.${field} must be a non-negative integer`);
767
+ }
768
+ }
769
+ if (Number.isInteger(counter.used) && Number.isInteger(counter.limit) && counter.used > counter.limit) {
770
+ issues.push(`budget.${key}.used exceeds limit`);
771
+ }
772
+ }
773
+ }
774
+ }
775
+
776
+ checkDocsAgainst(fm, path, warnings);
777
+
778
+ const steps = fm.steps;
779
+ if (!steps) return { legacy: true, issues, warnings };
780
+ checkFlowYaml(path, steps, warnings, issues);
781
+ // New-card rules (legacy cards above are exempt).
782
+ for (const forbidden of ['type', 'workflow']) {
783
+ if (fm[forbidden] !== undefined) issues.push(`${forbidden} must not be written on new cards (legacy-only field)`);
784
+ }
785
+ if (steps.source !== undefined && steps.source !== null) {
786
+ if (!/^[a-z0-9-]+@[0-9a-f]{12,64}$/.test(String(steps.source))) {
787
+ issues.push(`steps.source must look like <workflow>@<hash12+>: ${steps.source}`);
788
+ }
789
+ }
790
+
791
+ /* --- checkbox ↔ node coverage (checkbox may be indented; indent must match id depth) --- */
792
+ const boxes = [];
793
+ for (const line of body.split(/\r?\n/)) {
794
+ const m = /^(\s*)-\s*\[([ xX])\]\s+(S[0-9A-Za-z_.]*)\s+(.*)$/.exec(line);
795
+ if (m) boxes.push({ id: m[3], checked: m[2].toLowerCase() === 'x', indent: m[1].length, text: m[4].trim() });
796
+ }
797
+ const checkedSet = new Set(boxes.filter((b) => b.checked).map((b) => b.id));
798
+
799
+ /* --- routing/state diagnostics: single source shared with advance() --- */
800
+ const d = diagnoseSteps(steps, fm.status, checkedSet);
801
+ issues.push(...d.issues);
802
+ const { nodes, ids } = d;
803
+
804
+ /* --- checkbox ↔ node coverage --- */
805
+ const boxIds = new Set(boxes.map((b) => b.id));
806
+ for (const id of ids) if (!boxIds.has(id)) issues.push(`checkbox missing for node: ${id}`);
807
+ const dupIds = new Set();
808
+ for (const b of boxes) {
809
+ if (!nodes[b.id]) issues.push(`checkbox without node: ${b.id}`);
810
+ const depth = b.id.split('.').length;
811
+ const expectIndent = (depth - 1) * 2;
812
+ if (b.indent !== expectIndent) issues.push(`checkbox ${b.id}: indent ${b.indent} should be ${expectIndent} (must match id depth)`);
813
+ if (boxes.filter((x) => x.id === b.id).length > 1) dupIds.add(b.id);
814
+ }
815
+ for (const id of dupIds) issues.push(`duplicate checkbox: ${id}`);
816
+
817
+ for (const b of boxes) {
818
+ const node = nodes[b.id];
819
+ if (!node) continue;
820
+ const skillPrefix = SKILL_TEXT_PREFIX.exec(b.text ?? '');
821
+ if (skillPrefix) {
822
+ const from = node.from === undefined || node.from === null ? '' : String(node.from);
823
+ if (from !== skillPrefix[1]) {
824
+ issues.push(`checkbox ${b.id}: skill prefix "${skillPrefix[1]}" does not match from "${from}"`);
825
+ }
826
+ }
827
+ if (isSkipped(node) && b.checked) issues.push(`node ${b.id} is skip/waive but checkbox is checked`);
828
+ if (!['done', 'cancelled'].includes(fm.status) && b.id === steps.current && b.checked) {
829
+ issues.push(`current node ${b.id} is already checked`);
830
+ }
831
+ }
832
+ // v4.3:不再以卡旁有没有 flow.yaml 为前提;卡里有「按某 skill 做」的已勾步骤就查(gate-rules.md §2b)。
833
+ checkStageEvidence(path, nodes, boxes, body, warnings, issues, strict);
834
+
835
+ const exhausted = fm.budget && Object.entries(fm.budget)
836
+ .filter(([, counter]) => counter && typeof counter === 'object' && !Array.isArray(counter) &&
837
+ Number.isInteger(counter.used) && Number.isInteger(counter.limit) && counter.used >= counter.limit)
838
+ .map(([key]) => key);
839
+ if (exhausted?.length && !['done', 'cancelled'].includes(fm.status)) {
840
+ issues.push(`budget_exhausted: ${exhausted.join(', ')}; pause and report before continuing`);
841
+ }
842
+ const unreachable = unreachableBeforeCurrent(steps, nodes, checkedSet);
843
+ if (unreachable.length && !['done', 'cancelled'].includes(fm.status)) {
844
+ warnings.push(`当前步骤 ${steps.current} 之前的路线上有没勾也没跳过的步骤:${unreachable.join(', ')}。路线不经过它们,到收尾才报未完成;把当前步骤移过去,或给它们标跳过`);
845
+ }
846
+ checkSkillEval(path, steps, nodes, ids, boxes, body, warnings);
847
+
848
+ return { legacy: false, issues, warnings, ids, boxes };
849
+ }
850
+
851
+ /* ------------------ 步骤归属评估记录与步骤指纹(契约 §4.7) ------------------ */
852
+ // 这里只做机械部分:认记录、算指纹、核对 from 的合法范围、落盘前校验。
853
+ // skill 是否适用由评估和用户判断,脚本不判断(契约 §11 第 8 条)。流程见 gate-rules.md §1c。
854
+
855
+ const EVAL_SKIP_BY_USER = '跳过(用户决定)';
856
+ const EVAL_RESULTS = new Set(['已确认', '已否决', EVAL_SKIP_BY_USER, '跳过(本卡不再评估)', '无 skill 可评']);
857
+ const EVAL_SKIP_RESULTS = new Set([EVAL_SKIP_BY_USER, '跳过(本卡不再评估)']);
858
+ const EVAL_NO_SKILL_RESULT = '无 skill 可评';
859
+ const STEP_TOP_KEYS = new Set(['entry', 'current', 'source']);
860
+ // 指纹不取的节点键:这些在运行时会合法地变(跳过、放弃、决策指针、阻塞原因、重试与循环计数)。
861
+ const FINGERPRINT_SKIP_KEYS = new Set(['skip', 'waive', 'decided', 'block', 'retry', 'iter']);
862
+
863
+ function checkboxTexts(boxes) {
864
+ const texts = new Map();
865
+ for (const b of boxes || []) if (!texts.has(b.id)) texts.set(b.id, String(b.text ?? '').trim());
866
+ return texts;
867
+ }
868
+
869
+ /** 一个节点进指纹的部分:不取的键以外的全部键,按字母序,加上勾选框整行文案。 */
870
+ function nodeSignature(node, text) {
871
+ const n = node && typeof node === 'object' ? node : {};
872
+ const keys = Object.keys(n).filter((k) => !FINGERPRINT_SKIP_KEYS.has(k)).sort();
873
+ return `${keys.map((k) => `${k}=${JSON.stringify(n[k] ?? null)}`).join(',')}|${String(text ?? '').trim()}`;
874
+ }
875
+
876
+ const ROUTE_KEYS = ['next', 'pass', 'exhausted', 'exit'];
877
+
878
+ /** 一个节点沿路由指向哪些节点:next/pass/exhausted/exit,决策节点的 branches[].go,循环节点的 body[]。 */
879
+ function routeTargets(node) {
880
+ const outs = [];
881
+ for (const rk of ROUTE_KEYS) if (typeof node[rk] === 'string') outs.push(node[rk]);
882
+ if (Array.isArray(node.branches)) for (const b of node.branches) if (b && typeof b.go === 'string') outs.push(b.go);
883
+ if (Array.isArray(node.body)) for (const x of node.body) if (typeof x === 'string') outs.push(x);
884
+ return outs;
885
+ }
886
+
887
+ /** 一个节点的前驱和后继(只算两边都存在的节点,新增的不算)。用来认「先后顺序」有没有变。 */
888
+ function neighbors(allSteps, id, known) {
889
+ const preds = new Set();
890
+ const succs = new Set();
891
+ if (allSteps.entry === id) preds.add('<entry>');
892
+ for (const [k, n] of Object.entries(allSteps)) {
893
+ if (STEP_TOP_KEYS.has(k) || !n || typeof n !== 'object') continue;
894
+ for (const o of routeTargets(n)) {
895
+ if (o === id && known.has(k)) preds.add(k);
896
+ if (k === id && known.has(o)) succs.add(o);
897
+ }
898
+ }
899
+ return `${[...preds].sort().join(',')}→${[...succs].sort().join(',')}`;
900
+ }
901
+
902
+ /**
903
+ * 从 start 沿路由走得到的所有节点(不含 start 自己;走到过的不再走,防环)。
904
+ * 这是结构上的可达:决策的全部分支、循环体和出口都算,不看当前哪条分支是活的。
905
+ */
906
+ function reachableFrom(allSteps, start) {
907
+ const seen = new Set([start]);
908
+ const stack = [start];
909
+ while (stack.length) {
910
+ const node = allSteps[stack.pop()];
911
+ if (!node || typeof node !== 'object') continue;
912
+ for (const o of routeTargets(node)) {
913
+ if (seen.has(o) || !allSteps[o] || typeof allSteps[o] !== 'object' || STEP_TOP_KEYS.has(o)) continue;
914
+ seen.add(o);
915
+ stack.push(o);
916
+ }
917
+ }
918
+ seen.delete(start);
919
+ return seen;
920
+ }
921
+
922
+ /** 落盘前校验用来认「这一步改动过没有」:路由键和不取的键以外的全部键、前驱后继、勾选框整行文案。 */
923
+ function stepSignature(node, text, allSteps, id, known) {
924
+ const n = node && typeof node === 'object' ? node : {};
925
+ const keys = Object.keys(n).filter((k) => !FINGERPRINT_SKIP_KEYS.has(k) && !ROUTE_KEYS.includes(k)).sort();
926
+ return `${keys.map((k) => `${k}=${JSON.stringify(n[k] ?? null)}`).join(',')}|${neighbors(allSteps, id, known)}|${String(text ?? '').trim()}`;
927
+ }
928
+
929
+ /** 步骤指纹(契约 §4.7 第 2 条):编号和层级、from、先后顺序、勾选框整行文案。返回 12 位十六进制。 */
930
+ export function stepsFingerprint(steps, boxes) {
931
+ const s = steps && typeof steps === 'object' ? steps : {};
932
+ const texts = checkboxTexts(boxes);
933
+ const parts = [`entry=${String(s.entry ?? '')}`, `source=${String(s.source ?? '')}`];
934
+ for (const id of Object.keys(s).filter((k) => !STEP_TOP_KEYS.has(k)).sort()) {
935
+ parts.push(`${id}(${nodeSignature(s[id], texts.get(id))})`);
936
+ }
937
+ return createHash('sha256').update(parts.join('\n'), 'utf8').digest('hex').slice(0, 12);
938
+ }
939
+
940
+ /** 一张卡当前的步骤指纹(契约 §4.7 第 2 条)。没有 steps 块的旧格式卡返回 null。 */
941
+ export function fingerprintOf(cardPath) {
942
+ const r = checkCard(cardPath);
943
+ if (r.legacy) return null;
944
+ return stepsFingerprint(parseYaml(splitFrontMatter(readFileSync(cardPath, 'utf8')).front).steps, r.boxes);
945
+ }
946
+
947
+ /** 动作段的合法写法:恰好「skill 评估」,中间空白随意。 */
948
+ const EVAL_ACTION_EXACT = /^skill\s*评估$/;
949
+
950
+ /**
951
+ * 执行史里的「skill 评估」行:只认执行史节、动作段、结果段(契约 §4.7 第 1 条)。
952
+ * 动作段要以「skill 评估」开头才算评估行;合法还要动作段恰好是它、结果段是五种之一。
953
+ * 以它开头的其他写法(如「skill 评估(自评)」)算评估行但不合法——按"评估未完成"处理,不能冒充评过。
954
+ * 不再认「步骤归属评估」这个说法:动作段宽一截,结果段却按五种判,一行自评就能冒充评估记录。
955
+ */
956
+ export function parseSkillEvals(body) {
957
+ const rows = [];
958
+ for (const raw of String(sectionMap(body).get('执行史') ?? '').split(/\r?\n/)) {
959
+ const line = raw.trim();
960
+ if (!line.startsWith('-')) continue;
961
+ const cells = line.slice(1).split('|').map((c) => c.trim());
962
+ if (cells.length < 5) continue;
963
+ const [time, action, result, artifact, evidence] = cells;
964
+ if (!/^skill\s*评估/.test(action)) continue;
965
+ const fp = /steps=([0-9a-f]+)/i.exec(evidence);
966
+ rows.push({ time, action, result, artifact, fingerprint: fp ? fp[1].toLowerCase() : null, legal: EVAL_ACTION_EXACT.test(action) && EVAL_RESULTS.has(result) });
967
+ }
968
+ return rows;
969
+ }
970
+
971
+ /** 评估行不合法的原因(给告警和恢复摘要用):动作段不是恰好「skill 评估」、结果段不是五种之一,或两者都有。 */
972
+ function illegalWhy(row) {
973
+ const why = [];
974
+ if (!EVAL_ACTION_EXACT.test(row.action)) why.push('动作段不是恰好「skill 评估」');
975
+ if (!EVAL_RESULTS.has(row.result)) why.push(`结果段不是五种之一(写的是「${row.result || '空'}」)`);
976
+ return why.join(',');
977
+ }
978
+
979
+ function skillEvalState(body) {
980
+ const rows = parseSkillEvals(body);
981
+ const legal = rows.filter((r) => r.legal);
982
+ const lastRow = rows[rows.length - 1];
983
+ const incomplete = Boolean(rows.length && !lastRow.legal);
984
+ return {
985
+ rows,
986
+ last: legal.length ? legal[legal.length - 1] : null,
987
+ incomplete,
988
+ incompleteWhy: incomplete ? illegalWhy(lastRow) : null,
989
+ };
990
+ }
991
+
992
+ /** 结论表(templates/skill-eval.md)「清单」一节的 skill 名;读不出返回 null。 */
993
+ export function readEvalRoster(evalPath) {
994
+ let text;
995
+ try {
996
+ text = readFileSync(evalPath, 'utf8');
997
+ } catch {
998
+ return null;
999
+ }
1000
+ const names = new Set();
1001
+ let inRoster = false;
1002
+ for (const raw of text.replace(/\r\n/g, '\n').split('\n')) {
1003
+ if (/^##\s/.test(raw)) {
1004
+ inRoster = /清单/.test(raw);
1005
+ continue;
1006
+ }
1007
+ if (!inRoster) continue;
1008
+ // skill 名两端的反引号(Markdown 行内代码)不算名字的一部分:结论表里很常见,照写不该被当成"读不出"。
1009
+ const m = /^\|\s*`?([a-z0-9][a-z0-9-]*)`?\s*\|/.exec(raw);
1010
+ if (m && m[1] !== 'skill') names.add(m[1]);
1011
+ }
1012
+ return names.size ? names : null;
1013
+ }
1014
+
1015
+ /** 「skill 评估」行产物段写的结论表位置:按卡目录、项目根两处解析。占位符或空值不算。 */
1016
+ function resolveEvalFile(cardPath, artifact) {
1017
+ const a = String(artifact ?? '').trim();
1018
+ if (!a || /^[<((—-]/.test(a)) return null;
1019
+ const candidates = [resolve(dirname(resolve(cardPath)), a), resolve(projectRootForCard(cardPath), a)];
1020
+ return candidates.find((p) => existsSync(p) && statSync(p).isFile()) ?? null;
1021
+ }
1022
+
1023
+ /** 记录的指纹与当前指纹一致。指纹固定 12 位十六进制,两边都要是完整的 12 位,不接受前缀(同骨架钉版的规矩)。 */
1024
+ function fingerprintMatches(recorded, current) {
1025
+ return /^[0-9a-f]{12}$/.test(recorded ?? '') && recorded === current;
1026
+ }
1027
+
1028
+ const escapeRegExp = (s) => String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1029
+
1030
+ /** 缺收据的告警(check 用;落盘前校验也经 checkCard 的告警原样带出)。 */
1031
+ const receiptReminder = (skill) =>
1032
+ `步骤清单里有从 ${skill} 提取的步骤(文案带 skill:${skill} 前缀),执行史里找不到它的收据(展开 … → ${skill} 或 实例化 ${skill}@…):补一行收据(workflows.md §3、§3.1)`;
1033
+
1034
+ /** 缺收据的提示(落盘前校验用)。与上面的告警互补而不重复:告警说"找不到",这里说"落盘时怎么补、不补会怎样"。 */
1035
+ const receiptNote = (skill) =>
1036
+ `步骤清单里有从 ${skill} 提取的步骤(文案带 skill:${skill} 前缀):落盘时在执行史补一行收据(展开 <节点> → ${skill}(<n> 步),或 实例化 ${skill}@…;workflows.md §3、§3.1),否则落盘后 check 会告警`;
1037
+
1038
+ /**
1039
+ * 清单里有从某 skill 提取的步骤(文案带 skill:<名字> 前缀)、执行史里却找不到它收据的 skill 名。
1040
+ * 收据认两种写法(gate-rules.md §1c 第 3 步):`展开 <节点> → <skill>(<n> 步)`;`实例化 <workflow>@<hash 或 prose>`。
1041
+ * 只看执行史节。骨架实例化的步骤文案不带 skill: 前缀,不在其内。
1042
+ */
1043
+ export function missingReceipts(steps, boxes, body) {
1044
+ const s = steps && typeof steps === 'object' ? steps : {};
1045
+ const nodeIds = new Set(Object.keys(s).filter((k) => !STEP_TOP_KEYS.has(k)));
1046
+ const history = String(sectionMap(body).get('执行史') ?? '');
1047
+ const missing = new Set();
1048
+ for (const b of boxes || []) {
1049
+ if (!nodeIds.has(b.id)) continue;
1050
+ const m = SKILL_TEXT_PREFIX.exec(String(b.text ?? '').trim());
1051
+ if (!m || missing.has(m[1])) continue;
1052
+ const name = escapeRegExp(m[1]);
1053
+ // 名字后面不能再接 skill 名的字符:dev-feature 的收据不能拿 dev-feature-extra 来充数。
1054
+ const hasReceipt = new RegExp(`展开\\s+\\S+?\\s*→\\s*${name}(?![a-z0-9-])`).test(history)
1055
+ || new RegExp(`实例化\\s+${name}@[0-9A-Za-z]`).test(history);
1056
+ if (!hasReceipt) missing.add(m[1]);
1057
+ }
1058
+ return [...missing].sort();
1059
+ }
1060
+
1061
+ /** 本卡来源里的工作流名:steps.source 形如 <workflow>@<hash> 或 <workflow>@prose;没有来源返回 null。 */
1062
+ const sourceWorkflow = (steps) => (/^([a-z0-9][a-z0-9-]*)@/.exec(typeof steps?.source === 'string' ? steps.source : '') || [])[1] ?? null;
1063
+
1064
+ /** from 的合法范围:task、结论表清单里的 skill 名、本卡来源里的工作流名,加上用户点名的。 */
1065
+ function fromDomain(steps, roster, extra) {
1066
+ const allowed = new Set(['task']);
1067
+ const wf = sourceWorkflow(steps);
1068
+ if (wf) allowed.add(wf);
1069
+ for (const n of roster ?? []) allowed.add(n);
1070
+ for (const n of extra ?? []) if (n) allowed.add(String(n));
1071
+ return allowed;
1072
+ }
1073
+
1074
+ /** 落盘后核对(只告警,契约 §4.7 第 4 条):记录、指纹、from 的合法范围;另提醒缺收据。 */
1075
+ export function checkSkillEval(path, steps, nodes, ids, boxes, body, warnings) {
1076
+ const state = skillEvalState(body);
1077
+ if (state.incomplete) {
1078
+ warnings.push(`执行史里最新的「skill 评估」行${state.incompleteWhy}:按「评估未完成」处理,不算评过`);
1079
+ }
1080
+ if (!state.last) {
1081
+ // "只提醒、不拦"而不是"旧卡只提醒":带步骤块的新卡没有记录时出的也是这一条,说"旧卡"不准。
1082
+ warnings.push('卡上没有「skill 评估」记录:这张卡没做过步骤归属评估。只提醒、不拦;继续、恢复、加步骤、重开时先问用户要不要补评(recovery.md §1.2)');
1083
+ return state;
1084
+ }
1085
+ // 收据提醒只对评估过的卡做:没有评估记录的存量卡是 v4.3 之前建的,那时还没有收据的规矩(上面已经返回)。
1086
+ // 两种跳过的卡同样受提醒——跳过的是"要不要展开",不是"落盘要不要留收据"。
1087
+ for (const skill of missingReceipts(steps, boxes, body)) warnings.push(receiptReminder(skill));
1088
+ if (EVAL_SKIP_RESULTS.has(state.last.result)) return state;
1089
+ const current = stepsFingerprint(steps, boxes);
1090
+ if (!fingerprintMatches(state.last.fingerprint, current)) {
1091
+ warnings.push(state.last.fingerprint
1092
+ ? `步骤在评估之后被改过(记录的指纹 ${state.last.fingerprint},当前 ${current}):改步骤要走 gate-rules.md §1c,重新评估并更新记录`
1093
+ : '「skill 评估」行的证据段没有 steps=<指纹>:无法核对步骤在评估之后有没有被改过');
1094
+ }
1095
+ let roster = new Set();
1096
+ if (state.last.result !== EVAL_NO_SKILL_RESULT) {
1097
+ const file = resolveEvalFile(path, state.last.artifact);
1098
+ if (!file) {
1099
+ warnings.push(`「skill 评估」记录指向的结论表找不到(${state.last.artifact || '没写位置'}):评估记录不完整;再次触发时按全评`);
1100
+ return state;
1101
+ }
1102
+ roster = readEvalRoster(file);
1103
+ if (!roster) {
1104
+ warnings.push(`结论表 ${file} 的「清单」一节读不出 skill 名:无法核对 from`);
1105
+ return state;
1106
+ }
1107
+ }
1108
+ const allowed = fromDomain(steps, roster);
1109
+ for (const id of ids) {
1110
+ const from = nodes[id]?.from;
1111
+ const value = from === undefined || from === null ? '' : String(from).trim();
1112
+ if (value && value !== 'task' && !allowed.has(value)) {
1113
+ warnings.push(`步骤 ${id} 的 from「${value}」不在评估清单里:skill 名写错,或没评过`);
1114
+ }
1115
+ }
1116
+ return state;
1117
+ }
1118
+
1119
+ /** 当前步骤之前的路线上,没勾也没跳过的步骤(dependency.md §3.2 的位置规则)。当前步骤的上级不算。 */
1120
+ export function unreachableBeforeCurrent(steps, nodes, checkedSet) {
1121
+ const cur = steps?.current;
1122
+ if (!cur || cur === 'end' || !nodes[cur]) return [];
1123
+ const ancestors = new Set();
1124
+ const parts = String(cur).split('.');
1125
+ for (let i = parts.length - 1; i > 0; i -= 1) ancestors.add(parts.slice(0, i).join('.'));
1126
+ const isSkipped = (n) => Boolean(n && (n.skip !== undefined || n.waive !== undefined));
1127
+ const seen = new Set();
1128
+ const blocked = [];
1129
+ let id = steps.entry;
1130
+ while (id && id !== 'end' && nodes[id] && !seen.has(id)) {
1131
+ seen.add(id);
1132
+ if (id === cur) return blocked;
1133
+ const node = nodes[id];
1134
+ if (node.type === 'decision' || node.type === 'loop') return blocked;
1135
+ if (!checkedSet.has(id) && !isSkipped(node) && !ancestors.has(id)) blocked.push(id);
1136
+ id = node.next;
1137
+ }
1138
+ return blocked;
1139
+ }
1140
+
1141
+ /** from 的归一写法:没写或为空视同 task(契约里 from 一行:没写的按 task 看)。 */
1142
+ const fromOf = (node) => {
1143
+ const v = node && typeof node === 'object' ? node.from : undefined;
1144
+ const s = v === undefined || v === null ? '' : String(v).trim();
1145
+ return s || 'task';
1146
+ };
1147
+
1148
+ /**
1149
+ * 已勾的步骤不得改动(dependency.md §3.4)。对现有卡里已勾的每一步 X,草稿要同时满足:
1150
+ * ① 还在;② from 没变;③ 原有步骤之间的先后关系不变;④ X 后面的原有步骤都还能从 X 走到。
1151
+ * "原有步骤"指现有卡里就有的节点,新加的节点不算。所以在已勾的步骤后面插新步骤、返工时挂在它下面的新子步骤、
1152
+ * 标了跳过的新阶段步骤,都不算调顺序。
1153
+ * ③ 比的是"每个原有步骤 Y 原来走不走得到 X、现在还走不走得到",不是直接前驱是谁(复审 N-01、N-02):
1154
+ * 比直接前驱的话,返工 S1(反勾、下挂 S1.1)会让后面已勾的 S2 的前驱从 S1 变成 S1.1,被误判成调了顺序。
1155
+ * 草稿里把 X 反勾(返工)不算违规:这里只认"现有卡里已勾",不看草稿的勾选状态。
1156
+ */
1157
+ function checkedStepProblems(baseSteps, baseBoxes, steps, draftIds) {
1158
+ const problems = [];
1159
+ const inDraft = new Set(draftIds);
1160
+ const baseNodes = Object.keys(baseSteps).filter((k) => !STEP_TOP_KEYS.has(k) && baseSteps[k] && typeof baseSteps[k] === 'object');
1161
+ const inBase = new Set(baseNodes);
1162
+ // 两张可达表,各算一次,不在循环里重复算:现有卡里每个原有步骤走得到哪些节点;
1163
+ // 草稿里还活着的原有步骤各走得到哪些节点(被删的不在表里,查的时候按"走不到"算)。
1164
+ const wasReach = new Map(baseNodes.map((y) => [y, reachableFrom(baseSteps, y)]));
1165
+ const nowReach = new Map(baseNodes.filter((y) => inDraft.has(y)).map((y) => [y, reachableFrom(steps, y)]));
1166
+ for (const id of baseBoxes.filter((b) => b.checked).map((b) => b.id)) {
1167
+ // 现有卡里"有勾选框却没有节点"是它自己的结构问题,归 check 报告;这里没有"原值"可比,跳过。
1168
+ if (!inBase.has(id)) continue;
1169
+ if (!inDraft.has(id)) {
1170
+ problems.push(`已勾的步骤 ${id} 被删了:已完成的步骤不改编号`);
1171
+ continue; // 节点都没了,后面三件没有可比的对象
1172
+ }
1173
+ if (fromOf(baseSteps[id]) !== fromOf(steps[id])) {
1174
+ problems.push(`已勾的步骤 ${id} 的 from 被改了(原 ${fromOf(baseSteps[id])},现 ${fromOf(steps[id])}):已完成的步骤不改 from`);
1175
+ }
1176
+ // ③ 原有步骤之间的先后关系不变:原来走得到 X 的还要走得到,原来走不到的不能排到它前面。
1177
+ for (const y of baseNodes) {
1178
+ if (y === id) continue;
1179
+ const was = wasReach.get(y).has(id);
1180
+ const now = nowReach.get(y)?.has(id) === true;
1181
+ if (was === now) continue;
1182
+ problems.push(`已勾的步骤 ${id} 的前后位置变了(原有步骤 ${y} ${was ? '原来在它前面,现在走不到它了' : '原来不在它前面,现在排到了它前面'}):已完成的步骤不调顺序`);
1183
+ }
1184
+ // ④ 取现有卡里从它走得到的全部原有步骤,不只直接后继:只看直接后继的话,把更远的步骤挪成走不到就拦不住。
1185
+ // 被删的原有步骤也算"走不到"——否则删掉后续步骤就能绕过这条核对。
1186
+ const reach = nowReach.get(id);
1187
+ for (const y of wasReach.get(id)) {
1188
+ if (!reach.has(y)) problems.push(`已勾的步骤 ${id} 后面的原有步骤 ${y} 走不到了:已完成的步骤不调顺序`);
1189
+ }
1190
+ }
1191
+ return problems;
1192
+ }
1193
+
1194
+ /**
1195
+ * 落盘前校验(契约 §4.7 第 3 条):不过不落盘。
1196
+ * base = 磁盘上的现有卡;给了就只查本次新增或改动过的步骤,没给按新卡查(每个节点都要写 from);
1197
+ * 另查现有卡里已勾的步骤没被改动、「跳过(用户决定)」之后加步骤要重评(dependency.md §3.4)。
1198
+ * eval = 结论表位置;allowSkills = 用户在审核时点名的 skill。
1199
+ * 返回 { ok, problems, notes, warnings }:problems 有一条就不通过;notes、warnings 只提醒,不影响 ok——
1200
+ * 前者是"落盘后会被 check 告警"的事(点名的 skill 要补进清单、缺收据),后者是草稿本身的结构告警(如位置告警)。
1201
+ * 这两样早先不返回:校验通过时人看不到位置告警,落盘后才冒出来(独立复审 I-18)。
1202
+ */
1203
+ export function preflight(draftPath, options = {}) {
1204
+ const problems = [];
1205
+ const notes = [];
1206
+ const warnings = [];
1207
+ const done = () => ({ ok: problems.length === 0, problems, notes, warnings });
1208
+ // 点名的 skill 落盘后要进结论表清单,否则 check 一直告警它不在清单里(gate-rules.md §1c 第 4 步)。
1209
+ // 只提醒:清单是人写的,脚本不替人改。放在最前面:它说的是"落盘后要处理的事",与草稿本身过不过无关。
1210
+ const extra = typeof options.allowSkills === 'string' ? [options.allowSkills] : options.allowSkills || [];
1211
+ const named = [...new Set(extra.filter(Boolean).map(String))];
1212
+ if (named.length) notes.push(`用户点名的 skill(${named.join('、')})要补进结论表「清单」一节,否则落盘后 check 会告警`);
1213
+ if (options.base && !existsSync(options.base)) {
1214
+ return { ok: false, problems: [`--base 指向的现有卡不存在:${options.base}`], notes, warnings };
1215
+ }
1216
+ const r = checkCard(draftPath);
1217
+ warnings.push(...(r.warnings ?? []));
1218
+ for (const i of r.issues) {
1219
+ if (!/must equal directory name/.test(i)) problems.push(`结构:${i}`);
1220
+ }
1221
+ if (r.legacy) {
1222
+ problems.push('结构:草稿没有 steps 块(新卡必须有步骤)');
1223
+ return done();
1224
+ }
1225
+ if (problems.length) return done();
1226
+
1227
+ const { front, body } = splitFrontMatter(readFileSync(draftPath, 'utf8'));
1228
+ const fm = parseYaml(front);
1229
+ const steps = fm.steps;
1230
+ const state = skillEvalState(body);
1231
+ if (state.incomplete || !state.last) {
1232
+ problems.push('没有结果段合法的「skill 评估」行:先按 gate-rules.md §1c 评估、让用户确认并留痕');
1233
+ return done();
1234
+ }
1235
+ const skipped = EVAL_SKIP_RESULTS.has(state.last.result);
1236
+ // 缺收据只提醒(gate-rules.md §1c 第 3 步):没有它步骤照样能做,但落盘后没人记得补。
1237
+ for (const skill of missingReceipts(steps, r.boxes, body)) notes.push(receiptNote(skill));
1238
+
1239
+ if (!skipped) {
1240
+ const current = stepsFingerprint(steps, r.boxes);
1241
+ if (!state.last.fingerprint) problems.push('「skill 评估」行的证据段没有 steps=<指纹>:无法证明这份草稿就是评估过的那份');
1242
+ else if (!fingerprintMatches(state.last.fingerprint, current)) {
1243
+ problems.push(`步骤指纹对不上(记录 ${state.last.fingerprint},草稿 ${current}):草稿在评估之后被改过,重新评估,或改回评估过的版本`);
1244
+ }
1245
+ }
1246
+
1247
+ let roster = new Set();
1248
+ if (!skipped && state.last.result !== EVAL_NO_SKILL_RESULT) {
1249
+ const evalPath = options.eval || resolveEvalFile(draftPath, state.last.artifact);
1250
+ const file = evalPath && existsSync(evalPath) && statSync(evalPath).isFile() ? evalPath : null;
1251
+ if (!file) {
1252
+ problems.push(`找不到评估清单(结论表):${options.eval || state.last.artifact || '「skill 评估」行没写结论表位置'};草稿阶段用 --eval 指定`);
1253
+ } else {
1254
+ // 用 --eval 指定了别处的结论表,清单是找到了的(复审 N-03)。checkCard 按评估行产物段在草稿目录里找不到,
1255
+ // 报的那条"结论表找不到:评估记录不完整"跟这里的"通过"打架,照着"要处理"去做会白忙——落盘后结论表进了卡目录,它自然消失。
1256
+ // 去掉那条告警,换一句提示说清落盘时要把结论表放到哪。
1257
+ if (options.eval) {
1258
+ const i = warnings.findIndex((w) => w.includes('结论表找不到'));
1259
+ if (i >= 0) warnings.splice(i, 1);
1260
+ notes.push(state.last.artifact
1261
+ ? `落盘时把结论表放到评估行写的位置(${state.last.artifact})`
1262
+ : '落盘时把结论表放进卡目录,并把位置写进评估行的产物段');
1263
+ }
1264
+ roster = readEvalRoster(file);
1265
+ if (!roster) {
1266
+ roster = new Set();
1267
+ problems.push(`结论表 ${evalPath} 的「清单」一节读不出 skill 名`);
1268
+ }
1269
+ }
1270
+ }
1271
+ const allowed = fromDomain(steps, roster, extra);
1272
+
1273
+ let changed = null; // null = 不带 --base:不区分新旧步骤,每个都查
1274
+ if (options.base) {
1275
+ const base = checkCard(options.base);
1276
+ if (base.legacy) {
1277
+ problems.push('--base 指向的现有卡没有 steps 块,无法对比');
1278
+ return done();
1279
+ }
1280
+ const baseSteps = parseYaml(splitFrontMatter(readFileSync(options.base, 'utf8')).front).steps || {};
1281
+ const baseTexts = checkboxTexts(base.boxes);
1282
+ const draftTexts = checkboxTexts(r.boxes);
1283
+ const known = new Set(r.ids.filter((id) => baseSteps[id] !== undefined));
1284
+ changed = new Set();
1285
+ for (const id of r.ids) {
1286
+ if (!known.has(id) || stepSignature(baseSteps[id], baseTexts.get(id), baseSteps, id, known) !== stepSignature(steps[id], draftTexts.get(id), steps, id, known)) changed.add(id);
1287
+ }
1288
+ // 入口变了等于整体调了顺序:每一步都算改动过(from 都要查,也够不上"步骤没动")
1289
+ if (String(baseSteps.entry ?? '') !== String(steps.entry ?? '')) changed = new Set(r.ids);
1290
+ problems.push(...checkedStepProblems(baseSteps, base.boxes, steps, r.ids));
1291
+ // 说过"这次不评估"不等于以后加步骤也不用评估(recovery.md §1.2 两种跳过的区别):
1292
+ // 「跳过(用户决定)」的卡一旦新增或改动了步骤,就要照常评估并留新的评估行;「跳过(本卡不再评估)」不拦。
1293
+ if (state.last.result === EVAL_SKIP_BY_USER && changed.size > 0) {
1294
+ problems.push('这张卡上次是「跳过(用户决定)」:加步骤或改步骤要照常评估,先评估并留新的评估行');
1295
+ }
1296
+ }
1297
+ for (const id of r.ids) {
1298
+ if (changed && !changed.has(id)) continue;
1299
+ const from = steps[id]?.from;
1300
+ const value = from === undefined || from === null ? '' : String(from).trim();
1301
+ if (!value) problems.push(`步骤 ${id} 没写 from:新步骤都要写明这一步按谁的规范做(任务自有写 task)`);
1302
+ else if (!allowed.has(value)) problems.push(`步骤 ${id} 的 from「${value}」不在合法范围:只能是 task、评估清单里的 skill 名,或本卡来源里的工作流名;用户点名的用 --allow-skill 传入`);
1303
+ }
1304
+ return done();
1305
+ }
1306
+
1307
+ function cmdPreflight(args) {
1308
+ const draft = args[0];
1309
+ if (!draft) return usage();
1310
+ const allowSkills = [];
1311
+ for (let i = 0; i < args.length; i += 1) {
1312
+ if (args[i] === '--allow-skill' && args[i + 1]) allowSkills.push(args[++i]);
1313
+ }
1314
+ const r = preflight(draft, { base: argOf(args, '--base'), eval: argOf(args, '--eval'), allowSkills });
1315
+ if (r.ok) console.log(`PASS preflight ${draft}`);
1316
+ else {
1317
+ console.error(`FAIL preflight ${draft}`);
1318
+ for (const p of r.problems) console.error(` - ${p}`);
1319
+ }
1320
+ // 告警不改判定(草稿的结构告警,例如位置告警);提示是落盘后要处理的事。FAIL 时也照打:人得一次看全。
1321
+ for (const w of r.warnings ?? []) console.log(` 告警:${w}`);
1322
+ for (const n of r.notes ?? []) console.log(` 提示:${n}`);
1323
+ // 只设退出码、不调 process.exit():Windows 上 stdout 接管道时是异步写的,exit() 会把还没写完的输出丢掉。
1324
+ if (!r.ok) process.exitCode = 1;
1325
+ }
1326
+
1327
+ function cmdFingerprint(args) {
1328
+ const file = args[0];
1329
+ if (!file) return usage();
1330
+ const fp = fingerprintOf(file);
1331
+ if (fp === null) {
1332
+ console.error('这张卡没有 steps 块,没有步骤指纹');
1333
+ process.exitCode = 1; // 同 cmdPreflight:只设退出码,保证上面那句 stderr 写得完
1334
+ return;
1335
+ }
1336
+ console.log(fp);
1337
+ }
1338
+
1339
+ function cmdDrafts(args) {
1340
+ const root = args[0] || process.cwd();
1341
+ const drafts = listDrafts(root);
1342
+ if (!drafts.length) {
1343
+ console.log(`没有待确认的开卡草稿(${join(resolveConfig(root).config.tasksDir, '.drafts')} 不存在或为空)`);
1344
+ return;
1345
+ }
1346
+ for (const d of drafts) console.log(`${d.id}:${d.hasCard ? '有草稿 task.md' : '没有 task.md'} → ${d.dir}`);
1347
+ }
1348
+
1349
+ /** 项目里放 skill 的目录:与安装器的项目级目标根一致(宿主内置的 skill 不在这些目录里)。 */
1350
+ const PROJECT_SKILL_ROOTS = ['.agents/skills', '.dsh/skills', '.claude/skills', '.codex/skills'];
1351
+
1352
+ /** 某个 skill 在项目的 skill 目录里找不找得到(只看目录在不在)。名字不像 skill 名的一律算找不到,也不拿去拼路径。 */
1353
+ export function skillInProject(root, name) {
1354
+ const n = String(name ?? '').trim();
1355
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(n)) return false;
1356
+ return PROJECT_SKILL_ROOTS.some((rel) => {
1357
+ try {
1358
+ return statSync(join(resolve(root), rel, n)).isDirectory();
1359
+ } catch {
1360
+ return false;
1361
+ }
1362
+ });
1363
+ }
1364
+
1365
+ /** 数据根 .drafts/ 下的开卡草稿(契约 §1):还没落盘、等用户确认的卡。只认子目录,点开头的目录本身不参与任务扫描。 */
1366
+ export function listDrafts(root) {
1367
+ const { config } = resolveConfig(root);
1368
+ const dir = join(root, config.tasksDir, '.drafts');
1369
+ const entries = existsSync(dir) ? readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory()) : [];
1370
+ return entries
1371
+ .sort((a, b) => a.name.localeCompare(b.name))
1372
+ .map((e) => ({ id: e.name, hasCard: existsSync(join(dir, e.name, 'task.md')), dir: join(dir, e.name) }));
1373
+ }
1374
+
1375
+ function currentStepBlock(fm, body, cardPath) {
1376
+ const steps = fm.steps;
1377
+ const cur = steps ? steps.current : undefined;
1378
+ const out = ['## 当前步骤'];
1379
+ if (cur === undefined || cur === null || cur === '') out.push('(这张卡没有步骤块,或没写 current)');
1380
+ else if (cur === 'end') out.push('当前步骤路径已结束(current: end)。');
1381
+ else if (!steps[cur]) out.push(`current 指向的步骤 ${cur} 不存在。`);
1382
+ else {
1383
+ let text = null;
1384
+ for (const line of body.split(/\r?\n/)) {
1385
+ const m = /^\s*-\s*\[[ xX]\]\s+(S[0-9A-Za-z_.]*)\s+(.*)$/.exec(line);
1386
+ if (m && m[1] === cur) {
1387
+ text = m[2].trim();
1388
+ break;
1389
+ }
1390
+ }
1391
+ const from = steps[cur].from === undefined || steps[cur].from === null ? '' : String(steps[cur].from).trim();
1392
+ out.push(`${cur} ${text ?? '(勾选框文案缺失)'}:${!from || from === 'task' ? '任务自有' : `按 ${from} 规范`}`);
1393
+ // from 是本卡来源里的工作流名(骨架实例化):这一步是卡内实例,不是 skill。契约 §3.2 说运行时不重读工作流,
1394
+ // 所以既不去 skill 目录找它,也不叫人"执行时加载它"——那两句是针对 skill 的,套在实例上就是误报(审计 W6)。
1395
+ if (from && from !== 'task' && from === sourceWorkflow(steps)) {
1396
+ out.push('这一步来自骨架实例化:读卡内实例,不重读工作流,不重新推导步骤(契约 §3.2)。');
1397
+ } else {
1398
+ if (from && from !== 'task' && !skillInProject(projectRootForCard(cardPath), from)) {
1399
+ out.push(`当前步骤按 ${from} 规范做,但在项目的 skill 目录里找不到它(找过 ${PROJECT_SKILL_ROOTS.join('、')}):可能已下线或名字写错,也可能它由宿主内置提供;动手前先确认。`);
1400
+ }
1401
+ out.push('恢复时只读这一行,不去读那个 skill。执行到这一步时才按它的规范做:只是点了名、没有展开的,执行时加载它;已经展开成子步骤的(文案带 skill: 前缀),做每个子步骤时读它的对应小节,不重新推导步骤。');
1402
+ }
1403
+ }
1404
+ const handoff = join(dirname(resolve(cardPath)), '.handoff');
1405
+ if (existsSync(handoff) && statSync(handoff).isDirectory()) {
1406
+ const files = readdirSync(handoff).filter((f) => /\.(md|ya?ml)$/i.test(f));
1407
+ // .handoff/ 里也放委派证据(契约 §1),不只有评估:一口咬定"有没确认完的评估"会把人引去重评(审计 N9)。
1408
+ if (files.length) out.push(`卡目录的 .handoff/ 里有 ${files.length} 个暂存文件(${files.slice(0, 3).join('、')}${files.length > 3 ? '…' : ''}):可能是委派证据,也可能是等确认的评估;先确认有没有没做完的评估,不从头再评。`);
1409
+ }
1410
+ // 步骤归属评估的状态(recovery.md §1.2):恢复时靠这几行发现「旧卡」和「跳过的卡」,不靠人去翻执行史。只提示,不拦。
1411
+ // 没有步骤块的旧格式卡没有步骤可评(契约 §4.7 第 4 条),这一段整个不输出,也不用问。
1412
+ const state = skillEvalState(body);
1413
+ if (!steps || typeof steps !== 'object') {
1414
+ // 旧格式卡:不做步骤归属核对,也不提示
1415
+ } else if (!state.rows.length) {
1416
+ out.push('此卡未做 skill 评估(卡上没有「skill 评估」记录):继续、恢复、加步骤、重开时先问用户要不要补评;检查点不问(recovery.md §1.2)。');
1417
+ } else {
1418
+ if (state.incomplete) out.push(`此卡的 skill 评估没做完(执行史里最新的「skill 评估」行${state.incompleteWhy}):不能当评过,重试或改由主 agent 做。`);
1419
+ if (state.last && EVAL_SKIP_RESULTS.has(state.last.result)) {
1420
+ out.push('此卡未做 skill 评估(用户已决定跳过):只提示,不拦;以后还评不评按那条记录办(recovery.md §1.2)。');
1421
+ }
1422
+ }
1423
+ out.push('');
1424
+ return out.join('\n');
1425
+ }
1426
+
1427
+ /** One card check result for CLI/tests: legacy cards still enforce front-matter basics. */
1428
+ export function checkCardReport(path, options = {}) {
1429
+ const r = checkCard(path, options);
1430
+ const ok = r.issues.length === 0;
1431
+ return { ...r, ok, legacySkip: r.legacy && ok };
1432
+ }
1433
+
1434
+ function cmdCheck(args) {
1435
+ const strict = args.includes('--strict');
1436
+ const paths = args.filter((a) => a !== '--strict');
1437
+ if (!paths.length) return usage();
1438
+ let failed = 0;
1439
+ for (const p of paths) {
1440
+ const r = checkCardReport(p, { strict });
1441
+ for (const warning of r.warnings ?? []) console.log(`WARN ${p}: ${warning}`);
1442
+ if (r.legacy) {
1443
+ if (r.issues.length) {
1444
+ failed += 1;
1445
+ console.error(`FAIL(legacy) ${p}`);
1446
+ for (const i of r.issues) console.error(` - ${i}`);
1447
+ } else {
1448
+ console.log(`SKIP(legacy) ${p} — no steps block; front-matter basics OK`);
1449
+ }
1450
+ continue;
1451
+ }
1452
+ if (r.issues.length) {
1453
+ failed += 1;
1454
+ console.error(`FAIL ${p}`);
1455
+ for (const i of r.issues) console.error(` - ${i}`);
1456
+ } else {
1457
+ console.log(`PASS ${p} (${r.ids.length} steps, ${r.boxes.length} checkboxes)`);
1458
+ }
1459
+ }
1460
+ if (failed) process.exit(1);
1461
+ }
1462
+
1463
+ /* --------------------------- config resolution ------------------------- */
1464
+
1465
+ const CONFIG_DEFAULTS = {
1466
+ tasksDir: 'tasks',
1467
+ ledgerName: 'TASKS.md',
1468
+ archiveName: 'TASKFINISH.md',
1469
+ stateFile: null,
1470
+ };
1471
+
1472
+ function readConfigFile(dir) {
1473
+ const p = join(dir, 'task-card.config.yml');
1474
+ if (!existsSync(p)) return null;
1475
+ const raw = parseYaml(readFileSync(p, 'utf8'));
1476
+ const cfg = { ...CONFIG_DEFAULTS };
1477
+ for (const k of Object.keys(CONFIG_DEFAULTS)) {
1478
+ if (k in raw && raw[k] !== undefined) cfg[k] = raw[k];
1479
+ }
1480
+ return { cfg, path: p };
1481
+ }
1482
+
1483
+ function findGitRoot(start) {
1484
+ let dir = start;
1485
+ for (;;) {
1486
+ if (existsSync(join(dir, '.git'))) return dir;
1487
+ const parent = join(dir, '..');
1488
+ if (parent === dir) return null;
1489
+ dir = parent;
1490
+ }
1491
+ }
1492
+
1493
+ /** Resolve effective config: cwd -> git root -> built-in defaults (contract §7). */
1494
+ export function resolveConfig(cwd) {
1495
+ const here = readConfigFile(cwd);
1496
+ if (here) return { config: here.cfg, source: 'cwd', path: here.path };
1497
+ const gitRoot = findGitRoot(cwd);
1498
+ if (gitRoot && gitRoot !== cwd) {
1499
+ const atRoot = readConfigFile(gitRoot);
1500
+ if (atRoot) return { config: atRoot.cfg, source: 'git-root', path: atRoot.path };
1501
+ }
1502
+ return { config: { ...CONFIG_DEFAULTS }, source: 'default', path: null };
1503
+ }
1504
+
1505
+ /* --------------------------- project docs (docs) ----------------------- */
1506
+ // 契约 §2.4:docs 是「推进前必读的项目文档」路径数组。这里是唯一实现:
1507
+ // check 只告警(不阻断),context 输出恢复包。路径校验不猜:非法条目保留原值并报告。
1508
+
1509
+ const DOCS_DEFAULT_HEAD = 40;
1510
+ const DOCS_MAX_TOTAL_LINES = 300;
1511
+
1512
+ /**
1513
+ * 从卡路径向上定位项目根。
1514
+ * 配置可能不代表这张卡:只有 `<dir>/<tasksDir>/<id>/task.md` 结构匹配时 `dir` 才算根,
1515
+ * 否则继续向上(避免 examples/ 这类「演示配置」把根错定在配置所在目录)。
1516
+ */
1517
+ function projectRootForCard(cardPath) {
1518
+ const abs = resolve(cardPath);
1519
+ const start = dirname(abs);
1520
+ let dir = start;
1521
+ for (;;) {
1522
+ const cfg = readConfigFile(dir);
1523
+ if (cfg) {
1524
+ const tasksDir = typeof cfg.cfg.tasksDir === 'string' ? cfg.cfg.tasksDir : 'tasks';
1525
+ const dataDir = resolve(dir, tasksDir);
1526
+ const rel = relative(dataDir, abs);
1527
+ if (rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)) return dir;
1528
+ }
1529
+ if (existsSync(join(dir, '.git'))) return dir;
1530
+ const parent = dirname(dir);
1531
+ if (parent === dir) break;
1532
+ dir = parent;
1533
+ }
1534
+ return resolve(start, '..', '..');
1535
+ }
1536
+
1537
+ /** 归一化 docs:string -> [string];数组原样;其他形状返回 null(调用方报诊断)。 */
1538
+ function normalizeDocs(raw) {
1539
+ if (raw === undefined || raw === null) return [];
1540
+ if (typeof raw === 'string') return [raw];
1541
+ if (Array.isArray(raw)) return raw;
1542
+ return null;
1543
+ }
1544
+
1545
+ /** 解析单条 docs 引用:成功返回 {rel, abs, lineCount},失败返回 {error}。 */
1546
+ function resolveDocRef(root, entry, ledgerName, archiveName) {
1547
+ if (typeof entry !== 'string' || !entry.trim()) return { error: '是空值' };
1548
+ const rel = entry.trim();
1549
+ if (rel.includes('\\')) return { error: '请用 / 分隔路径' };
1550
+ if (isAbsolute(rel) || /^[A-Za-z]:/.test(rel)) return { error: '必须是相对项目根的路径' };
1551
+ if (!rel.toLowerCase().endsWith('.md')) return { error: '必须是 .md 文件' };
1552
+ const abs = resolve(root, rel);
1553
+ const back = relative(root, abs);
1554
+ if (back.startsWith('..') || isAbsolute(back)) return { error: '越出项目根' };
1555
+ const base = basename(abs);
1556
+ if (base === 'task.md') return { error: '不能指向任务卡(状态源)' };
1557
+ if (base === ledgerName || base === archiveName) return { error: '不能指向总账/归档表(状态源)' };
1558
+ if (!existsSync(abs)) return { error: '文件不存在' };
1559
+ if (!statSync(abs).isFile()) return { error: '不是文件' };
1560
+ const lineCount = readFileSync(abs, 'utf8').replace(/\r\n/g, '\n').split('\n').length;
1561
+ return { rel: back.replace(/\\/g, '/'), abs, lineCount };
1562
+ }
1563
+
1564
+ /** check 用:只告警,不阻断(契约 §2.4 / §12)。 */
1565
+ function checkDocsAgainst(fm, cardPath, warnings) {
1566
+ const list = normalizeDocs(fm.docs);
1567
+ if (list === null) {
1568
+ warnings.push('docs 必须是字符串或字符串列表(契约 §2.4)');
1569
+ return;
1570
+ }
1571
+ if (list.length === 0) return;
1572
+ const root = projectRootForCard(cardPath);
1573
+ const { config } = resolveConfig(root);
1574
+ const seen = new Set();
1575
+ for (const entry of list) {
1576
+ const ref = resolveDocRef(root, entry, config.ledgerName, config.archiveName);
1577
+ if (ref.error) {
1578
+ warnings.push(`docs ${ref.error}:${String(entry)}`);
1579
+ continue;
1580
+ }
1581
+ if (seen.has(ref.rel)) {
1582
+ warnings.push(`docs 重复引用:${ref.rel}`);
1583
+ continue;
1584
+ }
1585
+ seen.add(ref.rel);
1586
+ }
1587
+ }
1588
+
1589
+ /* --------------------------- receipt validation ------------------------ */
1590
+
1591
+ const RECEIPT_STATUSES = new Set(['completed', 'partial', 'failed', 'input_required']);
1592
+ const CHECK_STATUSES = new Set(['passed', 'failed', 'not_run']);
1593
+
1594
+ export function validateReceipt(receipt, brief) {
1595
+ const issues = [];
1596
+ if (!receipt || typeof receipt !== 'object') return ['receipt is not an object'];
1597
+ for (const k of ['task', 'step', 'attempt', 'status', 'summary', 'checks', 'artifacts']) {
1598
+ if (receipt[k] === undefined || receipt[k] === null) issues.push(`missing field: ${k}`);
1599
+ }
1600
+ if (brief) {
1601
+ for (const k of ['task', 'step', 'attempt']) {
1602
+ if (receipt[k] !== undefined && String(receipt[k]) !== String(brief[k])) {
1603
+ issues.push(`identity mismatch: ${k} (receipt=${receipt[k]}, brief=${brief[k]})`);
1604
+ }
1605
+ }
1606
+ }
1607
+ if (receipt.status !== undefined && !RECEIPT_STATUSES.has(receipt.status)) {
1608
+ issues.push(`invalid status: ${receipt.status}`);
1609
+ }
1610
+ if (receipt.summary !== undefined && typeof receipt.summary !== 'string') issues.push('summary must be a string');
1611
+ if (receipt.checks !== undefined) {
1612
+ if (!Array.isArray(receipt.checks)) issues.push('checks must be a list');
1613
+ else {
1614
+ receipt.checks.forEach((c, i) => {
1615
+ if (!c || typeof c !== 'object') return issues.push(`checks[${i}] must be a map`);
1616
+ if (!c.name) issues.push(`checks[${i}].name missing`);
1617
+ if (!CHECK_STATUSES.has(c.status)) issues.push(`checks[${i}] invalid status: ${c.status}`);
1618
+ });
1619
+ }
1620
+ }
1621
+ if (receipt.artifacts !== undefined && !Array.isArray(receipt.artifacts)) issues.push('artifacts must be a list');
1622
+ if (receipt.status === 'partial' && (!Array.isArray(receipt.remaining_work) || !receipt.remaining_work.length)) {
1623
+ issues.push('status=partial requires non-empty remaining_work');
1624
+ }
1625
+ if (receipt.status === 'input_required' && !receipt.question) {
1626
+ issues.push('status=input_required requires a question');
1627
+ }
1628
+ return issues;
1629
+ }
1630
+
1631
+ /* --------------------- step machine simulation (advance) ---------------- */
1632
+ // Pure simulation of contract §3.4/§3.5 runtime rules. Used by tests and by
1633
+ // `advance` to check a card's next state without mutating the file.
1634
+
1635
+ function parseCounter(v, fallbackMax) {
1636
+ if (typeof v === 'number') return [0, v];
1637
+ if (typeof v === 'string' && /^\d+\/\d+$/.test(v)) return v.split('/').map(Number);
1638
+ return [0, fallbackMax];
1639
+ }
1640
+
1641
+ function renderCounter([used, max]) {
1642
+ return `${used}/${max}`;
1643
+ }
1644
+
1645
+ /* Single source of step semantics (used by checkCard, advance and instantiate).
1646
+ Keeping these in one place is the fix for the "two brains" audit finding. */
1647
+ const END = 'end';
1648
+ const isSkipped = (node) => Boolean(node && (node.skip || node.waive));
1649
+
1650
+ function requireNext(node, id) {
1651
+ if (node && node.next !== undefined) return node.next;
1652
+ throw new Error(`node ${id} has no next (normal/skip/waive nodes must declare routing)`);
1653
+ }
1654
+
1655
+ function isLiveBranch(steps, br) {
1656
+ if (!br || br.go === END) return false;
1657
+ const target = steps[br.go];
1658
+ return Boolean(target) && !isSkipped(target);
1659
+ }
1660
+
1661
+ function liveBranches(steps, node) {
1662
+ return (node.branches || []).filter((br) => isLiveBranch(steps, br));
1663
+ }
1664
+
1665
+ function decisionTarget(steps, node, id) {
1666
+ const live = liveBranches(steps, node);
1667
+ if (live.length !== 1) throw new Error(`decision ${id} has ${live.length} live branches (need exactly 1)`);
1668
+ return live[0].go;
1669
+ }
1670
+
1671
+ function resolveNext(steps, id) {
1672
+ let cur = id;
1673
+ for (let guard = 0; guard < 100; guard += 1) {
1674
+ if (cur === END || cur === null || cur === undefined) return END;
1675
+ const node = steps[cur];
1676
+ if (!node) throw new Error(`unknown node: ${cur}`);
1677
+ if (isSkipped(node)) {
1678
+ cur = requireNext(node, cur);
1679
+ continue;
1680
+ }
1681
+ return cur;
1682
+ }
1683
+ throw new Error('routing guard exceeded (cycle?)');
1684
+ }
1685
+
1686
+ /** Node status with the contract's priority: done > skipped/waived > failed > blocked > doing > pending. */
1687
+ export function nodeStatus(steps, checked, id) {
1688
+ const node = steps[id];
1689
+ if (!node) throw new Error(`unknown node: ${id}`);
1690
+ const isChecked = checked.has ? checked.has(id) : checked.includes(id);
1691
+ if (isChecked) return 'done';
1692
+ if (node.skip) return 'skipped';
1693
+ if (node.waive) return 'waived';
1694
+ if (node.failed) return 'failed';
1695
+ if (node.retry) {
1696
+ const [used, max] = parseCounter(node.retry, 1);
1697
+ if (used >= max) return 'failed';
1698
+ }
1699
+ if (node.block) return 'blocked';
1700
+ if (steps.current === id) return 'doing';
1701
+ return 'pending';
1702
+ }
1703
+
1704
+ /** Apply one event: complete | fail | block | unblock. Returns a new state (input untouched). */
1705
+ export function advance(stepsIn, checkedIn, event) {
1706
+ const steps = JSON.parse(JSON.stringify(stepsIn));
1707
+ const checked = new Set(checkedIn);
1708
+ if (!event || !event.type) throw new Error('event.type is required');
1709
+ const nodeId = event.node;
1710
+ if (!nodeId || !steps[nodeId]) throw new Error(`event.node must reference an existing node: ${nodeId}`);
1711
+
1712
+ if (event.type === 'complete') {
1713
+ if (steps.current !== nodeId) {
1714
+ throw new Error(`complete ${nodeId}: node is not current (current=${steps.current})`);
1715
+ }
1716
+ const node = steps[nodeId];
1717
+ if (isSkipped(node)) throw new Error(`complete ${nodeId}: skip/waive nodes are transparent and cannot be completed`);
1718
+ if (node.block) throw new Error(`complete ${nodeId}: node is blocked (unblock before completing)`);
1719
+ // Parent/child invariant: a parent cannot complete before its children (contract §3.3).
1720
+ const children = Object.keys(steps).filter((k) => k.startsWith(`${nodeId}.`));
1721
+ const unfinishedChildren = children.filter((c) => !checked.has(c) && !steps[c].skip && !steps[c].waive);
1722
+ if (unfinishedChildren.length) {
1723
+ throw new Error(`complete ${nodeId}: children not finished: ${unfinishedChildren.join(', ')}`);
1724
+ }
1725
+ // Loop body: the last body node is routed by the loop itself, not by `next`.
1726
+ const loopId = Object.keys(steps).find((k) => steps[k].type === 'loop' && (steps[k].body || []).includes(nodeId));
1727
+ if (loopId) {
1728
+ const loop = steps[loopId];
1729
+ const body = loop.body;
1730
+ if (body[body.length - 1] === nodeId) {
1731
+ checked.add(nodeId);
1732
+ if (node.retry) node.retry = renderCounter([0, parseCounter(node.retry, 1)[1]]);
1733
+ const [used, max] = parseCounter(loop.iter, body.length);
1734
+ const nextIter = used + 1;
1735
+ if (nextIter >= max) {
1736
+ checked.add(loopId);
1737
+ loop.iter = renderCounter([max, max]);
1738
+ return finish(steps, checked, resolveNext(steps, loop.exit), `loop ${loopId} finished (${max}/${max})`);
1739
+ }
1740
+ loop.iter = renderCounter([nextIter, max]);
1741
+ return finish(steps, checked, resolveNext(steps, body[0]), `loop ${loopId} iteration ${nextIter + 1}/${max}`);
1742
+ }
1743
+ }
1744
+ let target;
1745
+ if (node.type === 'loop') {
1746
+ const [iter] = parseCounter(node.iter, 0);
1747
+ target = resolveNext(steps, node.body[0]);
1748
+ if (iter === 0) return finish(steps, checked, target, `enter loop body ${target}`);
1749
+ return finish(steps, checked, target, `continue loop (iter ${renderCounter(parseCounter(node.iter, 0))})`);
1750
+ }
1751
+ if (node.type === 'decision') {
1752
+ if (!node.decided) throw new Error(`complete ${nodeId}: decision node has no decided pointer`);
1753
+ target = resolveNext(steps, decisionTarget(steps, node, nodeId));
1754
+ } else if (node.pass) {
1755
+ // Retry-capable node: normal completion leaves through its pass exit.
1756
+ target = resolveNext(steps, node.pass);
1757
+ } else if (node.next !== undefined) {
1758
+ target = resolveNext(steps, node.next);
1759
+ } else {
1760
+ // Fail-closed: a missing `next` must never be silently treated as "plan finished".
1761
+ throw new Error(`complete ${nodeId}: no next defined (normal node requires next; only last loop-body node may omit)`);
1762
+ }
1763
+ checked.add(nodeId);
1764
+ if (node.retry) node.retry = renderCounter([0, parseCounter(node.retry, 1)[1]]);
1765
+ return finish(steps, checked, target, `advance ${nodeId} → ${target}`);
1766
+ }
1767
+
1768
+ if (event.type === 'fail') {
1769
+ if (steps.current !== nodeId) {
1770
+ throw new Error(`fail ${nodeId}: node is not current (current=${steps.current})`);
1771
+ }
1772
+ const node = steps[nodeId];
1773
+ if (!node.retry) {
1774
+ node.failed = true;
1775
+ return finish(steps, checked, steps.current, `failed ${nodeId} (no retry declared; needs decision)`);
1776
+ }
1777
+ const [used, max] = parseCounter(node.retry, 1);
1778
+ const next = used + 1;
1779
+ if (next >= max) {
1780
+ node.retry = renderCounter([max, max]);
1781
+ const target = node.exhausted ? resolveNext(steps, node.exhausted) : null;
1782
+ return finish(steps, checked, target ?? steps.current, `retry exhausted on ${nodeId} → ${target ?? 'no route (needs decision)'}`);
1783
+ }
1784
+ node.retry = renderCounter([next, max]);
1785
+ return finish(steps, checked, nodeId, `retry ${next}/${max} on ${nodeId}`);
1786
+ }
1787
+
1788
+ if (event.type === 'block') {
1789
+ steps[nodeId].block = event.reason || 'blocked';
1790
+ return finish(steps, checked, steps.current, `blocked ${nodeId}`);
1791
+ }
1792
+ if (event.type === 'unblock') {
1793
+ delete steps[nodeId].block;
1794
+ return finish(steps, checked, steps.current, `unblocked ${nodeId}`);
1795
+ }
1796
+ throw new Error(`unknown event type: ${event.type}`);
1797
+ }
1798
+
1799
+ function finish(steps, checked, current, action) {
1800
+ steps.current = current; // 'end' is a legal sentinel (task-format.md §3.1)
1801
+ return { steps, checked: [...checked], current: steps.current, action };
1802
+ }
1803
+
1804
+ /** Reconcile R1/R2/R3/R4 (delegation.md §5): actions only, never mutates.
1805
+ * delegations: [{step, hasReceipt}] — rows from the execution history (委派行 without 回执 → R4). */
1806
+ export function reconcile(steps, checkedIn, evidence = {}, delegations = []) {
1807
+ const checked = new Set(checkedIn);
1808
+ const actions = [];
1809
+ for (const id of Object.keys(steps)) {
1810
+ if (['source', 'entry', 'current'].includes(id)) continue;
1811
+ const node = steps[id];
1812
+ if (node.skip || node.waive) continue;
1813
+ if (checked.has(id)) {
1814
+ if (!evidence[id]) actions.push({ rule: 'R3', node: id, action: 'warn: done without evidence' });
1815
+ continue;
1816
+ }
1817
+ if (steps.current !== id) continue; // R1/R2 apply to the doing node only
1818
+ if (evidence[id]) actions.push({ rule: 'R2', node: id, action: 'committable: mark done and label 补记' });
1819
+ else actions.push({ rule: 'R1', node: id, action: 'must not tick: no evidence' });
1820
+ }
1821
+ for (const d of delegations) {
1822
+ if (d.hasReceipt) continue;
1823
+ if (checked.has(d.step)) {
1824
+ // gate-rules §4 invariant: a step must not be checked while its delegation has no receipt.
1825
+ actions.push({ rule: 'R5', node: d.step, action: 'invariant: checked step has a pending delegation (no receipt)' });
1826
+ continue;
1827
+ }
1828
+ actions.push({ rule: 'R4', node: d.step, action: 'delegation pending: no receipt yet, do not re-dispatch' });
1829
+ }
1830
+ return actions;
1831
+ }
1832
+
1833
+ /* ------------------------ integration map / brief ---------------------- */
1834
+ // Project-side data: which third-party skill stages to put into a card, and
1835
+ // what verifiable result each stage must return. task-card stays workflow-agnostic.
1836
+
1837
+ export function parseIntegrationMap(text) {
1838
+ const issues = [];
1839
+ const warnings = [];
1840
+ let raw;
1841
+ try {
1842
+ raw = parseYaml(text);
1843
+ } catch (e) {
1844
+ return { map: null, issues: [`map parse error: ${e.message}`], warnings };
1845
+ }
1846
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
1847
+ return { map: null, issues: ['map must be a map'], warnings };
1848
+ }
1849
+ const skill = typeof raw.skill === 'string' ? raw.skill.trim() : '';
1850
+ if (!skill) issues.push('map missing skill');
1851
+ const workflow = raw.workflow === undefined || raw.workflow === null ? null : String(raw.workflow).trim();
1852
+ const stages = Array.isArray(raw.stages) ? raw.stages : null;
1853
+ if (!stages || !stages.length) issues.push('map requires non-empty stages');
1854
+ const seen = new Set();
1855
+ const out = [];
1856
+ for (const [i, stage] of (stages || []).entries()) {
1857
+ const where = `stages[${i}]`;
1858
+ if (!stage || typeof stage !== 'object' || Array.isArray(stage)) {
1859
+ issues.push(`${where} must be a map`);
1860
+ continue;
1861
+ }
1862
+ const id = typeof stage.id === 'string' ? stage.id.trim() : '';
1863
+ if (!/^S[0-9A-Za-z_.]*$/.test(id)) issues.push(`${where}.id must look like S1 / S1.2`);
1864
+ else if (seen.has(id)) issues.push(`${where}.id duplicate: ${id}`);
1865
+ seen.add(id);
1866
+ const name = typeof stage.name === 'string' ? stage.name.trim() : '';
1867
+ if (!name) issues.push(`${where}.name required`);
1868
+ const evidence = Array.isArray(stage.evidence) ? stage.evidence : null;
1869
+ if (!evidence || !evidence.length) issues.push(`${where}.evidence requires at least one item`);
1870
+ const ev = [];
1871
+ for (const [j, item] of (evidence || []).entries()) {
1872
+ const ew = `${where}.evidence[${j}]`;
1873
+ if (!item || typeof item !== 'object' || Array.isArray(item)) {
1874
+ issues.push(`${ew} must be a map`);
1875
+ continue;
1876
+ }
1877
+ const type = item.type;
1878
+ if (!['file', 'command', 'user'].includes(type)) {
1879
+ issues.push(`${ew}.type must be file|command|user`);
1880
+ continue;
1881
+ }
1882
+ if (type === 'file') {
1883
+ const path = typeof item.path === 'string' ? item.path.trim() : '';
1884
+ if (!path) issues.push(`${ew}.path required`);
1885
+ else {
1886
+ ev.push({ type, path });
1887
+ if (/<[^>]+>/.test(path)) warnings.push(`${ew}.path still has a placeholder: ${path}`);
1888
+ }
1889
+ } else if (type === 'command') {
1890
+ const run = typeof item.run === 'string' ? item.run.trim() : '';
1891
+ if (!run) issues.push(`${ew}.run required`);
1892
+ else {
1893
+ ev.push({ type, run, expect: item.expect ? String(item.expect).trim() : 'exit=0' });
1894
+ if (/<[^>]+>/.test(run)) warnings.push(`${ew}.run still has a placeholder: ${run}`);
1895
+ }
1896
+ } else {
1897
+ ev.push({ type, note: item.note ? String(item.note).trim() : '用户明确点头' });
1898
+ }
1899
+ }
1900
+ out.push({ id, name, evidence: ev });
1901
+ }
1902
+ if (issues.length) return { map: null, issues, warnings };
1903
+ return { map: { skill, workflow, stages: out }, issues: [], warnings };
1904
+ }
1905
+
1906
+ export function buildIntegrationSteps(map) {
1907
+ const steps = {};
1908
+ const boxes = [];
1909
+ map.stages.forEach((stage, i) => {
1910
+ const next = i + 1 < map.stages.length ? map.stages[i + 1].id : 'end';
1911
+ steps[stage.id] = { from: map.skill, required: true, next };
1912
+ boxes.push(`- [ ] ${stage.id} ${stage.name}(按 ${map.skill})`);
1913
+ });
1914
+ return { steps, boxes };
1915
+ }
1916
+
1917
+ function evidenceLine(ev) {
1918
+ if (ev.type === 'file') return `产物:${ev.path}`;
1919
+ if (ev.type === 'command') return `命令:${ev.run} | ${ev.expect || 'exit=0'}`;
1920
+ return `用户:${ev.note || '用户明确点头'}`;
1921
+ }
1922
+
1923
+ export function buildIntegrationBrief(map, card = null) {
1924
+ const lines = [];
1925
+ lines.push(`## 任务卡交接(task-card → ${map.skill};只读,不是状态副本)`);
1926
+ lines.push('');
1927
+ if (card) {
1928
+ lines.push(`- 任务:${card.id} / ${card.title}`);
1929
+ lines.push(`- 卡:${card.path}(唯一任务状态)`);
1930
+ const current = card.current || '<Sx>';
1931
+ lines.push(`- 当前步骤:${current}(来自卡)`);
1932
+ if (map.workflow) lines.push(`- 工作流:${map.workflow}`);
1933
+ const stage = map.stages.find((s) => s.id === current);
1934
+ lines.push('- 本步预期结果:');
1935
+ if (stage) {
1936
+ for (const ev of stage.evidence) lines.push(` - ${evidenceLine(ev)}`);
1937
+ } else {
1938
+ lines.push(` - 警告:当前步骤 ${current} 不在映射阶段中;按卡内步骤文案执行,不猜。`);
1939
+ }
1940
+ } else {
1941
+ lines.push('- 任务:<id> / <title>');
1942
+ lines.push('- 卡:<task.md>(唯一任务状态)');
1943
+ lines.push('- 当前步骤:<Sx>(来自卡)');
1944
+ if (map.workflow) lines.push(`- 工作流:${map.workflow}`);
1945
+ lines.push('- 本步预期结果:');
1946
+ for (const stage of map.stages) {
1947
+ lines.push(` - ${stage.id} ${stage.name}`);
1948
+ for (const ev of stage.evidence) lines.push(` - ${evidenceLine(ev)}`);
1949
+ }
1950
+ }
1951
+ lines.push('- 你的本地文件(`task_plan.md`/`active.md` 等)只用于你自己的执行;不要写卡;不要用你的状态替代卡。');
1952
+ lines.push('- 结束时返回:status / artifacts / checks / user_approval / 建议步骤变更。');
1953
+ lines.push('');
1954
+ lines.push('## 回执后(所有者动作;skill 不执行)');
1955
+ lines.push('1. 核对回执中的产物/命令 exit/用户节点;缺证据不勾卡。');
1956
+ lines.push('2. 在卡内勾选当前阶段步骤,并在 `## 验证记录` 写一行证据(产物/命令/exit/验证人)。');
1957
+ lines.push('3. 卡未更新前,不进入下一阶段;skill 的 `task_plan`/`active` 完成不算任务完成。');
1958
+ return lines.join('\n');
1959
+ }
1960
+
1961
+ /* ------------------------ delegation bookkeeping ----------------------- */
1962
+
1963
+ const BRIEF_KEYS = ['task', 'step', 'attempt', 'assignment', 'scope', 'non_goals', 'acceptance', 'expected_evidence'];
1964
+
1965
+ /** Validate a delegation brief (delegation.md §3.1): 8 required + 1 optional. */
1966
+ export function validateBrief(brief) {
1967
+ const issues = [];
1968
+ if (!brief || typeof brief !== 'object') return ['brief is not an object'];
1969
+ for (const k of BRIEF_KEYS) {
1970
+ const v = brief[k];
1971
+ if (v === undefined || v === null || v === '') issues.push(`missing field: ${k}`);
1972
+ else if (['scope', 'non_goals', 'expected_evidence'].includes(k) && (!Array.isArray(v) || v.length === 0)) {
1973
+ issues.push(`${k} must be a non-empty list`);
1974
+ }
1975
+ }
1976
+ if (brief.contract !== undefined && !/^[a-z0-9-]+@[0-9a-f]{12,64}$/.test(String(brief.contract))) {
1977
+ issues.push(`contract must look like <workflow>@<hash>: ${brief.contract}`);
1978
+ }
1979
+ return issues;
1980
+ }
1981
+
1982
+ /** Apply the receipt → bookkeeping mapping (delegation.md §4). Pure; returns a new state. */
1983
+ export function applyReceipt(steps, checkedIn, brief, receipt) {
1984
+ const issues = [...validateBrief(brief), ...validateReceipt(receipt, brief)];
1985
+ if (issues.length) return { ok: false, issues };
1986
+ if (receipt.step !== steps.current) {
1987
+ return { ok: false, issues: [`receipt step ${receipt.step} is not current (current=${steps.current})`] };
1988
+ }
1989
+ const base = { steps: JSON.parse(JSON.stringify(steps)), checked: [...checkedIn], current: steps.current };
1990
+ const run = (fn) => {
1991
+ try {
1992
+ return { ok: true, state: fn() };
1993
+ } catch (e) {
1994
+ return { ok: false, issues: [String(e && e.message ? e.message : e)] };
1995
+ }
1996
+ };
1997
+ switch (receipt.status) {
1998
+ case 'completed': {
1999
+ const r = run(() => advance(base.steps, base.checked, { type: 'complete', node: receipt.step }));
2000
+ return r.ok ? { ...r, action: 'completed: verify evidence -> advance', detail: r.state.action } : r;
2001
+ }
2002
+ case 'failed': {
2003
+ const r = run(() => advance(base.steps, base.checked, { type: 'fail', node: receipt.step }));
2004
+ return r.ok ? { ...r, action: 'failed: retry or decision', detail: r.state.action } : r;
2005
+ }
2006
+ case 'partial':
2007
+ return { ok: true, state: base, action: 'partial: stay doing', detail: (receipt.remaining_work || [])[0] || '' };
2008
+ case 'input_required':
2009
+ return { ok: true, state: base, action: 'input_required: ask user, stay doing', detail: receipt.question };
2010
+ default:
2011
+ return { ok: false, issues: [`unmapped status: ${receipt.status}`] };
2012
+ }
2013
+ }
2014
+
2015
+ /** Extract delegation rows from execution-history lines (delegation.md §2): 委派 line without a later 回执 line => pending. */
2016
+ export function parseDelegations(lines) {
2017
+ const out = [];
2018
+ let idx = 0;
2019
+ for (const line of lines) {
2020
+ idx += 1;
2021
+ const m = /委派\s+(S[0-9A-Za-z_.]*)\s*→/.exec(line);
2022
+ if (m) {
2023
+ out.push({ step: m[1], hasReceipt: false, at: idx });
2024
+ continue;
2025
+ }
2026
+ const r = /回执\s+(S[0-9A-Za-z_.]*)/.exec(line);
2027
+ if (r) {
2028
+ const hit = out.find((d) => d.step === r[1] && !d.hasReceipt);
2029
+ if (hit) hit.hasReceipt = true;
2030
+ }
2031
+ }
2032
+ return out;
2033
+ }
2034
+
2035
+ /* ------------------------ cross-card consistency ----------------------- */
2036
+
2037
+ /** Audit ledgers against card front-matter (contract §11.5). Pure; returns issues. */
2038
+ export function auditCrossCard(activeRows, archivedRows, cardsById) {
2039
+ const issues = [];
2040
+ const byId = Object.fromEntries(activeRows.map((r) => [r.id, r]));
2041
+ const archivedIds = new Set(archivedRows.map((r) => r.id));
2042
+ const activeCounts = {};
2043
+ for (const r of activeRows) activeCounts[r.id] = (activeCounts[r.id] || 0) + 1;
2044
+ for (const [id, n] of Object.entries(activeCounts)) if (n > 1) issues.push(`duplicate active ledger row: ${id}`);
2045
+ for (const [id, row] of Object.entries(byId)) {
2046
+ const card = cardsById[id];
2047
+ if (!card) {
2048
+ issues.push(`ledger row ${id} has no card`);
2049
+ continue;
2050
+ }
2051
+ if (card.status !== row.status) issues.push(`${id}: card status ${card.status} != ledger ${row.status}`);
2052
+ if (archivedIds.has(id)) issues.push(`${id}: appears in both active ledger and archive`);
2053
+ }
2054
+ for (const row of archivedRows) {
2055
+ const card = cardsById[row.id];
2056
+ if (!card) {
2057
+ issues.push(`archived row ${row.id} has no card`);
2058
+ continue;
2059
+ }
2060
+ if (card.status !== row.status) issues.push(`${row.id}: archived status ${row.status} != card ${card.status}`);
2061
+ }
2062
+ for (const [id, card] of Object.entries(cardsById)) {
2063
+ if (!byId[id] && !archivedIds.has(id)) issues.push(`${id}: card missing from both ledgers`);
2064
+ if (archivedIds.has(id) && !['done', 'cancelled'].includes(card.status)) issues.push(`${id}: archived but status is ${card.status}`);
2065
+ }
2066
+ // blocked-by must resolve against active OR archived tasks; ledger column must match the card.
2067
+ for (const r of activeRows) {
2068
+ const card = cardsById[r.id];
2069
+ if (!card) continue;
2070
+ const cardBlocked = Array.isArray(card['blocked-by']) ? card['blocked-by'] : [];
2071
+ for (const dep of cardBlocked) {
2072
+ if (!byId[dep] && !archivedIds.has(dep)) issues.push(`${r.id}: blocked-by points to unknown task ${dep}`);
2073
+ }
2074
+ if (r.blocked !== undefined) {
2075
+ const ledgerBlocked = r.blocked === '—' || r.blocked === '' ? [] : String(r.blocked).split(',').map((s) => s.trim()).filter(Boolean);
2076
+ if (JSON.stringify([...cardBlocked].sort()) !== JSON.stringify([...ledgerBlocked].sort())) {
2077
+ issues.push(`${r.id}: ledger blocked-by ${JSON.stringify(ledgerBlocked)} != card ${JSON.stringify(cardBlocked)}`);
2078
+ }
2079
+ }
2080
+ }
2081
+ const focus = activeRows.filter((r) => r.focus === '★');
2082
+ if (focus.length > 1) issues.push(`multiple focus rows: ${focus.map((r) => r.id).join(', ')}`);
2083
+ return issues;
2084
+ }
2085
+
2086
+ /* ------------------------- next-task candidates ------------------------ */
2087
+
2088
+ const PRIORITY_RANK = { high: 0, medium: 1, low: 2 };
2089
+
2090
+ /** Next-task candidates (dependency.md §1): active + all blocked-by done; ★ -> priority -> updated desc. */
2091
+ export function nextCandidates(tasks) {
2092
+ const status = Object.fromEntries(tasks.map((t) => [t.id, t.status]));
2093
+ return tasks
2094
+ .filter((t) => t.status === 'active' && (t.blockedBy || []).every((d) => status[d] === 'done'))
2095
+ .sort((a, b) => {
2096
+ const fa = a.focus === '★' ? 0 : 1;
2097
+ const fb = b.focus === '★' ? 0 : 1;
2098
+ if (fa !== fb) return fa - fb;
2099
+ const pa = PRIORITY_RANK[a.priority] ?? 3;
2100
+ const pb = PRIORITY_RANK[b.priority] ?? 3;
2101
+ if (pa !== pb) return pa - pb;
2102
+ return String(b.updated || '').localeCompare(String(a.updated || ''));
2103
+ })
2104
+ .map((t) => t.id);
2105
+ }
2106
+
2107
+ /* -------------------------------- context ----------------------------- */
2108
+ // 恢复包:卡必读区(目标/下一步/Resume)+ docs 清单 + 头部摘要(recovery.md §1.1 的机械入口)。
2109
+ // 只输出相对项目根的路径;缺失/非法条目照实报告,不填充、不当作已读。
2110
+
2111
+ function sectionMap(body) {
2112
+ const out = new Map();
2113
+ let cur = null;
2114
+ let buf = [];
2115
+ const flush = () => {
2116
+ if (cur !== null) out.set(cur, buf.join('\n').trim());
2117
+ buf = [];
2118
+ };
2119
+ for (const line of body.replace(/\r\n/g, '\n').split('\n')) {
2120
+ const m = /^##\s+(.+?)\s*$/.exec(line);
2121
+ if (m) {
2122
+ flush();
2123
+ cur = m[1].trim();
2124
+ continue;
2125
+ }
2126
+ if (cur !== null) buf.push(line);
2127
+ }
2128
+ flush();
2129
+ return out;
2130
+ }
2131
+
2132
+ function firstParagraph(text) {
2133
+ const lines = (text || '').split('\n').map((line) => line.trim());
2134
+ const start = lines.findIndex((line) => line !== '');
2135
+ if (start < 0) return null;
2136
+ const out = [];
2137
+ for (let i = start; i < lines.length; i += 1) {
2138
+ if (lines[i] === '') break;
2139
+ out.push(lines[i]);
2140
+ }
2141
+ return out.join('\n');
2142
+ }
2143
+
2144
+ function docHeadLines(text, limit) {
2145
+ const lines = text.replace(/\r\n/g, '\n').split('\n');
2146
+ const out = [];
2147
+ for (const line of lines) {
2148
+ if (out.length > 0 && /^##\s+/.test(line)) break;
2149
+ out.push(line);
2150
+ if (out.length >= limit) break;
2151
+ }
2152
+ return out;
2153
+ }
2154
+
2155
+ // 恢复包必须带齐卡的必读区(recovery.md §1「二级」):验收清单原样列出;已验证事实、关键决策只取最近的几条,
2156
+ // 注明更早的还有几条。早先只输出目标第一段、当前步骤、下一步,靠它恢复的人拿不到验收、事实和决策,
2157
+ // 与"和手工读卡结果等价"的说法不符(独立判卷人按规则原文判了不通过)。
2158
+ const CONTEXT_FACTS_SHOWN = 10;
2159
+ const CONTEXT_DECISIONS_SHOWN = 5;
2160
+
2161
+ /** 把一节切成条目:行首「- 」开新条目,后面的缩进续行跟着它。没有条目时整节算一条。 */
2162
+ function splitItems(text) {
2163
+ const items = [];
2164
+ for (const raw of String(text ?? '').split(/\r?\n/)) {
2165
+ if (/^-\s/.test(raw)) items.push([raw]);
2166
+ else if (raw.trim() && items.length) items[items.length - 1].push(raw);
2167
+ }
2168
+ return items.length ? items : (String(text ?? '').trim() ? [[String(text).trim()]] : []);
2169
+ }
2170
+
2171
+ /** 「## 标题(最近 n 条 / 共 m 条;更早的 k 条见任务卡)」+ 条目原文。 */
2172
+ function recentSection(title, text, shown) {
2173
+ const items = splitItems(text);
2174
+ if (!items.length) return [`## ${title}`, '(缺失)', ''];
2175
+ const rest = Math.max(0, items.length - shown);
2176
+ const pick = items.slice(rest);
2177
+ const note = items.length > shown ? `(最近 ${pick.length} 条 / 共 ${items.length} 条;更早的 ${rest} 条见任务卡)` : `(共 ${items.length} 条)`;
2178
+ return [`## ${title}${note}`, ...pick.flat(), ''];
2179
+ }
2180
+
2181
+ /** 验收清单:目标与验收节里所有编号验收行,连同勾选状态原样列出。 */
2182
+ function acceptanceSection(text) {
2183
+ const rows = String(text ?? '').split(/\r?\n/).filter((l) => /^-\s+\[[xX ]\]\s*A\d/.test(l));
2184
+ return ['## 验收', ...(rows.length ? rows : ['- (没有编号的验收行)']), ''];
2185
+ }
2186
+
2187
+ export function buildContext(cardPath, options = {}) {
2188
+ const headLimit = Math.max(1, Number(options.head) || DOCS_DEFAULT_HEAD);
2189
+ const maxLines = Math.max(headLimit, Number(options.max) || DOCS_MAX_TOTAL_LINES);
2190
+ const text = readFileSync(cardPath, 'utf8');
2191
+ const { front, body } = splitFrontMatter(text);
2192
+ const fm = parseYaml(front);
2193
+ const sections = sectionMap(body);
2194
+ const id = fm.id === undefined ? basename(dirname(resolve(cardPath))) : String(fm.id);
2195
+ const lines = [];
2196
+ lines.push(`# 任务上下文:${id}`);
2197
+ lines.push(`标题:${fm.title ?? '(缺失)'}`);
2198
+ lines.push(`状态:${fm.status ?? '(缺失)'} | 更新:${fm.updated ?? '(缺失)'}`);
2199
+ lines.push('');
2200
+ lines.push('## 目标');
2201
+ lines.push(firstParagraph(sections.get('目标与验收')) ?? '(缺失)');
2202
+ lines.push('');
2203
+ lines.push(currentStepBlock(fm, body, cardPath));
2204
+ lines.push(...acceptanceSection(sections.get('目标与验收')));
2205
+ lines.push(...recentSection('已验证事实', sections.get('已验证事实'), CONTEXT_FACTS_SHOWN));
2206
+ lines.push(...recentSection('关键决策', sections.get('关键决策'), CONTEXT_DECISIONS_SHOWN));
2207
+ lines.push('## 下一步');
2208
+ lines.push(firstParagraph(sections.get('下一步')) ?? '(缺失)');
2209
+ lines.push('');
2210
+ lines.push('## Resume');
2211
+ lines.push((sections.get('Resume 指针') || '(缺失)').split('\n').slice(0, 12).join('\n'));
2212
+ lines.push('');
2213
+
2214
+ const root = projectRootForCard(cardPath);
2215
+ const { config } = resolveConfig(root);
2216
+ const rawList = normalizeDocs(fm.docs);
2217
+ const list = rawList === null ? [] : rawList;
2218
+ lines.push(`## 必读文档(${list.length})`);
2219
+ if (rawList === null) lines.push('- 诊断:docs 必须是字符串或字符串列表(契约 §2.4)');
2220
+ else if (list.length === 0) lines.push('- 无(未声明 docs)');
2221
+
2222
+ const refs = [];
2223
+ const seen = new Set();
2224
+ for (const entry of list) {
2225
+ const ref = resolveDocRef(root, entry, config.ledgerName, config.archiveName);
2226
+ if (ref.error) {
2227
+ lines.push(`- [缺失/非法] ${String(entry)}(${ref.error})`);
2228
+ continue;
2229
+ }
2230
+ if (seen.has(ref.rel)) {
2231
+ lines.push(`- [重复] ${ref.rel}`);
2232
+ continue;
2233
+ }
2234
+ seen.add(ref.rel);
2235
+ const mode = ref.lineCount <= 120 ? `整篇 ${ref.lineCount} 行` : `摘要 ${headLimit}/${ref.lineCount} 行`;
2236
+ lines.push(`- [存在] ${ref.rel}(${mode})`);
2237
+ refs.push(ref);
2238
+ }
2239
+ lines.push('');
2240
+
2241
+ if (refs.length > 0) {
2242
+ lines.push('## 预读摘要');
2243
+ lines.push('');
2244
+ let used = 0;
2245
+ for (const ref of refs) {
2246
+ const head = docHeadLines(readFileSync(ref.abs, 'utf8'), headLimit);
2247
+ let take = head;
2248
+ if (used + head.length > maxLines) {
2249
+ take = head.slice(0, Math.max(0, maxLines - used));
2250
+ lines.push(`### ${ref.rel}(本次只输出 ${take.length} 行,其余按需续读)`);
2251
+ } else {
2252
+ lines.push(`### ${ref.rel}`);
2253
+ }
2254
+ lines.push(...take);
2255
+ lines.push('');
2256
+ used += take.length;
2257
+ if (used >= maxLines) {
2258
+ lines.push(`(预读摘要已达上限 ${maxLines} 行;其余文档按需读,不当作已读。)`);
2259
+ break;
2260
+ }
2261
+ }
2262
+ }
2263
+
2264
+ lines.push('## 预读统计');
2265
+ const missing = Math.max(0, list.length - refs.length);
2266
+ // 行数按最终输出的文本算:先占上位、等末行也推进去再数(命令行就是 join 后打印的)。
2267
+ // 不能数数组元素:有的元素本身跨多行("当前步骤"一节、Resume 指针),数元素会少算好几行。
2268
+ // 口径与 --max 一致,都是含空行的行数。
2269
+ const statIndex = lines.length;
2270
+ lines.push('');
2271
+ lines.push('文档不是状态源:与任务卡/总账冲突时以卡为准;读完把预读结果写进 Resume 指针。');
2272
+ const total = lines.join('\n').split('\n').length;
2273
+ lines[statIndex] = `存在 ${refs.length} 份 / 缺失·非法·重复 ${missing} 份;本输出 ${total} 行(含空行;预读摘要上限 ${maxLines} 行,同一口径)。`;
2274
+ return lines;
2275
+ }
2276
+
2277
+ function cmdContext(args) {
2278
+ const cardPath = args[0];
2279
+ if (!cardPath) return usage();
2280
+ console.log(buildContext(cardPath, { head: argOf(args, '--head'), max: argOf(args, '--max') }).join('\n'));
2281
+ }
2282
+
2283
+ /* ------------------------------ docs 汇总 ----------------------------- */
2284
+ // 反查视图:从所有任务卡的 docs 聚合出「文档 → 引用任务」,并报告缺失/非法项。
2285
+ // 只读;不扫描未被引用的文档(野文档不归框架管,也不进本表)。
2286
+
2287
+ /** 汇总用的项目根:优先 cwd(配置在 cwd 时),否则 git 根。 */
2288
+ function docsScanRoot(dir) {
2289
+ const resolved = resolve(dir);
2290
+ const cfg = resolveConfig(resolved);
2291
+ if (cfg.source === 'cwd') return resolved;
2292
+ return findGitRoot(resolved) ?? resolved;
2293
+ }
2294
+
2295
+ export function buildDocsReport(dir = process.cwd()) {
2296
+ const root = docsScanRoot(dir);
2297
+ const { config } = resolveConfig(root);
2298
+ const dataDir = resolve(root, config.tasksDir);
2299
+ const lines = [];
2300
+ if (!existsSync(dataDir)) {
2301
+ lines.push(`数据目录不存在:${config.tasksDir}`);
2302
+ return lines;
2303
+ }
2304
+ const entries = new Map();
2305
+ let taskCount = 0;
2306
+ let declared = 0;
2307
+ for (const dirent of readdirSync(dataDir, { withFileTypes: true })) {
2308
+ if (!dirent.isDirectory() || dirent.name.startsWith('.')) continue;
2309
+ const cardPath = join(dataDir, dirent.name, 'task.md');
2310
+ if (!existsSync(cardPath)) continue;
2311
+ let fm;
2312
+ try {
2313
+ fm = parseYaml(splitFrontMatter(readFileSync(cardPath, 'utf8')).front);
2314
+ } catch {
2315
+ continue; // 坏卡归 check 报告,汇总只跳过
2316
+ }
2317
+ const list = normalizeDocs(fm.docs);
2318
+ if (list === null) {
2319
+ const key = `(${dirent.name} 的 docs 形状非法)`;
2320
+ const cur = entries.get(key) ?? { refs: [], error: 'docs 形状非法', lines: null };
2321
+ cur.refs.push(dirent.name);
2322
+ entries.set(key, cur);
2323
+ continue;
2324
+ }
2325
+ if (list.length === 0) continue;
2326
+ taskCount += 1;
2327
+ declared += list.length;
2328
+ for (const raw of list) {
2329
+ const ref = resolveDocRef(root, raw, config.ledgerName, config.archiveName);
2330
+ const key = ref.error ? String(raw) : ref.rel;
2331
+ const cur = entries.get(key) ?? { refs: [], error: null, lines: null };
2332
+ if (!cur.refs.includes(dirent.name)) cur.refs.push(dirent.name);
2333
+ if (ref.error) cur.error = ref.error;
2334
+ else cur.lines = ref.lineCount;
2335
+ entries.set(key, cur);
2336
+ }
2337
+ }
2338
+ const ok = [...entries.entries()].filter(([, value]) => !value.error).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
2339
+ const bad = [...entries.entries()].filter(([, value]) => value.error).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
2340
+ lines.push(`# 项目文档引用汇总(${ok.length} 份可用 / ${bad.length} 份异常)`);
2341
+ if (entries.size === 0) {
2342
+ lines.push(`数据目录:${config.tasksDir};没有任务声明 docs(无需管理)。`);
2343
+ return lines;
2344
+ }
2345
+ lines.push(`数据目录:${config.tasksDir};${taskCount} 个任务声明了 ${declared} 条引用。`);
2346
+ for (const [rel, info] of ok) {
2347
+ lines.push(`${rel}${info.lines === null ? '' : `(${info.lines} 行)`}`);
2348
+ lines.push(` ← ${info.refs.join(', ')}`);
2349
+ }
2350
+ for (const [rel, info] of bad) {
2351
+ lines.push(`[异常] ${rel}(${info.error})`);
2352
+ lines.push(` ← ${info.refs.join(', ')}`);
2353
+ }
2354
+ const reused = ok.filter(([, value]) => value.refs.length > 1).length;
2355
+ lines.push('');
2356
+ lines.push(`复用(≥2 个任务引用):${reused} 份;未声明 docs 的任务不在本表。`);
2357
+ return lines;
2358
+ }
2359
+
2360
+ function cmdDocs(args) {
2361
+ console.log(buildDocsReport(args[0] ?? process.cwd()).join('\n'));
2362
+ }
2363
+
2364
+ /* -------------------------------- CLI -------------------------------- */
2365
+
2366
+ function usage() {
2367
+ console.log(`Usage:
2368
+ node instantiate-skeleton.mjs hash <skillDir>
2369
+ node instantiate-skeleton.mjs verify <skeleton.md> <skillDir>
2370
+ node instantiate-skeleton.mjs test
2371
+ node instantiate-skeleton.mjs instantiate <skeleton.md> --skill <dir> [--params p.json] [--decisions d.json] [--out file]
2372
+ node instantiate-skeleton.mjs check <task.md> [<task.md> ...] [--strict]
2373
+ node instantiate-skeleton.mjs preflight <draft task.md> [--base <existing task.md>] [--eval <skill-eval.md>] [--allow-skill <name>]
2374
+ node instantiate-skeleton.mjs fingerprint <task.md> # 打印步骤指纹(写评估行用)
2375
+ node instantiate-skeleton.mjs drafts [dir]
2376
+ node instantiate-skeleton.mjs map <map.yaml> [--card <task.md>] [--step Sx] [--steps] [--brief] [--json]
2377
+ node instantiate-skeleton.mjs context <task.md> [--head 40] [--max 300]
2378
+ node instantiate-skeleton.mjs docs [dir]
2379
+ node instantiate-skeleton.mjs config [dir]
2380
+ node instantiate-skeleton.mjs check-receipt <receipt.yml|json> [brief.yml|json]
2381
+ node instantiate-skeleton.mjs advance <task.md> --event '{"type":"complete","node":"S1"}'
2382
+ `);
2383
+ }
2384
+
2385
+ function argOf(args, name) {
2386
+ const i = args.indexOf(name);
2387
+ return i >= 0 ? args[i + 1] : undefined;
2388
+ }
2389
+
2390
+ function cmdMap(args) {
2391
+ const mapPath = args[0];
2392
+ if (!mapPath) return usage();
2393
+ const cardPath = argOf(args, '--card');
2394
+ const stepArg = argOf(args, '--step');
2395
+ const asJson = args.includes('--json');
2396
+ const stepsOnly = args.includes('--steps');
2397
+ const briefOnly = args.includes('--brief');
2398
+
2399
+ let parsed;
2400
+ try {
2401
+ parsed = parseIntegrationMap(readFileSync(mapPath, 'utf8'));
2402
+ } catch (e) {
2403
+ console.error(`FAIL ${mapPath}: ${e.message}`);
2404
+ process.exit(1);
2405
+ }
2406
+ if (parsed.issues.length) {
2407
+ console.error(`FAIL ${mapPath}`);
2408
+ for (const issue of parsed.issues) console.error(` - ${issue}`);
2409
+ process.exit(1);
2410
+ }
2411
+ for (const warning of parsed.warnings) console.warn(`WARN ${mapPath}: ${warning}`);
2412
+
2413
+ const map = parsed.map;
2414
+ const { steps, boxes } = buildIntegrationSteps(map);
2415
+ let card = null;
2416
+ if (cardPath) {
2417
+ try {
2418
+ const text = readFileSync(cardPath, 'utf8');
2419
+ const { front } = splitFrontMatter(text);
2420
+ const fm = parseYaml(front);
2421
+ card = {
2422
+ id: fm.id ?? basename(dirname(resolve(cardPath))),
2423
+ title: fm.title ?? '(缺失)',
2424
+ path: cardPath,
2425
+ current: stepArg || (fm.steps && fm.steps.current) || null,
2426
+ steps: fm.steps || null,
2427
+ };
2428
+ if (card.steps) {
2429
+ for (const id of Object.keys(steps)) {
2430
+ if (card.steps[id]) console.warn(`WARN ${mapPath}: stage ${id} already exists in card steps`);
2431
+ }
2432
+ }
2433
+ } catch (e) {
2434
+ console.error(`card read error: ${e.message}`);
2435
+ process.exit(1);
2436
+ }
2437
+ }
2438
+
2439
+ const brief = buildIntegrationBrief(map, card);
2440
+ if (asJson) {
2441
+ console.log(JSON.stringify({ map, steps, boxes, brief }, null, 2));
2442
+ return;
2443
+ }
2444
+
2445
+ const showSteps = stepsOnly || (!briefOnly);
2446
+ const showBrief = briefOnly || (!stepsOnly);
2447
+ if (showSteps) {
2448
+ console.log('# 加到卡 front-matter 的 steps:');
2449
+ for (const [id, node] of Object.entries(steps)) {
2450
+ console.log(`${id}: {from: ${node.from}, required: ${node.required}, next: ${node.next}}`);
2451
+ }
2452
+ console.log('\n# 加到 ## 步骤清单:');
2453
+ for (const box of boxes) console.log(box);
2454
+ }
2455
+ if (showSteps && showBrief) console.log('\n---\n');
2456
+ if (showBrief) console.log(brief);
2457
+ }
2458
+
2459
+ function runMain() {
2460
+ const [command, ...rest] = process.argv.slice(2);
2461
+ switch (command) {
2462
+ case 'hash': {
2463
+ if (!rest[0]) return usage();
2464
+ console.log(skillHashDir(rest[0]));
2465
+ return;
2466
+ }
2467
+ case 'verify': {
2468
+ const [skeleton, skillDir] = rest;
2469
+ if (!skeleton || !skillDir) return usage();
2470
+ const r = verifySkeleton(skeleton, skillDir);
2471
+ if (!r.ok) {
2472
+ console.error(`STALE: skeleton pinned ${r.pinned}, current ${r.current.slice(0, 12)}`);
2473
+ process.exit(1);
2474
+ }
2475
+ console.log(`OK: skeleton pinned ${r.pinned} matches current skillHash`);
2476
+ return;
2477
+ }
2478
+ case 'test': {
2479
+ const expected = {
2480
+ T1: 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
2481
+ T2: 'c76c0a237189043844d75b5572219dfb28be9675d4211ead29cdb83d660ed3f8',
2482
+ T3: 'e7ea030086400e74ed88a6e9d026c68542e58265c02d7cd0b4bc55fe1100b928',
2483
+ };
2484
+ const got = {
2485
+ T1: skillHashFromEntries([]),
2486
+ T2: skillHashFromEntries([{ rel: 'SKILL.md', bytes: Buffer.from('---\nname: task-card\n---\n', 'utf8') }]),
2487
+ T3: skillHashFromEntries([
2488
+ { rel: 'references/a.md', bytes: Buffer.from('a\n', 'utf8') },
2489
+ { rel: 'SKILL.md', bytes: Buffer.from('---\nname: task-card\n---\n', 'utf8') },
2490
+ ]),
2491
+ };
2492
+ let failed = 0;
2493
+ for (const k of Object.keys(expected)) {
2494
+ const ok = got[k] === expected[k];
2495
+ if (!ok) failed += 1;
2496
+ console.log(`${ok ? 'PASS' : 'FAIL'} ${k}${ok ? '' : ` expected ${expected[k]} got ${got[k]}`}`);
2497
+ }
2498
+ if (failed) {
2499
+ console.error(`${failed} vector(s) failed — implementation does not match task-format.md §3.8`);
2500
+ process.exit(1);
2501
+ }
2502
+ console.log('all vectors passed');
2503
+ return;
2504
+ }
2505
+ case 'instantiate': {
2506
+ const skeletonPath = rest[0];
2507
+ const skillDir = argOf(rest, '--skill');
2508
+ if (!skeletonPath || !skillDir) return usage();
2509
+ const { yaml, boxes, workflow } = instantiate({
2510
+ skeletonPath,
2511
+ skillDir,
2512
+ paramsPath: argOf(rest, '--params'),
2513
+ decisionsPath: argOf(rest, '--decisions'),
2514
+ });
2515
+ const out = `${yaml}\n\n${boxes.join('\n')}\n`;
2516
+ const outPath = argOf(rest, '--out');
2517
+ if (outPath) {
2518
+ writeFileSync(outPath, out, 'utf8');
2519
+ console.error(`wrote ${outPath} (workflow ${workflow}, ${boxes.length} checkboxes)`);
2520
+ } else process.stdout.write(out);
2521
+ return;
2522
+ }
2523
+ case 'check': {
2524
+ cmdCheck(rest);
2525
+ return;
2526
+ }
2527
+ case 'map': {
2528
+ cmdMap(rest);
2529
+ return;
2530
+ }
2531
+ case 'context': {
2532
+ cmdContext(rest);
2533
+ return;
2534
+ }
2535
+ case 'preflight': {
2536
+ cmdPreflight(rest);
2537
+ return;
2538
+ }
2539
+ case 'fingerprint': {
2540
+ cmdFingerprint(rest);
2541
+ return;
2542
+ }
2543
+ case 'drafts': {
2544
+ cmdDrafts(rest);
2545
+ return;
2546
+ }
2547
+ case 'docs': {
2548
+ cmdDocs(rest);
2549
+ return;
2550
+ }
2551
+ case 'advance': {
2552
+ const card = rest[0];
2553
+ const eventArg = argOf(rest, '--event');
2554
+ if (!card || !eventArg) return usage();
2555
+ const { front, body } = splitFrontMatter(readFileSync(card, 'utf8'));
2556
+ const fm = parseYaml(front);
2557
+ const checked = [];
2558
+ for (const line of body.split(/\r?\n/)) {
2559
+ const m = /^\s*-\s*\[[xX]\]\s+(S[0-9A-Za-z_.]*)\s+/.exec(line);
2560
+ if (m) checked.push(m[2]);
2561
+ }
2562
+ const state = advance(fm.steps, checked, JSON.parse(eventArg));
2563
+ console.log(JSON.stringify({ action: state.action, current: state.current, checked: state.checked }, null, 2));
2564
+ return;
2565
+ }
2566
+ case 'config': {
2567
+ const r = resolveConfig(rest[0] || process.cwd());
2568
+ console.log(JSON.stringify(r, null, 2));
2569
+ return;
2570
+ }
2571
+ case 'check-receipt': {
2572
+ const [receiptPath, briefPath] = rest;
2573
+ if (!receiptPath) return usage();
2574
+ const receipt = parseYaml(readFileSync(receiptPath, 'utf8'));
2575
+ const brief = briefPath ? parseYaml(readFileSync(briefPath, 'utf8')) : undefined;
2576
+ const issues = validateReceipt(receipt, brief);
2577
+ if (issues.length) {
2578
+ console.error(`FAIL ${receiptPath}`);
2579
+ for (const i of issues) console.error(` - ${i}`);
2580
+ process.exit(1);
2581
+ }
2582
+ console.log(`PASS ${receiptPath}`);
2583
+ return;
2584
+ }
2585
+ case undefined:
2586
+ case '-h':
2587
+ case '--help':
2588
+ return usage();
2589
+ default:
2590
+ console.error(`Unknown command: ${command}`);
2591
+ usage();
2592
+ process.exit(2);
2593
+ }
2594
+ }
2595
+
2596
+ function main() {
2597
+ try {
2598
+ runMain();
2599
+ } catch (e) {
2600
+ console.error(`ERROR: ${e && e.message ? e.message : e}`);
2601
+ process.exit(1);
2602
+ }
2603
+ }
2604
+
2605
+ export { skillHashDir, skillHashFromEntries, instantiate, checkCard, parseYaml };
2606
+
2607
+ // symlink 安装(如本地 link 插件)下,argv[1] 是链接路径,import.meta.url 是真路径;
2608
+ // 直接比较永远不相等,会静默 exit 0。两边都 realpath 后再比。
2609
+ function isMainModule() {
2610
+ if (!process.argv[1]) return false;
2611
+ try {
2612
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
2613
+ } catch {
2614
+ return false;
2615
+ }
2616
+ }
2617
+
2618
+ if (isMainModule()) main();