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
package/lib/index.js ADDED
@@ -0,0 +1,1591 @@
1
+ // src/host/index.ts
2
+ import { existsSync as existsSync4 } from "node:fs";
3
+ import { basename as basename2, dirname as dirname2, isAbsolute as isAbsolute2, resolve as resolve3 } from "node:path";
4
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
5
+
6
+ // src/shared/protocol.ts
7
+ var PLUGIN_ID = "dsh-task-card";
8
+ var SNAPSHOT_ROUTES = {
9
+ /** GET:返回当前快照。 */
10
+ get: "/task-card/snapshot",
11
+ /** POST:丢弃缓存后重新读盘再返回快照(M2 无缓存,语义先占位)。 */
12
+ refresh: "/task-card/refresh",
13
+ /** GET:按 id 读取单张卡的 task.md 原文(详情预览用;只读、不缓存)。 */
14
+ card: "/task-card/card",
15
+ /** GET:按 id 列出任务目录内的文件树(打开任务文件用;只读、有深度/数量上限)。 */
16
+ files: "/task-card/files",
17
+ /** GET/POST:读取/保存插件设置(写 DSH 插件配置,不写任务文件)。 */
18
+ settings: "/task-card/settings"
19
+ };
20
+
21
+ // src/host/snapshot.ts
22
+ import { readdirSync, readFileSync, statSync } from "node:fs";
23
+ import { existsSync } from "node:fs";
24
+ import { basename, isAbsolute, join, relative, resolve, sep } from "node:path";
25
+
26
+ // src/host/markdown.ts
27
+ var FRONT_MATTER_FENCE = "---";
28
+ function splitFrontMatter(text) {
29
+ const diagnostics = [];
30
+ const normalized = text.replace(/\r\n/g, "\n");
31
+ const lines = normalized.split("\n");
32
+ if (lines[0]?.trim() !== FRONT_MATTER_FENCE) return { frontMatter: null, body: normalized, diagnostics };
33
+ for (let i = 1; i < lines.length; i += 1) {
34
+ if (lines[i]?.trim() === FRONT_MATTER_FENCE) {
35
+ return {
36
+ frontMatter: lines.slice(1, i).join("\n"),
37
+ body: lines.slice(i + 1).join("\n"),
38
+ diagnostics
39
+ };
40
+ }
41
+ }
42
+ diagnostics.push("front-matter \u672A\u95ED\u5408\uFF08\u7F3A\u5C11\u7ED3\u675F\u7684 --- \u884C\uFF09");
43
+ return { frontMatter: null, body: normalized, diagnostics };
44
+ }
45
+ function splitSections(body) {
46
+ const sections = [];
47
+ let current = null;
48
+ for (const line of body.split(/\r?\n/)) {
49
+ const heading = /^##\s+(.+?)\s*$/.exec(line);
50
+ if (heading && !line.startsWith("###")) {
51
+ if (current) sections.push(current);
52
+ current = { title: heading[1] ?? "", body: "" };
53
+ continue;
54
+ }
55
+ if (current) current.body += `${line}
56
+ `;
57
+ }
58
+ if (current) sections.push(current);
59
+ return sections;
60
+ }
61
+ function findSection(sections, title) {
62
+ return sections.find((section) => section.title === title) ?? null;
63
+ }
64
+ function extractCheckboxes(body) {
65
+ const items = [];
66
+ for (const line of body.split(/\r?\n/)) {
67
+ const match = /^([ ]*)-[ ]+\[( |x|X)\][ ]+(.*)$/.exec(line);
68
+ if (!match) continue;
69
+ items.push({
70
+ checked: match[2]?.toLowerCase() === "x",
71
+ text: (match[3] ?? "").trim(),
72
+ indent: (match[1] ?? "").length
73
+ });
74
+ }
75
+ return items;
76
+ }
77
+ function countListItems(body) {
78
+ let count = 0;
79
+ for (const line of body.split(/\r?\n/)) {
80
+ if (/^[ ]*-\s/.test(line)) count += 1;
81
+ }
82
+ return count;
83
+ }
84
+ function firstParagraph(body) {
85
+ const blocks = [];
86
+ let current = [];
87
+ for (const rawLine of body.split(/\r?\n/)) {
88
+ const line = rawLine.trim();
89
+ if (line === "") {
90
+ if (current.length > 0) {
91
+ blocks.push(current.join(" "));
92
+ current = [];
93
+ }
94
+ continue;
95
+ }
96
+ current.push(line);
97
+ }
98
+ if (current.length > 0) blocks.push(current.join(" "));
99
+ return blocks[0] ?? null;
100
+ }
101
+ function listItems(body) {
102
+ const out = [];
103
+ for (const line of body.split(/\r?\n/)) {
104
+ const match = /^[ ]*-\s+(.*)$/.exec(line);
105
+ if (match) out.push((match[1] ?? "").trim());
106
+ }
107
+ return out;
108
+ }
109
+ function parseResume(body) {
110
+ const items = listItems(body);
111
+ if (items.length === 0) return null;
112
+ const pick = (label) => {
113
+ const pattern = new RegExp(`^${label}\\s*[\uFF1A:]\\s*(.*)$`);
114
+ for (const item of items) {
115
+ const match = pattern.exec(item);
116
+ if (match) {
117
+ const value = (match[1] ?? "").trim();
118
+ if (value !== "") return value;
119
+ }
120
+ }
121
+ return null;
122
+ };
123
+ const resume = { where: pick("\u505A\u5230\u54EA"), entry: pick("\u5165\u53E3"), pauseReason: pick("\u6682\u505C\u539F\u56E0") };
124
+ return resume.where !== null || resume.entry !== null || resume.pauseReason !== null ? resume : null;
125
+ }
126
+ function goalParagraph(body) {
127
+ const paragraph = firstParagraph(body);
128
+ if (paragraph === null) return null;
129
+ const stripped = paragraph.replace(/^一句话目标\s*[::]\s*/, "").trim();
130
+ return stripped === "" ? null : stripped;
131
+ }
132
+
133
+ // src/host/yaml.ts
134
+ var YamlParseError = class extends Error {
135
+ constructor(message, line) {
136
+ super(`YAML \u7B2C ${line} \u884C\uFF1A${message}`);
137
+ this.line = line;
138
+ this.name = "YamlParseError";
139
+ }
140
+ line;
141
+ };
142
+ var TRUE_VALUES = /* @__PURE__ */ new Set(["true", "True", "TRUE", "yes", "Yes", "on", "On"]);
143
+ var FALSE_VALUES = /* @__PURE__ */ new Set(["false", "False", "FALSE", "no", "No", "off", "Off"]);
144
+ function stripComment(line) {
145
+ let inSingle = false;
146
+ let inDouble = false;
147
+ for (let i = 0; i < line.length; i += 1) {
148
+ const char = line[i];
149
+ if (char === "'" && !inDouble) inSingle = !inSingle;
150
+ else if (char === '"' && !inSingle) inDouble = !inDouble;
151
+ else if (char === "#" && !inSingle && !inDouble && (i === 0 || /\s/.test(line[i - 1] ?? ""))) {
152
+ return line.slice(0, i).replace(/\s+$/, "");
153
+ }
154
+ }
155
+ return line.replace(/\s+$/, "");
156
+ }
157
+ function isBalanced(text) {
158
+ let depth = 0;
159
+ let inSingle = false;
160
+ let inDouble = false;
161
+ for (const char of text) {
162
+ if (char === "'" && !inDouble) inSingle = !inSingle;
163
+ else if (char === '"' && !inSingle) inDouble = !inDouble;
164
+ else if (inSingle || inDouble) continue;
165
+ else if (char === "[" || char === "{") depth += 1;
166
+ else if (char === "]" || char === "}") depth -= 1;
167
+ }
168
+ return depth <= 0;
169
+ }
170
+ function toLines(input) {
171
+ const lines = [];
172
+ let inBlockScalar = false;
173
+ const rawLines = input.split(/\r?\n/);
174
+ for (let i = 0; i < rawLines.length; i += 1) {
175
+ const raw = rawLines[i] ?? "";
176
+ if (inBlockScalar) {
177
+ lines.push({ no: i + 1, raw, indent: 0, text: "" });
178
+ continue;
179
+ }
180
+ const indentMatch = /^[ ]*/.exec(raw) ?? [""];
181
+ const indent = indentMatch[0].length;
182
+ const text = stripComment(raw.slice(indent));
183
+ if (text === "" && indent === 0) continue;
184
+ lines.push({ no: i + 1, raw, indent, text });
185
+ }
186
+ return lines;
187
+ }
188
+ function parseValue(text, line) {
189
+ const trimmed = text.trim();
190
+ if (trimmed === "") return null;
191
+ if (trimmed.startsWith("[") || trimmed.startsWith("{")) return parseFlow(trimmed, line);
192
+ if (trimmed.startsWith('"')) {
193
+ if (!trimmed.endsWith('"') || trimmed.length < 2) throw new YamlParseError("\u53CC\u5F15\u53F7\u5B57\u7B26\u4E32\u672A\u95ED\u5408", line);
194
+ try {
195
+ return JSON.parse(trimmed);
196
+ } catch {
197
+ throw new YamlParseError(`\u65E0\u6CD5\u89E3\u6790\u53CC\u5F15\u53F7\u5B57\u7B26\u4E32\uFF1A${trimmed}`, line);
198
+ }
199
+ }
200
+ if (trimmed.startsWith("'")) {
201
+ if (!trimmed.endsWith("'") || trimmed.length < 2) throw new YamlParseError("\u5355\u5F15\u53F7\u5B57\u7B26\u4E32\u672A\u95ED\u5408", line);
202
+ return trimmed.slice(1, -1).replace(/''/g, "'");
203
+ }
204
+ if (trimmed === "[]") return [];
205
+ if (trimmed === "{}") return {};
206
+ if (trimmed === "~" || trimmed === "null" || trimmed === "Null" || trimmed === "NULL") return null;
207
+ if (TRUE_VALUES.has(trimmed)) return true;
208
+ if (FALSE_VALUES.has(trimmed)) return false;
209
+ if (/^-?\d+$/.test(trimmed)) return Number.parseInt(trimmed, 10);
210
+ if (/^-?\d*\.\d+$/.test(trimmed)) return Number.parseFloat(trimmed);
211
+ return trimmed;
212
+ }
213
+ function parseFlow(text, line) {
214
+ let index = 0;
215
+ const length = text.length;
216
+ const skip = () => {
217
+ while (index < length && /\s/.test(text[index] ?? "")) index += 1;
218
+ };
219
+ const parseNode = () => {
220
+ skip();
221
+ const char = text[index];
222
+ if (char === "[") return parseList();
223
+ if (char === "{") return parseMap();
224
+ if (char === '"') {
225
+ let i = index + 1;
226
+ while (i < length) {
227
+ if (text[i] === "\\") {
228
+ i += 2;
229
+ continue;
230
+ }
231
+ if (text[i] === '"') break;
232
+ i += 1;
233
+ }
234
+ const raw = text.slice(index, i + 1);
235
+ index = i + 1;
236
+ try {
237
+ return JSON.parse(raw);
238
+ } catch {
239
+ throw new YamlParseError(`\u65E0\u6CD5\u89E3\u6790\u53CC\u5F15\u53F7\u5B57\u7B26\u4E32\uFF1A${raw}`, line);
240
+ }
241
+ }
242
+ if (char === "'") {
243
+ let i = index + 1;
244
+ while (i < length) {
245
+ if (text[i] === "'") {
246
+ if (text[i + 1] === "'") {
247
+ i += 2;
248
+ continue;
249
+ }
250
+ break;
251
+ }
252
+ i += 1;
253
+ }
254
+ const value = text.slice(index + 1, i).replace(/''/g, "'");
255
+ index = i + 1;
256
+ return value;
257
+ }
258
+ const start = index;
259
+ while (index < length && !/[,}\]]/.test(text[index] ?? "")) index += 1;
260
+ return parseValue(text.slice(start, index), line);
261
+ };
262
+ const expect = (char) => {
263
+ skip();
264
+ if (text[index] !== char) throw new YamlParseError(`\u671F\u671B "${char}"\uFF0C\u5B9E\u9645 "${text[index] ?? "EOF"}"`, line);
265
+ index += 1;
266
+ };
267
+ const parseList = () => {
268
+ expect("[");
269
+ const out = [];
270
+ skip();
271
+ if (text[index] === "]") {
272
+ index += 1;
273
+ return out;
274
+ }
275
+ for (; ; ) {
276
+ out.push(parseNode());
277
+ skip();
278
+ if (text[index] === ",") {
279
+ index += 1;
280
+ skip();
281
+ if (text[index] === "]") {
282
+ index += 1;
283
+ return out;
284
+ }
285
+ continue;
286
+ }
287
+ expect("]");
288
+ return out;
289
+ }
290
+ };
291
+ const parseMap = () => {
292
+ expect("{");
293
+ const out = {};
294
+ skip();
295
+ if (text[index] === "}") {
296
+ index += 1;
297
+ return out;
298
+ }
299
+ for (; ; ) {
300
+ skip();
301
+ const keyStart = index;
302
+ while (index < length && text[index] !== ":" && text[index] !== "}") index += 1;
303
+ const key = text.slice(keyStart, index).trim().replace(/^['"]|['"]$/g, "");
304
+ if (text[index] !== ":") throw new YamlParseError(`\u5185\u8054\u6620\u5C04\u7F3A ":" \u5206\u9694\uFF08\u952E ${key}\uFF09`, line);
305
+ index += 1;
306
+ out[key] = parseNode();
307
+ skip();
308
+ if (text[index] === ",") {
309
+ index += 1;
310
+ skip();
311
+ if (text[index] === "}") {
312
+ index += 1;
313
+ return out;
314
+ }
315
+ continue;
316
+ }
317
+ expect("}");
318
+ return out;
319
+ }
320
+ };
321
+ const result = parseNode();
322
+ skip();
323
+ if (index < length) throw new YamlParseError(`\u5185\u8054\u503C\u540E\u6709\u591A\u4F59\u5B57\u7B26\uFF1A${text.slice(index)}`, line);
324
+ return result;
325
+ }
326
+ function splitKeyValue(text, line) {
327
+ let inSingle = false;
328
+ let inDouble = false;
329
+ for (let i = 0; i < text.length; i += 1) {
330
+ const char = text[i];
331
+ if (char === "'" && !inDouble) inSingle = !inSingle;
332
+ else if (char === '"' && !inSingle) inDouble = !inDouble;
333
+ else if (char === ":" && !inSingle && !inDouble) {
334
+ const next = text[i + 1];
335
+ if (next === void 0 || /\s/.test(next)) {
336
+ return { key: text.slice(0, i).trim(), rest: text.slice(i + 1).trim() };
337
+ }
338
+ continue;
339
+ }
340
+ }
341
+ if (text.endsWith(":")) return { key: text.slice(0, -1).trim(), rest: "" };
342
+ void line;
343
+ return null;
344
+ }
345
+ var ParsedLines = class {
346
+ constructor(lines, index = 0) {
347
+ this.lines = lines;
348
+ this.index = index;
349
+ }
350
+ lines;
351
+ index;
352
+ /** 跳过多行 flow 值直到括号配平,返回合并后的文本与消耗的行数。 */
353
+ consumeFlow(rest) {
354
+ let merged = rest;
355
+ while (!isBalanced(merged)) {
356
+ this.index += 1;
357
+ const next = this.lines[this.index];
358
+ if (!next) throw new YamlParseError("\u5185\u8054 flow \u503C\u672A\u95ED\u5408\uFF08\u6587\u4EF6\u63D0\u524D\u7ED3\u675F\uFF09", 1);
359
+ merged += ` ${next.text}`;
360
+ }
361
+ return merged;
362
+ }
363
+ parse(indent) {
364
+ const line = this.lines[this.index];
365
+ if (!line) return null;
366
+ if (line.text.startsWith("- ") || line.text === "-") return this.parseList(line.indent);
367
+ return this.parseMap(line.indent);
368
+ }
369
+ parseMap(indent) {
370
+ const out = {};
371
+ while (this.index < this.lines.length) {
372
+ const line = this.lines[this.index];
373
+ if (!line) break;
374
+ if (line.indent < indent) break;
375
+ if (line.indent > indent) throw new YamlParseError(`\u7F29\u8FDB\u5F02\u5E38\uFF08\u671F\u671B ${indent} \u7A7A\u683C\uFF0C\u5B9E\u9645 ${line.indent}\uFF09`, line.no);
376
+ if (line.text.startsWith("-")) break;
377
+ const pair = splitKeyValue(line.text, line.no);
378
+ if (!pair) throw new YamlParseError(`\u4E0D\u662F\u5408\u6CD5\u7684\u300C\u952E: \u503C\u300D\u884C\uFF1A${line.text}`, line.no);
379
+ if (pair.key === "") throw new YamlParseError("\u952E\u4E3A\u7A7A", line.no);
380
+ if (pair.rest !== "") {
381
+ const flow = this.consumeFlow(pair.rest);
382
+ out[pair.key] = parseValue(flow, line.no);
383
+ this.index += 1;
384
+ continue;
385
+ }
386
+ this.index += 1;
387
+ const child = this.lines[this.index];
388
+ if (!child) {
389
+ out[pair.key] = null;
390
+ continue;
391
+ }
392
+ if (child.indent > indent) {
393
+ out[pair.key] = this.parse(child.indent);
394
+ } else if (child.indent === indent && (child.text.startsWith("- ") || child.text === "-")) {
395
+ out[pair.key] = this.parseList(indent);
396
+ } else {
397
+ out[pair.key] = null;
398
+ }
399
+ }
400
+ return out;
401
+ }
402
+ parseList(indent) {
403
+ const out = [];
404
+ while (this.index < this.lines.length) {
405
+ const line = this.lines[this.index];
406
+ if (!line) break;
407
+ if (line.indent !== indent) break;
408
+ if (!(line.text.startsWith("- ") || line.text === "-")) break;
409
+ const itemText = line.text === "-" ? "" : line.text.slice(2).trim();
410
+ if (itemText === "") {
411
+ this.index += 1;
412
+ const child = this.lines[this.index];
413
+ out.push(child && child.indent > indent ? this.parse(child.indent) : null);
414
+ continue;
415
+ }
416
+ const pair = splitKeyValue(itemText, line.no);
417
+ if (pair) {
418
+ this.index += 1;
419
+ const rest = pair.rest === "" ? null : parseValue(this.consumeFlow(pair.rest), line.no);
420
+ const obj = { [pair.key]: rest };
421
+ while (this.index < this.lines.length) {
422
+ const next = this.lines[this.index];
423
+ if (!next || next.indent <= indent) break;
424
+ if (next.indent !== indent + 2) throw new YamlParseError("\u5217\u8868\u9879\u5185\u6620\u5C04\u7F29\u8FDB\u5E94\u4E3A 2 \u7A7A\u683C", next.no);
425
+ const inner = splitKeyValue(next.text, next.no);
426
+ if (!inner) throw new YamlParseError(`\u4E0D\u662F\u5408\u6CD5\u7684\u300C\u952E: \u503C\u300D\u884C\uFF1A${next.text}`, next.no);
427
+ this.index += 1;
428
+ obj[inner.key] = inner.rest === "" ? null : parseValue(this.consumeFlow(inner.rest), next.no);
429
+ }
430
+ out.push(obj);
431
+ continue;
432
+ }
433
+ out.push(parseValue(this.consumeFlow(itemText), line.no));
434
+ this.index += 1;
435
+ }
436
+ return out;
437
+ }
438
+ };
439
+ function parseYaml(input) {
440
+ const lines = toLines(input);
441
+ if (lines.length === 0) return null;
442
+ return new ParsedLines(lines).parse(lines[0]?.indent ?? 0);
443
+ }
444
+ function asRecord(value, what) {
445
+ if (value === null) return {};
446
+ if (typeof value !== "object" || Array.isArray(value)) throw new YamlParseError(`${what} \u9876\u5C42\u5FC5\u987B\u662F\u6620\u5C04`, 1);
447
+ return value;
448
+ }
449
+ function asString(value) {
450
+ if (typeof value === "string") return value;
451
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
452
+ return null;
453
+ }
454
+ function asStringArray(value) {
455
+ if (!Array.isArray(value)) return [];
456
+ return value.map((item) => asString(item)).filter((item) => item !== null);
457
+ }
458
+ function asBoolean(value) {
459
+ return typeof value === "boolean" ? value : null;
460
+ }
461
+
462
+ // src/host/card.ts
463
+ var VALID_STATUS = /* @__PURE__ */ new Set(["active", "paused", "blocked", "done", "cancelled"]);
464
+ var VALID_CATEGORY = /* @__PURE__ */ new Set(["feature", "fix", "refactor", "docs", "test", "research", "design", "ops", "maintenance", "perf", "security", "release"]);
465
+ var STEP_ID = /^S\d+(?:\.\d+)*$/;
466
+ var STEP_KEY_WHITELIST = /* @__PURE__ */ new Set([
467
+ "from",
468
+ "required",
469
+ "decided",
470
+ "skip",
471
+ "waive",
472
+ "block",
473
+ "next",
474
+ "type",
475
+ "branches",
476
+ "over",
477
+ "body",
478
+ "exit",
479
+ "iter",
480
+ "retry",
481
+ "pass",
482
+ "exhausted"
483
+ ]);
484
+ function parseCard(input) {
485
+ const diagnostics = [];
486
+ const frontMatter = splitFrontMatter(input.text);
487
+ diagnostics.push(...frontMatter.diagnostics);
488
+ let meta = {};
489
+ if (frontMatter.frontMatter === null) {
490
+ diagnostics.push("\u7F3A\u5C11 front-matter\uFF08--- \u5305\u88F9\u7684\u5143\u6570\u636E\u5757\uFF09");
491
+ } else {
492
+ try {
493
+ meta = asRecord(parseYaml(frontMatter.frontMatter), "front-matter");
494
+ } catch (error) {
495
+ diagnostics.push(`front-matter \u89E3\u6790\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}`);
496
+ }
497
+ }
498
+ const sections = splitSections(frontMatter.body);
499
+ const goalSection = findSection(sections, "\u76EE\u6807\u4E0E\u9A8C\u6536");
500
+ const stepListSection = findSection(sections, "\u6B65\u9AA4\u6E05\u5355");
501
+ const legacy = meta.steps === void 0 || asString(meta.type) !== null;
502
+ const acceptanceItems = parseAcceptance(goalSection?.body ?? "", diagnostics, legacy);
503
+ const doneAcceptance = acceptanceItems.filter((item) => item.checked).length;
504
+ const id = asString(meta.id);
505
+ const title = asString(meta.title);
506
+ const status = asString(meta.status);
507
+ const category = asString(meta.category);
508
+ const dirName = input.dir.split("/").filter(Boolean).pop() ?? input.dir;
509
+ if (id === null) diagnostics.push("front-matter \u7F3A\u5C11\u5FC5\u586B\u952E id");
510
+ else if (id !== dirName) diagnostics.push(`id\uFF08${id}\uFF09\u4E0E\u76EE\u5F55\u540D\uFF08${dirName}\uFF09\u4E0D\u4E00\u81F4`);
511
+ if (title === null) diagnostics.push("front-matter \u7F3A\u5C11\u5FC5\u586B\u952E title");
512
+ if (status === null) diagnostics.push("front-matter \u7F3A\u5C11\u5FC5\u586B\u952E status");
513
+ else if (!VALID_STATUS.has(status)) diagnostics.push(`status \u4E0D\u662F\u5408\u6CD5\u679A\u4E3E\uFF1A${status}`);
514
+ if (category !== null && !VALID_CATEGORY.has(category)) {
515
+ diagnostics.push(`category \u4E0D\u662F\u5408\u6CD5\u679A\u4E3E\uFF1A${category}\uFF08\u6309\u672A\u5206\u7C7B\u663E\u793A\uFF1B\u5408\u6CD5\u503C\u89C1\u683C\u5F0F\u5951\u7EA6 \xA72\uFF09`);
516
+ }
517
+ const blockedBy = asStringArray(meta["blocked-by"]);
518
+ const blockedReason = asString(meta["blocked-reason"]);
519
+ if (status === "blocked" && blockedBy.length === 0 && blockedReason === null) {
520
+ diagnostics.push("status=blocked \u4F46 blocked-by \u4E0E blocked-reason \u90FD\u4E3A\u7A7A");
521
+ }
522
+ const steps = parseSteps(meta.steps, stepListSection?.body ?? "", diagnostics);
523
+ const factsBody = findSection(sections, "\u5DF2\u9A8C\u8BC1\u4E8B\u5B9E")?.body ?? "";
524
+ const decisionsBody = findSection(sections, "\u5173\u952E\u51B3\u7B56")?.body ?? "";
525
+ const resumeSection = findSection(sections, "Resume \u6307\u9488");
526
+ return {
527
+ id: id ?? dirName,
528
+ dir: input.dir,
529
+ title,
530
+ status,
531
+ category: category !== null && VALID_CATEGORY.has(category) ? category : null,
532
+ focus: false,
533
+ // 焦点来自总账,由 snapshot 装配时覆盖
534
+ archived: false,
535
+ // 归档标记来自 TASKFINISH.md,由 snapshot 装配时覆盖
536
+ registered: false,
537
+ // 总账登记标记,由 snapshot 装配时覆盖
538
+ goal: goalParagraph(goalSection?.body ?? ""),
539
+ parent: asString(meta.parent),
540
+ blockedBy,
541
+ blockedReason,
542
+ spawns: asStringArray(meta.spawns),
543
+ tags: asStringArray(meta.tags),
544
+ docs: parseDocs(meta.docs, diagnostics),
545
+ priority: asString(meta.priority),
546
+ created: asString(meta.created),
547
+ updated: asString(meta.updated),
548
+ acceptance: { done: doneAcceptance, total: acceptanceItems.length, items: acceptanceItems },
549
+ steps,
550
+ sections: {
551
+ verifiedFacts: countListItems(factsBody),
552
+ verifiedFactsList: listItems(factsBody),
553
+ decisions: countListItems(decisionsBody),
554
+ decisionsList: listItems(decisionsBody),
555
+ next: firstParagraph(findSection(sections, "\u4E0B\u4E00\u6B65")?.body ?? ""),
556
+ hasResume: resumeSection !== null,
557
+ resume: resumeSection === null ? null : parseResume(resumeSection.body),
558
+ executionLines: countListItems(findSection(sections, "\u6267\u884C\u53F2")?.body ?? ""),
559
+ hasVerification: findSection(sections, "\u9A8C\u8BC1\u8BB0\u5F55") !== null
560
+ },
561
+ flow: input.flow,
562
+ diagnostics
563
+ };
564
+ }
565
+ function parseDocs(value, diagnostics) {
566
+ if (value === void 0 || value === null) return [];
567
+ const list = typeof value === "string" ? [value] : Array.isArray(value) ? value : null;
568
+ if (list === null) {
569
+ diagnostics.push("docs \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6216\u5B57\u7B26\u4E32\u5217\u8868\uFF08\u5951\u7EA6 \xA72.4\uFF09");
570
+ return [];
571
+ }
572
+ const out = [];
573
+ const seen = /* @__PURE__ */ new Set();
574
+ for (const item of list) {
575
+ if (typeof item !== "string" || item.trim() === "") {
576
+ diagnostics.push("docs \u542B\u7A7A\u503C\u6216\u975E\u5B57\u7B26\u4E32\u6761\u76EE\uFF08\u5DF2\u5FFD\u7565\uFF09");
577
+ continue;
578
+ }
579
+ const raw = item.trim();
580
+ const error = docPathError(raw);
581
+ if (error !== null) {
582
+ diagnostics.push(`docs ${error}\uFF1A${raw}`);
583
+ continue;
584
+ }
585
+ if (seen.has(raw)) {
586
+ diagnostics.push(`docs \u91CD\u590D\u5F15\u7528\uFF1A${raw}`);
587
+ continue;
588
+ }
589
+ seen.add(raw);
590
+ out.push({ path: raw, raw, error: null, exists: false, lines: null });
591
+ }
592
+ return out;
593
+ }
594
+ function docPathError(raw) {
595
+ if (raw.includes("\\")) return "\u8DEF\u5F84\u8BF7\u7528 / \u5206\u9694";
596
+ if (raw.startsWith("/") || /^[A-Za-z]:/.test(raw)) return "\u5FC5\u987B\u662F\u76F8\u5BF9\u9879\u76EE\u6839\u7684\u8DEF\u5F84";
597
+ if (raw.split("/").includes("..")) return "\u4E0D\u80FD\u8D8A\u51FA\u9879\u76EE\u6839";
598
+ if (!raw.toLowerCase().endsWith(".md")) return "\u5FC5\u987B\u662F .md \u6587\u4EF6";
599
+ if (raw.split("/").pop() === "task.md") return "\u4E0D\u80FD\u6307\u5411\u4EFB\u52A1\u5361\uFF08\u72B6\u6001\u6E90\uFF09";
600
+ return null;
601
+ }
602
+ function parseAcceptance(body, diagnostics, legacy) {
603
+ const items = [];
604
+ const seen = /* @__PURE__ */ new Set();
605
+ for (const box of extractCheckboxes(body)) {
606
+ const match = /^(A\d+)\b[ \t—:-]*(.*)$/.exec(box.text);
607
+ if (!match) continue;
608
+ const id = match[1] ?? "";
609
+ if (seen.has(id)) {
610
+ diagnostics.push(`\u9A8C\u6536\u7F16\u53F7\u91CD\u590D\uFF1A${id}`);
611
+ continue;
612
+ }
613
+ seen.add(id);
614
+ items.push({ id, checked: box.checked, text: (match[2] ?? "").trim() });
615
+ }
616
+ if (items.length === 0 && body.trim() !== "" && !legacy) diagnostics.push("\u300C\u76EE\u6807\u4E0E\u9A8C\u6536\u300D\u8282\u6CA1\u6709 A* \u7F16\u53F7\u9A8C\u6536\u9879");
617
+ return items;
618
+ }
619
+ function parseSteps(value, stepListBody, diagnostics) {
620
+ if (value === void 0 || value === null) return null;
621
+ if (typeof value !== "object" || Array.isArray(value)) {
622
+ diagnostics.push("front-matter steps \u4E0D\u662F\u6620\u5C04");
623
+ return null;
624
+ }
625
+ const record = value;
626
+ const raw = {
627
+ current: asString(record.current),
628
+ entry: asString(record.entry),
629
+ source: asString(record.source),
630
+ nodes: /* @__PURE__ */ new Map()
631
+ };
632
+ for (const [key, nodeValue] of Object.entries(record)) {
633
+ if (key === "current" || key === "entry" || key === "source") continue;
634
+ if (!STEP_ID.test(key)) {
635
+ diagnostics.push(`steps \u542B\u672A\u77E5\u952E\uFF1A${key}`);
636
+ continue;
637
+ }
638
+ if (nodeValue === null || typeof nodeValue !== "object" || Array.isArray(nodeValue)) {
639
+ diagnostics.push(`\u6B65\u9AA4 ${key} \u7684\u503C\u4E0D\u662F\u6620\u5C04`);
640
+ continue;
641
+ }
642
+ const node = nodeValue;
643
+ for (const nodeKey of Object.keys(node)) {
644
+ if (!STEP_KEY_WHITELIST.has(nodeKey)) diagnostics.push(`\u6B65\u9AA4 ${key} \u542B\u672A\u77E5\u952E\uFF1A${nodeKey}`);
645
+ }
646
+ raw.nodes.set(key, node);
647
+ }
648
+ if (raw.nodes.size === 0) {
649
+ diagnostics.push("steps \u5757\u5B58\u5728\u4F46\u6CA1\u6709\u6B65\u9AA4\u8282\u70B9");
650
+ return null;
651
+ }
652
+ const boxes = /* @__PURE__ */ new Map();
653
+ for (const box of extractCheckboxes(stepListBody)) {
654
+ const match = /^(S\d+(?:\.\d+)*)\b/.exec(box.text);
655
+ if (!match) continue;
656
+ const id = match[1] ?? "";
657
+ let rest = box.text.slice(id.length).replace(/^[\s—::\-]+/, "").trim();
658
+ rest = rest.replace(/^skill:[a-z0-9][a-z0-9-]*\s+/, "").trim();
659
+ boxes.set(id, { checked: box.checked, text: rest === "" ? null : rest });
660
+ }
661
+ for (const nodeId of raw.nodes.keys()) {
662
+ if (!boxes.has(nodeId)) diagnostics.push(`\u6B65\u9AA4 ${nodeId} \u5728\u300C\u6B65\u9AA4\u6E05\u5355\u300D\u91CC\u6CA1\u6709\u5BF9\u5E94 checkbox`);
663
+ }
664
+ for (const boxId of boxes.keys()) {
665
+ if (!raw.nodes.has(boxId)) diagnostics.push(`\u300C\u6B65\u9AA4\u6E05\u5355\u300D\u6709 checkbox ${boxId}\uFF0C\u4F46 steps \u91CC\u6CA1\u6709\u8BE5\u8282\u70B9`);
666
+ }
667
+ const nodes = [];
668
+ for (const [nodeId, node] of raw.nodes) {
669
+ const box = boxes.get(nodeId);
670
+ const nodeChecked = box?.checked ?? false;
671
+ const depth = nodeId.split(".").length;
672
+ const skip = asString(node.skip);
673
+ const waive = asString(node.waive);
674
+ const decided = asString(node.decided);
675
+ const block = asString(node.block);
676
+ const declaredType = asString(node.type);
677
+ let kind = "step";
678
+ if (declaredType === "decision") kind = "decision";
679
+ else if (declaredType === "loop") kind = "loop";
680
+ else if (declaredType !== null) diagnostics.push(`\u6B65\u9AA4 ${nodeId} \u7684 type \u4E0D\u662F\u5408\u6CD5\u679A\u4E3E\uFF1A${declaredType}\uFF08\u6309\u666E\u901A\u6B65\u5904\u7406\uFF09`);
681
+ const branches = kind === "decision" ? parseBranches(node.branches, nodeId, diagnostics) : [];
682
+ const loop = kind === "loop" ? parseLoop(node, nodeId, diagnostics) : null;
683
+ const retry = parseCount(node.retry, `\u6B65\u9AA4 ${nodeId} \u7684 retry`, diagnostics);
684
+ const failed = retry !== null && retry.total !== null && retry.done !== null && retry.done >= retry.total && !nodeChecked && skip === null && waive === null;
685
+ let runtime;
686
+ if (nodeChecked) runtime = "done";
687
+ else if (skip !== null) runtime = "skipped";
688
+ else if (waive !== null) runtime = "waived";
689
+ else if (failed) runtime = "failed";
690
+ else if (block !== null) runtime = "blocked";
691
+ else if (raw.current === nodeId) runtime = "doing";
692
+ else runtime = "pending";
693
+ nodes.push({
694
+ id: nodeId,
695
+ text: box?.text ?? null,
696
+ skill: skillOf(node.from),
697
+ depth,
698
+ checked: nodeChecked,
699
+ status: runtime,
700
+ required: asBoolean(node.required) === true,
701
+ block,
702
+ next: asString(node.next),
703
+ decisionRef: skip ?? waive ?? decided,
704
+ kind,
705
+ branches,
706
+ loop,
707
+ retry,
708
+ exhausted: asString(node.exhausted),
709
+ pass: asString(node.pass),
710
+ failed
711
+ });
712
+ }
713
+ const known = new Set(nodes.map((node) => node.id));
714
+ known.add("end");
715
+ for (const node of nodes) {
716
+ const edges = [
717
+ ["next", node.next],
718
+ ...node.branches.map((branch) => [`branch(${branch.condition ?? "?"})`, branch.go]),
719
+ ...node.loop === null ? [] : [
720
+ ...node.loop.body.map((id) => ["loop.body", id]),
721
+ ["loop.exit", node.loop.exit]
722
+ ],
723
+ ["pass", node.pass],
724
+ ["exhausted", node.exhausted]
725
+ ];
726
+ for (const [label, target] of edges) {
727
+ if (target !== null && target !== "" && !known.has(target)) {
728
+ diagnostics.push(`\u6B65\u9AA4 ${node.id} \u7684 ${label} \u6307\u5411\u4E0D\u5B58\u5728\u7684\u8282\u70B9\uFF1A${target}`);
729
+ }
730
+ }
731
+ }
732
+ const leaves = nodes.filter((node) => !nodes.some((other) => other.id.startsWith(`${node.id}.`)));
733
+ const done = leaves.filter((node) => node.checked || node.status === "skipped" || node.status === "waived").length;
734
+ if (raw.current === null) diagnostics.push("steps \u7F3A\u5C11 current");
735
+ else if (raw.current !== "end" && !raw.nodes.has(raw.current)) diagnostics.push(`steps.current \u6307\u5411\u4E0D\u5B58\u5728\u7684\u8282\u70B9\uFF1A${raw.current}`);
736
+ return {
737
+ current: raw.current,
738
+ entry: raw.entry,
739
+ source: raw.source,
740
+ total: leaves.length,
741
+ done,
742
+ nodeTotal: nodes.length,
743
+ nodes
744
+ };
745
+ }
746
+ function parseBranches(value, nodeId, diagnostics) {
747
+ if (value === void 0 || value === null) {
748
+ diagnostics.push(`decision \u6B65\u9AA4 ${nodeId} \u7F3A\u5C11 branches`);
749
+ return [];
750
+ }
751
+ if (!Array.isArray(value)) {
752
+ diagnostics.push(`\u6B65\u9AA4 ${nodeId} \u7684 branches \u4E0D\u662F\u5217\u8868`);
753
+ return [];
754
+ }
755
+ const out = [];
756
+ for (const item of value) {
757
+ if (item === null || typeof item !== "object" || Array.isArray(item)) {
758
+ diagnostics.push(`\u6B65\u9AA4 ${nodeId} \u7684 branches \u9879\u4E0D\u662F\u6620\u5C04`);
759
+ continue;
760
+ }
761
+ const record = item;
762
+ const condition = asString(record.if);
763
+ const go = asString(record.go);
764
+ if (go === null || go === "") {
765
+ diagnostics.push(`\u6B65\u9AA4 ${nodeId} \u7684 branches \u9879\u7F3A\u5C11 go`);
766
+ continue;
767
+ }
768
+ out.push({ condition, go });
769
+ }
770
+ if (out.length === 0) diagnostics.push(`decision \u6B65\u9AA4 ${nodeId} \u6CA1\u6709\u53EF\u7528\u5206\u652F`);
771
+ return out;
772
+ }
773
+ function parseLoop(node, nodeId, diagnostics) {
774
+ const overRaw = node.over;
775
+ let over = null;
776
+ let overCount = null;
777
+ if (Array.isArray(overRaw)) {
778
+ const items = overRaw.map((item) => asString(item)).filter((item) => item !== null);
779
+ over = items.join("\u3001");
780
+ overCount = items.length;
781
+ } else {
782
+ over = asString(overRaw);
783
+ }
784
+ const body = asStringArray(node.body);
785
+ const exit = asString(node.exit);
786
+ const iter = parseCount(node.iter, `\u6B65\u9AA4 ${nodeId} \u7684 iter`, diagnostics);
787
+ if (over === null) diagnostics.push(`loop \u6B65\u9AA4 ${nodeId} \u7F3A\u5C11 over`);
788
+ if (body.length === 0) diagnostics.push(`loop \u6B65\u9AA4 ${nodeId} \u7F3A\u5C11 body`);
789
+ if (exit === null) diagnostics.push(`loop \u6B65\u9AA4 ${nodeId} \u7F3A\u5C11 exit`);
790
+ return { over, overCount, body, exit, iter };
791
+ }
792
+ function skillOf(from) {
793
+ const value = asString(from)?.trim();
794
+ return value && value !== "task" ? value : null;
795
+ }
796
+ function parseCount(value, label, diagnostics) {
797
+ if (value === void 0 || value === null) return null;
798
+ if (typeof value === "number" && Number.isInteger(value) && value >= 0) return { done: null, total: value };
799
+ const text = asString(value);
800
+ if (text === null) {
801
+ diagnostics.push(`${label} \u4E0D\u662F\u53EF\u89E3\u6790\u7684\u8BA1\u6570`);
802
+ return null;
803
+ }
804
+ const pair = /^(\d+)\s*\/\s*(\d+)$/.exec(text.trim());
805
+ if (pair !== null) return { done: Number(pair[1]), total: Number(pair[2]) };
806
+ if (/^\d+$/.test(text.trim())) return { done: null, total: Number(text) };
807
+ diagnostics.push(`${label} \u4E0D\u662F k/n \u5F62\u5F0F\uFF1A${text}`);
808
+ return null;
809
+ }
810
+
811
+ // src/host/ledger.ts
812
+ function parseMarkdownTable(text) {
813
+ const diagnostics = [];
814
+ const lines = text.replace(/\r\n/g, "\n").split("\n");
815
+ const rows = [];
816
+ let header = null;
817
+ for (const line of lines) {
818
+ const trimmed = line.trim();
819
+ if (!trimmed.startsWith("|")) continue;
820
+ const cells = splitRow(trimmed);
821
+ if (cells.every((cell) => /^:?-{2,}:?$/.test(cell) || /^:?-+:?$/.test(cell))) continue;
822
+ if (header === null) {
823
+ header = cells.map((cell) => cell.toLowerCase());
824
+ continue;
825
+ }
826
+ rows.push(cells);
827
+ }
828
+ if (header === null) diagnostics.push("\u672A\u627E\u5230 Markdown \u8868\u683C\u8868\u5934");
829
+ return { rows, header, diagnostics };
830
+ }
831
+ function splitRow(line) {
832
+ const withoutEdges = line.replace(/^\|/, "").replace(/\|$/, "");
833
+ return withoutEdges.split("|").map((cell) => cell.trim());
834
+ }
835
+ function cellOf(cells, header, name2) {
836
+ const index = header.indexOf(name2);
837
+ if (index < 0) return null;
838
+ return cells[index] ?? null;
839
+ }
840
+ function isEmptyCell(value) {
841
+ return value === null || value === "" || value === "\u2014" || value === "-" || value === "\u2013";
842
+ }
843
+ function parseIdList(value) {
844
+ if (isEmptyCell(value)) return [];
845
+ return (value ?? "").split(/[,,;;\s]+/).map((item) => item.trim()).filter((item) => item !== "" && item !== "\u2014");
846
+ }
847
+ function parseLedger(text) {
848
+ const table = parseMarkdownTable(text);
849
+ const diagnostics = [...table.diagnostics];
850
+ const header = table.header;
851
+ const rows = [];
852
+ if (!header) return { rows, diagnostics };
853
+ for (const required of ["id", "\u6807\u9898", "\u72B6\u6001"]) {
854
+ if (!header.includes(required)) diagnostics.push(`\u603B\u8D26\u8868\u5934\u7F3A\u5C11\u5FC5\u9700\u5217\uFF1A${required}`);
855
+ }
856
+ for (const cells of table.rows) {
857
+ const id = cellOf(cells, header, "id");
858
+ if (isEmptyCell(id)) {
859
+ diagnostics.push(`\u603B\u8D26\u6709\u4E00\u884C\u7F3A\u5C11 id\uFF1A${cells.join(" | ")}`);
860
+ continue;
861
+ }
862
+ const title = cellOf(cells, header, "\u6807\u9898") ?? "";
863
+ const status = cellOf(cells, header, "\u72B6\u6001") ?? "";
864
+ const focusCell = cellOf(cells, header, "\u7126\u70B9") ?? "";
865
+ rows.push({
866
+ id: id ?? "",
867
+ title,
868
+ status,
869
+ focus: focusCell.includes("\u2605"),
870
+ blockedBy: parseIdList(cellOf(cells, header, "blocked-by"))
871
+ });
872
+ if (isEmptyCell(status)) diagnostics.push(`\u603B\u8D26\u884C ${id} \u7F3A\u5C11\u72B6\u6001`);
873
+ }
874
+ return { rows, diagnostics };
875
+ }
876
+ function parseArchive(text) {
877
+ const table = parseMarkdownTable(text);
878
+ const diagnostics = [...table.diagnostics];
879
+ const header = table.header;
880
+ const rows = [];
881
+ if (!header) return { rows, diagnostics };
882
+ for (const cells of table.rows) {
883
+ const id = cellOf(cells, header, "id");
884
+ if (isEmptyCell(id)) continue;
885
+ rows.push({
886
+ id: id ?? "",
887
+ title: cellOf(cells, header, "\u6807\u9898") ?? "",
888
+ completed: cellOf(cells, header, "\u5B8C\u6210\u65E5") ?? "",
889
+ path: cellOf(cells, header, "\u8DEF\u5F84") ?? "",
890
+ products: cellOf(cells, header, "\u4EA7\u7269\u53BB\u5411") ?? ""
891
+ });
892
+ }
893
+ return { rows, diagnostics };
894
+ }
895
+
896
+ // src/host/snapshot.ts
897
+ var DEFAULTS = {
898
+ tasksDir: "tasks",
899
+ ledgerName: "TASKS.md",
900
+ archiveName: "TASKFINISH.md"
901
+ };
902
+ var CONFIG_FILE = "task-card.config.yml";
903
+ function toPosix(path) {
904
+ return path.split(sep).join("/");
905
+ }
906
+ function isInside(parent, child) {
907
+ const rel = relative(parent, child);
908
+ return rel !== "" && !rel.startsWith("..") && !rel.includes("..");
909
+ }
910
+ function readProjectConfig(projectRoot, diagnostics) {
911
+ const path = join(projectRoot, CONFIG_FILE);
912
+ if (!existsSync(path)) return { values: {}, exists: false };
913
+ try {
914
+ const parsed = asRecord(parseYaml(readFileSync(path, "utf8")), CONFIG_FILE);
915
+ const values = {};
916
+ for (const key of ["tasksDir", "ledgerName", "archiveName"]) {
917
+ const value = asString(parsed[key]);
918
+ if (value !== null && value !== "") values[key] = value;
919
+ }
920
+ return { values, exists: true };
921
+ } catch (error) {
922
+ diagnostics.push(`${CONFIG_FILE} \u89E3\u6790\u5931\u8D25\uFF0C\u6309\u63D2\u4EF6\u914D\u7F6E/\u9ED8\u8BA4\u503C\u5904\u7406\uFF1A${error instanceof Error ? error.message : String(error)}`);
923
+ return { values: {}, exists: true };
924
+ }
925
+ }
926
+ function resolveConfig(projectRoot, pluginConfig = {}) {
927
+ const diagnostics = [];
928
+ const projectRootAbs = resolve(projectRoot);
929
+ const project = readProjectConfig(projectRootAbs, diagnostics);
930
+ const sourceOf = (key, pluginValue) => {
931
+ if (project.values[key] !== void 0) return "project";
932
+ return pluginValue !== void 0 && pluginValue !== "" ? "plugin" : "default";
933
+ };
934
+ const tasksDir = project.values.tasksDir ?? pluginConfig.dataDir ?? DEFAULTS.tasksDir;
935
+ const ledgerName = project.values.ledgerName ?? pluginConfig.ledgerName ?? DEFAULTS.ledgerName;
936
+ const archiveName = project.values.archiveName ?? pluginConfig.archiveName ?? DEFAULTS.archiveName;
937
+ const dataDir = resolve(projectRootAbs, tasksDir);
938
+ if (!isInside(projectRootAbs, dataDir)) {
939
+ throw new Error(`\u6570\u636E\u76EE\u5F55\u8D8A\u51FA\u9879\u76EE\u6839\uFF08\u62D2\u7EDD\u8BFB\u53D6\uFF09\uFF1A${dataDir}`);
940
+ }
941
+ return {
942
+ projectRoot: projectRootAbs,
943
+ dataDir,
944
+ dataDirRel: toPosix(relative(projectRootAbs, dataDir)),
945
+ sources: {
946
+ dataDir: sourceOf("tasksDir", pluginConfig.dataDir),
947
+ ledgerName: sourceOf("ledgerName", pluginConfig.ledgerName),
948
+ archiveName: sourceOf("archiveName", pluginConfig.archiveName)
949
+ },
950
+ configFile: project.exists ? CONFIG_FILE : null,
951
+ ledgerPath: join(dataDir, ledgerName),
952
+ ledgerRel: toPosix(relative(projectRootAbs, join(dataDir, ledgerName))),
953
+ archivePath: join(dataDir, archiveName),
954
+ archiveRel: toPosix(relative(projectRootAbs, join(dataDir, archiveName))),
955
+ diagnostics
956
+ };
957
+ }
958
+ function readSnapshot(source) {
959
+ const config = resolveConfig(source.projectRoot, source.pluginConfig);
960
+ const diagnostics = [...config.diagnostics];
961
+ const generatedAt = (/* @__PURE__ */ new Date()).toISOString();
962
+ let ledgerRows = [];
963
+ const ledgerDiagnostics = [];
964
+ if (existsSync(config.ledgerPath)) {
965
+ const parsed = parseLedger(readFileSync(config.ledgerPath, "utf8"));
966
+ ledgerRows = parsed.rows;
967
+ ledgerDiagnostics.push(...parsed.diagnostics);
968
+ } else {
969
+ ledgerDiagnostics.push(`\u603B\u8D26\u6587\u4EF6\u4E0D\u5B58\u5728\uFF1A${config.ledgerRel}`);
970
+ }
971
+ const archiveDiagnostics = [];
972
+ let archiveRows = [];
973
+ if (existsSync(config.archivePath)) {
974
+ const parsed = parseArchive(readFileSync(config.archivePath, "utf8"));
975
+ archiveRows = parsed.rows;
976
+ archiveDiagnostics.push(...parsed.diagnostics);
977
+ } else {
978
+ archiveDiagnostics.push(`\u5F52\u6863\u6587\u4EF6\u4E0D\u5B58\u5728\uFF1A${config.archiveRel}`);
979
+ }
980
+ diagnostics.push(...ledgerDiagnostics, ...archiveDiagnostics);
981
+ const ledgerById = new Map(ledgerRows.map((row) => [row.id, row]));
982
+ const archiveById = new Map(archiveRows.map((row) => [row.id, row]));
983
+ const focused = ledgerRows.filter((row) => row.focus);
984
+ if (focused.length > 1) diagnostics.push(`\u603B\u8D26\u91CC\u51FA\u73B0 ${focused.length} \u4E2A \u2605\uFF08\u7126\u70B9\u5FC5\u987B\u552F\u4E00\uFF09`);
985
+ const focusId = focused[0]?.id ?? null;
986
+ if (!existsSync(config.dataDir) || !statSync(config.dataDir).isDirectory()) {
987
+ diagnostics.push(`\u6570\u636E\u76EE\u5F55\u4E0D\u5B58\u5728\uFF1A${config.dataDirRel}`);
988
+ return {
989
+ kind: "task-card.snapshot",
990
+ version: 1,
991
+ generatedAt,
992
+ projectRoot: config.projectRoot,
993
+ dataDir: config.dataDirRel,
994
+ configSources: config.sources,
995
+ configFile: config.configFile,
996
+ ledger: { file: config.ledgerRel, rows: ledgerRows, diagnostics: ledgerDiagnostics },
997
+ archive: { file: config.archiveRel, rows: archiveRows, diagnostics: archiveDiagnostics },
998
+ cards: [],
999
+ focusId,
1000
+ diagnostics
1001
+ };
1002
+ }
1003
+ const dirs = readdirSync(config.dataDir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => entry.name).sort();
1004
+ const cards = [];
1005
+ const seen = /* @__PURE__ */ new Set();
1006
+ const cardFor = (id) => {
1007
+ const cardDir = join(config.dataDir, id);
1008
+ const cardPath = join(cardDir, "task.md");
1009
+ const dirRel = toPosix(relative(config.projectRoot, cardDir));
1010
+ if (!existsSync(cardPath)) {
1011
+ diagnostics.push(`\u603B\u8D26\u767B\u8BB0\u4E86 ${id}\uFF0C\u4F46\u76EE\u5F55\u91CC\u6CA1\u6709 task.md\uFF08${dirRel}\uFF09`);
1012
+ return;
1013
+ }
1014
+ let text = "";
1015
+ try {
1016
+ text = readFileSync(cardPath, "utf8");
1017
+ } catch (error) {
1018
+ diagnostics.push(`\u8BFB\u53D6 ${dirRel}/task.md \u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}`);
1019
+ return;
1020
+ }
1021
+ const flowDiagnostics = [];
1022
+ const flow = readFlowLabels(join(cardDir, "flow.yaml"), flowDiagnostics);
1023
+ const card = parseCard({ text, dir: dirRel, flow });
1024
+ card.diagnostics.push(...flowDiagnostics);
1025
+ hydrateDocs(card, config);
1026
+ const ledgerRow = ledgerById.get(card.id);
1027
+ card.focus = ledgerRow?.focus ?? false;
1028
+ card.archived = archiveById.has(card.id);
1029
+ card.registered = ledgerRow !== void 0 || card.archived;
1030
+ if (ledgerRow) {
1031
+ if (ledgerRow.status !== "" && card.status !== null && ledgerRow.status !== card.status) {
1032
+ card.diagnostics.push(`\u5361\u72B6\u6001\uFF08${card.status}\uFF09\u4E0E\u603B\u8D26\u72B6\u6001\uFF08${ledgerRow.status}\uFF09\u4E0D\u4E00\u81F4\uFF08\u51B2\u7A81\u4EE5\u5361\u4E3A\u51C6\uFF09`);
1033
+ }
1034
+ if (ledgerRow.title !== "" && card.title !== null && ledgerRow.title !== card.title) {
1035
+ card.diagnostics.push("\u6807\u9898\u4E0E\u603B\u8D26\u4E0D\u540C\u6587\uFF08\u5951\u7EA6\u8981\u6C42\u540C\u6587\uFF09");
1036
+ }
1037
+ }
1038
+ if (!card.registered) {
1039
+ card.diagnostics.push("\u8BE5\u5361\u6CA1\u6709\u767B\u8BB0\u5728\u603B\u8D26\u91CC\uFF08\u672A\u6CE8\u518C\u4EFB\u52A1\uFF09");
1040
+ }
1041
+ cards.push(card);
1042
+ seen.add(id);
1043
+ };
1044
+ for (const row of ledgerRows) cardFor(row.id);
1045
+ for (const id of dirs) {
1046
+ if (seen.has(id)) continue;
1047
+ if (!existsSync(join(config.dataDir, id, "task.md"))) continue;
1048
+ cardFor(id);
1049
+ }
1050
+ return {
1051
+ kind: "task-card.snapshot",
1052
+ version: 1,
1053
+ generatedAt,
1054
+ projectRoot: config.projectRoot,
1055
+ dataDir: config.dataDirRel,
1056
+ configSources: config.sources,
1057
+ configFile: config.configFile,
1058
+ ledger: { file: config.ledgerRel, rows: ledgerRows, diagnostics: ledgerDiagnostics },
1059
+ archive: { file: config.archiveRel, rows: archiveRows, diagnostics: archiveDiagnostics },
1060
+ cards,
1061
+ focusId,
1062
+ diagnostics
1063
+ };
1064
+ }
1065
+ var CardFileError = class extends Error {
1066
+ constructor(message, status) {
1067
+ super(message);
1068
+ this.status = status;
1069
+ this.name = "CardFileError";
1070
+ }
1071
+ status;
1072
+ };
1073
+ var CARD_FILE_LIMIT = 1024 * 1024;
1074
+ var CARD_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
1075
+ var TASK_FILES_LIMIT = 500;
1076
+ var TASK_FILES_DEPTH = 8;
1077
+ var TASK_FILES_IGNORED = /* @__PURE__ */ new Set([".git", "node_modules"]);
1078
+ function readCardFile(source, id) {
1079
+ if (!CARD_ID.test(id)) throw new CardFileError(`\u4EFB\u52A1 id \u4E0D\u5408\u6CD5\uFF1A${id}`, 400);
1080
+ const config = resolveConfig(source.projectRoot, source.pluginConfig);
1081
+ if (!existsSync(config.dataDir) || !statSync(config.dataDir).isDirectory()) {
1082
+ throw new CardFileError(`\u6570\u636E\u76EE\u5F55\u4E0D\u5B58\u5728\uFF1A${config.dataDirRel}`, 404);
1083
+ }
1084
+ const cardDir = join(config.dataDir, id);
1085
+ if (!isInside(config.dataDir, cardDir)) throw new CardFileError(`\u4EFB\u52A1\u76EE\u5F55\u8D8A\u51FA\u6570\u636E\u76EE\u5F55\uFF1A${id}`, 400);
1086
+ const cardPath = join(cardDir, "task.md");
1087
+ if (!existsSync(cardPath)) throw new CardFileError(`\u4EFB\u52A1\u5361\u4E0D\u5B58\u5728\uFF1A${toPosix(relative(config.projectRoot, cardPath))}`, 404);
1088
+ let text;
1089
+ try {
1090
+ text = readFileSync(cardPath, "utf8");
1091
+ } catch (error) {
1092
+ throw new CardFileError(`\u8BFB\u53D6\u4EFB\u52A1\u5361\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}`, 500);
1093
+ }
1094
+ const truncated = text.length > CARD_FILE_LIMIT;
1095
+ return {
1096
+ id,
1097
+ dir: toPosix(relative(config.projectRoot, cardDir)),
1098
+ path: toPosix(relative(config.projectRoot, cardPath)),
1099
+ markdown: truncated ? text.slice(0, CARD_FILE_LIMIT) : text,
1100
+ truncated
1101
+ };
1102
+ }
1103
+ function readTaskFiles(source, id) {
1104
+ if (!CARD_ID.test(id)) throw new CardFileError(`\u4EFB\u52A1 id \u4E0D\u5408\u6CD5\uFF1A${id}`, 400);
1105
+ const config = resolveConfig(source.projectRoot, source.pluginConfig);
1106
+ if (!existsSync(config.dataDir) || !statSync(config.dataDir).isDirectory()) {
1107
+ throw new CardFileError(`\u6570\u636E\u76EE\u5F55\u4E0D\u5B58\u5728\uFF1A${config.dataDirRel}`, 404);
1108
+ }
1109
+ const cardDir = join(config.dataDir, id);
1110
+ if (!isInside(config.dataDir, cardDir)) throw new CardFileError(`\u4EFB\u52A1\u76EE\u5F55\u8D8A\u51FA\u6570\u636E\u76EE\u5F55\uFF1A${id}`, 400);
1111
+ if (!existsSync(cardDir) || !statSync(cardDir).isDirectory()) {
1112
+ throw new CardFileError(`\u4EFB\u52A1\u76EE\u5F55\u4E0D\u5B58\u5728\uFF1A${toPosix(relative(config.projectRoot, cardDir))}`, 404);
1113
+ }
1114
+ let count = 0;
1115
+ let truncated = false;
1116
+ const walk = (dir, prefix, depth) => {
1117
+ if (depth > TASK_FILES_DEPTH) {
1118
+ truncated = true;
1119
+ return [];
1120
+ }
1121
+ let dirents;
1122
+ try {
1123
+ dirents = readdirSync(dir, { withFileTypes: true });
1124
+ } catch (error) {
1125
+ throw new CardFileError(`\u8BFB\u53D6\u4EFB\u52A1\u76EE\u5F55\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}`, 500);
1126
+ }
1127
+ const sorted = [...dirents].sort((a, b) => {
1128
+ if (a.isDirectory() !== b.isDirectory()) return a.isDirectory() ? -1 : 1;
1129
+ if (a.name === "task.md") return -1;
1130
+ if (b.name === "task.md") return 1;
1131
+ return a.name.localeCompare(b.name);
1132
+ });
1133
+ const out = [];
1134
+ for (const entry of sorted) {
1135
+ if (count >= TASK_FILES_LIMIT) {
1136
+ truncated = true;
1137
+ break;
1138
+ }
1139
+ if (TASK_FILES_IGNORED.has(entry.name) || entry.isSymbolicLink()) continue;
1140
+ const absolute = join(dir, entry.name);
1141
+ const rel = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
1142
+ if (entry.isDirectory()) {
1143
+ count += 1;
1144
+ out.push({ name: entry.name, path: rel, kind: "dir", size: null, children: walk(absolute, rel, depth + 1) });
1145
+ } else if (entry.isFile()) {
1146
+ let size = null;
1147
+ try {
1148
+ size = statSync(absolute).size;
1149
+ } catch {
1150
+ }
1151
+ count += 1;
1152
+ out.push({ name: entry.name, path: rel, kind: "file", size, children: [] });
1153
+ }
1154
+ }
1155
+ return out;
1156
+ };
1157
+ return {
1158
+ id,
1159
+ dir: toPosix(relative(config.projectRoot, cardDir)),
1160
+ entries: walk(cardDir, "", 0),
1161
+ truncated
1162
+ };
1163
+ }
1164
+ function hydrateDocs(card, config) {
1165
+ const ledgerBase = basename(config.ledgerPath);
1166
+ const archiveBase = basename(config.archivePath);
1167
+ for (const doc of card.docs) {
1168
+ if (doc.error !== null) continue;
1169
+ const abs = resolve(config.projectRoot, doc.path);
1170
+ const back = relative(config.projectRoot, abs);
1171
+ if (back.startsWith("..") || isAbsolute(back)) {
1172
+ doc.error = "\u8D8A\u51FA\u9879\u76EE\u6839";
1173
+ continue;
1174
+ }
1175
+ const base = basename(abs);
1176
+ if (base === ledgerBase || base === archiveBase) {
1177
+ doc.error = "\u4E0D\u80FD\u6307\u5411\u603B\u8D26/\u5F52\u6863\u8868\uFF08\u72B6\u6001\u6E90\uFF09";
1178
+ continue;
1179
+ }
1180
+ if (!existsSync(abs)) {
1181
+ card.diagnostics.push(`docs \u5F15\u7528\u4E0D\u5B58\u5728\uFF1A${doc.path}`);
1182
+ continue;
1183
+ }
1184
+ try {
1185
+ if (!statSync(abs).isFile()) {
1186
+ card.diagnostics.push(`docs \u4E0D\u662F\u6587\u4EF6\uFF1A${doc.path}`);
1187
+ continue;
1188
+ }
1189
+ doc.exists = true;
1190
+ doc.lines = readFileSync(abs, "utf8").replace(/\r\n/g, "\n").split("\n").length;
1191
+ } catch (error) {
1192
+ card.diagnostics.push(`docs \u8BFB\u53D6\u5931\u8D25\uFF1A${doc.path}\uFF08${error instanceof Error ? error.message : String(error)}\uFF09`);
1193
+ }
1194
+ }
1195
+ }
1196
+ function readFlowLabels(path, diagnostics) {
1197
+ if (!existsSync(path)) return null;
1198
+ try {
1199
+ const record = asRecord(parseYaml(readFileSync(path, "utf8")), "flow.yaml");
1200
+ const workflow = asString(record.workflow);
1201
+ const kind = asString(record.kind);
1202
+ const ref = asString(record.ref);
1203
+ if (workflow === null || kind === null || ref === null) {
1204
+ diagnostics.push("flow.yaml \u7F3A\u5C11\u5FC5\u586B\u952E\uFF08workflow/kind/ref\uFF09\uFF0C\u6309\u300C\u672A\u7ED1\u5B9A\u300D\u5904\u7406");
1205
+ return null;
1206
+ }
1207
+ return { workflow, kind, ref, currentStage: asString(record.current_stage) };
1208
+ } catch (error) {
1209
+ diagnostics.push(`flow.yaml \u89E3\u6790\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}`);
1210
+ return null;
1211
+ }
1212
+ }
1213
+
1214
+ // src/host/skill.ts
1215
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";
1216
+ import { dirname, join as join2, resolve as resolve2 } from "node:path";
1217
+ import { fileURLToPath } from "node:url";
1218
+ var MODULE_DIR = dirname(fileURLToPath(import.meta.url));
1219
+ var SKILL_DIR = resolve2(MODULE_DIR, "skill/task-card");
1220
+ function loadBundledSkill(dir = SKILL_DIR) {
1221
+ const file = join2(dir, "SKILL.md");
1222
+ if (!existsSync2(file)) return null;
1223
+ let text = "";
1224
+ try {
1225
+ text = readFileSync2(file, "utf8");
1226
+ } catch {
1227
+ return null;
1228
+ }
1229
+ const frontMatter = splitFrontMatter(text);
1230
+ if (frontMatter.frontMatter === null) return null;
1231
+ let meta;
1232
+ try {
1233
+ meta = asRecord(parseYaml(frontMatter.frontMatter), "SKILL.md front-matter");
1234
+ } catch {
1235
+ return null;
1236
+ }
1237
+ const name2 = asString(meta.name);
1238
+ const description = asString(meta.description);
1239
+ if (name2 === null || name2 === "" || description === null || description === "") return null;
1240
+ return {
1241
+ name: name2,
1242
+ description,
1243
+ content: frontMatter.body.replace(/^\r?\n+/, ""),
1244
+ path: file,
1245
+ resourceBase: { kind: "directory", path: dir },
1246
+ source: "runtime"
1247
+ };
1248
+ }
1249
+ function registerBundledSkill(ctx) {
1250
+ const skill = loadBundledSkill();
1251
+ if (skill === null) {
1252
+ ctx.logger?.warn("[dsh-task-card] \u5185\u7F6E skill \u7F3A\u5931\u6216\u4E0D\u53EF\u89E3\u6790\uFF08lib/skill/task-card/SKILL.md\uFF09\uFF0C\u8DF3\u8FC7\u6CE8\u518C");
1253
+ return;
1254
+ }
1255
+ const attempt = (scoped) => {
1256
+ const registry = scoped?.skills;
1257
+ if (registry === void 0 || registry === null) {
1258
+ ctx.logger?.warn("[dsh-task-card] \u5BBF\u4E3B\u6CA1\u6709 skills \u670D\u52A1\uFF0C\u8DF3\u8FC7\u5185\u7F6E skill \u6CE8\u518C\uFF08\u770B\u677F\u5176\u4F59\u529F\u80FD\u7167\u5E38\uFF09");
1259
+ return void 0;
1260
+ }
1261
+ try {
1262
+ return registry.register(skill);
1263
+ } catch (error) {
1264
+ ctx.logger?.warn(`[dsh-task-card] \u5185\u7F6E skill \u6CE8\u518C\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}`);
1265
+ return void 0;
1266
+ }
1267
+ };
1268
+ if (typeof ctx.inject === "function") {
1269
+ ctx.inject(["skills"], (scoped) => attempt(scoped));
1270
+ return;
1271
+ }
1272
+ attempt(ctx);
1273
+ }
1274
+
1275
+ // src/host/config-file.ts
1276
+ import { existsSync as existsSync3, readFileSync as readFileSync3, writeFileSync } from "node:fs";
1277
+ import { join as join3 } from "node:path";
1278
+ var CONFIG_FILE2 = "task-card.config.yml";
1279
+ var HEADER = [
1280
+ "# task-card \u9879\u76EE\u914D\u7F6E\uFF08\u770B\u677F\u8BBE\u7F6E\u4F1A\u6539\u8FD9\u4E09\u4E2A\u952E\uFF1B\u4E5F\u53EF\u4EE5\u624B\u5DE5\u7F16\u8F91\uFF09",
1281
+ "# \u7701\u7565\u67D0\u4E2A\u952E = \u4F7F\u7528\u63D2\u4EF6\u8BBE\u7F6E\u6216\u5185\u7F6E\u9ED8\u8BA4\u3002"
1282
+ ].join("\n");
1283
+ var KEYS = ["tasksDir", "ledgerName", "archiveName"];
1284
+ function writeProjectConfig(projectRoot, values) {
1285
+ const file = join3(projectRoot, CONFIG_FILE2);
1286
+ const existed = existsSync3(file);
1287
+ const text = existed ? readFileSync3(file, "utf8") : "";
1288
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
1289
+ const lines = text === "" ? [] : text.split(/\r?\n/);
1290
+ if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
1291
+ for (const key of KEYS) {
1292
+ const rendered = `${key}: ${JSON.stringify(values[key])}`;
1293
+ const index = lines.findIndex((line) => new RegExp(`^${key}\\s*:`).test(line));
1294
+ if (index >= 0) {
1295
+ const comment = /^[^#]*?(\s+#.*)$/.exec(lines[index] ?? "");
1296
+ lines[index] = comment === null ? rendered : `${rendered}${comment[1]}`;
1297
+ } else {
1298
+ lines.push(rendered);
1299
+ }
1300
+ }
1301
+ const body = `${existed ? "" : `${HEADER}${eol}`}${lines.join(eol)}${eol}`;
1302
+ writeFileSync(file, body, "utf8");
1303
+ return CONFIG_FILE2;
1304
+ }
1305
+
1306
+ // src/host/index.ts
1307
+ var name = PLUGIN_ID;
1308
+ var inject = ["webServer"];
1309
+ var MODULE_DIR2 = dirname2(fileURLToPath2(import.meta.url));
1310
+ var REPO_ROOT_GUESS = resolve3(MODULE_DIR2, "../../..");
1311
+ function hasTaskData(root) {
1312
+ try {
1313
+ return existsSync4(resolveConfig(root).dataDir);
1314
+ } catch {
1315
+ return false;
1316
+ }
1317
+ }
1318
+ function resolveProjectRoot(ctx, config, requestedRoot) {
1319
+ const explicit = config.projectRoot !== void 0 && config.projectRoot !== "" ? config.projectRoot : null;
1320
+ if (explicit !== null) return { root: explicit, tried: [explicit] };
1321
+ const tried = [];
1322
+ const requested = requestedRoot !== void 0 && requestedRoot !== null && requestedRoot !== "" && isAbsolute2(requestedRoot) ? requestedRoot : null;
1323
+ if (requested !== null) {
1324
+ return { root: requested, tried: [requested] };
1325
+ }
1326
+ const candidates = [];
1327
+ const workingDirectory = ctx.get("workingDirectory");
1328
+ if (workingDirectory?.defaultDirectory !== void 0 && workingDirectory.defaultDirectory !== "") {
1329
+ candidates.push(workingDirectory.defaultDirectory);
1330
+ }
1331
+ candidates.push(REPO_ROOT_GUESS, process.cwd());
1332
+ const unique = [...new Set(candidates)];
1333
+ for (const candidate of unique) {
1334
+ tried.push(candidate);
1335
+ if (hasTaskData(candidate)) return { root: candidate, tried };
1336
+ }
1337
+ return { root: unique[0] ?? process.cwd(), tried };
1338
+ }
1339
+ function sendJson(res, status, payload) {
1340
+ const body = `${JSON.stringify(payload)}
1341
+ `;
1342
+ res.writeHead(status, {
1343
+ "content-type": "application/json; charset=utf-8",
1344
+ "cache-control": "no-store",
1345
+ "content-length": String(Buffer.byteLength(body))
1346
+ });
1347
+ res.end(body);
1348
+ }
1349
+ function buildSnapshot(ctx, config, requestedRoot) {
1350
+ const resolution = resolveProjectRoot(ctx, config, requestedRoot);
1351
+ const snapshot = readSnapshot({ projectRoot: resolution.root, pluginConfig: config });
1352
+ if (requestedRoot !== void 0 && requestedRoot !== null && requestedRoot !== "" && resolution.root !== requestedRoot) {
1353
+ snapshot.diagnostics.push(`\u5BA2\u6237\u7AEF\u9879\u76EE\u6839\u4E0D\u53EF\u7528\uFF1A${requestedRoot}\uFF1B\u5DF2\u56DE\u9000\u5230 ${resolution.root}`);
1354
+ } else if (requestedRoot !== void 0 && requestedRoot !== null && requestedRoot !== "" && snapshot.diagnostics.some((item) => item.startsWith("\u6570\u636E\u76EE\u5F55\u4E0D\u5B58\u5728"))) {
1355
+ snapshot.diagnostics.push(`\u5BA2\u6237\u7AEF\u9879\u76EE\u6839\u6CA1\u6709\u4EFB\u52A1\u6570\u636E\uFF1A${requestedRoot}`);
1356
+ }
1357
+ if (snapshot.diagnostics.some((item) => item.startsWith("\u6570\u636E\u76EE\u5F55\u4E0D\u5B58\u5728"))) {
1358
+ snapshot.diagnostics.push(`\u672A\u627E\u5230\u4EFB\u52A1\u6570\u636E\uFF1B\u5DF2\u5C1D\u8BD5\u9879\u76EE\u6839\uFF1A${resolution.tried.join("\u3001")}`);
1359
+ }
1360
+ return snapshot;
1361
+ }
1362
+ function buildCardFile(ctx, config, id, requestedRoot) {
1363
+ const resolution = resolveProjectRoot(ctx, config, requestedRoot);
1364
+ return readCardFile({ projectRoot: resolution.root, pluginConfig: config }, id);
1365
+ }
1366
+ function buildTaskFiles(ctx, config, id, requestedRoot) {
1367
+ const resolution = resolveProjectRoot(ctx, config, requestedRoot);
1368
+ return readTaskFiles({ projectRoot: resolution.root, pluginConfig: config }, id);
1369
+ }
1370
+ var MAX_BODY_BYTES = 64 * 1024;
1371
+ function readRequestBody(req) {
1372
+ return new Promise((resolveBody, rejectBody) => {
1373
+ const chunks = [];
1374
+ let size = 0;
1375
+ req.on("data", (chunk) => {
1376
+ size += chunk.length;
1377
+ if (size > MAX_BODY_BYTES) {
1378
+ rejectBody(new Error("\u8BF7\u6C42\u4F53\u8FC7\u5927"));
1379
+ req.destroy();
1380
+ return;
1381
+ }
1382
+ chunks.push(chunk);
1383
+ });
1384
+ req.on("end", () => resolveBody(Buffer.concat(chunks).toString("utf8")));
1385
+ req.on("error", (error) => rejectBody(error));
1386
+ });
1387
+ }
1388
+ function validateSettings(input) {
1389
+ if (input === null || typeof input !== "object" || Array.isArray(input)) return { error: "\u8BBE\u7F6E\u5FC5\u987B\u662F JSON \u5BF9\u8C61" };
1390
+ const record = input;
1391
+ const text = (key) => typeof record[key] === "string" ? record[key].trim() : "";
1392
+ const tasksDir = text("tasksDir").replace(/\\/g, "/").replace(/\/+$/, "");
1393
+ const ledgerName = text("ledgerName");
1394
+ const archiveName = text("archiveName");
1395
+ if (tasksDir === "" || tasksDir.length > 120) return { error: "\u6570\u636E\u76EE\u5F55\u4E0D\u80FD\u4E3A\u7A7A\uFF08\u6700\u591A 120 \u5B57\u7B26\uFF09" };
1396
+ if (isAbsolute2(tasksDir) || /^[A-Za-z]:/.test(tasksDir)) return { error: "\u6570\u636E\u76EE\u5F55\u5FC5\u987B\u662F\u9879\u76EE\u5185\u7684\u76F8\u5BF9\u8DEF\u5F84" };
1397
+ if (tasksDir === "." || tasksDir.split("/").some((part) => part === ".." || part === "")) {
1398
+ return { error: "\u6570\u636E\u76EE\u5F55\u4E0D\u80FD\u662F .\uFF0C\u4E5F\u4E0D\u80FD\u5305\u542B .. \u6216\u7A7A\u6BB5" };
1399
+ }
1400
+ for (const [label, value] of [["\u603B\u8D26\u6587\u4EF6\u540D", ledgerName], ["\u5F52\u6863\u6587\u4EF6\u540D", archiveName]]) {
1401
+ if (value === "" || value.length > 80) return { error: `${label}\u4E0D\u80FD\u4E3A\u7A7A\uFF08\u6700\u591A 80 \u5B57\u7B26\uFF09` };
1402
+ if (/[\\/]/.test(value) || value === "." || value === "..") return { error: `${label}\u53EA\u80FD\u662F\u6587\u4EF6\u540D\uFF0C\u4E0D\u80FD\u5E26\u8DEF\u5F84` };
1403
+ }
1404
+ for (const value of [tasksDir, ledgerName, archiveName]) {
1405
+ if (/[\u0000-\u001f]/.test(value)) return { error: "\u8BBE\u7F6E\u503C\u4E0D\u80FD\u5305\u542B\u63A7\u5236\u5B57\u7B26" };
1406
+ }
1407
+ return { value: { tasksDir, ledgerName, archiveName } };
1408
+ }
1409
+ function effectiveSettings(config) {
1410
+ return {
1411
+ tasksDir: config.dataDirRel,
1412
+ ledgerName: basename2(config.ledgerRel),
1413
+ archiveName: basename2(config.archiveRel)
1414
+ };
1415
+ }
1416
+ function settingsRoot(config, requestedRoot) {
1417
+ if (config.projectRoot !== void 0 && config.projectRoot !== "") return resolve3(config.projectRoot);
1418
+ if (requestedRoot !== void 0 && requestedRoot !== null && isAbsolute2(requestedRoot)) return resolve3(requestedRoot);
1419
+ return null;
1420
+ }
1421
+ function settingsState(config, requestedRoot) {
1422
+ const root = settingsRoot(config, requestedRoot);
1423
+ if (root === null) {
1424
+ return {
1425
+ values: { tasksDir: "", ledgerName: "", archiveName: "" },
1426
+ editable: false,
1427
+ reason: "\u8FD8\u6CA1\u6709\u786E\u5B9A\u9879\u76EE\u6839\uFF08\u5148\u5237\u65B0\u9762\u677F\uFF0C\u518D\u6253\u5F00\u8BBE\u7F6E\uFF09"
1428
+ };
1429
+ }
1430
+ try {
1431
+ return { values: effectiveSettings(resolveConfig(root, config)), editable: true, reason: null };
1432
+ } catch (error) {
1433
+ return {
1434
+ values: { tasksDir: "", ledgerName: "", archiveName: "" },
1435
+ editable: false,
1436
+ reason: `\u8BFB\u53D6\u9879\u76EE\u914D\u7F6E\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}`
1437
+ };
1438
+ }
1439
+ }
1440
+ async function saveSettings(config, req, res, requestedRoot) {
1441
+ try {
1442
+ const raw = await readRequestBody(req);
1443
+ let parsed;
1444
+ try {
1445
+ parsed = JSON.parse(raw);
1446
+ } catch {
1447
+ sendJson(res, 400, { ok: false, error: "\u8BF7\u6C42\u4F53\u4E0D\u662F\u5408\u6CD5 JSON" });
1448
+ return;
1449
+ }
1450
+ const validated = validateSettings(parsed);
1451
+ if ("error" in validated) {
1452
+ sendJson(res, 400, { ok: false, error: validated.error });
1453
+ return;
1454
+ }
1455
+ const root = settingsRoot(config, requestedRoot);
1456
+ if (root === null) {
1457
+ sendJson(res, 400, { ok: false, error: "\u7F3A\u5C11\u6709\u6548\u7684 projectRoot\uFF0C\u65E0\u6CD5\u786E\u5B9A\u8981\u5199\u5165\u54EA\u4E2A\u9879\u76EE" });
1458
+ return;
1459
+ }
1460
+ const file = writeProjectConfig(root, validated.value);
1461
+ sendJson(res, 200, { ok: true, data: { saved: true, values: validated.value, file, projectRoot: root } });
1462
+ } catch (error) {
1463
+ sendJson(res, 500, { ok: false, error: `\u4FDD\u5B58\u8BBE\u7F6E\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}` });
1464
+ }
1465
+ }
1466
+ function registerRoutes(ctx, config = {}) {
1467
+ const webServer = ctx.get("webServer");
1468
+ if (webServer === void 0 || webServer === null) {
1469
+ ctx.logger?.warn("[dsh-task-card] \u5BBF\u4E3B\u6CA1\u6709 webServer \u670D\u52A1\uFF0C\u5FEB\u7167\u8DEF\u7531\u672A\u6CE8\u518C");
1470
+ return () => {
1471
+ };
1472
+ }
1473
+ const handler = (req, res) => {
1474
+ const method = (req.method ?? "GET").toUpperCase();
1475
+ const url = new URL(req.url ?? "/", "http://dsh.invalid");
1476
+ const path = url.pathname;
1477
+ const requestedRoot = url.searchParams.get("projectRoot");
1478
+ try {
1479
+ if (path === SNAPSHOT_ROUTES.get) {
1480
+ if (method !== "GET") {
1481
+ res.setHeader("allow", "GET");
1482
+ sendJson(res, 405, { ok: false, error: `method ${method} not allowed on ${path}` });
1483
+ return;
1484
+ }
1485
+ sendJson(res, 200, { ok: true, data: buildSnapshot(ctx, config, requestedRoot) });
1486
+ return;
1487
+ }
1488
+ if (path === SNAPSHOT_ROUTES.refresh) {
1489
+ if (method !== "POST") {
1490
+ res.setHeader("allow", "POST");
1491
+ sendJson(res, 405, { ok: false, error: `method ${method} not allowed on ${path}` });
1492
+ return;
1493
+ }
1494
+ sendJson(res, 200, { ok: true, data: buildSnapshot(ctx, config, requestedRoot) });
1495
+ return;
1496
+ }
1497
+ if (path === SNAPSHOT_ROUTES.card) {
1498
+ if (method !== "GET") {
1499
+ res.setHeader("allow", "GET");
1500
+ sendJson(res, 405, { ok: false, error: `method ${method} not allowed on ${path}` });
1501
+ return;
1502
+ }
1503
+ const id = url.searchParams.get("id") ?? "";
1504
+ try {
1505
+ sendJson(res, 200, { ok: true, data: buildCardFile(ctx, config, id, requestedRoot) });
1506
+ } catch (error) {
1507
+ if (error instanceof CardFileError) sendJson(res, error.status, { ok: false, error: error.message });
1508
+ else throw error;
1509
+ }
1510
+ return;
1511
+ }
1512
+ if (path === SNAPSHOT_ROUTES.files) {
1513
+ if (method !== "GET") {
1514
+ res.setHeader("allow", "GET");
1515
+ sendJson(res, 405, { ok: false, error: `method ${method} not allowed on ${path}` });
1516
+ return;
1517
+ }
1518
+ const id = url.searchParams.get("id") ?? "";
1519
+ try {
1520
+ sendJson(res, 200, { ok: true, data: buildTaskFiles(ctx, config, id, requestedRoot) });
1521
+ } catch (error) {
1522
+ if (error instanceof CardFileError) sendJson(res, error.status, { ok: false, error: error.message });
1523
+ else throw error;
1524
+ }
1525
+ return;
1526
+ }
1527
+ if (path === SNAPSHOT_ROUTES.settings) {
1528
+ if (method === "GET") {
1529
+ sendJson(res, 200, { ok: true, data: settingsState(config, requestedRoot) });
1530
+ return;
1531
+ }
1532
+ if (method === "POST") {
1533
+ void saveSettings(config, req, res, requestedRoot);
1534
+ return;
1535
+ }
1536
+ res.setHeader("allow", "GET, POST");
1537
+ sendJson(res, 405, { ok: false, error: `method ${method} not allowed on ${path}` });
1538
+ return;
1539
+ }
1540
+ sendJson(res, 404, { ok: false, error: `no route ${path}` });
1541
+ } catch (error) {
1542
+ sendJson(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) });
1543
+ }
1544
+ };
1545
+ return ctx.effect(() => {
1546
+ const disposeGet = webServer.register({ kind: "exact", path: SNAPSHOT_ROUTES.get, handler });
1547
+ const disposeRefresh = webServer.register({ kind: "exact", path: SNAPSHOT_ROUTES.refresh, handler });
1548
+ const disposeCard = webServer.register({ kind: "exact", path: SNAPSHOT_ROUTES.card, handler });
1549
+ const disposeFiles = webServer.register({ kind: "exact", path: SNAPSHOT_ROUTES.files, handler });
1550
+ const disposeSettings = webServer.register({ kind: "exact", path: SNAPSHOT_ROUTES.settings, handler });
1551
+ return () => {
1552
+ disposeGet();
1553
+ disposeRefresh();
1554
+ disposeCard();
1555
+ disposeFiles();
1556
+ disposeSettings();
1557
+ };
1558
+ }, "task-card: snapshot routes");
1559
+ }
1560
+ function apply(ctx, config = {}) {
1561
+ registerRoutes(ctx, config);
1562
+ registerBundledSkill(ctx);
1563
+ }
1564
+ var __test = {
1565
+ readSnapshot,
1566
+ resolveConfig,
1567
+ resolveProjectRoot,
1568
+ buildSnapshot,
1569
+ readCardFile,
1570
+ readTaskFiles,
1571
+ CardFileError,
1572
+ parseCard,
1573
+ parseLedger,
1574
+ parseArchive,
1575
+ parseYaml,
1576
+ splitFrontMatter,
1577
+ splitSections,
1578
+ registerRoutes,
1579
+ validateSettings,
1580
+ settingsState,
1581
+ loadBundledSkill,
1582
+ registerBundledSkill,
1583
+ writeProjectConfig,
1584
+ CONFIG_FILE: CONFIG_FILE2
1585
+ };
1586
+ export {
1587
+ __test,
1588
+ apply,
1589
+ inject,
1590
+ name
1591
+ };