@katlux/mcp-workflow 0.0.0-stage → 0.1.0-alpha.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1826 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ const node_fs = require('node:fs');
6
+ const mcpCore = require('@katlux/mcp-core');
7
+ const node_path = require('node:path');
8
+ const node_child_process = require('node:child_process');
9
+ const zod = require('zod');
10
+
11
+ const version="0.1.0-alpha.27";const pkg = {version:version};
12
+
13
+ const CANONICAL_TASK_STATUSES = [
14
+ "[ ] TODO",
15
+ "[~] IN PROGRESS",
16
+ "PAUSED (Feature Freeze)",
17
+ "[x] CLOSED"
18
+ ];
19
+ const TASK_PRIORITIES = ["Critical", "High", "Medium", "Low"];
20
+ const TASK_PREFIXES = ["TASK", "BUG", "DEBT", "RFC"];
21
+
22
+ const TODAY_ISO$1 = () => (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
23
+ const CANONICAL_STATUS_SET = new Set(CANONICAL_TASK_STATUSES);
24
+ function normalizeTaskStatus(raw) {
25
+ if (!raw) return null;
26
+ const trimmed = raw.trim().replace(/^`+|`+$/g, "");
27
+ if (CANONICAL_STATUS_SET.has(trimmed)) {
28
+ return trimmed;
29
+ }
30
+ const upper = trimmed.toUpperCase();
31
+ if (upper === "CLOSED" || upper === "[X] CLOSED" || upper === "DONE" || upper === "[X] DONE" || upper === "COMPLETED" || upper === "COMPLETE" || upper === "RESOLVED" || upper === "FIXED") {
32
+ return "[x] CLOSED";
33
+ }
34
+ if (upper === "IN PROGRESS" || upper === "IN_PROGRESS" || upper === "[~] IN PROGRESS" || upper === "WIP" || upper === "ACTIVE" || upper === "STARTED") {
35
+ return "[~] IN PROGRESS";
36
+ }
37
+ if (upper.includes("PAUSED") || upper.includes("FREEZE") || upper === "ON HOLD" || upper === "BLOCKED") {
38
+ return "PAUSED (Feature Freeze)";
39
+ }
40
+ if (upper === "TODO" || upper === "[ ] TODO" || upper === "OPEN" || upper === "PLANNED" || upper === "NEW" || upper === "BACKLOG") {
41
+ return "[ ] TODO";
42
+ }
43
+ return null;
44
+ }
45
+ function formatCanonicalPriority(raw) {
46
+ const trimmed = (raw || "").trim().replace(/^`+|`+$/g, "");
47
+ if (!trimmed) return "P2 (Medium)";
48
+ const lower = trimmed.toLowerCase();
49
+ if (lower === "critical" || lower === "p0" || lower === "p0 (critical)") return "P0 (Critical)";
50
+ if (lower === "high" || lower === "p1" || lower === "p1 (high)") return "P1 (High)";
51
+ if (lower === "medium" || lower === "p2" || lower === "p2 (medium)") return "P2 (Medium)";
52
+ if (lower === "low" || lower === "p3" || lower === "p3 (low)") return "P3 (Low)";
53
+ return trimmed;
54
+ }
55
+ function slugifyTitle(title) {
56
+ return title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 64).replace(/-+$/g, "") || "task";
57
+ }
58
+ function extractIdParts(rawId, fallbackFile) {
59
+ const match = (rawId || "").match(/\b(TASK|DEBT|BUG|FEAT|RFC)-(\d+)(?:-(\d+))?\b/i);
60
+ if (match) {
61
+ const prefix = match[1].toUpperCase();
62
+ const num = parseInt(match[2], 10);
63
+ const subNum = match[3] !== void 0 ? parseInt(match[3], 10) : void 0;
64
+ const id = subNum !== void 0 ? `${prefix}-${String(num).padStart(3, "0")}-${String(subNum).padStart(2, "0")}` : `${prefix}-${String(num).padStart(3, "0")}`;
65
+ return {
66
+ id,
67
+ prefix,
68
+ numericId: num,
69
+ ...subNum !== void 0 ? { subNumericId: subNum } : {}
70
+ };
71
+ }
72
+ if (fallbackFile) {
73
+ const fileMatch = fallbackFile.match(/\b(TASK|DEBT|BUG|FEAT|RFC)-(\d+)(?:-(\d+))?\b/i);
74
+ if (fileMatch) {
75
+ const prefix = fileMatch[1].toUpperCase();
76
+ const num = parseInt(fileMatch[2], 10);
77
+ const subNum = fileMatch[3] !== void 0 ? parseInt(fileMatch[3], 10) : void 0;
78
+ const id = subNum !== void 0 ? `${prefix}-${String(num).padStart(3, "0")}-${String(subNum).padStart(2, "0")}` : `${prefix}-${String(num).padStart(3, "0")}`;
79
+ return {
80
+ id,
81
+ prefix,
82
+ numericId: num,
83
+ ...subNum !== void 0 ? { subNumericId: subNum } : {}
84
+ };
85
+ }
86
+ }
87
+ return {
88
+ id: rawId || "TASK-000",
89
+ prefix: "TASK",
90
+ numericId: 0
91
+ };
92
+ }
93
+ function extractBacktickFilePaths(content) {
94
+ const found = /* @__PURE__ */ new Set();
95
+ const regex = /`([a-zA-Z0-9_@./-]+\.(?:ts|tsx|mts|js|mjs|cjs|vue|json|scss|css|md))`/g;
96
+ let match;
97
+ while ((match = regex.exec(content)) !== null) {
98
+ const candidate = match[1];
99
+ if (candidate.startsWith("packages/") || candidate.startsWith("apps/") || candidate.startsWith("src/") || candidate.startsWith("tests/") || candidate.startsWith("scripts/") || candidate.startsWith(".agents/")) {
100
+ found.add(candidate);
101
+ }
102
+ }
103
+ return Array.from(found);
104
+ }
105
+ function parseChecklistItems(lines) {
106
+ const items = [];
107
+ for (const line of lines) {
108
+ const m = line.match(/^\s*[-*]\s+\[([ xX])\]\s+(.+)$/);
109
+ if (m) {
110
+ items.push({
111
+ index: items.length,
112
+ checked: m[1].toLowerCase() === "x",
113
+ text: m[2].trim()
114
+ });
115
+ }
116
+ }
117
+ return items;
118
+ }
119
+ function parseSections(body) {
120
+ const lines = body.split(/\r?\n/);
121
+ const sections = [];
122
+ const preambleLines = [];
123
+ let currentHeading = null;
124
+ let currentLines = [];
125
+ for (const line of lines) {
126
+ const h2Match = line.match(/^##\s+(.+)$/);
127
+ if (h2Match) {
128
+ if (currentHeading !== null) {
129
+ sections.push({ heading: currentHeading, content: currentLines.join("\n").trim() });
130
+ } else {
131
+ preambleLines.push(...currentLines);
132
+ }
133
+ currentHeading = h2Match[1].trim();
134
+ currentLines = [];
135
+ } else {
136
+ currentLines.push(line);
137
+ }
138
+ }
139
+ if (currentHeading !== null) {
140
+ sections.push({ heading: currentHeading, content: currentLines.join("\n").trim() });
141
+ } else {
142
+ preambleLines.push(...currentLines);
143
+ }
144
+ return {
145
+ preamble: preambleLines.join("\n").trim(),
146
+ sections
147
+ };
148
+ }
149
+ function parseTaskMarkdown(rawContent, filePath, relPath) {
150
+ const lines = rawContent.split(/\r?\n/);
151
+ const formatIssues = [];
152
+ const h1Line = lines.find((l) => /^#\s+/.test(l));
153
+ let title = "";
154
+ let rawId = "";
155
+ if (h1Line) {
156
+ const h1Text = h1Line.replace(/^#\s+/, "").trim();
157
+ const idTitleMatch = h1Text.match(/^\[?((?:TASK|DEBT|BUG|FEAT|RFC)-\d+(?:-\d+)?)\]?\s*(?:[:\-–—]\s*|\s+)(.+)$/i);
158
+ if (idTitleMatch) {
159
+ rawId = idTitleMatch[1];
160
+ title = idTitleMatch[2].trim();
161
+ } else {
162
+ title = h1Text;
163
+ }
164
+ } else {
165
+ formatIssues.push("Missing top-level # <ID>: <Title> heading");
166
+ }
167
+ const hasMetadataTable = /^\|\s*\*?\*?(?:ID|Task ID|Priority|Status)\*?\*?\s*\|/im.test(rawContent);
168
+ if (hasMetadataTable) {
169
+ formatIssues.push("Uses legacy metadata table instead of canonical **Key:** Value header");
170
+ }
171
+ const extractMeta = (keys, stripAllOuterBackticks = true) => {
172
+ for (const key of keys) {
173
+ const boldRegex = new RegExp(`^[-*]?\\s*\\*\\*${key}\\s*:?\\*\\*\\s*:?\\s*(.+)$`, "im");
174
+ const bm = rawContent.match(boldRegex);
175
+ if (bm) {
176
+ const raw = bm[1].trim().replace(/\|$/, "").trim();
177
+ return stripAllOuterBackticks ? raw.replace(/^`+([^`]+)`+$/, "$1").trim() : raw;
178
+ }
179
+ const tableRegex = new RegExp(`^\\|\\s*\\*?\\*?${key}\\*?\\*?\\s*\\|\\s*([^|\\n]+)\\|`, "im");
180
+ const tm = rawContent.match(tableRegex);
181
+ if (tm) {
182
+ const raw = tm[1].trim();
183
+ return stripAllOuterBackticks ? raw.replace(/^`+([^`]+)`+$/, "$1").trim() : raw;
184
+ }
185
+ }
186
+ return void 0;
187
+ };
188
+ if (!rawId) {
189
+ rawId = extractMeta(["ID", "Task ID"]) || "";
190
+ }
191
+ const { id, prefix, numericId } = extractIdParts(rawId, relPath);
192
+ if (!title) {
193
+ title = extractMeta(["Title"]) || relPath.split("/").pop()?.replace(/\.md$/i, "") || id;
194
+ }
195
+ const priority = formatCanonicalPriority(extractMeta(["Priority"]));
196
+ const type = extractMeta(["Type"]);
197
+ const created = extractMeta(["Created", "Date"]) || TODAY_ISO$1();
198
+ const createdAt = extractMeta(["Created At", "CreatedAt"]);
199
+ const updated = extractMeta(["Updated"]);
200
+ const closedAt = extractMeta(["Closed At", "ClosedAt"]);
201
+ const rawTokens = extractMeta(["Tokens Spent", "TokensSpent"]);
202
+ const tokensSpent = rawTokens !== void 0 && rawTokens !== "" && !Number.isNaN(Number(rawTokens)) ? Number(rawTokens) : void 0;
203
+ const dependencies = extractMeta(["Related Tasks", "Dependencies", "Depends On"]);
204
+ const milestone = extractMeta(["Target Milestone", "Milestone"]);
205
+ const component = extractMeta(["Component / Package", "Component", "Package"], false);
206
+ const assignee = extractMeta(["Assignee"]);
207
+ const rawStatus = extractMeta(["Status"]);
208
+ if (!rawStatus) {
209
+ formatIssues.push("Missing **Status:** metadata field");
210
+ }
211
+ const normalizedStatus = normalizeTaskStatus(rawStatus);
212
+ const statusIsCanonical = rawStatus !== void 0 && CANONICAL_STATUS_SET.has(rawStatus);
213
+ if (rawStatus && !statusIsCanonical) {
214
+ formatIssues.push(`Non-canonical status "${rawStatus}" (expected one of ${CANONICAL_TASK_STATUSES.join(", ")})`);
215
+ }
216
+ const status = normalizedStatus || rawStatus || "[ ] TODO";
217
+ const firstH2Idx = lines.findIndex((l) => /^##\s+/.test(l));
218
+ const bodyText = firstH2Idx >= 0 ? lines.slice(firstH2Idx).join("\n") : "";
219
+ const { sections } = parseSections(bodyText);
220
+ let problem = "";
221
+ let scope = "";
222
+ let acceptanceCriteria = [];
223
+ const extraSections = [];
224
+ let hasProblemSection = false;
225
+ let hasScopeSection = false;
226
+ let hasAcceptanceSection = false;
227
+ for (const sec of sections) {
228
+ const lower = sec.heading.toLowerCase();
229
+ const normalizedHeading = lower.replace(/^\d+\.\s*/, "").trim();
230
+ const cleanedContent = sec.content.replace(/\n---\s*$/g, "").trim();
231
+ if (!hasProblemSection && (normalizedHeading.startsWith("problem statement") || normalizedHeading.startsWith("objective") || normalizedHeading.startsWith("description") || normalizedHeading === "problem" || normalizedHeading === "overview" || normalizedHeading === "background & problem")) {
232
+ problem = cleanedContent;
233
+ hasProblemSection = true;
234
+ const isCanonicalProblem = normalizedHeading.startsWith("problem statement") || normalizedHeading.startsWith("objective") || normalizedHeading.startsWith("description");
235
+ if (!isCanonicalProblem) {
236
+ formatIssues.push(`Section "## ${sec.heading}" should be "## 1. Objective"`);
237
+ }
238
+ } else if (!hasScopeSection && (normalizedHeading === "implementation scope" || normalizedHeading.startsWith("deliverables & architecture") || normalizedHeading.startsWith("scope & requirements") || normalizedHeading.startsWith("requirements & scope") || normalizedHeading.startsWith("proposed architecture") || normalizedHeading.startsWith("technical architecture") || normalizedHeading === "proposed solution" || normalizedHeading === "technical scope" || normalizedHeading === "scope")) {
239
+ scope = cleanedContent;
240
+ hasScopeSection = true;
241
+ const isCanonicalScope = normalizedHeading === "implementation scope" || normalizedHeading.startsWith("deliverables & architecture") || normalizedHeading.startsWith("scope & requirements") || normalizedHeading.startsWith("requirements & scope") || normalizedHeading.startsWith("proposed architecture") || normalizedHeading.startsWith("technical architecture");
242
+ if (!isCanonicalScope) {
243
+ formatIssues.push(`Section "## ${sec.heading}" should be "## 2. Scope & Requirements"`);
244
+ }
245
+ } else if (!hasAcceptanceSection && normalizedHeading === "acceptance criteria") {
246
+ acceptanceCriteria = parseChecklistItems(cleanedContent.split(/\r?\n/));
247
+ hasAcceptanceSection = true;
248
+ } else {
249
+ extraSections.push({ heading: sec.heading, body: cleanedContent });
250
+ }
251
+ }
252
+ if (!hasProblemSection) formatIssues.push('Missing "## Problem Statement" section');
253
+ if (!hasScopeSection) formatIssues.push('Missing "## Implementation Scope" section');
254
+ if (!hasAcceptanceSection) {
255
+ formatIssues.push('Missing "## Acceptance Criteria" section');
256
+ acceptanceCriteria = parseChecklistItems(lines);
257
+ }
258
+ if (!problem && firstH2Idx < 0) {
259
+ const plainBody = lines.filter((l) => !/^#\s+/.test(l) && !/^\*\*[A-Za-z ]+:\*\*/.test(l) && !/^---$/.test(l.trim())).join("\n").trim();
260
+ if (plainBody) problem = plainBody;
261
+ }
262
+ const legacyFormat = formatIssues.length > 0;
263
+ return {
264
+ id,
265
+ prefix,
266
+ numericId,
267
+ title,
268
+ filePath,
269
+ relPath,
270
+ priority,
271
+ type,
272
+ created,
273
+ createdAt,
274
+ updated,
275
+ closedAt,
276
+ tokensSpent,
277
+ status,
278
+ statusIsCanonical: statusIsCanonical && Boolean(normalizedStatus),
279
+ dependencies,
280
+ milestone,
281
+ component,
282
+ assignee,
283
+ problem,
284
+ scope,
285
+ acceptanceCriteria,
286
+ extraSections,
287
+ legacyFormat,
288
+ formatIssues,
289
+ backtickPaths: extractBacktickFilePaths(rawContent)
290
+ };
291
+ }
292
+ function serializeCanonicalTask(task) {
293
+ const canonicalStatus = normalizeTaskStatus(task.status) || "[ ] TODO";
294
+ const canonicalPriority = formatCanonicalPriority(task.priority);
295
+ const metaLines = [
296
+ `# [${task.id}] ${task.title}`,
297
+ "",
298
+ `- **Status**: \`${canonicalStatus}\``,
299
+ `- **Priority**: \`${canonicalPriority}\``
300
+ ];
301
+ if (task.milestone) metaLines.push(`- **Target Milestone**: \`${task.milestone.replace(/^`+|`+$/g, "")}\``);
302
+ if (task.component) metaLines.push(`- **Component / Package**: ${task.component}`);
303
+ if (task.type) metaLines.push(`- **Type**: \`${task.type}\``);
304
+ if (task.dependencies) metaLines.push(`- **Related Tasks**: ${task.dependencies}`);
305
+ metaLines.push(`- **Assignee**: ${task.assignee || "Unassigned"}`);
306
+ if (task.createdAt) metaLines.push(`- **Created At**: ${task.createdAt}`);
307
+ if (task.updated) metaLines.push(`- **Updated**: ${task.updated}`);
308
+ if (task.closedAt) metaLines.push(`- **Closed At**: ${task.closedAt}`);
309
+ if (task.tokensSpent !== void 0) metaLines.push(`- **Tokens Spent**: ${task.tokensSpent}`);
310
+ const blocks = [
311
+ metaLines.join("\n"),
312
+ "",
313
+ "---",
314
+ "",
315
+ "## 1. Objective",
316
+ "",
317
+ task.problem?.trim() || "_No objective provided._",
318
+ "",
319
+ "---",
320
+ "",
321
+ "## 2. Scope & Requirements",
322
+ "",
323
+ task.scope?.trim() || "_Implementation scope pending definition._"
324
+ ];
325
+ let sectionNum = 3;
326
+ for (const sec of task.extraSections || []) {
327
+ const cleanHeading = sec.heading.replace(/^\d+\.\s*/, "").trim();
328
+ blocks.push("", "---", "", `## ${sectionNum}. ${cleanHeading}`, "", sec.body.trim());
329
+ sectionNum++;
330
+ }
331
+ blocks.push("", "---", "", `## ${sectionNum}. Acceptance Criteria`, "");
332
+ if (task.acceptanceCriteria.length === 0) {
333
+ blocks.push("- [ ] Define explicit verification criteria");
334
+ } else {
335
+ for (const item of task.acceptanceCriteria) {
336
+ blocks.push(`- [${item.checked ? "x" : " "}] ${item.text}`);
337
+ }
338
+ }
339
+ return `${blocks.join("\n")}
340
+ `;
341
+ }
342
+
343
+ function toPosix(p) {
344
+ return p.split("\\").join("/");
345
+ }
346
+ function getTodoPaths(root) {
347
+ const todoDir = node_path.resolve(root, "todo");
348
+ return {
349
+ todoDir,
350
+ tasksDir: node_path.resolve(todoDir, "tasks"),
351
+ archiveDir: node_path.resolve(todoDir, "archive"),
352
+ indexPath: node_path.resolve(todoDir, "INDEX.md")
353
+ };
354
+ }
355
+ function collectMarkdownFiles(dir, recursive) {
356
+ if (!node_fs.existsSync(dir)) return [];
357
+ const out = [];
358
+ for (const entry of node_fs.readdirSync(dir, { withFileTypes: true })) {
359
+ const full = node_path.join(dir, entry.name);
360
+ if (entry.isDirectory()) {
361
+ out.push(...collectMarkdownFiles(full));
362
+ } else if (entry.isFile() && entry.name.endsWith(".md")) {
363
+ const upper = entry.name.toUpperCase();
364
+ if (upper === "INDEX.MD" || upper === "README.MD") continue;
365
+ out.push(full);
366
+ }
367
+ }
368
+ return out.sort();
369
+ }
370
+ function loadActiveTasks(root) {
371
+ const { tasksDir } = getTodoPaths(root);
372
+ return collectMarkdownFiles(tasksDir).map((absPath) => {
373
+ const relPath = toPosix(node_path.relative(root, absPath));
374
+ const content = node_fs.readFileSync(absPath, "utf-8");
375
+ return parseTaskMarkdown(content, absPath, relPath);
376
+ });
377
+ }
378
+ function loadArchiveEntries(root) {
379
+ const { archiveDir } = getTodoPaths(root);
380
+ return collectMarkdownFiles(archiveDir).map((absPath) => {
381
+ const relPath = toPosix(node_path.relative(root, absPath));
382
+ const relFromArchive = toPosix(node_path.relative(archiveDir, absPath));
383
+ const parts = relFromArchive.split("/");
384
+ const milestone = parts.length > 1 ? parts[0] : "unscoped";
385
+ const content = node_fs.readFileSync(absPath, "utf-8");
386
+ const parsed = parseTaskMarkdown(content, absPath, relPath);
387
+ const checkedCount = parsed.acceptanceCriteria.filter((c) => c.checked).length;
388
+ return {
389
+ id: parsed.id,
390
+ numericId: parsed.numericId,
391
+ title: parsed.title,
392
+ status: parsed.status,
393
+ priority: parsed.priority,
394
+ milestone,
395
+ relPath,
396
+ legacyFormat: parsed.legacyFormat,
397
+ formatIssues: parsed.formatIssues,
398
+ checkedCount,
399
+ totalCount: parsed.acceptanceCriteria.length
400
+ };
401
+ });
402
+ }
403
+ function allocateNextTaskId(root, prefix = "TASK", parentId) {
404
+ const active = loadActiveTasks(root);
405
+ const archived = loadArchiveEntries(root);
406
+ if (parentId?.trim()) {
407
+ const parent = extractIdParts(parentId.trim());
408
+ let maxSubNum = 0;
409
+ for (const item of [...active, ...archived]) {
410
+ const { prefix: itemPrefix, numericId, subNumericId } = extractIdParts(item.id, item.relPath);
411
+ if (itemPrefix === parent.prefix && numericId === parent.numericId && subNumericId !== void 0 && subNumericId > maxSubNum) {
412
+ maxSubNum = subNumericId;
413
+ }
414
+ }
415
+ return `${parent.prefix}-${String(parent.numericId).padStart(3, "0")}-${String(maxSubNum + 1).padStart(2, "0")}`;
416
+ }
417
+ let maxNum = 0;
418
+ for (const item of [...active, ...archived]) {
419
+ const { prefix: itemPrefix, numericId } = extractIdParts(item.id, item.relPath);
420
+ if (itemPrefix === prefix && numericId > maxNum) maxNum = numericId;
421
+ }
422
+ return `${prefix}-${String(maxNum + 1).padStart(3, "0")}`;
423
+ }
424
+ function parseTodoIndexRows(indexContent) {
425
+ const rows = [];
426
+ const lines = indexContent.split(/\r?\n/);
427
+ for (let i = 0; i < lines.length; i++) {
428
+ const line = lines[i].trim();
429
+ if (!line.startsWith("|")) continue;
430
+ if (/^\|\s*:?-{2,}/.test(line)) continue;
431
+ if (/^\|\s*ID\s*\|/i.test(line)) continue;
432
+ const cells = line.split("|").slice(1, -1).map((c) => c.trim());
433
+ if (cells.length < 4) continue;
434
+ const idCell = cells[0];
435
+ if (/^\*?\(none\)\*?$/i.test(idCell) || idCell === "\u2014" || idCell === "-") continue;
436
+ if (cells.length >= 6) {
437
+ const cleanId = idCell.replace(/[`*\[\]]/g, "").trim();
438
+ const status = cells[1].replace(/^`+|`+$/g, "").trim();
439
+ const specMatch = cells[5].match(/^\[([^\]]+)\]\(([^)]+)\)$/);
440
+ const linkPath2 = specMatch ? specMatch[2].trim() : "";
441
+ if (!cleanId) continue;
442
+ rows.push({
443
+ id: cleanId,
444
+ linkPath: linkPath2,
445
+ title: cells[4],
446
+ priority: "",
447
+ status,
448
+ rawLine: i + 1
449
+ });
450
+ continue;
451
+ }
452
+ if (cells.length === 5) {
453
+ const cleanId = idCell.replace(/[`*\[\]]/g, "").trim();
454
+ const specMatch = cells[4].match(/^\[([^\]]+)\]\(([^)]+)\)$/);
455
+ const linkPath2 = specMatch ? specMatch[2].trim() : "";
456
+ if (!cleanId) continue;
457
+ rows.push({
458
+ id: cleanId,
459
+ linkPath: linkPath2,
460
+ title: cells[3],
461
+ priority: cells[1],
462
+ status: "",
463
+ rawLine: i + 1
464
+ });
465
+ continue;
466
+ }
467
+ const linkMatch = idCell.match(/^\[([^\]]+)\]\(([^)]+)\)$/);
468
+ const id = linkMatch ? linkMatch[1].trim() : idCell.replace(/\*\*/g, "").trim();
469
+ const linkPath = linkMatch ? linkMatch[2].trim() : "";
470
+ if (!id) continue;
471
+ rows.push({
472
+ id,
473
+ linkPath,
474
+ title: cells[1],
475
+ priority: cells[2],
476
+ status: cells[3],
477
+ rawLine: i + 1
478
+ });
479
+ }
480
+ return rows;
481
+ }
482
+ function formatIndexStatus(status) {
483
+ const normalized = normalizeTaskStatus(status);
484
+ if (normalized === "[x] CLOSED") return "**[x] CLOSED**";
485
+ if (normalized === "[~] IN PROGRESS") return "**[~] IN PROGRESS**";
486
+ return normalized || status;
487
+ }
488
+ function syncTodoIndex(root, activeTasks) {
489
+ const { todoDir, indexPath } = getTodoPaths(root);
490
+ node_fs.mkdirSync(todoDir, { recursive: true });
491
+ const tasks = [...activeTasks || loadActiveTasks(root)].sort((a, b) => {
492
+ if (a.numericId !== b.numericId) return a.numericId - b.numericId;
493
+ return a.id.localeCompare(b.id);
494
+ });
495
+ const tableLines = [
496
+ "| ID | Task | Priority | Status |",
497
+ "| :--- | :--- | :--- | :--- |",
498
+ ...tasks.map((t) => {
499
+ const relFromTodo = toPosix(node_path.relative(todoDir, t.filePath));
500
+ const safeTitle = t.title.replace(/\|/g, "\\|");
501
+ return `| [${t.id}](${relFromTodo}) | ${safeTitle} | ${t.priority} | ${formatIndexStatus(t.status)} |`;
502
+ })
503
+ ];
504
+ if (!node_fs.existsSync(indexPath)) {
505
+ const initial = [
506
+ "# Katlux Workflow \u2014 Master Task Index",
507
+ "",
508
+ "> Managed via `@katlux/mcp-workflow` (`katlux_workflow_task` / `katlux_workflow_inspect`).",
509
+ "",
510
+ "## Active Task Queue",
511
+ "",
512
+ ...tableLines,
513
+ ""
514
+ ].join("\n");
515
+ node_fs.writeFileSync(indexPath, initial, "utf-8");
516
+ return;
517
+ }
518
+ const existing = node_fs.readFileSync(indexPath, "utf-8");
519
+ const lines = existing.split(/\r?\n/);
520
+ let sixColStart = -1;
521
+ let sixColEnd = -1;
522
+ for (let i = 0; i < lines.length; i++) {
523
+ if (/^\|\s*ID\s*\|\s*Status\s*\|\s*Target Milestone\s*\|\s*Component\s*\/\s*Package\s*\|\s*Title\s*\|\s*Spec File\s*\|/i.test(lines[i])) {
524
+ sixColStart = i;
525
+ let j = i + 1;
526
+ while (j < lines.length && lines[j].trim().startsWith("|")) {
527
+ j++;
528
+ }
529
+ sixColEnd = j;
530
+ break;
531
+ }
532
+ }
533
+ if (sixColStart >= 0) {
534
+ const existingMetaById = /* @__PURE__ */ new Map();
535
+ for (let i = sixColStart + 2; i < sixColEnd; i++) {
536
+ const cells = lines[i].trim().split("|").slice(1, -1).map((c) => c.trim());
537
+ if (cells.length >= 6) {
538
+ const cleanId = cells[0].replace(/[`*\[\]]/g, "").trim().toUpperCase();
539
+ if (cleanId) {
540
+ existingMetaById.set(cleanId, {
541
+ status: cells[1].replace(/^`+|`+$/g, "").trim(),
542
+ milestone: cells[2],
543
+ pkg: cells[3]
544
+ });
545
+ }
546
+ }
547
+ }
548
+ const sixColLines = [
549
+ "| ID | Status | Target Milestone | Component / Package | Title | Spec File |",
550
+ "| :--- | :--- | :--- | :--- | :--- | :--- |",
551
+ ...tasks.map((t) => {
552
+ const relFromTodo = toPosix(node_path.relative(todoDir, t.filePath));
553
+ const safeTitle = t.title.replace(/\|/g, "\\|");
554
+ const meta = existingMetaById.get(t.id.toUpperCase());
555
+ const existingMilestone = meta?.milestone && meta.milestone !== "`TBD`" && meta.milestone !== "TBD" ? meta.milestone : void 0;
556
+ const milestone = existingMilestone || (t.milestone ? `\`${t.milestone.replace(/^`+|`+$/g, "")}\`` : "`TBD`");
557
+ const existingPkg = meta?.pkg && meta.pkg !== "\u2014" && meta.pkg !== "-" ? meta.pkg : void 0;
558
+ const shortComponent = t.component ? t.component.replace(/\s*\([^)]*\)\s*$/, "").trim() : void 0;
559
+ const pkg = existingPkg || shortComponent || "\u2014";
560
+ const fileStatusNorm = normalizeTaskStatus(t.status) || t.status;
561
+ const statusNorm = fileStatusNorm === "[ ] TODO" && meta?.status === "PAUSED (Feature Freeze)" ? "PAUSED (Feature Freeze)" : fileStatusNorm;
562
+ return `| \`[${t.id}]\` | \`${statusNorm}\` | ${milestone} | ${pkg} | ${safeTitle} | [${t.id}](${relFromTodo}) |`;
563
+ })
564
+ ];
565
+ const updated = [
566
+ ...lines.slice(0, sixColStart),
567
+ ...sixColLines,
568
+ ...lines.slice(sixColEnd)
569
+ ].join("\n");
570
+ node_fs.writeFileSync(indexPath, updated.endsWith("\n") ? updated : `${updated}
571
+ `, "utf-8");
572
+ return;
573
+ }
574
+ let tableStart = -1;
575
+ let tableEnd = -1;
576
+ for (let i = 0; i < lines.length; i++) {
577
+ if (/^\|\s*ID\s*\|\s*Task\s*\|/i.test(lines[i])) {
578
+ tableStart = i;
579
+ let j = i + 1;
580
+ while (j < lines.length && lines[j].trim().startsWith("|")) {
581
+ j++;
582
+ }
583
+ tableEnd = j;
584
+ break;
585
+ }
586
+ }
587
+ if (tableStart >= 0) {
588
+ const updated = [
589
+ ...lines.slice(0, tableStart),
590
+ ...tableLines,
591
+ ...lines.slice(tableEnd)
592
+ ].join("\n");
593
+ node_fs.writeFileSync(indexPath, updated.endsWith("\n") ? updated : `${updated}
594
+ `, "utf-8");
595
+ } else {
596
+ const trimmed = existing.trimEnd();
597
+ const updated = `${trimmed}
598
+
599
+ ## Active Task Queue
600
+
601
+ ${tableLines.join("\n")}
602
+ `;
603
+ node_fs.writeFileSync(indexPath, updated, "utf-8");
604
+ }
605
+ }
606
+ function syncArchiveMilestoneIndex(root, milestone) {
607
+ const { archiveDir } = getTodoPaths(root);
608
+ const safeMilestone = milestone.replace(/[^a-zA-Z0-9._-]/g, "-").replace(/^-+|-+$/g, "") || "archive";
609
+ const milestoneDir = node_path.resolve(archiveDir, safeMilestone);
610
+ if (!mcpCore.isDescendantOf(archiveDir, milestoneDir) && milestoneDir !== archiveDir) {
611
+ throw new Error(`Invalid milestone directory: ${milestone}`);
612
+ }
613
+ node_fs.mkdirSync(milestoneDir, { recursive: true });
614
+ const entries = loadArchiveEntries(root).filter((e) => e.milestone === safeMilestone).sort((a, b) => a.numericId - b.numericId);
615
+ const lines = [
616
+ `# Archive Index \u2014 ${safeMilestone}`,
617
+ "",
618
+ "| ID | Title | Priority | Status | Criteria |",
619
+ "| :--- | :--- | :--- | :--- | :--- |",
620
+ ...entries.map((e) => {
621
+ const relFromMilestone = toPosix(node_path.relative(milestoneDir, node_path.resolve(root, e.relPath)));
622
+ const title = e.title.replace(/\|/g, "\\|");
623
+ const criteria = e.totalCount > 0 ? `${e.checkedCount}/${e.totalCount}` : "legacy";
624
+ return `| [${e.id}](./${relFromMilestone}) | ${title} | ${e.priority || "-"} | ${e.status} | ${criteria} |`;
625
+ }),
626
+ ""
627
+ ];
628
+ node_fs.writeFileSync(node_path.resolve(milestoneDir, "INDEX.md"), lines.join("\n"), "utf-8");
629
+ }
630
+
631
+ function handleWorkflowInit(args = {}, defaultCwd) {
632
+ try {
633
+ const root = mcpCore.assertSafeWorkspace(args.cwd || defaultCwd);
634
+ const { todoDir, tasksDir, archiveDir, indexPath } = getTodoPaths(root);
635
+ const existedBefore = node_fs.existsSync(indexPath);
636
+ node_fs.mkdirSync(todoDir, { recursive: true });
637
+ node_fs.mkdirSync(tasksDir, { recursive: true });
638
+ node_fs.mkdirSync(archiveDir, { recursive: true });
639
+ const activeTasks = loadActiveTasks(root);
640
+ const archiveEntries = loadArchiveEntries(root);
641
+ if (!existedBefore) {
642
+ syncTodoIndex(root, activeTasks);
643
+ }
644
+ const lines = [
645
+ existedBefore ? "## Workflow Workspace Already Initialized" : "## Workflow Workspace Initialized",
646
+ "",
647
+ `- **Workspace Root**: \`${root}\``,
648
+ `- **Todo Directory**: \`todo/\` (created/verified \`todo/tasks/\`, \`todo/archive/\`, \`todo/INDEX.md\`)`,
649
+ `- **Active Tasks**: ${activeTasks.length}`,
650
+ `- **Archived Tasks**: ${archiveEntries.length}`,
651
+ "",
652
+ "Use `katlux_workflow_task` (`create`, `update`, `transition`, `archive`) and `katlux_workflow_inspect` (`list`, `get`, `archive`, `doctor`) to manage tasks via schema-enforced operations."
653
+ ];
654
+ return {
655
+ content: [{ type: "text", text: lines.join("\n") }]
656
+ };
657
+ } catch (error) {
658
+ return {
659
+ isError: true,
660
+ content: [{ type: "text", text: `Workflow init failed: ${error instanceof Error ? error.message : String(error)}` }]
661
+ };
662
+ }
663
+ }
664
+
665
+ const TODAY_ISO = () => (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
666
+ const CriterionInputSchema = zod.z.union([
667
+ zod.z.string().min(1),
668
+ zod.z.object({
669
+ text: zod.z.string().min(1),
670
+ checked: zod.z.boolean().optional()
671
+ })
672
+ ]);
673
+ const CriterionUpdateSchema = zod.z.object({
674
+ index: zod.z.number().int().min(0).optional(),
675
+ match: zod.z.string().min(1).optional(),
676
+ checked: zod.z.boolean()
677
+ });
678
+ const WorkflowTaskSchema = zod.z.object({
679
+ cwd: zod.z.string().optional(),
680
+ action: zod.z.enum(["create", "update", "transition", "archive"]),
681
+ id: zod.z.string().optional(),
682
+ parentId: zod.z.string().optional(),
683
+ prefix: zod.z.enum(["TASK", "BUG", "DEBT", "RFC"]).optional(),
684
+ title: zod.z.string().optional(),
685
+ priority: zod.z.string().optional(),
686
+ type: zod.z.string().optional(),
687
+ dependencies: zod.z.string().optional(),
688
+ problem: zod.z.string().optional(),
689
+ scope: zod.z.union([zod.z.string(), zod.z.array(zod.z.string())]).optional(),
690
+ notes: zod.z.string().optional(),
691
+ acceptanceCriteria: zod.z.array(CriterionInputSchema).optional(),
692
+ addCriteria: zod.z.array(CriterionInputSchema).optional(),
693
+ criteriaUpdates: zod.z.array(CriterionUpdateSchema).optional(),
694
+ status: zod.z.string().optional(),
695
+ milestone: zod.z.string().optional(),
696
+ component: zod.z.string().optional(),
697
+ force: zod.z.boolean().optional(),
698
+ runCheck: zod.z.boolean().optional(),
699
+ runTest: zod.z.boolean().optional(),
700
+ tokensSpent: zod.z.number().min(0).optional()
701
+ });
702
+ function errorResult$1(message) {
703
+ return {
704
+ isError: true,
705
+ content: [{ type: "text", text: message }]
706
+ };
707
+ }
708
+ function normalizeScope(scope) {
709
+ if (!scope) return "";
710
+ if (Array.isArray(scope)) {
711
+ return scope.map((s) => s.trim().startsWith("-") ? s.trim() : `- ${s.trim()}`).join("\n");
712
+ }
713
+ return scope.trim();
714
+ }
715
+ function normalizeCriteriaList(items) {
716
+ return items.map((item, idx) => {
717
+ if (typeof item === "string") {
718
+ return { index: idx, checked: false, text: item.trim() };
719
+ }
720
+ return { index: idx, checked: Boolean(item.checked), text: item.text.trim() };
721
+ });
722
+ }
723
+ function validateCanonicalStatusExact(raw) {
724
+ return typeof raw === "string" && CANONICAL_TASK_STATUSES.includes(raw.trim());
725
+ }
726
+ function runCompletionGates(root, runCheck, runTest) {
727
+ const gates = [
728
+ { enabled: runCheck, script: "ai:check" },
729
+ { enabled: runTest, script: "ai:test" }
730
+ ];
731
+ for (const gate of gates) {
732
+ if (!gate.enabled) continue;
733
+ try {
734
+ node_child_process.execSync(`npm run ${gate.script}`, { cwd: root, stdio: "pipe", encoding: "utf-8" });
735
+ } catch (error) {
736
+ const err = error;
737
+ const details = (err.stderr || err.stdout || err.message || "Unknown error").trim();
738
+ return `Completion gate "npm run ${gate.script}" failed:
739
+ ${details}`;
740
+ }
741
+ }
742
+ return null;
743
+ }
744
+ function enforceCloseGate(task, targetStatus) {
745
+ if (targetStatus !== "[x] CLOSED") return null;
746
+ if (task.acceptanceCriteria.length === 0) {
747
+ return `Close gate blocked ${task.id}: Cannot transition to "[x] CLOSED" without defined acceptance criteria.`;
748
+ }
749
+ const unchecked = task.acceptanceCriteria.filter((c) => !c.checked);
750
+ if (unchecked.length > 0) {
751
+ const list = unchecked.map((c) => ` - [ ] [${c.index}] ${c.text}`).join("\n");
752
+ return `Close gate blocked ${task.id}: Cannot transition to "[x] CLOSED" while ${unchecked.length} acceptance criterion(s) remain unchecked:
753
+ ${list}`;
754
+ }
755
+ return null;
756
+ }
757
+ const MAX_CRITERIA_GATE = 6;
758
+ const MAX_SCOPE_FILES_GATE = 8;
759
+ function enforceOneTaskOneConcernGate(task) {
760
+ const reasons = [];
761
+ if (task.acceptanceCriteria.length > MAX_CRITERIA_GATE) {
762
+ reasons.push(`${task.acceptanceCriteria.length} acceptance criteria (max: ${MAX_CRITERIA_GATE})`);
763
+ }
764
+ const fileMatches = /* @__PURE__ */ new Set();
765
+ const fileRegex = /`([a-zA-Z0-9_@./-]+\.[a-z0-9]{1,6})`/g;
766
+ for (const source of [task.scope, task.problem]) {
767
+ let m;
768
+ while ((m = fileRegex.exec(source)) !== null) {
769
+ fileMatches.add(m[1]);
770
+ }
771
+ }
772
+ if (fileMatches.size > MAX_SCOPE_FILES_GATE) {
773
+ reasons.push(`${fileMatches.size} referenced files (max: ${MAX_SCOPE_FILES_GATE})`);
774
+ }
775
+ if (reasons.length === 0) return null;
776
+ return `One-task-one-concern gate blocked ${task.id}: This task has ${reasons.join(" and ")}. Explode it into separate main tasks or \`PREFIX-XXX-YY\` subtasks (via \`parentId\`).`;
777
+ }
778
+ function maybeAutoCompleteParentTask(root, completedTask) {
779
+ if (completedTask.status !== "[x] CLOSED") return "";
780
+ const match = /^([A-Z]+-\d+)-\d+$/i.exec(completedTask.id);
781
+ if (!match) return "";
782
+ const parentId = match[1].toUpperCase();
783
+ const active = loadActiveTasks(root);
784
+ const parent = active.find((t) => t.id.toUpperCase() === parentId);
785
+ if (!parent || normalizeTaskStatus(parent.status) === "[x] CLOSED") return "";
786
+ const subtaskRegex = new RegExp(`^${parentId}-\\d+$`, "i");
787
+ const subtasks = active.filter((t) => subtaskRegex.test(t.id));
788
+ if (subtasks.length === 0 || !subtasks.every((s) => normalizeTaskStatus(s.status) === "[x] CLOSED")) {
789
+ return "";
790
+ }
791
+ const updatedParent = {
792
+ ...parent,
793
+ status: "[x] CLOSED",
794
+ updated: TODAY_ISO()
795
+ };
796
+ node_fs.writeFileSync(updatedParent.filePath, serializeCanonicalTask(updatedParent), "utf-8");
797
+ return `
798
+ - Auto-completed parent task **${updatedParent.id}** (all ${subtasks.length} subtask(s) closed)`;
799
+ }
800
+ function findActiveTaskById(root, idInput) {
801
+ if (!idInput) return null;
802
+ const target = extractIdParts(idInput).id.toUpperCase();
803
+ const active = loadActiveTasks(root);
804
+ return active.find((t) => t.id.toUpperCase() === target) || null;
805
+ }
806
+ function handleWorkflowTask(rawArgs, defaultCwd) {
807
+ const parsedArgs = WorkflowTaskSchema.safeParse(rawArgs);
808
+ if (!parsedArgs.success) {
809
+ return errorResult$1(`Schema validation error: ${parsedArgs.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ")}`);
810
+ }
811
+ const args = parsedArgs.data;
812
+ let root;
813
+ try {
814
+ root = mcpCore.assertSafeWorkspace(args.cwd || defaultCwd);
815
+ } catch (error) {
816
+ return errorResult$1(`Workspace security error: ${error instanceof Error ? error.message : String(error)}`);
817
+ }
818
+ const { tasksDir, archiveDir } = getTodoPaths(root);
819
+ if (args.action === "create") {
820
+ if (args.id !== void 0 && args.id.trim() !== "") {
821
+ return errorResult$1(
822
+ 'Validation error: "id" must not be provided for action="create". Task ID and filename (<ID>-<slug>.md) are allocated automatically from "prefix" and "title".'
823
+ );
824
+ }
825
+ if (!args.title?.trim()) return errorResult$1('Validation error: "title" is required for action="create".');
826
+ if (!args.problem?.trim()) return errorResult$1('Validation error: "problem" is required for action="create".');
827
+ const scopeText = normalizeScope(args.scope);
828
+ if (!scopeText) return errorResult$1('Validation error: "scope" is required for action="create".');
829
+ if (!args.acceptanceCriteria || args.acceptanceCriteria.length === 0) {
830
+ return errorResult$1('Validation error: At least one entry in "acceptanceCriteria" is required for action="create".');
831
+ }
832
+ const status = args.status !== void 0 ? args.status.trim() : "[ ] TODO";
833
+ if (!validateCanonicalStatusExact(status)) {
834
+ return errorResult$1(`Invalid status "${status}". Allowed canonical statuses: ${CANONICAL_TASK_STATUSES.map((s) => `"${s}"`).join(", ")}.`);
835
+ }
836
+ const id = allocateNextTaskId(root, args.prefix || "TASK", args.parentId);
837
+ const criteria = normalizeCriteriaList(args.acceptanceCriteria);
838
+ const { prefix, numericId } = extractIdParts(id);
839
+ const fileName = `${id}-${slugifyTitle(args.title)}.md`;
840
+ const absFile = node_path.resolve(tasksDir, fileName);
841
+ if (!mcpCore.isDescendantOf(tasksDir, absFile)) {
842
+ return errorResult$1(`Security error: Invalid task path "${absFile}".`);
843
+ }
844
+ const task = {
845
+ id,
846
+ title: args.title.trim(),
847
+ relPath: `todo/tasks/${fileName}`,
848
+ priority: formatCanonicalPriority(args.priority),
849
+ type: args.type?.trim(),
850
+ created: TODAY_ISO(),
851
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
852
+ closedAt: status === "[x] CLOSED" ? (/* @__PURE__ */ new Date()).toISOString() : void 0,
853
+ tokensSpent: args.tokensSpent,
854
+ status,
855
+ dependencies: args.dependencies?.trim(),
856
+ milestone: args.milestone?.trim(),
857
+ component: args.component?.trim(),
858
+ problem: args.problem.trim(),
859
+ scope: scopeText,
860
+ acceptanceCriteria: criteria,
861
+ extraSections: args.notes?.trim() ? [{ heading: "Notes", body: args.notes.trim() }] : []};
862
+ const closeError = enforceCloseGate(task, status);
863
+ if (closeError) return errorResult$1(closeError);
864
+ const concernError = enforceOneTaskOneConcernGate(task);
865
+ if (concernError) return errorResult$1(concernError);
866
+ node_fs.mkdirSync(tasksDir, { recursive: true });
867
+ node_fs.writeFileSync(absFile, serializeCanonicalTask(task), "utf-8");
868
+ syncTodoIndex(root);
869
+ return {
870
+ content: [
871
+ {
872
+ type: "text",
873
+ text: `Created task **${task.id}**: ${task.title}
874
+ - File: \`${task.relPath}\`
875
+ - Status: \`${task.status}\`
876
+ - Criteria: ${task.acceptanceCriteria.filter((c) => c.checked).length}/${task.acceptanceCriteria.length} checked
877
+ - Updated \`todo/INDEX.md\``
878
+ }
879
+ ]
880
+ };
881
+ }
882
+ if (!args.id) {
883
+ return errorResult$1(`Validation error: "id" is required for action="${args.action}".`);
884
+ }
885
+ const existing = findActiveTaskById(root, args.id);
886
+ if (!existing) {
887
+ return errorResult$1(`Task "${args.id}" was not found in todo/tasks/. Use katlux_workflow_inspect (action="list" or "archive") to verify task location.`);
888
+ }
889
+ if (args.action === "update") {
890
+ const updated = {
891
+ ...existing,
892
+ title: args.title?.trim() || existing.title,
893
+ priority: args.priority !== void 0 ? formatCanonicalPriority(args.priority) : existing.priority,
894
+ type: args.type !== void 0 ? args.type.trim() || void 0 : existing.type,
895
+ dependencies: args.dependencies !== void 0 ? args.dependencies.trim() || void 0 : existing.dependencies,
896
+ milestone: args.milestone !== void 0 ? args.milestone.trim() || void 0 : existing.milestone,
897
+ component: args.component !== void 0 ? args.component.trim() || void 0 : existing.component,
898
+ problem: args.problem !== void 0 ? args.problem.trim() : existing.problem,
899
+ scope: args.scope !== void 0 ? normalizeScope(args.scope) : existing.scope,
900
+ updated: TODAY_ISO(),
901
+ acceptanceCriteria: existing.acceptanceCriteria.map((c) => ({ ...c })),
902
+ extraSections: existing.extraSections.map((s) => ({ ...s }))
903
+ };
904
+ if (args.notes !== void 0) {
905
+ const noteIdx = updated.extraSections.findIndex((s) => s.heading.toLowerCase() === "notes");
906
+ if (noteIdx >= 0) {
907
+ updated.extraSections[noteIdx].body = args.notes.trim();
908
+ } else if (args.notes.trim()) {
909
+ updated.extraSections.push({ heading: "Notes", body: args.notes.trim() });
910
+ }
911
+ }
912
+ if (args.addCriteria && args.addCriteria.length > 0) {
913
+ for (const item of args.addCriteria) {
914
+ const normalized = typeof item === "string" ? { text: item.trim(), checked: false } : { text: item.text.trim(), checked: Boolean(item.checked) };
915
+ updated.acceptanceCriteria.push({
916
+ index: updated.acceptanceCriteria.length,
917
+ checked: normalized.checked,
918
+ text: normalized.text
919
+ });
920
+ }
921
+ }
922
+ if (args.criteriaUpdates && args.criteriaUpdates.length > 0) {
923
+ for (const cu of args.criteriaUpdates) {
924
+ if (cu.index !== void 0) {
925
+ const target = updated.acceptanceCriteria[cu.index];
926
+ if (!target) {
927
+ return errorResult$1(`Criterion index ${cu.index} out of bounds for ${updated.id} (0..${updated.acceptanceCriteria.length - 1}).`);
928
+ }
929
+ target.checked = cu.checked;
930
+ } else if (cu.match) {
931
+ const needle = cu.match.toLowerCase();
932
+ const matches = updated.acceptanceCriteria.filter((c) => c.text.toLowerCase().includes(needle));
933
+ if (matches.length === 0) {
934
+ return errorResult$1(`No acceptance criterion matched substring "${cu.match}" on ${updated.id}.`);
935
+ }
936
+ for (const m of matches) m.checked = cu.checked;
937
+ }
938
+ }
939
+ }
940
+ if (args.status !== void 0) {
941
+ const candidateStatus = args.status.trim();
942
+ if (!validateCanonicalStatusExact(candidateStatus)) {
943
+ return errorResult$1(`Invalid status "${args.status}". Allowed canonical statuses: ${CANONICAL_TASK_STATUSES.map((s) => `"${s}"`).join(", ")}.`);
944
+ }
945
+ const closeError = enforceCloseGate(updated, candidateStatus);
946
+ if (closeError) return errorResult$1(closeError);
947
+ if (candidateStatus === "[x] CLOSED") {
948
+ const gateError = runCompletionGates(root, args.runCheck, args.runTest);
949
+ if (gateError) return errorResult$1(gateError);
950
+ updated.closedAt = (/* @__PURE__ */ new Date()).toISOString();
951
+ }
952
+ if (args.tokensSpent !== void 0) {
953
+ updated.tokensSpent = args.tokensSpent;
954
+ }
955
+ updated.status = candidateStatus;
956
+ updated.statusIsCanonical = true;
957
+ } else {
958
+ updated.status = normalizeTaskStatus(updated.status) || updated.status;
959
+ }
960
+ if (args.addCriteria?.length || args.scope !== void 0 || args.problem !== void 0) {
961
+ const concernError = enforceOneTaskOneConcernGate(updated);
962
+ if (concernError) return errorResult$1(concernError);
963
+ }
964
+ node_fs.writeFileSync(updated.filePath, serializeCanonicalTask(updated), "utf-8");
965
+ const autoCompletedNote = maybeAutoCompleteParentTask(root, updated);
966
+ syncTodoIndex(root);
967
+ const checkedCount = updated.acceptanceCriteria.filter((c) => c.checked).length;
968
+ return {
969
+ content: [
970
+ {
971
+ type: "text",
972
+ text: `Updated task **${updated.id}**: ${updated.title}
973
+ - File: \`${updated.relPath}\`
974
+ - Status: \`${updated.status}\`
975
+ - Criteria: ${checkedCount}/${updated.acceptanceCriteria.length} checked
976
+ - Updated \`todo/INDEX.md\`${autoCompletedNote}`
977
+ }
978
+ ]
979
+ };
980
+ }
981
+ if (args.action === "transition") {
982
+ if (!args.status) {
983
+ return errorResult$1('Validation error: "status" is required for action="transition".');
984
+ }
985
+ const targetStatus = args.status.trim();
986
+ if (!validateCanonicalStatusExact(targetStatus)) {
987
+ return errorResult$1(`Invalid status "${args.status}". Allowed canonical statuses: ${CANONICAL_TASK_STATUSES.map((s) => `"${s}"`).join(", ")}.`);
988
+ }
989
+ const closeError = enforceCloseGate(existing, targetStatus);
990
+ if (closeError) return errorResult$1(closeError);
991
+ if (targetStatus === "[x] CLOSED") {
992
+ const gateError = runCompletionGates(root, args.runCheck, args.runTest);
993
+ if (gateError) return errorResult$1(gateError);
994
+ }
995
+ const updated = {
996
+ ...existing,
997
+ status: targetStatus,
998
+ updated: TODAY_ISO(),
999
+ ...targetStatus === "[x] CLOSED" ? { closedAt: (/* @__PURE__ */ new Date()).toISOString() } : {},
1000
+ ...args.tokensSpent !== void 0 ? { tokensSpent: args.tokensSpent } : {}
1001
+ };
1002
+ node_fs.writeFileSync(updated.filePath, serializeCanonicalTask(updated), "utf-8");
1003
+ const autoCompletedNote = maybeAutoCompleteParentTask(root, updated);
1004
+ syncTodoIndex(root);
1005
+ return {
1006
+ content: [
1007
+ {
1008
+ type: "text",
1009
+ text: `Transitioned **${updated.id}** to \`${updated.status}\`
1010
+ - File: \`${updated.relPath}\`
1011
+ - Updated \`todo/INDEX.md\`${autoCompletedNote}`
1012
+ }
1013
+ ]
1014
+ };
1015
+ }
1016
+ const milestone = args.milestone?.trim().replace(/[^a-zA-Z0-9._-]/g, "-").replace(/^-+|-+$/g, "");
1017
+ if (!milestone) {
1018
+ return errorResult$1('Validation error: "milestone" (e.g. "sprint-04" or "alpha-25") is required for action="archive".');
1019
+ }
1020
+ const currentCanonical = normalizeTaskStatus(existing.status);
1021
+ if (!args.force && currentCanonical !== "[x] CLOSED") {
1022
+ return errorResult$1(`Archive blocked ${existing.id}: Task status is "${existing.status}" instead of "[x] CLOSED". Transition to "[x] CLOSED" first (or pass force: true).`);
1023
+ }
1024
+ const targetDir = node_path.resolve(archiveDir, milestone, "tasks");
1025
+ const destPath = node_path.resolve(targetDir, node_path.basename(existing.filePath));
1026
+ if (!mcpCore.isDescendantOf(archiveDir, destPath)) {
1027
+ return errorResult$1(`Security error: Invalid archive destination "${destPath}".`);
1028
+ }
1029
+ node_fs.mkdirSync(targetDir, { recursive: true });
1030
+ const contentToArchive = node_fs.readFileSync(existing.filePath, "utf-8");
1031
+ node_fs.writeFileSync(destPath, contentToArchive, "utf-8");
1032
+ if (node_fs.existsSync(existing.filePath) && existing.filePath !== destPath) {
1033
+ node_fs.unlinkSync(existing.filePath);
1034
+ }
1035
+ syncArchiveMilestoneIndex(root, milestone);
1036
+ syncTodoIndex(root);
1037
+ return {
1038
+ content: [
1039
+ {
1040
+ type: "text",
1041
+ text: `Archived **${existing.id}** to \`todo/archive/${milestone}/tasks/${node_path.basename(existing.filePath)}\`
1042
+ - Updated \`todo/archive/${milestone}/INDEX.md\`
1043
+ - Removed from active queue in \`todo/INDEX.md\``
1044
+ }
1045
+ ]
1046
+ };
1047
+ }
1048
+
1049
+ const WorkflowInspectSchema = zod.z.object({
1050
+ cwd: zod.z.string().optional(),
1051
+ action: zod.z.enum(["list", "get", "archive", "doctor"]),
1052
+ id: zod.z.string().optional(),
1053
+ status: zod.z.string().optional(),
1054
+ priority: zod.z.string().optional(),
1055
+ type: zod.z.string().optional(),
1056
+ milestone: zod.z.string().optional(),
1057
+ relatedTask: zod.z.string().optional(),
1058
+ component: zod.z.string().optional(),
1059
+ createdAfter: zod.z.string().optional(),
1060
+ createdBefore: zod.z.string().optional(),
1061
+ closedAfter: zod.z.string().optional(),
1062
+ closedBefore: zod.z.string().optional(),
1063
+ minTokens: zod.z.number().min(0).optional(),
1064
+ maxTokens: zod.z.number().min(0).optional(),
1065
+ sortBy: zod.z.enum(["id", "priority", "status", "milestone"]).optional(),
1066
+ limit: zod.z.number().int().min(1).max(500).optional(),
1067
+ repair: zod.z.boolean().optional()
1068
+ });
1069
+ function getPriorityRank(priority) {
1070
+ const p = (priority || "").toLowerCase();
1071
+ if (/\bp0\b/.test(p) || p.includes("critical") || p.includes("urgent") || p.includes("blocker")) return 0;
1072
+ if (/\bp1\b/.test(p) || p.includes("high")) return 1;
1073
+ if (/\bp2\b/.test(p) || p.includes("medium")) return 2;
1074
+ if (/\bp3\b/.test(p) || p.includes("low")) return 3;
1075
+ return 4;
1076
+ }
1077
+ function matchesPriorityFilter(taskPriority, filterRaw) {
1078
+ const tp = (taskPriority || "").toLowerCase();
1079
+ const fp = filterRaw.trim().toLowerCase();
1080
+ if (!fp) return true;
1081
+ if (tp.includes(fp)) return true;
1082
+ const filterRank = getPriorityRank(fp);
1083
+ return filterRank < 4 && getPriorityRank(tp) === filterRank;
1084
+ }
1085
+ function errorResult(message) {
1086
+ return {
1087
+ isError: true,
1088
+ content: [{ type: "text", text: message }]
1089
+ };
1090
+ }
1091
+ function untrustedTextResult(text) {
1092
+ return {
1093
+ content: [
1094
+ {
1095
+ type: "text",
1096
+ text,
1097
+ annotations: { audience: ["assistant"] },
1098
+ _meta: { untrustedWorkspaceContent: true, contentOrigin: "workspace" }
1099
+ }
1100
+ ]
1101
+ };
1102
+ }
1103
+ async function handleWorkflowInspect(rawArgs, defaultCwd, _hostCtx) {
1104
+ const parsed = WorkflowInspectSchema.safeParse(rawArgs);
1105
+ if (!parsed.success) {
1106
+ return errorResult(`Schema validation error: ${parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ")}`);
1107
+ }
1108
+ const args = parsed.data;
1109
+ let root;
1110
+ try {
1111
+ root = mcpCore.assertSafeWorkspace(args.cwd || defaultCwd);
1112
+ } catch (error) {
1113
+ return errorResult(`Workspace security error: ${error instanceof Error ? error.message : String(error)}`);
1114
+ }
1115
+ const { todoDir, indexPath } = getTodoPaths(root);
1116
+ if (args.action === "list") {
1117
+ let tasks = loadActiveTasks(root);
1118
+ if (node_fs.existsSync(indexPath)) {
1119
+ const indexRows = parseTodoIndexRows(node_fs.readFileSync(indexPath, "utf-8"));
1120
+ const rowById = new Map(indexRows.map((r) => [r.id.toUpperCase(), r]));
1121
+ tasks = tasks.map((t) => {
1122
+ const row = rowById.get(t.id.toUpperCase());
1123
+ if (row && normalizeTaskStatus(t.status) === "[ ] TODO" && normalizeTaskStatus(row.status) === "PAUSED (Feature Freeze)") {
1124
+ return { ...t, status: "PAUSED (Feature Freeze)" };
1125
+ }
1126
+ return t;
1127
+ });
1128
+ }
1129
+ if (args.status) {
1130
+ const filterRaw = args.status.trim().toLowerCase();
1131
+ if (filterRaw === "open" || filterRaw === "active") {
1132
+ tasks = tasks.filter((t) => normalizeTaskStatus(t.status) !== "[x] CLOSED");
1133
+ } else {
1134
+ const targetStatus = normalizeTaskStatus(args.status) || args.status.trim();
1135
+ tasks = tasks.filter(
1136
+ (t) => (normalizeTaskStatus(t.status) || t.status).toLowerCase() === targetStatus.toLowerCase() || String(t.status).toLowerCase().includes(filterRaw)
1137
+ );
1138
+ }
1139
+ }
1140
+ if (args.priority) {
1141
+ tasks = tasks.filter((t) => matchesPriorityFilter(t.priority, args.priority));
1142
+ }
1143
+ if (args.milestone) {
1144
+ const m = args.milestone.trim().toLowerCase();
1145
+ tasks = tasks.filter((t) => (t.milestone || "").toLowerCase().includes(m));
1146
+ }
1147
+ if (args.relatedTask) {
1148
+ const relNeedle = args.relatedTask.trim().toLowerCase().replace(/^\[|\]$/g, "");
1149
+ tasks = tasks.filter((t) => (t.dependencies || "").toLowerCase().includes(relNeedle));
1150
+ }
1151
+ if (args.component) {
1152
+ const compNeedle = args.component.trim().toLowerCase();
1153
+ tasks = tasks.filter((t) => (t.component || "").toLowerCase().includes(compNeedle));
1154
+ }
1155
+ if (args.type) {
1156
+ const ty = args.type.trim().toLowerCase();
1157
+ tasks = tasks.filter((t) => (t.type || "").toLowerCase().includes(ty));
1158
+ }
1159
+ if (args.createdAfter) {
1160
+ const afterMs = Date.parse(args.createdAfter);
1161
+ if (!Number.isNaN(afterMs)) {
1162
+ tasks = tasks.filter((t) => {
1163
+ const ts = Date.parse(t.createdAt || t.created);
1164
+ return !Number.isNaN(ts) && ts >= afterMs;
1165
+ });
1166
+ }
1167
+ }
1168
+ if (args.createdBefore) {
1169
+ const beforeMs = Date.parse(args.createdBefore);
1170
+ if (!Number.isNaN(beforeMs)) {
1171
+ tasks = tasks.filter((t) => {
1172
+ const ts = Date.parse(t.createdAt || t.created);
1173
+ return !Number.isNaN(ts) && ts <= beforeMs;
1174
+ });
1175
+ }
1176
+ }
1177
+ if (args.closedAfter) {
1178
+ const afterMs = Date.parse(args.closedAfter);
1179
+ if (!Number.isNaN(afterMs)) {
1180
+ tasks = tasks.filter((t) => {
1181
+ if (!t.closedAt) return false;
1182
+ const ts = Date.parse(t.closedAt);
1183
+ return !Number.isNaN(ts) && ts >= afterMs;
1184
+ });
1185
+ }
1186
+ }
1187
+ if (args.closedBefore) {
1188
+ const beforeMs = Date.parse(args.closedBefore);
1189
+ if (!Number.isNaN(beforeMs)) {
1190
+ tasks = tasks.filter((t) => {
1191
+ if (!t.closedAt) return false;
1192
+ const ts = Date.parse(t.closedAt);
1193
+ return !Number.isNaN(ts) && ts <= beforeMs;
1194
+ });
1195
+ }
1196
+ }
1197
+ if (args.minTokens !== void 0) {
1198
+ tasks = tasks.filter((t) => t.tokensSpent !== void 0 && t.tokensSpent >= args.minTokens);
1199
+ }
1200
+ if (args.maxTokens !== void 0) {
1201
+ tasks = tasks.filter((t) => t.tokensSpent !== void 0 && t.tokensSpent <= args.maxTokens);
1202
+ }
1203
+ const sortBy = args.sortBy || "id";
1204
+ tasks.sort((a, b) => {
1205
+ if (sortBy === "priority") {
1206
+ const diff = getPriorityRank(a.priority) - getPriorityRank(b.priority);
1207
+ if (diff !== 0) return diff;
1208
+ } else if (sortBy === "status") {
1209
+ const diff = String(a.status).localeCompare(String(b.status));
1210
+ if (diff !== 0) return diff;
1211
+ } else if (sortBy === "milestone") {
1212
+ const diff = String(a.milestone || "zzz").localeCompare(String(b.milestone || "zzz"));
1213
+ if (diff !== 0) return diff;
1214
+ }
1215
+ return a.numericId - b.numericId || a.id.localeCompare(b.id);
1216
+ });
1217
+ if (args.limit) tasks = tasks.slice(0, args.limit);
1218
+ const lines2 = [
1219
+ `Active Tasks (${tasks.length}):`,
1220
+ ...tasks.length > 0 ? tasks.map((t) => `- ${t.id}: ${t.title}`) : ["- _No matching tasks in `todo/tasks/`._"],
1221
+ `Hint: Call katlux_workflow_inspect({ action: "get", id: "<ID>" }) for full task details.`
1222
+ ];
1223
+ return untrustedTextResult(lines2.join("\n"));
1224
+ }
1225
+ if (args.action === "get") {
1226
+ if (!args.id) return errorResult('Validation error: "id" is required for action="get".');
1227
+ const target = extractIdParts(args.id).id.toUpperCase();
1228
+ const active = loadActiveTasks(root);
1229
+ const foundActive = active.find((t) => t.id.toUpperCase() === target);
1230
+ if (foundActive) {
1231
+ const checked = foundActive.acceptanceCriteria.filter((c) => c.checked).length;
1232
+ const criteriaLines = foundActive.acceptanceCriteria.map(
1233
+ (c) => `- [${c.checked ? "x" : " "}] [${c.index}] ${c.text}`
1234
+ );
1235
+ const lines2 = [
1236
+ `## ${foundActive.id}: ${foundActive.title}`,
1237
+ "",
1238
+ `- **Location**: Active (\`${foundActive.relPath}\`)`,
1239
+ `- **Priority**: ${foundActive.priority}`,
1240
+ ...foundActive.type ? [`- **Type**: ${foundActive.type}`] : [],
1241
+ `- **Status**: \`${foundActive.status}\``,
1242
+ ...foundActive.milestone ? [`- **Target Milestone**: \`${foundActive.milestone}\``] : [],
1243
+ ...foundActive.component ? [`- **Component / Package**: ${foundActive.component}`] : [],
1244
+ `- **Created**: ${foundActive.created}`,
1245
+ ...foundActive.updated ? [`- **Updated**: ${foundActive.updated}`] : [],
1246
+ ...foundActive.dependencies ? [`- **Related Tasks / Dependencies**: ${foundActive.dependencies}`] : [],
1247
+ `- **Legacy Format**: ${foundActive.legacyFormat ? `yes (${foundActive.formatIssues.join("; ")})` : "no"}`,
1248
+ "",
1249
+ "### Problem Statement",
1250
+ foundActive.problem || "_None_",
1251
+ "",
1252
+ "### Implementation Scope",
1253
+ foundActive.scope || "_None_",
1254
+ "",
1255
+ `### Acceptance Criteria (${checked}/${foundActive.acceptanceCriteria.length})`,
1256
+ ...criteriaLines.length > 0 ? criteriaLines : ["_No acceptance criteria defined._"]
1257
+ ];
1258
+ return untrustedTextResult(lines2.join("\n"));
1259
+ }
1260
+ const archived = loadArchiveEntries(root);
1261
+ const foundArchived = archived.find((a) => a.id.toUpperCase() === target);
1262
+ if (foundArchived) {
1263
+ const abs = node_path.resolve(root, foundArchived.relPath);
1264
+ const raw = node_fs.readFileSync(abs, "utf-8");
1265
+ const parsedArchive = parseTaskMarkdown(raw, abs, foundArchived.relPath);
1266
+ const lines2 = [
1267
+ `## ${foundArchived.id}: ${foundArchived.title}${foundArchived.legacyFormat ? " `[legacy format]`" : ""}`,
1268
+ "",
1269
+ `- **Location**: Archived (\`${foundArchived.relPath}\`, milestone \`${foundArchived.milestone}\`)`,
1270
+ `- **Status**: \`${foundArchived.status}\``,
1271
+ `- **Priority**: ${foundArchived.priority || "Unknown"}`,
1272
+ `- **Criteria**: ${foundArchived.checkedCount}/${foundArchived.totalCount}`,
1273
+ ...foundArchived.formatIssues.length > 0 ? [`- **Format Notes**: ${foundArchived.formatIssues.join("; ")}`] : [],
1274
+ "",
1275
+ "### Problem Statement",
1276
+ parsedArchive.problem || "_None_"
1277
+ ];
1278
+ return untrustedTextResult(lines2.join("\n"));
1279
+ }
1280
+ return errorResult(`Task "${args.id}" was not found in todo/tasks/ or todo/archive/.`);
1281
+ }
1282
+ if (args.action === "archive") {
1283
+ let entries = loadArchiveEntries(root);
1284
+ if (args.milestone) {
1285
+ const m = args.milestone.trim().toLowerCase();
1286
+ entries = entries.filter((e) => e.milestone.toLowerCase() === m);
1287
+ }
1288
+ entries.sort((a, b) => b.numericId - a.numericId || a.id.localeCompare(b.id));
1289
+ if (args.limit) entries = entries.slice(0, args.limit);
1290
+ const legacyCount = entries.filter((e) => e.legacyFormat).length;
1291
+ const lines2 = [
1292
+ `## Archived Tasks (${entries.length} indexed, ${legacyCount} legacy format)`,
1293
+ "",
1294
+ "| ID | Milestone | Title | Status | Format | File |",
1295
+ "| :--- | :--- | :--- | :--- | :--- | :--- |",
1296
+ ...entries.map((e) => {
1297
+ const tag = e.legacyFormat ? "`[legacy format]`" : "canonical";
1298
+ return `| ${e.id} | ${e.milestone} | ${e.title} | ${e.status} | ${tag} | \`${e.relPath}\` |`;
1299
+ })
1300
+ ];
1301
+ if (entries.length === 0) {
1302
+ lines2.push("| - | - | _No archived task files found under `todo/archive/`._ | - | - | - |");
1303
+ }
1304
+ return untrustedTextResult(lines2.join("\n"));
1305
+ }
1306
+ const repair = Boolean(args.repair);
1307
+ const issues = [];
1308
+ let repairedCount = 0;
1309
+ const activeTasks = loadActiveTasks(root);
1310
+ const archiveEntries = loadArchiveEntries(root);
1311
+ for (const task of activeTasks) {
1312
+ let needsRewrite = false;
1313
+ const nextTask = { ...task };
1314
+ if (!task.statusIsCanonical) {
1315
+ const mapped = normalizeTaskStatus(task.status);
1316
+ const issue = {
1317
+ severity: "error",
1318
+ code: "INVALID_STATUS",
1319
+ taskId: task.id,
1320
+ file: task.relPath,
1321
+ message: `Non-canonical status "${task.status}"${mapped ? ` (can normalize to "${mapped}")` : ""}.`,
1322
+ repaired: false
1323
+ };
1324
+ if (repair) {
1325
+ nextTask.status = mapped || "[ ] TODO";
1326
+ nextTask.statusIsCanonical = true;
1327
+ needsRewrite = true;
1328
+ issue.repaired = true;
1329
+ repairedCount++;
1330
+ }
1331
+ issues.push(issue);
1332
+ }
1333
+ const headerIssues = task.formatIssues.filter(
1334
+ (msg) => msg.includes("metadata table") || msg.includes("top-level #") || msg.includes("Missing **Status:**") || msg.includes('should be "##')
1335
+ );
1336
+ if (headerIssues.length > 0) {
1337
+ const issue = {
1338
+ severity: "warning",
1339
+ code: "LEGACY_HEADER",
1340
+ taskId: task.id,
1341
+ file: task.relPath,
1342
+ message: headerIssues.join("; "),
1343
+ repaired: false
1344
+ };
1345
+ if (repair) {
1346
+ needsRewrite = true;
1347
+ issue.repaired = true;
1348
+ repairedCount++;
1349
+ }
1350
+ issues.push(issue);
1351
+ }
1352
+ const missingSectionIssues = task.formatIssues.filter((msg) => msg.startsWith('Missing "##'));
1353
+ if (missingSectionIssues.length > 0) {
1354
+ const issue = {
1355
+ severity: "warning",
1356
+ code: "MISSING_SECTION",
1357
+ taskId: task.id,
1358
+ file: task.relPath,
1359
+ message: missingSectionIssues.join("; "),
1360
+ repaired: false
1361
+ };
1362
+ if (repair) {
1363
+ needsRewrite = true;
1364
+ issue.repaired = true;
1365
+ repairedCount++;
1366
+ }
1367
+ issues.push(issue);
1368
+ }
1369
+ if (needsRewrite && repair) {
1370
+ node_fs.writeFileSync(task.filePath, serializeCanonicalTask(nextTask), "utf-8");
1371
+ }
1372
+ for (const refPath of task.backtickPaths) {
1373
+ if (refPath.includes("*") || refPath.includes("<") || refPath.includes("{")) continue;
1374
+ const absRef = node_path.resolve(root, refPath);
1375
+ if (!mcpCore.isDescendantOf(root, absRef)) continue;
1376
+ if (!node_fs.existsSync(absRef)) {
1377
+ issues.push({
1378
+ severity: "warning",
1379
+ code: "STALE_FILE_REF",
1380
+ taskId: task.id,
1381
+ file: task.relPath,
1382
+ message: `Referenced path \`${refPath}\` does not exist in workspace.`
1383
+ });
1384
+ }
1385
+ }
1386
+ }
1387
+ const seenActiveIds = /* @__PURE__ */ new Map();
1388
+ for (const t of activeTasks) {
1389
+ const list = seenActiveIds.get(t.id) || [];
1390
+ list.push(t.relPath);
1391
+ seenActiveIds.set(t.id, list);
1392
+ }
1393
+ const archiveIdSet = /* @__PURE__ */ new Map();
1394
+ for (const a of archiveEntries) {
1395
+ if (!archiveIdSet.has(a.id)) archiveIdSet.set(a.id, a.relPath);
1396
+ }
1397
+ for (const [id, paths] of seenActiveIds.entries()) {
1398
+ if (paths.length > 1) {
1399
+ issues.push({
1400
+ severity: "error",
1401
+ code: "DUPLICATE_ID",
1402
+ taskId: id,
1403
+ file: paths.join(", "),
1404
+ message: `Duplicate active task ID "${id}" across ${paths.length} files.`
1405
+ });
1406
+ }
1407
+ if (archiveIdSet.has(id)) {
1408
+ issues.push({
1409
+ severity: "error",
1410
+ code: "DUPLICATE_ID",
1411
+ taskId: id,
1412
+ file: paths[0],
1413
+ message: `Active task ID "${id}" collides with archived task \`${archiveIdSet.get(id)}\`.`
1414
+ });
1415
+ }
1416
+ }
1417
+ const reloadedActive = repair ? loadActiveTasks(root) : activeTasks;
1418
+ let indexNeedsSync = false;
1419
+ if (!node_fs.existsSync(indexPath)) {
1420
+ const issue = {
1421
+ severity: "error",
1422
+ code: "INDEX_MISSING_TASK",
1423
+ file: "todo/INDEX.md",
1424
+ message: "todo/INDEX.md does not exist.",
1425
+ repaired: false
1426
+ };
1427
+ if (repair) {
1428
+ indexNeedsSync = true;
1429
+ issue.repaired = true;
1430
+ repairedCount++;
1431
+ }
1432
+ issues.push(issue);
1433
+ } else {
1434
+ const indexRows = parseTodoIndexRows(node_fs.readFileSync(indexPath, "utf-8"));
1435
+ const activeById = new Map(reloadedActive.map((t) => [t.id.toUpperCase(), t]));
1436
+ const indexedIds = /* @__PURE__ */ new Set();
1437
+ for (const row of indexRows) {
1438
+ const upperId = row.id.toUpperCase();
1439
+ indexedIds.add(upperId);
1440
+ const resolvedLink = row.linkPath ? node_path.resolve(todoDir, row.linkPath) : "";
1441
+ const matchingTask = activeById.get(upperId);
1442
+ if (!matchingTask || row.linkPath && !node_fs.existsSync(resolvedLink)) {
1443
+ const issue = {
1444
+ severity: "error",
1445
+ code: "INDEX_STALE_PATH",
1446
+ taskId: row.id,
1447
+ file: "todo/INDEX.md",
1448
+ message: `Index row "${row.id}" points to missing or archived file "${row.linkPath || "(no link)"}" at line ${row.rawLine}.`,
1449
+ repaired: false
1450
+ };
1451
+ if (repair) {
1452
+ indexNeedsSync = true;
1453
+ issue.repaired = true;
1454
+ repairedCount++;
1455
+ }
1456
+ issues.push(issue);
1457
+ continue;
1458
+ }
1459
+ const cleanRowStatus = normalizeTaskStatus(row.status.replace(/\*\*/g, ""));
1460
+ const cleanTaskStatus = normalizeTaskStatus(matchingTask.status);
1461
+ if (cleanRowStatus !== cleanTaskStatus || row.priority && row.priority !== matchingTask.priority) {
1462
+ const issue = {
1463
+ severity: "warning",
1464
+ code: "INDEX_METADATA_MISMATCH",
1465
+ taskId: row.id,
1466
+ file: "todo/INDEX.md",
1467
+ message: `Index row "${row.id}" metadata (${row.priority} / ${row.status}) differs from task file (${matchingTask.priority} / ${matchingTask.status}).`,
1468
+ repaired: false
1469
+ };
1470
+ if (repair) {
1471
+ indexNeedsSync = true;
1472
+ issue.repaired = true;
1473
+ repairedCount++;
1474
+ }
1475
+ issues.push(issue);
1476
+ }
1477
+ }
1478
+ for (const t of reloadedActive) {
1479
+ if (!indexedIds.has(t.id.toUpperCase())) {
1480
+ const issue = {
1481
+ severity: "error",
1482
+ code: "INDEX_MISSING_TASK",
1483
+ taskId: t.id,
1484
+ file: t.relPath,
1485
+ message: `Active task "${t.id}" is missing from todo/INDEX.md.`,
1486
+ repaired: false
1487
+ };
1488
+ if (repair) {
1489
+ indexNeedsSync = true;
1490
+ issue.repaired = true;
1491
+ repairedCount++;
1492
+ }
1493
+ issues.push(issue);
1494
+ }
1495
+ }
1496
+ }
1497
+ if (repair && indexNeedsSync) {
1498
+ syncTodoIndex(root, reloadedActive);
1499
+ }
1500
+ if (_hostCtx?.getWorkspaceIndex) {
1501
+ try {
1502
+ const wsIndex = await _hostCtx.getWorkspaceIndex(root);
1503
+ const testSummary = wsIndex.testSummary;
1504
+ if (testSummary) {
1505
+ for (const unmatched of testSummary.unmatchedBddSteps) {
1506
+ issues.push({
1507
+ severity: "warning",
1508
+ code: "UNMATCHED_BDD_STEP",
1509
+ file: `${unmatched.featureFile}:${unmatched.line}`,
1510
+ message: `Unmatched BDD step in Scenario "${unmatched.scenarioTitle}": ${unmatched.keyword} "${unmatched.text}".`
1511
+ });
1512
+ }
1513
+ if (testSummary.totalTestFiles > 0 && testSummary.untestedSourceFiles.length > 0) {
1514
+ const untestedSet = new Set(testSummary.untestedSourceFiles);
1515
+ for (const task of reloadedActive) {
1516
+ if (normalizeTaskStatus(task.status) === "[x] CLOSED") continue;
1517
+ for (const refPath of task.backtickPaths) {
1518
+ const normRef = refPath.replace(/\\/g, "/").replace(/^\.\//, "");
1519
+ if (untestedSet.has(normRef)) {
1520
+ issues.push({
1521
+ severity: "warning",
1522
+ code: "UNTESTED_TASK_FILE",
1523
+ taskId: task.id,
1524
+ file: normRef,
1525
+ message: `Source file \`${normRef}\` referenced by ${task.id} has 0 linked test files.`
1526
+ });
1527
+ }
1528
+ }
1529
+ }
1530
+ }
1531
+ }
1532
+ } catch {
1533
+ }
1534
+ }
1535
+ const report = {
1536
+ healthy: issues.length === 0,
1537
+ checkedActiveTasks: activeTasks.length,
1538
+ checkedArchiveFiles: archiveEntries.length,
1539
+ issues,
1540
+ repairedCount
1541
+ };
1542
+ const lines = [
1543
+ `## Workflow Doctor Report (${report.healthy ? "Healthy" : `${report.issues.length} issue(s) found`})`,
1544
+ "",
1545
+ `- **Active Tasks Scanned**: ${report.checkedActiveTasks}`,
1546
+ `- **Archive Files Indexed**: ${report.checkedArchiveFiles} (historical archive files are read-only and never rewritten by repair)`,
1547
+ `- **Issues Found**: ${report.issues.length}`,
1548
+ ...repair ? [`- **Issues Repaired**: ${report.repairedCount}`] : [],
1549
+ ""
1550
+ ];
1551
+ if (issues.length > 0) {
1552
+ lines.push("| Code | Severity | Task | File | Repaired | Details |");
1553
+ lines.push("| :--- | :--- | :--- | :--- | :--- | :--- |");
1554
+ for (const iss of issues) {
1555
+ lines.push(
1556
+ `| \`${iss.code}\` | ${iss.severity} | ${iss.taskId || "-"} | \`${iss.file}\` | ${iss.repaired ? "yes" : "no"} | ${iss.message.replace(/\|/g, "\\|")} |`
1557
+ );
1558
+ }
1559
+ }
1560
+ return untrustedTextResult(lines.join("\n"));
1561
+ }
1562
+
1563
+ const WORKFLOW_PLUGIN_TOOLS = [
1564
+ {
1565
+ name: "katlux_workflow_init",
1566
+ description: "Idempotently initializes todo/tasks/, todo/archive/, and todo/INDEX.md inside the workspace without overwriting existing tasks.",
1567
+ inputSchema: {
1568
+ type: "object",
1569
+ properties: {
1570
+ cwd: {
1571
+ type: "string",
1572
+ description: "Optional workspace root path (defaults to current MCP workspace root)"
1573
+ },
1574
+ projectName: {
1575
+ type: "string",
1576
+ description: "Optional project name for initial INDEX header"
1577
+ }
1578
+ }
1579
+ },
1580
+ annotations: {
1581
+ title: "Initialize Workflow Workspace",
1582
+ readOnlyHint: false,
1583
+ destructiveHint: false,
1584
+ idempotentHint: true,
1585
+ openWorldHint: false
1586
+ }
1587
+ },
1588
+ {
1589
+ name: "katlux_workflow_task",
1590
+ description: "Schema-enforced CRUD and lifecycle manager for todo/tasks/ and todo/INDEX.md. Enforces canonical statuses and close-gate checks instead of raw markdown edits.",
1591
+ inputSchema: {
1592
+ type: "object",
1593
+ properties: {
1594
+ cwd: { type: "string", description: "Optional workspace root path" },
1595
+ action: {
1596
+ type: "string",
1597
+ enum: ["create", "update", "transition", "archive"],
1598
+ description: "Operation to perform on a task"
1599
+ },
1600
+ id: { type: "string", description: 'Task ID (e.g. "TASK-072" or "TASK-072-01") for existing tasks. Forbidden on action="create" (auto-generated); required for update/transition/archive.' },
1601
+ parentId: { type: "string", description: 'Optional parent task ID (e.g. "TASK-072") on action="create" to allocate a subtask ID like "TASK-072-01".' },
1602
+ prefix: { type: "string", enum: ["TASK", "BUG", "DEBT", "RFC"], description: "ID prefix when auto-allocating on create (default: TASK)" },
1603
+ title: { type: "string", description: "Task title (required on create)" },
1604
+ priority: { type: "string", enum: [...TASK_PRIORITIES], description: "Priority level" },
1605
+ type: { type: "string", description: "Task type (e.g. Feature, Refactor, Bugfix, Architecture)" },
1606
+ dependencies: { type: "string", description: "Comma-separated task IDs or None" },
1607
+ problem: { type: "string", description: "Problem statement markdown (required on create)" },
1608
+ scope: {
1609
+ oneOf: [{ type: "string" }, { type: "array", items: { type: "string" } }],
1610
+ description: "Implementation scope markdown or bullet list (required on create)"
1611
+ },
1612
+ notes: { type: "string", description: "Optional notes section" },
1613
+ acceptanceCriteria: {
1614
+ type: "array",
1615
+ description: "Checklist items required on create",
1616
+ items: {
1617
+ oneOf: [
1618
+ { type: "string" },
1619
+ {
1620
+ type: "object",
1621
+ properties: { text: { type: "string" }, checked: { type: "boolean" } },
1622
+ required: ["text"]
1623
+ }
1624
+ ]
1625
+ }
1626
+ },
1627
+ addCriteria: {
1628
+ type: "array",
1629
+ description: "Additional acceptance criteria to append during update",
1630
+ items: {
1631
+ oneOf: [
1632
+ { type: "string" },
1633
+ {
1634
+ type: "object",
1635
+ properties: { text: { type: "string" }, checked: { type: "boolean" } },
1636
+ required: ["text"]
1637
+ }
1638
+ ]
1639
+ }
1640
+ },
1641
+ criteriaUpdates: {
1642
+ type: "array",
1643
+ description: "Toggle acceptance criteria by 0-based index or case-insensitive substring match",
1644
+ items: {
1645
+ type: "object",
1646
+ properties: {
1647
+ index: { type: "number" },
1648
+ match: { type: "string" },
1649
+ checked: { type: "boolean" }
1650
+ },
1651
+ required: ["checked"]
1652
+ }
1653
+ },
1654
+ status: {
1655
+ type: "string",
1656
+ enum: [...CANONICAL_TASK_STATUSES],
1657
+ description: "Canonical task status enum"
1658
+ },
1659
+ milestone: {
1660
+ type: "string",
1661
+ description: 'Target milestone (e.g. "v0.4.0-alpha") on create/update, or archive milestone folder name (required for action="archive")'
1662
+ },
1663
+ component: {
1664
+ type: "string",
1665
+ description: 'Target component or package for the task (e.g. "`@katlux/mcp-core` (`packages/katlux-mcp-core/**`)")'
1666
+ },
1667
+ force: {
1668
+ type: "boolean",
1669
+ description: "Allow archiving even if status is not [x] CLOSED"
1670
+ },
1671
+ runCheck: {
1672
+ type: "boolean",
1673
+ description: "Run `npm run ai:check` before closing a task (default: false; recommended for coding tasks)"
1674
+ },
1675
+ runTest: {
1676
+ type: "boolean",
1677
+ description: "Run `npm run ai:test` before closing a task (default: false; recommended for coding tasks)"
1678
+ },
1679
+ tokensSpent: {
1680
+ type: "number",
1681
+ description: "Optional token count spent on the task, recorded on completion"
1682
+ }
1683
+ },
1684
+ required: ["action"]
1685
+ },
1686
+ annotations: {
1687
+ title: "Manage Workflow Tasks",
1688
+ readOnlyHint: false,
1689
+ destructiveHint: false,
1690
+ idempotentHint: false,
1691
+ openWorldHint: false
1692
+ }
1693
+ },
1694
+ {
1695
+ name: "katlux_workflow_inspect",
1696
+ description: 'Read, filter, sort, audit, and repair todo/tasks/, todo/archive/, and todo/INDEX.md. action="list" returns a compact, token-efficient summary (ID + Title only); use action="get" with id="<ID>" to fetch full task details, metadata, problem statement, scope, and acceptance criteria. Supports filtering by status, priority, milestone, relatedTask, component, type, and sorting via sortBy="priority" | "id" | "status" | "milestone".',
1697
+ inputSchema: {
1698
+ type: "object",
1699
+ properties: {
1700
+ cwd: { type: "string", description: "Optional workspace root path" },
1701
+ action: {
1702
+ type: "string",
1703
+ enum: ["list", "get", "archive", "doctor"],
1704
+ description: 'Inspection or repair mode ("list" returns compact ID + Title; "get" returns full single-task spec)'
1705
+ },
1706
+ id: { type: "string", description: 'Task ID for action="get" (e.g. "TASK-067")' },
1707
+ status: {
1708
+ type: "string",
1709
+ description: 'Filter by status ("open", "active", or canonical status: "[ ] TODO", "[~] IN PROGRESS", "PAUSED (Feature Freeze)", "[x] CLOSED")'
1710
+ },
1711
+ priority: {
1712
+ type: "string",
1713
+ description: 'Filter by priority tier or keyword (e.g. "P0", "P1", "P2", "P3", "Critical", "High", "Medium", "Low")'
1714
+ },
1715
+ type: { type: "string", description: "Filter by task type" },
1716
+ milestone: {
1717
+ type: "string",
1718
+ description: 'Filter active (action="list") or archived (action="archive") tasks by target milestone (e.g. "v0.3.0-alpha", "v0.4.0-alpha")'
1719
+ },
1720
+ relatedTask: {
1721
+ type: "string",
1722
+ description: 'Filter active tasks by related task or dependency ID (e.g. "TASK-071", "DEBT-038")'
1723
+ },
1724
+ component: {
1725
+ type: "string",
1726
+ description: 'Filter active tasks by component or package name (e.g. "@katlux/toolkit", "KDatatable")'
1727
+ },
1728
+ createdAfter: {
1729
+ type: "string",
1730
+ description: "Filter active tasks created at or after this ISO-8601 date/timestamp"
1731
+ },
1732
+ createdBefore: {
1733
+ type: "string",
1734
+ description: "Filter active tasks created at or before this ISO-8601 date/timestamp"
1735
+ },
1736
+ closedAfter: {
1737
+ type: "string",
1738
+ description: "Filter active tasks closed at or after this ISO-8601 date/timestamp"
1739
+ },
1740
+ closedBefore: {
1741
+ type: "string",
1742
+ description: "Filter active tasks closed at or before this ISO-8601 date/timestamp"
1743
+ },
1744
+ minTokens: {
1745
+ type: "number",
1746
+ description: "Filter active tasks with tokensSpent >= minTokens"
1747
+ },
1748
+ maxTokens: {
1749
+ type: "number",
1750
+ description: "Filter active tasks with tokensSpent <= maxTokens"
1751
+ },
1752
+ sortBy: {
1753
+ type: "string",
1754
+ enum: ["id", "priority", "status", "milestone"],
1755
+ description: 'Sort order for action="list" (default: "id"; "priority" sorts P0/Critical -> P1/High -> P2/Medium -> P3/Low)'
1756
+ },
1757
+ limit: { type: "number", description: "Maximum entries returned" },
1758
+ repair: {
1759
+ type: "boolean",
1760
+ description: 'When true on action="doctor", repairs malformed active headers, invalid statuses, missing sections, and todo/INDEX.md desyncs'
1761
+ }
1762
+ },
1763
+ required: ["action"]
1764
+ },
1765
+ annotations: {
1766
+ title: "Inspect & Audit Workflow Tasks",
1767
+ readOnlyHint: false,
1768
+ destructiveHint: false,
1769
+ idempotentHint: true,
1770
+ openWorldHint: false
1771
+ }
1772
+ }
1773
+ ];
1774
+
1775
+ async function dispatchWorkflowTool(name, args, ctx) {
1776
+ switch (name) {
1777
+ case "katlux_workflow_init":
1778
+ return handleWorkflowInit(args, ctx?.cwd);
1779
+ case "katlux_workflow_task":
1780
+ return handleWorkflowTask(args, ctx?.cwd);
1781
+ case "katlux_workflow_inspect":
1782
+ return await handleWorkflowInspect(args, ctx?.cwd, ctx);
1783
+ default:
1784
+ return null;
1785
+ }
1786
+ }
1787
+ function createKatluxWorkflowPlugin() {
1788
+ return {
1789
+ id: "workflow",
1790
+ name: "@katlux/mcp-workflow",
1791
+ version: pkg.version,
1792
+ description: "Katlux-agnostic schema-enforced AI task & workflow plugin",
1793
+ isActiveForWorkspace: () => true,
1794
+ getTools: () => WORKFLOW_PLUGIN_TOOLS,
1795
+ handleTool: (name, args, ctx) => dispatchWorkflowTool(name, args, ctx),
1796
+ getGuidance: () => [
1797
+ 'Task & Workflow Management (@katlux/mcp-workflow active): Never read/write/edit todo/** directly. Use katlux_workflow_inspect(action="list", status/priority/milestone/relatedTask/component, sortBy="priority"|"id") for a compact ID+Title list, katlux_workflow_inspect(action="get", id="<ID>") for full single-task details, and katlux_workflow_task for create/update/transition/archive.'
1798
+ ]
1799
+ };
1800
+ }
1801
+ const createPlugin = createKatluxWorkflowPlugin;
1802
+
1803
+ exports.CANONICAL_TASK_STATUSES = CANONICAL_TASK_STATUSES;
1804
+ exports.TASK_PREFIXES = TASK_PREFIXES;
1805
+ exports.TASK_PRIORITIES = TASK_PRIORITIES;
1806
+ exports.WORKFLOW_PLUGIN_TOOLS = WORKFLOW_PLUGIN_TOOLS;
1807
+ exports.allocateNextTaskId = allocateNextTaskId;
1808
+ exports.createKatluxWorkflowPlugin = createKatluxWorkflowPlugin;
1809
+ exports.createPlugin = createPlugin;
1810
+ exports.default = createKatluxWorkflowPlugin;
1811
+ exports.dispatchWorkflowTool = dispatchWorkflowTool;
1812
+ exports.extractIdParts = extractIdParts;
1813
+ exports.formatCanonicalPriority = formatCanonicalPriority;
1814
+ exports.getTodoPaths = getTodoPaths;
1815
+ exports.handleWorkflowInit = handleWorkflowInit;
1816
+ exports.handleWorkflowInspect = handleWorkflowInspect;
1817
+ exports.handleWorkflowTask = handleWorkflowTask;
1818
+ exports.loadActiveTasks = loadActiveTasks;
1819
+ exports.loadArchiveEntries = loadArchiveEntries;
1820
+ exports.normalizeTaskStatus = normalizeTaskStatus;
1821
+ exports.parseTaskMarkdown = parseTaskMarkdown;
1822
+ exports.parseTodoIndexRows = parseTodoIndexRows;
1823
+ exports.serializeCanonicalTask = serializeCanonicalTask;
1824
+ exports.slugifyTitle = slugifyTitle;
1825
+ exports.syncArchiveMilestoneIndex = syncArchiveMilestoneIndex;
1826
+ exports.syncTodoIndex = syncTodoIndex;