@letra-ai/cli 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/client/assets/index-9KbFvLoH.css +1 -0
  2. package/dist/client/assets/index-s9Re0Bnf.js +84 -0
  3. package/dist/client/favicon.svg +4 -0
  4. package/dist/client/index.html +20 -0
  5. package/dist/index.js +2242 -862
  6. package/package.json +2 -35
  7. package/.letra/adapters/opencode.json +0 -21
  8. package/.letra/brand/logo-01-terminal.svg +0 -6
  9. package/.letra/brand/logo-02-bookmark.svg +0 -6
  10. package/.letra/brand/logo-03-diamond.svg +0 -7
  11. package/.letra/constitution.md +0 -35
  12. package/.letra/context.md +0 -29
  13. package/.letra/decisions/flow-mvp-escopo-enxuto-3-comandos-valor-imediato.md +0 -35
  14. package/.letra/glossary.md +0 -21
  15. package/.letra/lessons-learned.md +0 -20
  16. package/.letra/specs/_template.md +0 -27
  17. package/.letra/specs/adapter-claude-code/acceptance.md +0 -6
  18. package/.letra/specs/adapter-claude-code/spec.md +0 -27
  19. package/.letra/specs/adapter-codex-cli/acceptance.md +0 -6
  20. package/.letra/specs/adapter-codex-cli/spec.md +0 -27
  21. package/.letra/specs/adapter-cursor/acceptance.md +0 -6
  22. package/.letra/specs/adapter-cursor/spec.md +0 -29
  23. package/.letra/specs/adapter-opencode/acceptance.md +0 -6
  24. package/.letra/specs/adapter-opencode/spec.md +0 -35
  25. package/.letra/specs/adapter-vscode/acceptance.md +0 -6
  26. package/.letra/specs/adapter-vscode/spec.md +0 -29
  27. package/.letra/specs/adapter-windsurf/acceptance.md +0 -6
  28. package/.letra/specs/adapter-windsurf/spec.md +0 -27
  29. package/.letra/specs/ci-cd-pipeline/acceptance.md +0 -6
  30. package/.letra/specs/ci-cd-pipeline/spec.md +0 -30
  31. package/.letra/specs/cli-skeleton/acceptance.md +0 -7
  32. package/.letra/specs/cli-skeleton/spec.md +0 -30
  33. package/.letra/specs/decision-new/acceptance.md +0 -7
  34. package/.letra/specs/decision-new/spec.md +0 -29
  35. package/.letra/specs/flow-edit-diff/acceptance.md +0 -7
  36. package/.letra/specs/flow-edit-diff/spec.md +0 -30
  37. package/.letra/specs/flow-export-import/acceptance.md +0 -7
  38. package/.letra/specs/flow-export-import/spec.md +0 -27
  39. package/.letra/specs/flow-mvp/roadmap.md +0 -40
  40. package/.letra/specs/flow-mvp/spec.md +0 -40
  41. package/.letra/specs/flow-serve/spec.md +0 -47
  42. package/.letra/specs/flow-visualize/acceptance.md +0 -7
  43. package/.letra/specs/flow-visualize/spec.md +0 -28
  44. package/.letra/specs/init-interactive/acceptance.md +0 -7
  45. package/.letra/specs/init-interactive/spec.md +0 -29
  46. package/.letra/specs/session-focus/acceptance.md +0 -7
  47. package/.letra/specs/session-focus/spec.md +0 -30
  48. package/.letra/specs/spec-templates-domain/acceptance.md +0 -7
  49. package/.letra/specs/spec-templates-domain/spec.md +0 -29
  50. package/.letra/specs/validate-config/acceptance.md +0 -9
  51. package/.letra/specs/validate-config/spec.md +0 -32
  52. package/.letra/specs/validate-conflict/acceptance.md +0 -7
  53. package/.letra/specs/validate-conflict/spec.md +0 -29
  54. package/.letra/specs/validate-format-pr/acceptance.md +0 -7
  55. package/.letra/specs/validate-format-pr/spec.md +0 -28
  56. package/.letra/specs/validate-intelligence/acceptance.md +0 -9
  57. package/.letra/specs/validate-intelligence/spec.md +0 -30
  58. package/.letra/specs/validate-watch/acceptance.md +0 -7
  59. package/.letra/specs/validate-watch/spec.md +0 -29
  60. package/.letra/workflow.json +0 -47
  61. package/.letra/workspace.schema.json +0 -32
  62. package/LICENSE +0 -21
  63. package/README.md +0 -240
package/dist/index.js CHANGED
@@ -1,19 +1,19 @@
1
1
  #!/usr/bin/env node
2
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
+ }) : x)(function(x) {
5
+ if (typeof require !== "undefined") return require.apply(this, arguments);
6
+ throw Error('Dynamic require of "' + x + '" is not supported');
7
+ });
2
8
 
3
9
  // src/index.ts
4
- import { readFileSync as readFileSync11 } from "fs";
5
- import { join as join13, resolve as resolve15 } from "path";
6
- import { fileURLToPath as fileURLToPath2 } from "url";
10
+ import { readFileSync as readFileSync18 } from "fs";
11
+ import { join as join24, resolve as resolve17 } from "path";
12
+ import { fileURLToPath as fileURLToPath3 } from "url";
7
13
  import { Command as Command4 } from "commander";
8
14
 
9
15
  // src/commands/decision.ts
10
- import {
11
- existsSync,
12
- mkdirSync,
13
- readFileSync,
14
- readdirSync,
15
- writeFileSync
16
- } from "fs";
16
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "fs";
17
17
  import { join, resolve } from "path";
18
18
  import chalk from "chalk";
19
19
  import { Command } from "commander";
@@ -35,9 +35,7 @@ function decisionCommand() {
35
35
  }
36
36
  if (existsSync(filePath)) {
37
37
  console.log(
38
- chalk.red(
39
- `Decision "${slug}" already exists at .letra/decisions/${slug}.md`
40
- )
38
+ chalk.red(`Decision "${slug}" already exists at .letra/decisions/${slug}.md`)
41
39
  );
42
40
  return;
43
41
  }
@@ -59,19 +57,13 @@ What was decided?
59
57
  What are the trade-offs? What does this enable or prevent?
60
58
  `;
61
59
  writeFileSync(filePath, content);
62
- console.log(
63
- chalk.green(
64
- `Decision "${slug}" created at .letra/decisions/${slug}.md`
65
- )
66
- );
60
+ console.log(chalk.green(`Decision "${slug}" created at .letra/decisions/${slug}.md`));
67
61
  });
68
62
  cmd.command("list").description("Lista todos os Architecture Decision Records").action(() => {
69
63
  const root = resolve(process.cwd());
70
64
  const decisionsDir = join(root, ".letra", "decisions");
71
65
  if (!existsSync(decisionsDir)) {
72
- console.log(
73
- chalk.yellow("No decisions directory found at .letra/decisions/")
74
- );
66
+ console.log(chalk.yellow("No decisions directory found at .letra/decisions/"));
75
67
  return;
76
68
  }
77
69
  const files = readdirSync(decisionsDir).filter((f) => f.endsWith(".md")).sort();
@@ -104,12 +96,12 @@ import ora from "ora";
104
96
  function askText(query, defaultValue) {
105
97
  if (!process.stdin.isTTY) return Promise.resolve(defaultValue);
106
98
  const rl = createInterface({ input: process.stdin, output: process.stdout });
107
- return new Promise((resolve16) => {
99
+ return new Promise((resolve18) => {
108
100
  const formatted = `${chalk2.cyan(query)} ${chalk2.gray(`(default: ${defaultValue})`)}
109
101
  > `;
110
102
  rl.question(formatted, (answer) => {
111
103
  rl.close();
112
- resolve16(answer.trim() || defaultValue);
104
+ resolve18(answer.trim() || defaultValue);
113
105
  });
114
106
  });
115
107
  }
@@ -119,8 +111,7 @@ function detectExistingTools(root) {
119
111
  if (existsSync2(join2(root, "CLAUDE.md"))) tools.push("claude-code");
120
112
  if (existsSync2(join2(root, ".windsurfrules"))) tools.push("windsurf");
121
113
  if (existsSync2(join2(root, "AGENTS.md"))) tools.push("opencode");
122
- if (existsSync2(join2(root, ".github", "copilot-instructions.md")))
123
- tools.push("vscode");
114
+ if (existsSync2(join2(root, ".github", "copilot-instructions.md"))) tools.push("vscode");
124
115
  return tools;
125
116
  }
126
117
  function detectProjectName(root) {
@@ -163,13 +154,23 @@ function loadWorkflow(root) {
163
154
  function saveWorkflow(root, workflow) {
164
155
  const dir = join2(root, ".letra");
165
156
  if (!existsSync2(dir)) mkdirSync2(dir, { recursive: true });
166
- writeFileSync2(workflowFilePath(root), JSON.stringify(workflow, null, 2));
157
+ const filePath = workflowFilePath(root);
158
+ if (existsSync2(filePath)) {
159
+ const backupDir = join2(root, ".letra", "backups");
160
+ if (!existsSync2(backupDir)) mkdirSync2(backupDir, { recursive: true });
161
+ const ts = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
162
+ const backupPath = join2(backupDir, `workflow-${ts}.json`);
163
+ try {
164
+ const existing = readFileSync2(filePath, "utf-8");
165
+ writeFileSync2(backupPath, existing, "utf-8");
166
+ } catch {
167
+ }
168
+ }
169
+ writeFileSync2(filePath, JSON.stringify(workflow, null, 2));
167
170
  }
168
171
  async function flowInit(root, options) {
169
172
  if (!process.stdin.isTTY && !options?.quick) {
170
- console.log(
171
- chalk2.yellow("Non-TTY: usando defaults. Passe --quick para confirmar.")
172
- );
173
+ console.log(chalk2.yellow("Non-TTY: usando defaults. Passe --quick para confirmar."));
173
174
  return flowInitQuick(root);
174
175
  }
175
176
  if (options?.quick) {
@@ -202,10 +203,7 @@ async function flowInitQuick(root) {
202
203
  const detected = detectExistingTools(root);
203
204
  const defaultTools = detected.length > 0 ? detected.join(", ") : "cursor, opencode";
204
205
  const name = await askText("Workflow name?", defaultName);
205
- const stagesInput = await askText(
206
- "Stages (comma-separated)?",
207
- defaultStagesList
208
- );
206
+ const stagesInput = await askText("Stages (comma-separated)?", defaultStagesList);
209
207
  const stages = stagesFromInput(stagesInput);
210
208
  const toolsInput = await askText("Tools (comma-separated)?", defaultTools);
211
209
  const tools = toolsInput.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
@@ -224,9 +222,7 @@ async function flowInitAction(targetPath, options) {
224
222
  const root = resolve2(process.cwd(), targetPath || ".");
225
223
  const filePath = workflowFilePath(root);
226
224
  if (existsSync2(filePath)) {
227
- console.log(
228
- chalk2.yellow("Workflow already exists at .letra/workflow.json")
229
- );
225
+ console.log(chalk2.yellow("Workflow already exists at .letra/workflow.json"));
230
226
  return;
231
227
  }
232
228
  const spinner = ora("Setting up workflow...").start();
@@ -238,18 +234,14 @@ async function flowInitAction(targetPath, options) {
238
234
  spinner.succeed(chalk2.green("Workflow created at .letra/workflow.json"));
239
235
  console.log("");
240
236
  console.log(` Name: ${chalk2.cyan(workflow.name)}`);
241
- console.log(
242
- ` Stages: ${chalk2.cyan(workflow.stages.map((s) => s.name).join(" \u2192 "))}`
243
- );
237
+ console.log(` Stages: ${chalk2.cyan(workflow.stages.map((s) => s.name).join(" \u2192 "))}`);
244
238
  console.log(` Tools: ${chalk2.cyan(workflow.tools.join(", "))}`);
245
239
  console.log("");
246
240
  console.log(" Next steps:");
247
241
  console.log(
248
242
  ` ${chalk2.cyan("letra flow backlog add <desc>")} Add items to your backlog`
249
243
  );
250
- console.log(
251
- ` ${chalk2.cyan("letra flow board")} View your board`
252
- );
244
+ console.log(` ${chalk2.cyan("letra flow board")} View your board`);
253
245
  } catch (error) {
254
246
  spinner.fail(chalk2.red("Failed to create workflow"));
255
247
  process.exit(1);
@@ -281,9 +273,7 @@ function backlogAdd(root, description) {
281
273
  }
282
274
  const workflow = workflowExists(root);
283
275
  if (!workflow) {
284
- console.log(
285
- chalk3.red("No workflow found. Run 'letra flow init --quick' first")
286
- );
276
+ console.log(chalk3.red("No workflow found. Run 'letra flow init --quick' first"));
287
277
  process.exit(1);
288
278
  }
289
279
  if (workflow.stages.length === 0) {
@@ -307,9 +297,7 @@ function backlogAdd(root, description) {
307
297
  function backlogList(root) {
308
298
  const workflow = workflowExists(root);
309
299
  if (!workflow) {
310
- console.log(
311
- chalk3.yellow("No workflow found. Run 'letra flow init --quick' first")
312
- );
300
+ console.log(chalk3.yellow("No workflow found. Run 'letra flow init --quick' first"));
313
301
  return;
314
302
  }
315
303
  if (workflow.items.length === 0) {
@@ -325,9 +313,7 @@ function backlogList(root) {
325
313
  for (const item of workflow.items) {
326
314
  const stageName2 = stageNames.get(item.stage) || item.stage;
327
315
  const created = new Date(item.createdAt);
328
- const age = Math.floor(
329
- (Date.now() - created.getTime()) / (1e3 * 60 * 60 * 24)
330
- );
316
+ const age = Math.floor((Date.now() - created.getTime()) / (1e3 * 60 * 60 * 24));
331
317
  const ageStr = age === 0 ? "today" : `${age}d`;
332
318
  const desc = item.description.length > 28 ? `${item.description.slice(0, 27)}\u2026` : item.description.padEnd(30);
333
319
  console.log(
@@ -350,17 +336,13 @@ import { resolve as resolve4 } from "path";
350
336
  import chalk4 from "chalk";
351
337
  function ageLabel(createdAt) {
352
338
  const created = new Date(createdAt);
353
- const age = Math.floor(
354
- (Date.now() - created.getTime()) / (1e3 * 60 * 60 * 24)
355
- );
339
+ const age = Math.floor((Date.now() - created.getTime()) / (1e3 * 60 * 60 * 24));
356
340
  return age === 0 ? "today" : `${age}d`;
357
341
  }
358
342
  function flowBoard(root) {
359
343
  const workflow = loadWorkflow(root);
360
344
  if (!workflow) {
361
- console.log(
362
- chalk4.yellow("No workflow found. Run 'letra flow init --quick' first")
363
- );
345
+ console.log(chalk4.yellow("No workflow found. Run 'letra flow init --quick' first"));
364
346
  return;
365
347
  }
366
348
  console.log(`
@@ -431,13 +413,9 @@ function loadVersion(root, version) {
431
413
  function getLatestBackupVersion(root) {
432
414
  const dir = join3(root, ".letra");
433
415
  if (!existsSync3(dir)) return null;
434
- const files = readdirSync2(dir).filter(
435
- (f) => f.startsWith("workflow.v") && f.endsWith(".json")
436
- );
416
+ const files = readdirSync2(dir).filter((f) => f.startsWith("workflow.v") && f.endsWith(".json"));
437
417
  if (files.length === 0) return null;
438
- const versions = files.map(
439
- (f) => f.replace("workflow.v", "").replace(".json", "")
440
- );
418
+ const versions = files.map((f) => f.replace("workflow.v", "").replace(".json", ""));
441
419
  versions.sort((a, b) => {
442
420
  const pa = a.split(".").map(Number);
443
421
  const pb = b.split(".").map(Number);
@@ -454,9 +432,7 @@ function backupFilePath(root, version) {
454
432
  function flowEdit(root, options) {
455
433
  const workflow = loadWorkflow(root);
456
434
  if (!workflow) {
457
- console.log(
458
- chalk5.yellow("No workflow found. Run 'letra flow init --quick' first")
459
- );
435
+ console.log(chalk5.yellow("No workflow found. Run 'letra flow init --quick' first"));
460
436
  return;
461
437
  }
462
438
  const currentVersion = normalizeVersion(workflow.version);
@@ -563,9 +539,7 @@ function flowDiff(root, v1, v2) {
563
539
  const wf1 = loadVersion(root, stripVPrefix(v1));
564
540
  const wf2 = loadVersion(root, stripVPrefix(v2));
565
541
  if (!wf1 && !wf2) {
566
- console.log(
567
- chalk5.yellow(`No backups found for versions ${v1} and ${v2}`)
568
- );
542
+ console.log(chalk5.yellow(`No backups found for versions ${v1} and ${v2}`));
569
543
  return;
570
544
  }
571
545
  if (!wf1) {
@@ -587,9 +561,7 @@ function flowDiff(root, v1, v2) {
587
561
  }
588
562
  const backup = loadBackup(root, latestVersion);
589
563
  if (!backup) {
590
- console.log(
591
- chalk5.yellow(`Failed to load backup version ${latestVersion}`)
592
- );
564
+ console.log(chalk5.yellow(`Failed to load backup version ${latestVersion}`));
593
565
  return;
594
566
  }
595
567
  const diff = computeDiff(backup, current);
@@ -651,534 +623,1829 @@ function flowImport(root, filePath) {
651
623
  const imported = parsed;
652
624
  const existingWorkflow = loadWorkflow(root);
653
625
  if (existingWorkflow) {
654
- const backup = join4(
655
- root,
656
- ".letra",
657
- `workflow.v${existingWorkflow.version}.json`
658
- );
626
+ const backup = join4(root, ".letra", `workflow.v${existingWorkflow.version}.json`);
659
627
  if (!existsSync4(backup)) {
660
628
  writeFileSync4(backup, JSON.stringify(existingWorkflow, null, 2));
661
629
  console.log(
662
- chalk6.gray(
663
- `Backup saved: .letra/workflow.v${existingWorkflow.version}.json`
664
- )
630
+ chalk6.gray(`Backup saved: .letra/workflow.v${existingWorkflow.version}.json`)
665
631
  );
666
632
  }
667
633
  }
668
634
  imported.createdAt = now4();
669
635
  imported.updatedAt = now4();
670
636
  saveWorkflow(root, imported);
671
- console.log(
672
- chalk6.green(`Workflow imported: ${imported.name} (${imported.version})`)
673
- );
637
+ console.log(chalk6.green(`Workflow imported: ${imported.name} (${imported.version})`));
674
638
  }
675
639
  function flowImportAction(targetPath, filePath) {
676
640
  const root = resolve6(process.cwd(), targetPath || ".");
677
641
  flowImport(root, filePath);
678
642
  }
679
643
 
680
- // src/commands/flow-move.ts
681
- import { existsSync as existsSync5, mkdirSync as mkdirSync3, writeFileSync as writeFileSync5 } from "fs";
682
- import { join as join5, resolve as resolve7 } from "path";
644
+ // src/commands/flow-import-issues.ts
645
+ import { resolve as resolve7 } from "path";
683
646
  import chalk7 from "chalk";
684
647
  function now5() {
685
648
  return (/* @__PURE__ */ new Date()).toISOString();
686
649
  }
687
- function resolveStage(workflow, input) {
688
- const lower = input.toLowerCase();
689
- for (const stage of workflow.stages) {
690
- if (stage.id === lower) return stage.id;
691
- if (stage.name.toLowerCase() === lower) return stage.id;
650
+ function nextItemId2(workflow) {
651
+ let max = 0;
652
+ for (const item of workflow.items) {
653
+ const match = item.id.match(/^ITEM-(\d+)$/);
654
+ if (match) {
655
+ const num = Number.parseInt(match[1], 10);
656
+ if (num > max) max = num;
657
+ }
692
658
  }
693
- return null;
659
+ return `ITEM-${max + 1}`;
694
660
  }
695
- function adapterContent(workflowName, currentStageName, items, stageNames) {
696
- const stageItems = items.filter(
697
- (item) => item.stage === currentStageName.toLowerCase().replace(/[^a-z0-9]+/g, "-") || stageNames.get(item.stage) === currentStageName
661
+ function ensureWorkflow(root) {
662
+ const workflow = loadWorkflow(root);
663
+ if (!workflow) {
664
+ console.log(chalk7.red("No workflow found. Run 'letra flow init --quick' first"));
665
+ process.exit(1);
666
+ }
667
+ if (workflow.stages.length === 0) {
668
+ console.log(chalk7.red("Workflow has no stages defined"));
669
+ process.exit(1);
670
+ }
671
+ return workflow;
672
+ }
673
+ async function backlogImportGitHub(root, repo, options) {
674
+ const workflow = ensureWorkflow(root);
675
+ const limit = options?.limit ?? 50;
676
+ const token = process.env.GITHUB_TOKEN;
677
+ const url = new URL(`https://api.github.com/repos/${repo}/issues`);
678
+ url.searchParams.set("state", "open");
679
+ url.searchParams.set("per_page", String(limit));
680
+ if (options?.label) {
681
+ url.searchParams.set("labels", options.label);
682
+ }
683
+ const headers = {
684
+ Accept: "application/vnd.github.v3+json",
685
+ "User-Agent": "letra-cli"
686
+ };
687
+ if (token) {
688
+ headers.Authorization = `Bearer ${token}`;
689
+ }
690
+ let response;
691
+ try {
692
+ response = await fetch(url.toString(), { headers });
693
+ } catch (err) {
694
+ const msg = err instanceof Error ? err.message : String(err);
695
+ console.log(chalk7.red(`Failed to fetch issues: ${msg}`));
696
+ process.exit(1);
697
+ }
698
+ if (!response.ok) {
699
+ const text = await response.text().catch(() => "unknown error");
700
+ if (response.status === 404) {
701
+ console.log(chalk7.red(`Repository "${repo}" not found or is private`));
702
+ } else if (response.status === 401 || response.status === 403) {
703
+ console.log(chalk7.red(`GitHub API error (${response.status}). Check GITHUB_TOKEN`));
704
+ } else {
705
+ console.log(chalk7.red(`GitHub API error (${response.status}): ${text}`));
706
+ }
707
+ process.exit(1);
708
+ }
709
+ let issues;
710
+ try {
711
+ issues = await response.json();
712
+ } catch {
713
+ console.log(chalk7.red("Failed to parse GitHub response"));
714
+ process.exit(1);
715
+ }
716
+ issues = issues.filter((i) => !("pull_request" in i));
717
+ if (issues.length === 0) {
718
+ console.log(chalk7.yellow("No open issues found"));
719
+ return { imported: 0, total: 0 };
720
+ }
721
+ const firstStage = workflow.stages[0].id;
722
+ let imported = 0;
723
+ for (const issue of issues) {
724
+ const labels = issue.labels?.map((l) => l.name).join(", ") || "";
725
+ const description = labels ? `[${issue.number}] ${issue.title} (${labels})` : `[${issue.number}] ${issue.title}`;
726
+ const item = {
727
+ id: nextItemId2(workflow),
728
+ description,
729
+ stage: firstStage,
730
+ createdAt: now5(),
731
+ source: "github",
732
+ sourceUrl: issue.html_url
733
+ };
734
+ workflow.items.push(item);
735
+ imported++;
736
+ }
737
+ workflow.updatedAt = now5();
738
+ saveWorkflow(root, workflow);
739
+ console.log(
740
+ ` ${chalk7.green("\u2713")} Imported ${chalk7.cyan(String(imported))} issue${imported !== 1 ? "s" : ""} from ${chalk7.cyan(repo)}`
741
+ );
742
+ return { imported, total: issues.length };
743
+ }
744
+ async function backlogImportLinear(root, team, options) {
745
+ const apiKey = process.env.LINEAR_API_KEY;
746
+ if (!apiKey) {
747
+ console.log(chalk7.red("LINEAR_API_KEY environment variable is required for Linear import"));
748
+ process.exit(1);
749
+ }
750
+ const workflow = ensureWorkflow(root);
751
+ const limit = options?.limit ?? 50;
752
+ const query = `
753
+ query($team: String!, $limit: Int!) {
754
+ team(key: $team) {
755
+ issues(first: $limit, filter: { state: { type: { in: [todo, inProgress] } } }) {
756
+ nodes {
757
+ id
758
+ title
759
+ url
760
+ identifier
761
+ }
762
+ }
763
+ }
764
+ }`;
765
+ let response;
766
+ try {
767
+ response = await fetch("https://api.linear.app/graphql", {
768
+ method: "POST",
769
+ headers: {
770
+ "Content-Type": "application/json",
771
+ Authorization: apiKey
772
+ },
773
+ body: JSON.stringify({ query, variables: { team, limit } })
774
+ });
775
+ } catch (err) {
776
+ const msg = err instanceof Error ? err.message : String(err);
777
+ console.log(chalk7.red(`Failed to fetch Linear issues: ${msg}`));
778
+ process.exit(1);
779
+ }
780
+ if (!response.ok) {
781
+ const text = await response.text().catch(() => "unknown error");
782
+ if (response.status === 401) {
783
+ console.log(chalk7.red("Invalid Linear API key. Check LINEAR_API_KEY"));
784
+ } else {
785
+ console.log(chalk7.red(`Linear API error (${response.status}): ${text}`));
786
+ }
787
+ process.exit(1);
788
+ }
789
+ let data;
790
+ try {
791
+ data = await response.json();
792
+ } catch {
793
+ console.log(chalk7.red("Failed to parse Linear response"));
794
+ process.exit(1);
795
+ }
796
+ if (data.data?.team?.issues?.nodes == null) {
797
+ const errMsg = data?.data?.team == null ? `Team "${team}" not found` : "Failed to fetch Linear issues";
798
+ console.log(chalk7.red(errMsg));
799
+ process.exit(1);
800
+ }
801
+ const issues = data.data.team.issues.nodes;
802
+ if (issues.length === 0) {
803
+ console.log(chalk7.yellow(`No open issues found for team "${team}"`));
804
+ return { imported: 0, total: 0 };
805
+ }
806
+ const firstStage = workflow.stages[0].id;
807
+ let imported = 0;
808
+ for (const issue of issues) {
809
+ const description = `${issue.identifier} ${issue.title}`;
810
+ const item = {
811
+ id: nextItemId2(workflow),
812
+ description,
813
+ stage: firstStage,
814
+ createdAt: now5(),
815
+ source: "linear",
816
+ sourceUrl: issue.url
817
+ };
818
+ workflow.items.push(item);
819
+ imported++;
820
+ }
821
+ workflow.updatedAt = now5();
822
+ saveWorkflow(root, workflow);
823
+ console.log(
824
+ ` ${chalk7.green("\u2713")} Imported ${chalk7.cyan(String(imported))} issue${imported !== 1 ? "s" : ""} from Linear team ${chalk7.cyan(team)}`
698
825
  );
699
- const itemsBlock = stageItems.length > 0 ? stageItems.map((item) => `- ${item.id}: ${item.description}`).join("\n") : "(nenhum item ativo neste estagio)";
700
- return `# Letra Context \u2014 ${workflowName}
826
+ return { imported, total: issues.length };
827
+ }
828
+ async function backlogImportGitHubAction(targetPath, repo, options) {
829
+ const root = resolve7(process.cwd(), targetPath || ".");
830
+ await backlogImportGitHub(root, repo, {
831
+ label: options.label,
832
+ limit: options.limit ? Number(options.limit) : void 0
833
+ });
834
+ }
835
+ async function backlogImportLinearAction(targetPath, team, options) {
836
+ const root = resolve7(process.cwd(), targetPath || ".");
837
+ await backlogImportLinear(root, team, {
838
+ limit: options.limit ? Number(options.limit) : void 0
839
+ });
840
+ }
701
841
 
702
- ## Workflow
842
+ // src/commands/flow-move.ts
843
+ import { resolve as resolve8 } from "path";
844
+ import chalk9 from "chalk";
703
845
 
704
- **Estagio atual:** ${currentStageName}
846
+ // src/adapters/generate.ts
847
+ import { existsSync as existsSync8, mkdirSync as mkdirSync3, writeFileSync as writeFileSync6 } from "fs";
848
+ import { join as join8 } from "path";
849
+ import chalk8 from "chalk";
705
850
 
706
- ### Itens neste estagio
851
+ // src/adapters/builder.ts
852
+ import { existsSync as existsSync7 } from "fs";
853
+ import { join as join7 } from "path";
707
854
 
708
- ${itemsBlock}
855
+ // src/adapters/ac-counter.ts
856
+ import { existsSync as existsSync5, readFileSync as readFileSync5 } from "fs";
857
+ import { join as join5 } from "path";
858
+ var PENDING_PATTERN = /-\s*\[ \]\s*\*\*(.+?)\*\*/g;
859
+ var DONE_PATTERN = /-\s*\[[xX]\]\s*\*\*(.+?)\*\*/g;
860
+ function countInText(text) {
861
+ const pendingMatches = text.match(PENDING_PATTERN) || [];
862
+ const doneMatches = text.match(DONE_PATTERN) || [];
863
+ const pending = pendingMatches.length;
864
+ const total = pending + doneMatches.length;
865
+ return { pending, total };
866
+ }
867
+ function countACs(specDir) {
868
+ const acceptanceFile = join5(specDir, "acceptance.md");
869
+ const specFile = join5(specDir, "spec.md");
870
+ let acceptancePending = 0;
871
+ let acceptanceTotal = 0;
872
+ let specPending = 0;
873
+ let specTotal = 0;
874
+ let hasAcceptance = false;
875
+ let hasSpec = false;
876
+ if (existsSync5(acceptanceFile)) {
877
+ hasAcceptance = true;
878
+ const content = readFileSync5(acceptanceFile, "utf-8");
879
+ const counts = countInText(content);
880
+ acceptancePending = counts.pending;
881
+ acceptanceTotal = counts.total;
882
+ }
883
+ if (existsSync5(specFile)) {
884
+ hasSpec = true;
885
+ const content = readFileSync5(specFile, "utf-8");
886
+ const match = content.match(/## Acceptance Criteria\s+([\s\S]*?)(?=\n## |\n*$)/);
887
+ const sectionContent = match ? match[1] : "";
888
+ const counts = countInText(sectionContent);
889
+ specPending = counts.pending;
890
+ specTotal = counts.total;
891
+ }
892
+ const drift = hasAcceptance && hasSpec && acceptanceTotal !== specTotal;
893
+ if (hasAcceptance) {
894
+ return {
895
+ pending: acceptancePending,
896
+ total: acceptanceTotal,
897
+ specCount: specTotal,
898
+ acceptanceCount: acceptanceTotal,
899
+ drift
900
+ };
901
+ }
902
+ return {
903
+ pending: specPending,
904
+ total: specTotal,
905
+ specCount: specTotal,
906
+ acceptanceCount: 0,
907
+ drift: false
908
+ };
909
+ }
709
910
 
710
- ### Regras
911
+ // src/adapters/focus-sync.ts
912
+ import { existsSync as existsSync6, readFileSync as readFileSync6, unlinkSync, writeFileSync as writeFileSync5 } from "fs";
913
+ import { join as join6 } from "path";
914
+ function extractOutcome(rootDir, specName) {
915
+ const specFile = join6(rootDir, ".letra", "specs", specName, "spec.md");
916
+ if (!existsSync6(specFile)) return null;
917
+ const content = readFileSync6(specFile, "utf-8");
918
+ const match = content.match(/## Outcome\s+([\s\S]*?)(?=\n## |\n*$)/);
919
+ return match ? match[1].trim() : null;
920
+ }
921
+ function writeFocusFile(rootDir, specName, itemId) {
922
+ const focusFile = join6(rootDir, ".letra", "focus.md");
923
+ const outcome = extractOutcome(rootDir, specName) || specName;
924
+ const content = [
925
+ `# Focus: ${specName}`,
926
+ "",
927
+ `**Path**: .letra/specs/${specName}/`,
928
+ `**Item**: ${itemId}`,
929
+ `**Outcome**: ${outcome}`,
930
+ ""
931
+ ].join("\n");
932
+ writeFileSync5(focusFile, content, "utf-8");
933
+ }
934
+ function clearFocusFile(rootDir) {
935
+ const focusFile = join6(rootDir, ".letra", "focus.md");
936
+ if (existsSync6(focusFile)) {
937
+ unlinkSync(focusFile);
938
+ }
939
+ }
940
+ function readFocusFile(rootDir) {
941
+ const focusFile = join6(rootDir, ".letra", "focus.md");
942
+ if (!existsSync6(focusFile)) return null;
943
+ const content = readFileSync6(focusFile, "utf-8");
944
+ const specMatch = content.match(/# Focus:\s*(.+)/);
945
+ const itemMatch = content.match(/\*\*Item\*\*:\s*(.+)/);
946
+ const outcomeMatch = content.match(/\*\*Outcome\*\*:\s*([\s\S]*?)(?=\n\*\*|\n*$)/);
947
+ if (!specMatch) return null;
948
+ return {
949
+ specName: specMatch[1].trim(),
950
+ itemId: itemMatch ? itemMatch[1].trim() : "",
951
+ outcome: outcomeMatch ? outcomeMatch[1].trim() : ""
952
+ };
953
+ }
954
+
955
+ // src/adapters/builder.ts
956
+ function buildHarnessSnapshot(root, options) {
957
+ const hasFocus = existsSync7(join7(root, ".letra", "focus.md"));
958
+ if (!options.workflow || !options.activeStageId) {
959
+ return {
960
+ workflowName: "letra",
961
+ hasWorkflow: false,
962
+ items: [],
963
+ hasFocus,
964
+ primaryItemId: null,
965
+ focusSpec: null,
966
+ focusPath: null
967
+ };
968
+ }
969
+ const { workflow, activeStageId } = options;
970
+ const stage = workflow.stages.find((s) => s.id === activeStageId);
971
+ const stageItems = workflow.items.filter((item) => item.stage === activeStageId);
972
+ let primaryItemId = null;
973
+ if (options.primaryItemId && stageItems.some((i) => i.id === options.primaryItemId)) {
974
+ primaryItemId = options.primaryItemId;
975
+ } else if (stageItems.length > 0) {
976
+ primaryItemId = stageItems[0].id;
977
+ }
978
+ const acDrifts = [];
979
+ const items = stageItems.map((item) => {
980
+ const harnessItem = {
981
+ id: item.id,
982
+ description: item.description,
983
+ spec: item.spec
984
+ };
985
+ if (item.spec) {
986
+ harnessItem.specPath = `.letra/specs/${item.spec}/spec.md`;
987
+ harnessItem.acceptancePath = `.letra/specs/${item.spec}/acceptance.md`;
988
+ const specDir = join7(root, ".letra", "specs", item.spec);
989
+ const acCount = countACs(specDir);
990
+ harnessItem.acPending = acCount.pending;
991
+ harnessItem.acTotal = acCount.total;
992
+ if (acCount.drift) {
993
+ acDrifts.push({
994
+ spec: item.spec,
995
+ specCount: acCount.specCount,
996
+ acceptanceCount: acCount.acceptanceCount
997
+ });
998
+ }
999
+ }
1000
+ if (item.tasks) {
1001
+ harnessItem.tasksTotal = item.tasks.length;
1002
+ harnessItem.tasksOpen = item.tasks.filter((t) => !t.done).length;
1003
+ } else {
1004
+ harnessItem.tasksTotal = 0;
1005
+ harnessItem.tasksOpen = 0;
1006
+ }
1007
+ return harnessItem;
1008
+ });
1009
+ let focusSpec = null;
1010
+ let focusPath = null;
1011
+ const parsedFocus = readFocusFile(root);
1012
+ if (parsedFocus) {
1013
+ focusSpec = parsedFocus.specName;
1014
+ focusPath = `.letra/specs/${parsedFocus.specName}/`;
1015
+ } else {
1016
+ const primaryItem = items.find((i) => i.id === primaryItemId);
1017
+ if (primaryItem?.spec) {
1018
+ focusSpec = primaryItem.spec;
1019
+ focusPath = `.letra/specs/${primaryItem.spec}/`;
1020
+ }
1021
+ }
1022
+ return {
1023
+ workflowName: workflow.name,
1024
+ hasWorkflow: true,
1025
+ activeStage: stage ? { id: stage.id, name: stage.name } : { id: activeStageId, name: activeStageId },
1026
+ items,
1027
+ hasFocus,
1028
+ primaryItemId,
1029
+ focusSpec,
1030
+ focusPath,
1031
+ acDrifts: acDrifts.length > 0 ? acDrifts : void 0
1032
+ };
1033
+ }
1034
+
1035
+ // src/adapters/formatters.ts
1036
+ var L1_FILES = [".letra/context.md", ".letra/constitution.md", ".letra/glossary.md"];
1037
+ function formatL1(snapshot, format) {
1038
+ if (format === "at") {
1039
+ const lines2 = ["# Context", ...L1_FILES.map((path) => `@${path}`)];
1040
+ if (snapshot.hasFocus) lines2.push("@.letra/focus.md");
1041
+ return lines2.join("\n");
1042
+ }
1043
+ const lines = [
1044
+ "Read the following files before starting any task:",
1045
+ ...L1_FILES.map((path) => `- ${path}`)
1046
+ ];
1047
+ if (snapshot.hasFocus) {
1048
+ lines.push("- .letra/focus.md (defines current session focus)");
1049
+ } else {
1050
+ lines.push("- .letra/focus.md (if exists, defines current session focus)");
1051
+ }
1052
+ return lines.join("\n");
1053
+ }
1054
+ function formatL2(snapshot) {
1055
+ if (!snapshot.hasWorkflow || !snapshot.activeStage) return null;
1056
+ const itemsBlock = snapshot.items.length > 0 ? snapshot.items.map((item) => {
1057
+ let line = `- ${item.id}: ${item.description}`;
1058
+ if (item.spec) {
1059
+ line += `
1060
+ - spec: ${item.specPath}
1061
+ - acceptance: ${item.acceptancePath}`;
1062
+ }
1063
+ return line;
1064
+ }).join("\n") : "(nenhum item ativo neste estagio)";
1065
+ return `## Workflow
1066
+
1067
+ **Estagio atual:** ${snapshot.activeStage.name}
1068
+
1069
+ ### Itens neste estagio
1070
+
1071
+ ${itemsBlock}`;
1072
+ }
1073
+ function formatL3(snapshot) {
1074
+ if (!snapshot.hasWorkflow) return null;
1075
+ const primaryItem = snapshot.items.find((i) => i.id === snapshot.primaryItemId);
1076
+ const primaryLine = primaryItem ? `**Item primario:** ${primaryItem.id}${primaryItem.spec ? ` (${primaryItem.spec})` : ""}` : "**Item primario:** nenhum";
1077
+ let acPending = 0;
1078
+ let acTotal = 0;
1079
+ let tasksOpen = 0;
1080
+ let tasksTotal = 0;
1081
+ if (primaryItem) {
1082
+ acPending = primaryItem.acPending ?? 0;
1083
+ acTotal = primaryItem.acTotal ?? 0;
1084
+ tasksOpen = primaryItem.tasksOpen ?? 0;
1085
+ tasksTotal = primaryItem.tasksTotal ?? 0;
1086
+ }
1087
+ const lines = [
1088
+ "## Sinais de trabalho",
1089
+ "",
1090
+ primaryLine,
1091
+ `**ACs:** ${acPending}/${acTotal} pendentes`,
1092
+ `**Tasks:** ${tasksOpen}/${tasksTotal} abertas`
1093
+ ];
1094
+ if (primaryItem?.spec && snapshot.acDrifts) {
1095
+ const drift = snapshot.acDrifts.find((d) => d.spec === primaryItem.spec);
1096
+ if (drift) {
1097
+ lines.push(
1098
+ `\u26A0 ac-source-drift: spec.md=${drift.specCount}, acceptance.md=${drift.acceptanceCount}`
1099
+ );
1100
+ }
1101
+ }
1102
+ return lines.join("\n");
1103
+ }
1104
+ function formatRules(snapshot) {
1105
+ if (snapshot.hasWorkflow) {
1106
+ return `## Regras
711
1107
 
712
1108
  - Leia as specs em .letra/specs/ antes de codificar
713
1109
  - Execute \`letra validate\` para verificar acceptance criteria
714
1110
  - Siga a constitution.md rigorosamente
715
- - Ao concluir, mova o item com \`letra flow move <id> --to <proximo_estagio>\`
716
- `;
1111
+ - Ao concluir, mova o item com \`letra flow move <id> --to <proximo_estagio>\``;
1112
+ }
1113
+ return `# Rules
1114
+ - Always read specs in .letra/specs/ before writing code
1115
+ - Run \`letra validate\` to check acceptance criteria
1116
+ - Follow the constitution.md rules strictly
1117
+ - Use formal tone in all generated content`;
717
1118
  }
718
- function generateAdapters(root, tools, content) {
719
- const adapters = [];
720
- const header = `# Gerado por letra flow move. Nao edite manualmente.
1119
+ function formatAdapterContent(snapshot, format, options) {
1120
+ const title = snapshot.hasWorkflow ? `# Letra Context \u2014 ${snapshot.workflowName}` : `# Letra Context \u2014 ${options.displayName} Adapter`;
1121
+ const sections = [title, formatL1(snapshot, format)];
1122
+ const l2 = formatL2(snapshot);
1123
+ if (l2) sections.push(l2);
1124
+ const l3 = formatL3(snapshot);
1125
+ if (l3) sections.push(l3);
1126
+ sections.push(formatRules(snapshot));
1127
+ return `${sections.join("\n\n")}
721
1128
  `;
1129
+ }
1130
+
1131
+ // src/adapters/generate.ts
1132
+ var ADAPTER_HEADER = {
1133
+ init: "# Generated by letra init. Do not edit manually.\n",
1134
+ "flow-move": "# Gerado por letra flow move. Nao edite manualmente.\n",
1135
+ focus: "# Gerado por letra focus. Nao edite manualmente.\n"
1136
+ };
1137
+ var TOOL_TARGETS = {
1138
+ cursor: { path: ".cursorrules", format: "at", displayName: "Cursor" },
1139
+ "claude-code": { path: "CLAUDE.md", format: "text", displayName: "Claude Code" },
1140
+ windsurf: { path: ".windsurfrules", format: "at", displayName: "Windsurf" },
1141
+ vscode: {
1142
+ path: ".github/copilot-instructions.md",
1143
+ format: "text",
1144
+ displayName: "VSCode Copilot"
1145
+ },
1146
+ opencode: { path: "AGENTS.md", format: "text", displayName: "OpenCode" }
1147
+ };
1148
+ function generateAdapters(root, tools, options) {
1149
+ const snapshot = buildHarnessSnapshot(root, options);
1150
+ const header = ADAPTER_HEADER[options.source];
1151
+ const verb = options.verb ?? (options.source === "init" ? "Created" : "Updated");
722
1152
  for (const tool of tools) {
723
- switch (tool) {
724
- case "cursor":
725
- adapters.push({
726
- path: join5(root, ".cursorrules"),
727
- content: header + content
728
- });
729
- break;
730
- case "claude-code":
731
- adapters.push({
732
- path: join5(root, "CLAUDE.md"),
733
- content: header + content
734
- });
735
- break;
736
- case "windsurf":
737
- adapters.push({
738
- path: join5(root, ".windsurfrules"),
739
- content: header + content
740
- });
741
- break;
742
- case "vscode": {
743
- const dir = join5(root, ".github");
744
- if (!existsSync5(dir)) mkdirSync3(dir, { recursive: true });
745
- adapters.push({
746
- path: join5(dir, "copilot-instructions.md"),
747
- content: header + content
748
- });
749
- break;
750
- }
751
- case "opencode":
752
- adapters.push({
753
- path: join5(root, "AGENTS.md"),
754
- content: header + content
755
- });
756
- break;
1153
+ const target = TOOL_TARGETS[tool];
1154
+ if (!target) continue;
1155
+ const content = formatAdapterContent(snapshot, target.format, {
1156
+ source: options.source,
1157
+ displayName: target.displayName
1158
+ });
1159
+ const filePath = join8(root, target.path);
1160
+ const dir = join8(filePath, "..");
1161
+ if (!existsSync8(dir)) mkdirSync3(dir, { recursive: true });
1162
+ writeFileSync6(filePath, header + content);
1163
+ if (!options.quiet) {
1164
+ console.log(
1165
+ ` ${chalk8.gray(verb)} ${filePath.replace(`${root}/`, "").replace(`${root}\\`, "")}`
1166
+ );
757
1167
  }
758
1168
  }
759
- for (const { path, content: fileContent } of adapters) {
760
- const dir = join5(path, "..");
761
- if (!existsSync5(dir)) mkdirSync3(dir, { recursive: true });
762
- writeFileSync5(path, fileContent);
763
- console.log(` ${chalk7.gray("Updated")} ${path.replace(`${root}/`, "")}`);
1169
+ }
1170
+
1171
+ // src/commands/flow-move.ts
1172
+ function now6() {
1173
+ return (/* @__PURE__ */ new Date()).toISOString();
1174
+ }
1175
+ function resolveStage(workflow, input) {
1176
+ const lower = input.toLowerCase();
1177
+ for (const stage of workflow.stages) {
1178
+ if (stage.id === lower) return stage.id;
1179
+ if (stage.name.toLowerCase() === lower) return stage.id;
764
1180
  }
1181
+ return null;
765
1182
  }
766
1183
  function flowMove(root, itemId, targetStageInput) {
767
1184
  const workflow = loadWorkflow(root);
768
1185
  if (!workflow) {
769
- console.log(
770
- chalk7.red("No workflow found. Run 'letra flow init --quick' first")
771
- );
1186
+ console.log(chalk9.red("No workflow found. Run 'letra flow init --quick' first"));
772
1187
  process.exit(1);
773
1188
  }
774
1189
  const item = workflow.items.find((i) => i.id === itemId) || workflow.items.find((i) => i.description === itemId);
775
1190
  if (!item) {
776
- console.log(chalk7.red(`Item "${itemId}" not found`));
1191
+ console.log(chalk9.red(`Item "${itemId}" not found`));
777
1192
  process.exit(1);
778
1193
  }
779
1194
  const targetStageId = resolveStage(workflow, targetStageInput);
780
1195
  if (!targetStageId) {
781
1196
  const valid = workflow.stages.map((s) => `${s.id} (${s.name})`).join(", ");
782
- console.log(
783
- chalk7.red(
784
- `Stage "${targetStageInput}" not found. Valid stages: ${valid}`
785
- )
786
- );
1197
+ console.log(chalk9.red(`Stage "${targetStageInput}" not found. Valid stages: ${valid}`));
787
1198
  process.exit(1);
788
1199
  }
789
1200
  if (item.stage === targetStageId) {
790
- console.log(
791
- chalk7.yellow(`Item ${itemId} is already in stage "${targetStageId}"`)
792
- );
1201
+ console.log(chalk9.yellow(`Item ${itemId} is already in stage "${targetStageId}"`));
793
1202
  return;
794
1203
  }
795
1204
  const fromStage = workflow.stages.find((s) => s.id === item.stage)?.name || item.stage;
796
1205
  const toStage = workflow.stages.find((s) => s.id === targetStageId)?.name || targetStageId;
797
1206
  item.stage = targetStageId;
798
- workflow.updatedAt = now5();
1207
+ workflow.updatedAt = now6();
799
1208
  saveWorkflow(root, workflow);
800
- const stageNames = new Map(workflow.stages.map((s) => [s.id, s.name]));
801
- const currentStageName = stageNames.get(targetStageId) || targetStageId;
802
- const content = adapterContent(
803
- workflow.name,
804
- currentStageName,
805
- workflow.items,
806
- stageNames
807
- );
808
- generateAdapters(root, workflow.tools, content);
809
- console.log(
810
- ` ${chalk7.green("\u2713")} Item ${chalk7.cyan(itemId)} moved: ${chalk7.yellow(fromStage)} \u2192 ${chalk7.green(toStage)}`
811
- );
1209
+ generateAdapters(root, workflow.tools, {
1210
+ source: "flow-move",
1211
+ workflow: {
1212
+ name: workflow.name,
1213
+ stages: workflow.stages,
1214
+ items: workflow.items
1215
+ },
1216
+ activeStageId: targetStageId,
1217
+ primaryItemId: itemId
1218
+ });
1219
+ if (item.spec) {
1220
+ writeFocusFile(root, item.spec, item.id);
1221
+ }
812
1222
  console.log(
813
- ` ${chalk7.gray("Adapters regenerated for:")} ${workflow.tools.join(", ")}`
1223
+ ` ${chalk9.green("\u2713")} Item ${chalk9.cyan(itemId)} moved: ${chalk9.yellow(fromStage)} \u2192 ${chalk9.green(toStage)}`
814
1224
  );
1225
+ console.log(` ${chalk9.gray("Adapters regenerated for:")} ${workflow.tools.join(", ")}`);
815
1226
  }
816
1227
  function flowMoveAction(targetPath, itemId, options) {
817
- const root = resolve7(process.cwd(), targetPath || ".");
1228
+ const root = resolve8(process.cwd(), targetPath || ".");
818
1229
  flowMove(root, itemId, options.to);
819
1230
  }
820
1231
 
821
1232
  // src/commands/flow-serve.ts
1233
+ import { existsSync as existsSync16, mkdirSync as mkdirSync6, readFileSync as readFileSync12, readdirSync as readdirSync6, watch, writeFileSync as writeFileSync8 } from "fs";
1234
+ import { createServer } from "http";
1235
+ import { dirname, extname, join as join17, resolve as resolve9 } from "path";
1236
+ import { fileURLToPath } from "url";
1237
+
1238
+ // src/diagnostics/engine.ts
1239
+ import { existsSync as existsSync15 } from "fs";
1240
+ import { join as join16 } from "path";
1241
+
1242
+ // src/diagnostics/snapshot.ts
822
1243
  import {
823
- existsSync as existsSync6,
824
- readFileSync as readFileSync5,
1244
+ readFileSync as readFileSync7,
1245
+ writeFileSync as writeFileSync7,
1246
+ mkdirSync as mkdirSync4,
1247
+ existsSync as existsSync9,
825
1248
  readdirSync as readdirSync3,
826
- statSync,
827
- watch
1249
+ rmSync
828
1250
  } from "fs";
829
- import {
830
- createServer
831
- } from "http";
832
- import { join as join6, resolve as resolve8 } from "path";
833
- var DEFAULT_PORT = 3e3;
834
- function loadSpecs(root) {
835
- const specsDir = join6(root, ".letra", "specs");
836
- if (!existsSync6(specsDir)) return [];
837
- return readdirSync3(specsDir).filter((entry) => {
838
- const specFile = join6(specsDir, entry, "spec.md");
839
- return statSync(join6(specsDir, entry)).isDirectory() && existsSync6(specFile);
840
- }).map((entry) => {
841
- const content = readFileSync5(join6(specsDir, entry, "spec.md"), "utf-8");
842
- return { name: entry, content };
843
- });
1251
+ import { join as join10 } from "path";
1252
+ var SNAPSHOTS_DIR = ".letra/snapshots";
1253
+ var MAX_SNAPSHOTS = 20;
1254
+ var TTL_MS = 7 * 24 * 60 * 60 * 1e3;
1255
+ var SnapshotStore = class {
1256
+ rootDir;
1257
+ snapshotsDir;
1258
+ constructor(rootDir) {
1259
+ this.rootDir = rootDir;
1260
+ this.snapshotsDir = join10(rootDir, SNAPSHOTS_DIR);
1261
+ if (!existsSync9(this.snapshotsDir)) {
1262
+ mkdirSync4(this.snapshotsDir, { recursive: true });
1263
+ }
1264
+ this.cleanup();
1265
+ this.enforceMax();
1266
+ }
1267
+ async save(diagnosticId, diagnosticTitle, files) {
1268
+ if (this.isDuplicate(diagnosticId, files)) {
1269
+ return null;
1270
+ }
1271
+ const id = `${Date.now()}_${diagnosticId}`;
1272
+ const snapshot = {
1273
+ id,
1274
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1275
+ diagnosticId,
1276
+ diagnosticTitle,
1277
+ files
1278
+ };
1279
+ writeFileSync7(
1280
+ join10(this.snapshotsDir, `${id}.json`),
1281
+ JSON.stringify(snapshot, null, 0),
1282
+ "utf-8"
1283
+ );
1284
+ this.enforceMax();
1285
+ return id;
1286
+ }
1287
+ async restore(snapshotId) {
1288
+ const filePath = join10(this.snapshotsDir, `${snapshotId}.json`);
1289
+ if (!existsSync9(filePath)) {
1290
+ return { ok: false, restoredFiles: [] };
1291
+ }
1292
+ const snapshot = JSON.parse(readFileSync7(filePath, "utf-8"));
1293
+ const restoredFiles = [];
1294
+ for (const file of snapshot.files) {
1295
+ const absolutePath = join10(this.rootDir, file.path);
1296
+ writeFileSync7(absolutePath, file.before, "utf-8");
1297
+ restoredFiles.push(file.path);
1298
+ }
1299
+ rmSync(filePath);
1300
+ return { ok: true, restoredFiles };
1301
+ }
1302
+ list() {
1303
+ if (!existsSync9(this.snapshotsDir)) return [];
1304
+ return readdirSync3(this.snapshotsDir).filter((f) => f.endsWith(".json")).map((f) => {
1305
+ const content = readFileSync7(join10(this.snapshotsDir, f), "utf-8");
1306
+ return JSON.parse(content);
1307
+ }).sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
1308
+ }
1309
+ isDuplicate(diagnosticId, files) {
1310
+ const last = this.getLastForDiagnostic(diagnosticId);
1311
+ if (!last) return false;
1312
+ if (last.files.length !== files.length) return false;
1313
+ for (let i = 0; i < files.length; i++) {
1314
+ if (last.files[i]?.after !== files[i]?.after) return false;
1315
+ }
1316
+ return true;
1317
+ }
1318
+ getLastForDiagnostic(diagnosticId) {
1319
+ if (!existsSync9(this.snapshotsDir)) return null;
1320
+ const entries = readdirSync3(this.snapshotsDir).filter(
1321
+ (f) => f.endsWith(".json") && f.includes(`_${diagnosticId}`)
1322
+ );
1323
+ if (entries.length === 0) return null;
1324
+ entries.sort().reverse();
1325
+ try {
1326
+ const content = readFileSync7(join10(this.snapshotsDir, entries[0]), "utf-8");
1327
+ return JSON.parse(content);
1328
+ } catch {
1329
+ return null;
1330
+ }
1331
+ }
1332
+ enforceMax() {
1333
+ if (!existsSync9(this.snapshotsDir)) return;
1334
+ const entries = readdirSync3(this.snapshotsDir).filter((f) => f.endsWith(".json")).sort();
1335
+ while (entries.length > MAX_SNAPSHOTS) {
1336
+ const oldest = entries.shift();
1337
+ if (oldest) {
1338
+ rmSync(join10(this.snapshotsDir, oldest));
1339
+ }
1340
+ }
1341
+ }
1342
+ cleanup() {
1343
+ if (!existsSync9(this.snapshotsDir)) return;
1344
+ const cutoff = Date.now() - TTL_MS;
1345
+ for (const file of readdirSync3(this.snapshotsDir)) {
1346
+ if (!file.endsWith(".json")) continue;
1347
+ try {
1348
+ const filePath = join10(this.snapshotsDir, file);
1349
+ const snapshot = JSON.parse(readFileSync7(filePath, "utf-8"));
1350
+ if (new Date(snapshot.timestamp).getTime() < cutoff) {
1351
+ rmSync(filePath);
1352
+ }
1353
+ } catch {
1354
+ }
1355
+ }
1356
+ }
1357
+ };
1358
+
1359
+ // src/diagnostics/detectors/ac-stale.ts
1360
+ import { readFileSync as readFileSync8, existsSync as existsSync10 } from "fs";
1361
+ import { join as join11 } from "path";
1362
+ import { readdirSync as readdirSync4 } from "fs";
1363
+ var STALE_AC_PATTERN = /-\s\[ \]\s\*\*`([^`]+)`\*\*/g;
1364
+ var acStaleDetector = {
1365
+ name: "ac-stale",
1366
+ async run(rootDir) {
1367
+ const results = [];
1368
+ const specsDir = join11(rootDir, ".letra", "specs");
1369
+ if (!existsSync10(specsDir)) return results;
1370
+ const specDirs = readdirSync4(specsDir, { withFileTypes: true }).filter(
1371
+ (d) => d.isDirectory() && !d.name.startsWith("_")
1372
+ );
1373
+ for (const dir of specDirs) {
1374
+ const specFile = join11(specsDir, dir.name, "spec.md");
1375
+ if (!existsSync10(specFile)) continue;
1376
+ const content = readFileSync8(specFile, "utf-8");
1377
+ const matches = content.matchAll(STALE_AC_PATTERN);
1378
+ for (const match of matches) {
1379
+ const command = match[1].trim();
1380
+ if (!command) continue;
1381
+ const commandWords = command.split(/\s+/);
1382
+ const camelCaseName = commandWords.map((w, i) => i === 0 ? w : w.charAt(0).toUpperCase() + w.slice(1)).join("");
1383
+ const pascalCaseName = commandWords.map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("");
1384
+ const foundInSource = searchInSource(rootDir, [
1385
+ command,
1386
+ camelCaseName,
1387
+ pascalCaseName
1388
+ ]);
1389
+ if (foundInSource) {
1390
+ results.push({
1391
+ id: `ac-stale_${dir.name}_${command.replace(/\s+/g, "-")}`,
1392
+ type: "info",
1393
+ title: `AC "${command}" marcado [ ] mas implementado`,
1394
+ description: `O acceptance criteria "${command}" do spec ${dir.name} est\xE1 marcado como n\xE3o feito ([ ]), mas o c\xF3digo-fonte cont\xE9m implementa\xE7\xE3o correspondente.`,
1395
+ certainty: 0.9,
1396
+ detector: "ac-stale",
1397
+ autoFix: async () => {
1398
+ const newContent = content.replace(
1399
+ new RegExp(
1400
+ `(- \\[ \\] \\*\\*\`)(${escapeRegex(command)}(\\s[^*]+)?\\*\\*)`
1401
+ ),
1402
+ (m) => m.replace("[ ]", "[x]")
1403
+ );
1404
+ const before = readFileSync8(specFile, "utf-8");
1405
+ return {
1406
+ files: [
1407
+ {
1408
+ path: `.letra/specs/${dir.name}/spec.md`,
1409
+ before,
1410
+ after: newContent
1411
+ }
1412
+ ],
1413
+ snapshotId: ""
1414
+ };
1415
+ }
1416
+ });
1417
+ }
1418
+ }
1419
+ }
1420
+ return results;
1421
+ }
1422
+ };
1423
+ function searchInSource(rootDir, terms) {
1424
+ const searchDirs = ["packages/cli/src", "packages/client/src", "packages/ui/src"];
1425
+ for (const searchDir of searchDirs) {
1426
+ const dir = join11(rootDir, searchDir);
1427
+ if (!existsSync10(dir)) continue;
1428
+ try {
1429
+ const files = walkDir(dir);
1430
+ for (const file of files) {
1431
+ const content = readFileSync8(file, "utf-8");
1432
+ for (const term of terms) {
1433
+ if (content.includes(term)) return true;
1434
+ }
1435
+ }
1436
+ } catch {
1437
+ }
1438
+ }
1439
+ return false;
844
1440
  }
845
- function findItemSpec(item, specs) {
846
- const desc = item.description.toLowerCase();
847
- return specs.find(
848
- (s) => desc.includes(s.name.toLowerCase().replace(/-/g, " ")) || desc.includes(s.name.toLowerCase())
849
- );
1441
+ function walkDir(dir) {
1442
+ const files = [];
1443
+ try {
1444
+ for (const entry of readdirSync4(dir, { withFileTypes: true })) {
1445
+ const fullPath = join11(dir, entry.name);
1446
+ if (entry.isDirectory() && entry.name !== "node_modules") {
1447
+ files.push(...walkDir(fullPath));
1448
+ } else if (entry.isFile() && (entry.name.endsWith(".ts") || entry.name.endsWith(".tsx"))) {
1449
+ files.push(fullPath);
1450
+ }
1451
+ }
1452
+ } catch {
1453
+ }
1454
+ return files;
850
1455
  }
851
- function boardHtml(workflow, specs = []) {
852
- const stages = workflow?.stages ?? [];
853
- const items = workflow?.items ?? [];
854
- const itemsByStage = /* @__PURE__ */ new Map();
855
- for (const s of stages) itemsByStage.set(s.id, []);
856
- for (const it of items) {
857
- const list = itemsByStage.get(it.stage);
858
- if (list) list.push(it);
859
- }
860
- function ageLabel2(createdAt) {
861
- const age = Math.floor(
862
- (Date.now() - new Date(createdAt).getTime()) / (1e3 * 60 * 60 * 24)
863
- );
864
- if (age === 0) return "today";
865
- if (age === 1) return "1d ago";
866
- return `${age}d ago`;
867
- }
868
- const stageCards = stages.map((s) => {
869
- const stageItems = itemsByStage.get(s.id) ?? [];
870
- const itemsHtml = stageItems.length === 0 ? '<div class="empty">(empty)</div>' : stageItems.map((it) => {
871
- const spec = findItemSpec(it, specs);
872
- const specBtn = spec ? `<button class="spec-btn" data-spec="${esc(spec.name)}">spec</button>` : "";
873
- return `<div class="item stage-${esc(s.id)}"><span class="item-id">${it.id}</span><span class="item-desc">${esc(it.description)}</span><span class="item-bottom">${specBtn}<span class="item-age">${ageLabel2(it.createdAt)}</span></span></div>`;
874
- }).join("");
875
- const count = stageItems.length;
876
- return `<div class="stage stage-${esc(s.id)}"><h2>${esc(s.name)} <span class="count">${count} ${count === 1 ? "item" : "items"}</span></h2><div class="items">${itemsHtml}</div></div>`;
877
- }).join("\n");
878
- const name = workflow ? esc(workflow.name) : "No workflow";
879
- const updatedAt = workflow ? new Date(workflow.updatedAt).toLocaleString() : "-";
880
- return `<!DOCTYPE html>
881
- <html lang="en">
882
- <head>
883
- <meta charset="UTF-8">
884
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
885
- <title>${name} \u2014 Flow Board</title>
886
- <style>
887
- *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
888
- body {
889
- font-family: system-ui, -apple-system, sans-serif;
890
- background: #0f1117; color: #e1e4e8;
891
- padding: 2rem 1rem; max-width: 1200px; margin: 0 auto;
892
- }
893
- header {
894
- display: flex; justify-content: space-between; align-items: center;
895
- }
896
- .brand {
897
- display: flex; align-items: center; gap: 0.625rem;
898
- }
899
- .brand svg { width: 36px; height: 36px; flex-shrink: 0; }
900
- .brand-text { font-weight: 600; font-size: 1rem; color: #e1e4e8; }
901
- .brand-text span { color: #8b949e; font-weight: 300; }
902
- .header-status { color: #8b949e; font-size: 0.75rem; }
903
- .live { color: #3fb950; }
904
- .live::before { content: "\u25CF"; margin-right: 0.3rem; }
905
- .project-desc { margin: 15px 0 1.5rem; }
906
- .project-desc h1 { font-size: 1.4rem; font-weight: 700; margin-bottom: 0.25rem; }
907
- .project-desc p { color: #8b949e; font-size: 0.9rem; line-height: 1.4; }
908
- .board-scroll { overflow-x: auto; padding-bottom: 0.5rem; }
909
- .board { display: flex; gap: 1rem; }
910
- .stage {
911
- flex: 0 0 280px; width: 280px;
912
- background: #161b22; border: 1px solid #30363d; border-top: 3px solid #30363d;
913
- border-radius: 10px; padding: 1rem; display: flex; flex-direction: column; gap: 0.5rem;
914
- transition: border-top-color .2s;
915
- }
916
- .stage.stage-backlog { border-top-color: #8b949e; }
917
- .stage.stage-design { border-top-color: #d29922; }
918
- .stage.stage-code { border-top-color: #58a6ff; }
919
- .stage.stage-review { border-top-color: #bc8cff; }
920
- .stage.stage-done { border-top-color: #3fb950; }
921
- .stage h2 { font-size: 1rem; font-weight: 600; display: flex; justify-content: space-between; align-items: center; }
922
- .count { font-size: 0.7rem; color: #8b949e; font-weight: 400; background: rgba(139,148,158,0.1); padding: 0.15rem 0.5rem; border-radius: 10px; }
923
- .items { display: flex; flex-direction: column; gap: 0.5rem; min-height: 2rem; }
924
- .empty { color: #484f58; font-size: 0.8rem; padding: 0.75rem 0; text-align: center; border: 1px dashed #21262d; border-radius: 6px; }
925
- .item {
926
- background: #0f1117; border-radius: 8px; padding: 0.625rem 0.75rem;
927
- display: flex; flex-direction: column; gap: 0.3rem;
928
- border-left: 3px solid #30363d; box-shadow: 0 1px 2px rgba(0,0,0,0.2);
929
- transition: border-color .15s, transform .15s, box-shadow .15s;
930
- }
931
- .item:hover { transform: translateY(-1px); box-shadow: 0 3px 8px rgba(0,0,0,0.3); }
932
- .item.stage-backlog { border-left-color: #8b949e; }
933
- .item.stage-design { border-left-color: #d29922; }
934
- .item.stage-code { border-left-color: #58a6ff; }
935
- .item.stage-review { border-left-color: #bc8cff; }
936
- .item.stage-done { border-left-color: #3fb950; }
937
- .item-id {
938
- font-family: monospace; font-size: 0.65rem; color: #58a6ff; font-weight: 600;
939
- background: rgba(88,166,255,0.1); padding: 0.1rem 0.4rem; border-radius: 4px;
940
- display: inline-block; width: fit-content;
941
- }
942
- .item-desc { font-size: 0.85rem; color: #e1e4e8; line-height: 1.35; margin-top: 0.1rem; }
943
- .item-bottom { display: flex; justify-content: space-between; align-items: center; margin-top: 0.2rem; }
944
- .item-age { font-size: 0.65rem; color: #8b949e; }
945
- .spec-btn {
946
- background: none; border: 1px solid #30363d; border-radius: 4px;
947
- color: #8b949e; font-size: 0.6rem; padding: 0.1rem 0.4rem;
948
- cursor: pointer; font-family: monospace; transition: .15s;
949
- }
950
- .spec-btn:hover { border-color: #58a6ff; color: #58a6ff; background: rgba(88,166,255,0.08); }
951
- .board-fade { animation: fadeIn .3s ease; }
952
- @keyframes fadeIn { from { opacity: 0.5; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } }
953
- .modal { position: fixed; inset: 0; z-index: 100; display: flex; align-items: center; justify-content: center; }
954
- .modal.hidden { display: none; }
955
- .modal-backdrop { position: absolute; inset: 0; background: rgba(0,0,0,0.7); }
956
- .modal-content {
957
- position: relative; background: #161b22; border: 1px solid #30363d;
958
- border-radius: 12px; max-width: 700px; width: 90%; max-height: 80vh;
959
- display: flex; flex-direction: column;
960
- }
961
- .modal-header {
962
- display: flex; justify-content: space-between; align-items: center;
963
- padding: 1rem 1.25rem; border-bottom: 1px solid #30363d;
964
- }
965
- .modal-header h2 { font-size: 1rem; font-weight: 600; }
966
- .modal-close {
967
- background: none; border: none; color: #8b949e; font-size: 1.5rem;
968
- cursor: pointer; line-height: 1; padding: 0;
969
- }
970
- .modal-close:hover { color: #e1e4e8; }
971
- .modal-body {
972
- padding: 1.25rem; overflow-y: auto; font-size: 0.875rem; line-height: 1.6;
973
- white-space: pre-wrap; font-family: monospace; color: #e1e4e8;
974
- }
975
- .modal-body h1, .modal-body h2, .modal-body h3 { font-family: system-ui; margin: 1rem 0 0.5rem; }
976
- .modal-body h1 { font-size: 1.2rem; }
977
- .modal-body h2 { font-size: 1rem; color: #58a6ff; }
978
- .modal-body h3 { font-size: 0.9rem; color: #d29922; }
979
- .modal-body ul, .modal-body ol { padding-left: 1.5rem; margin: 0.5rem 0; }
980
- .modal-body li { margin-bottom: 0.25rem; }
981
- .modal-body code { background: #0f1117; padding: 0.1rem 0.3rem; border-radius: 3px; font-size: 0.8rem; }
982
- .modal-body pre { background: #0f1117; padding: 0.75rem; border-radius: 6px; overflow-x: auto; margin: 0.5rem 0; }
983
- .modal-body pre code { background: none; padding: 0; }
984
- @media (max-width: 600px) {
985
- .board { grid-template-columns: 1fr; }
986
- body { padding: 1rem 0.5rem; }
1456
+ function escapeRegex(s) {
1457
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1458
+ }
1459
+
1460
+ // src/diagnostics/detectors/missing-dir.ts
1461
+ import { existsSync as existsSync11, mkdirSync as mkdirSync5 } from "fs";
1462
+ import { join as join12 } from "path";
1463
+ var REQUIRED_DIRS = [
1464
+ {
1465
+ path: ".letra/templates",
1466
+ spec: "spec-templates-domain",
1467
+ description: "templates customizados de specs"
1468
+ },
1469
+ { path: ".letra/brand", spec: "flow-serve", description: "logos SVG do Letra" }
1470
+ ];
1471
+ var missingDirDetector = {
1472
+ name: "missing-dir",
1473
+ async run(rootDir) {
1474
+ const results = [];
1475
+ for (const required of REQUIRED_DIRS) {
1476
+ const dirPath = join12(rootDir, required.path);
1477
+ if (existsSync11(dirPath)) continue;
1478
+ results.push({
1479
+ id: `missing-dir_${required.path.replace(/[/.]/g, "-")}`,
1480
+ type: "info",
1481
+ title: `Diret\xF3rio ausente: ${required.path}/`,
1482
+ description: `O diret\xF3rio ${required.path}/ \xE9 referenciado pelo spec ${required.spec} (${required.description}), mas n\xE3o existe.`,
1483
+ certainty: 1,
1484
+ detector: "missing-dir",
1485
+ autoFix: async () => ({
1486
+ files: [],
1487
+ snapshotId: ""
1488
+ })
1489
+ });
1490
+ }
1491
+ for (const r of results) {
1492
+ const originalAutoFix = r.autoFix;
1493
+ if (!originalAutoFix) continue;
1494
+ r.autoFix = async () => {
1495
+ const dirs = [];
1496
+ for (const required of REQUIRED_DIRS) {
1497
+ const dirPath = join12(rootDir, required.path);
1498
+ if (existsSync11(dirPath)) continue;
1499
+ mkdirSync5(dirPath, { recursive: true });
1500
+ dirs.push(required.path);
1501
+ }
1502
+ return {
1503
+ files: [],
1504
+ snapshotId: ""
1505
+ };
1506
+ };
1507
+ }
1508
+ return results;
1509
+ }
1510
+ };
1511
+
1512
+ // src/diagnostics/detectors/dead-icons.ts
1513
+ import { readFileSync as readFileSync9, existsSync as existsSync12 } from "fs";
1514
+ import { join as join13 } from "path";
1515
+ import { readdirSync as readdirSync5 } from "fs";
1516
+ var ICON_USAGE_PATTERN = /<Icon\s+name="([^"]+)"/g;
1517
+ var ICON_DEF_PATTERN = /"([a-z-]+)":\s*\(/g;
1518
+ var deadIconsDetector = {
1519
+ name: "dead-icons",
1520
+ async run(rootDir) {
1521
+ const results = [];
1522
+ const iconFiles = findIconFiles(rootDir);
1523
+ if (iconFiles.length === 0) return results;
1524
+ const definedIcons = /* @__PURE__ */ new Set();
1525
+ const usedIcons = /* @__PURE__ */ new Set();
1526
+ for (const file of iconFiles) {
1527
+ const content = readFileSync9(file, "utf-8");
1528
+ const defs = content.matchAll(ICON_DEF_PATTERN);
1529
+ for (const d of defs) {
1530
+ definedIcons.add(d[1]);
1531
+ }
1532
+ const usages = content.matchAll(ICON_USAGE_PATTERN);
1533
+ for (const u of usages) {
1534
+ usedIcons.add(u[1]);
1535
+ }
1536
+ }
1537
+ const srcDir = join13(rootDir, "packages", "client", "src");
1538
+ if (existsSync12(srcDir)) {
1539
+ const files = walkDir2(srcDir);
1540
+ for (const file of files) {
1541
+ const content = readFileSync9(file, "utf-8");
1542
+ const usages = content.matchAll(ICON_USAGE_PATTERN);
1543
+ for (const u of usages) {
1544
+ usedIcons.add(u[1]);
1545
+ }
1546
+ }
1547
+ }
1548
+ for (const iconName of usedIcons) {
1549
+ if (definedIcons.has(iconName)) continue;
1550
+ results.push({
1551
+ id: `dead-icons_${iconName}`,
1552
+ type: "warning",
1553
+ title: `\xCDcone "${iconName}" referenciado mas n\xE3o definido`,
1554
+ description: `O \xEDcone "${iconName}" \xE9 usado em <Icon name="${iconName}" /> mas n\xE3o est\xE1 definido no ICONS map. Renderiza null silenciosamente.`,
1555
+ certainty: 1,
1556
+ detector: "dead-icons",
1557
+ autoFix: async () => {
1558
+ const fixes = [];
1559
+ for (const file of iconFiles) {
1560
+ const content = readFileSync9(file, "utf-8");
1561
+ if (!content.includes("const ICONS")) continue;
1562
+ const lines = content.split("\n");
1563
+ const insertLine = lines.findIndex(
1564
+ (l) => l.includes("];") || l.includes("};")
1565
+ );
1566
+ if (insertLine === -1) continue;
1567
+ const indent = " ";
1568
+ const iconSvg = `${indent}"${iconName}": () => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/></svg>,`;
1569
+ const before = content;
1570
+ const afterLines = [...lines];
1571
+ afterLines.splice(insertLine, 0, iconSvg);
1572
+ const after = afterLines.join("\n");
1573
+ fixes.push({
1574
+ path: file.replace(`${rootDir}\\`, "").replace(/\\/g, "/"),
1575
+ before,
1576
+ after
1577
+ });
1578
+ }
1579
+ return { files: fixes, snapshotId: "" };
1580
+ }
1581
+ });
1582
+ }
1583
+ return results;
987
1584
  }
988
- </style>
989
- </head>
990
- <body>
991
- <header>
992
- <div class="brand">
993
- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40" fill="none">
994
- <rect width="40" height="40" rx="8" fill="#d29922"/>
995
- <path d="M20 10l10 14-10 14-10-14L20 10z" fill="#0f1117"/>
996
- <circle cx="20" cy="24" r="3" fill="#d29922"/>
997
- </svg>
998
- <div class="brand-text">letra<span>.dev</span></div>
999
- </div>
1000
- <div class="header-status">
1001
- <span class="live"></span>
1002
- <span id="status">connected</span>
1003
- <span>&middot; updated ${updatedAt}</span>
1004
- </div>
1005
- </header>
1006
- <div class="project-desc" id="projectDesc">
1007
- <h1>${name}</h1>
1008
- ${workflow?.description ? `<p>${esc(workflow.description)}</p>` : ""}
1009
- </div>
1010
- <div class="board-scroll">
1011
- <div class="board" id="board">
1012
- ${stageCards}
1013
- </div>
1014
- </div>
1015
- <div id="modal" class="modal hidden">
1016
- <div class="modal-backdrop" id="modalBackdrop"></div>
1017
- <div class="modal-content">
1018
- <div class="modal-header">
1019
- <h2 id="modalTitle"></h2>
1020
- <button class="modal-close" id="modalClose">&times;</button>
1021
- </div>
1022
- <div class="modal-body" id="modalBody"></div>
1023
- </div>
1024
- </div>
1025
- <script>
1026
- var __specs = null;
1027
- fetch("/api/specs").then(r => r.json()).then(s => { __specs = s; attachSpecButtons(); }).catch(() => {});
1028
- const evtSource = new EventSource("/events");
1029
- evtSource.addEventListener("workflow-updated", () => {
1030
- document.getElementById("status").textContent = "refreshing...";
1031
- fetch("/api/workflow")
1032
- .then(r => r.json())
1033
- .then(data => {
1034
- document.getElementById("status").textContent = "updated " + new Date().toLocaleTimeString();
1035
- renderBoard(data);
1036
- })
1037
- .catch(() => {
1038
- document.getElementById("status").textContent = "update failed";
1039
- });
1040
- });
1041
- evtSource.onerror = () => {
1042
- document.getElementById("status").textContent = "disconnected";
1043
1585
  };
1044
- function esc(s) {
1045
- const d = document.createElement("div");
1046
- d.textContent = s;
1047
- return d.innerHTML;
1586
+ function findIconFiles(rootDir) {
1587
+ const candidates = [
1588
+ join13(rootDir, "packages", "client", "src", "components", "ui", "icon.tsx"),
1589
+ join13(rootDir, "packages", "ui", "src", "icon.tsx")
1590
+ ];
1591
+ return candidates.filter((f) => existsSync12(f));
1048
1592
  }
1049
- function ageLabel(createdAt) {
1050
- const age = Math.floor((Date.now() - new Date(createdAt).getTime()) / (1000 * 60 * 60 * 24));
1051
- if (age === 0) return "today";
1052
- if (age === 1) return "1d ago";
1053
- return age + "d ago";
1593
+ function walkDir2(dir) {
1594
+ const files = [];
1595
+ try {
1596
+ for (const entry of readdirSync5(dir, { withFileTypes: true })) {
1597
+ const fullPath = join13(dir, entry.name);
1598
+ if (entry.isDirectory() && entry.name !== "node_modules") {
1599
+ files.push(...walkDir2(fullPath));
1600
+ } else if (entry.isFile() && (entry.name.endsWith(".tsx") || entry.name.endsWith(".ts"))) {
1601
+ files.push(fullPath);
1602
+ }
1603
+ }
1604
+ } catch {
1605
+ }
1606
+ return files;
1054
1607
  }
1055
- function matchSpec(desc, specs) {
1056
- const lower = desc.toLowerCase();
1057
- for (const s of specs) {
1058
- if (lower.includes(s.name.replace(/-/g, " ")) || lower.includes(s.name)) return s.name;
1608
+
1609
+ // src/diagnostics/detectors/stage-drift.ts
1610
+ import { readFileSync as readFileSync10, existsSync as existsSync13 } from "fs";
1611
+ import { join as join14 } from "path";
1612
+ var STALE_AC_PATTERN2 = /-\s\[ \]\s\*\*`([^`]+)`\*\*/g;
1613
+ var DONE_AC_PATTERN = /-\s\[x\]\s\*\*`([^`]+)`\*\*/g;
1614
+ var stageDriftDetector = {
1615
+ name: "stage-drift",
1616
+ async run(rootDir) {
1617
+ const results = [];
1618
+ const workflowFile = join14(rootDir, ".letra", "workflow.json");
1619
+ if (!existsSync13(workflowFile)) return results;
1620
+ const workflow = JSON.parse(readFileSync10(workflowFile, "utf-8"));
1621
+ const items = workflow.items || [];
1622
+ const stages = workflow.stages || [];
1623
+ const doneStageIds = stages.filter((s) => s.zone === "done").map((s) => s.id);
1624
+ const reviewStageIds = stages.filter(
1625
+ (s) => s.name?.toLowerCase() === "review" || s.id === "review"
1626
+ ).map((s) => s.id);
1627
+ for (const item of items) {
1628
+ if (!item.spec) continue;
1629
+ const specDir = join14(rootDir, ".letra", "specs", item.spec);
1630
+ const specFile = join14(specDir, "spec.md");
1631
+ if (!existsSync13(specFile)) continue;
1632
+ const content = readFileSync10(specFile, "utf-8");
1633
+ const staleMatches = [...content.matchAll(STALE_AC_PATTERN2)];
1634
+ const doneMatches = [...content.matchAll(DONE_AC_PATTERN)];
1635
+ const totalACs = staleMatches.length + doneMatches.length;
1636
+ if (totalACs === 0) continue;
1637
+ const pctDone = doneMatches.length / totalACs;
1638
+ const isInReview = reviewStageIds.includes(item.stage);
1639
+ const isInBacklog = item.stage === "backlog";
1640
+ if (pctDone === 1 && (isInReview || isInBacklog)) {
1641
+ results.push({
1642
+ id: `stage-drift_${item.id}`,
1643
+ type: "info",
1644
+ title: `${item.id} (${item.description}) \u2014 100% ACs prontos`,
1645
+ description: `O item ${item.id} (${item.description}) tem ${doneMatches.length}/${totalACs} ACs implementados. Est\xE1 em "${item.stage}" mas deveria estar em "done".`,
1646
+ certainty: 0.85,
1647
+ detector: "stage-drift",
1648
+ autoFix: async () => {
1649
+ const before = readFileSync10(workflowFile, "utf-8");
1650
+ const newWorkflow = JSON.parse(before);
1651
+ const target = newWorkflow.items.find(
1652
+ (i) => i.id === item.id
1653
+ );
1654
+ if (target) {
1655
+ target.stage = doneStageIds[0] || "done";
1656
+ target.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1657
+ }
1658
+ const after = JSON.stringify(newWorkflow, null, 2);
1659
+ return {
1660
+ files: [{ path: ".letra/workflow.json", before, after }],
1661
+ snapshotId: ""
1662
+ };
1663
+ }
1664
+ });
1665
+ } else if (pctDone > 0 && pctDone < 1 && isInBacklog) {
1666
+ results.push({
1667
+ id: `stage-drift_${item.id}_partial`,
1668
+ type: "info",
1669
+ title: `${item.id} (${item.description}) \u2014 ${doneMatches.length}/${totalACs} ACs prontos`,
1670
+ description: `O item ${item.id} tem ${doneMatches.length}/${totalACs} ACs implementados mas est\xE1 em backlog. Considere mover para "code".`,
1671
+ certainty: 0.7,
1672
+ detector: "stage-drift"
1673
+ });
1674
+ }
1675
+ }
1676
+ return results;
1059
1677
  }
1060
- return null;
1678
+ };
1679
+
1680
+ // src/diagnostics/detectors/harness-stale.ts
1681
+ import { existsSync as existsSync14, readFileSync as readFileSync11 } from "fs";
1682
+ import { join as join15 } from "path";
1683
+ var ADAPTER_FILES = {
1684
+ cursor: { path: ".cursorrules", format: "at" },
1685
+ "claude-code": { path: "CLAUDE.md", format: "text" },
1686
+ windsurf: { path: ".windsurfrules", format: "at" },
1687
+ vscode: { path: ".github/copilot-instructions.md", format: "text" },
1688
+ opencode: { path: "AGENTS.md", format: "text" }
1689
+ };
1690
+ var harnessStaleDetector = {
1691
+ name: "harness-stale",
1692
+ async run(rootDir) {
1693
+ const results = [];
1694
+ const workflowFile = join15(rootDir, ".letra", "workflow.json");
1695
+ let tools = ["cursor", "opencode", "vscode"];
1696
+ if (existsSync14(workflowFile)) {
1697
+ try {
1698
+ const wf = JSON.parse(readFileSync11(workflowFile, "utf-8"));
1699
+ if (Array.isArray(wf.tools)) {
1700
+ tools = wf.tools;
1701
+ }
1702
+ } catch {
1703
+ }
1704
+ }
1705
+ for (const tool of tools) {
1706
+ const info = ADAPTER_FILES[tool];
1707
+ if (!info) continue;
1708
+ const filePath = join15(rootDir, info.path);
1709
+ if (!existsSync14(filePath)) continue;
1710
+ const content = readFileSync11(filePath, "utf-8");
1711
+ let isStale = false;
1712
+ if (info.format === "at") {
1713
+ if (!content.includes("@.letra/context.md") || !content.includes("@.letra/constitution.md")) {
1714
+ isStale = true;
1715
+ }
1716
+ } else {
1717
+ if (!content.includes(".letra/context.md") || !content.includes(".letra/constitution.md")) {
1718
+ isStale = true;
1719
+ }
1720
+ }
1721
+ if (isStale) {
1722
+ results.push({
1723
+ id: `harness-stale_${tool}`,
1724
+ type: "warning",
1725
+ title: `Adapter desatualizado: ${tool}`,
1726
+ description: `O adaptador ${info.path} do ${tool} existe mas est\xE1 sem as refer\xEAncias de contexto globais (L1). Execute 'letra flow move' ou 'letra focus' para regener\xE1-lo.`,
1727
+ certainty: 0.85,
1728
+ detector: "harness-stale"
1729
+ });
1730
+ }
1731
+ }
1732
+ return results;
1733
+ }
1734
+ };
1735
+
1736
+ // src/diagnostics/engine.ts
1737
+ var DiagnosticEngine = class {
1738
+ rootDir;
1739
+ snapshots;
1740
+ detectors = [
1741
+ acStaleDetector,
1742
+ missingDirDetector,
1743
+ deadIconsDetector,
1744
+ stageDriftDetector,
1745
+ harnessStaleDetector
1746
+ ];
1747
+ lastOutput = { fixes: [], suggestions: [], errors: [] };
1748
+ appliedFixes = /* @__PURE__ */ new Set();
1749
+ constructor(rootDir) {
1750
+ this.rootDir = rootDir;
1751
+ this.snapshots = new SnapshotStore(rootDir);
1752
+ }
1753
+ async runAll() {
1754
+ const output = { fixes: [], suggestions: [], errors: [] };
1755
+ const newApplied = /* @__PURE__ */ new Set();
1756
+ for (const detector of this.detectors) {
1757
+ try {
1758
+ const results = await detector.run(this.rootDir);
1759
+ for (const result of results) {
1760
+ if (result.autoFix && result.certainty >= 0.9) {
1761
+ if (this.appliedFixes.has(result.id)) {
1762
+ continue;
1763
+ }
1764
+ try {
1765
+ const fix = await result.autoFix();
1766
+ const snapshotId = await this.snapshots.save(
1767
+ result.id,
1768
+ result.title,
1769
+ fix.files
1770
+ );
1771
+ newApplied.add(result.id);
1772
+ if (snapshotId) {
1773
+ output.fixes.push({
1774
+ id: result.id,
1775
+ title: result.title,
1776
+ description: result.description,
1777
+ snapshotId
1778
+ });
1779
+ }
1780
+ } catch (fixError) {
1781
+ output.errors.push(`Auto-fix falhou para ${result.id}: ${fixError}`);
1782
+ }
1783
+ } else {
1784
+ output.suggestions.push({
1785
+ id: result.id,
1786
+ title: result.title,
1787
+ description: result.description,
1788
+ type: result.type,
1789
+ detector: result.detector
1790
+ });
1791
+ }
1792
+ }
1793
+ } catch (detError) {
1794
+ output.errors.push(`Detector ${detector.name} falhou: ${detError}`);
1795
+ }
1796
+ }
1797
+ this.appliedFixes = newApplied;
1798
+ this.lastOutput = output;
1799
+ return output;
1800
+ }
1801
+ getLastOutput() {
1802
+ return this.lastOutput;
1803
+ }
1804
+ async undo(snapshotId) {
1805
+ return this.snapshots.restore(snapshotId);
1806
+ }
1807
+ listSnapshots() {
1808
+ return this.snapshots.list();
1809
+ }
1810
+ ensureDirs() {
1811
+ const requiredDirs = [".letra/templates", ".letra/brand", ".letra/snapshots"];
1812
+ for (const dir of requiredDirs) {
1813
+ const fullPath = join16(this.rootDir, dir);
1814
+ if (!existsSync15(fullPath)) {
1815
+ try {
1816
+ const { mkdirSync: mkdirSync9 } = __require("fs");
1817
+ mkdirSync9(fullPath, { recursive: true });
1818
+ } catch {
1819
+ }
1820
+ }
1821
+ }
1822
+ }
1823
+ };
1824
+
1825
+ // src/commands/flow-serve.ts
1826
+ var DEFAULT_PORT = 3e3;
1827
+ function loadSpecs(root, workflow) {
1828
+ const result = [];
1829
+ if (workflow?.specLinks) {
1830
+ for (const [id, link] of Object.entries(workflow.specLinks)) {
1831
+ const filePath = join17(root, link.path);
1832
+ if (existsSync16(filePath)) {
1833
+ result.push({ id, content: readFileSync12(filePath, "utf-8") });
1834
+ }
1835
+ }
1836
+ }
1837
+ const specsDir = join17(root, ".letra", "specs");
1838
+ const registered = new Set(result.map((s) => s.id));
1839
+ if (existsSync16(specsDir)) {
1840
+ for (const entry of readdirSync6(specsDir, { withFileTypes: true })) {
1841
+ if (entry.isDirectory() && !registered.has(entry.name)) {
1842
+ const specPath = join17(specsDir, entry.name, "spec.md");
1843
+ if (existsSync16(specPath)) {
1844
+ result.push({ id: entry.name, content: readFileSync12(specPath, "utf-8") });
1845
+ }
1846
+ }
1847
+ }
1848
+ }
1849
+ return result;
1061
1850
  }
1062
- function renderBoard(wf) {
1063
- const sorted = (wf.stages || []).sort((a, b) => a.order - b.order);
1064
- const itemsByStage = {};
1065
- for (const s of sorted) itemsByStage[s.id] = [];
1066
- for (const it of (wf.items || [])) {
1067
- const list = itemsByStage[it.stage];
1068
- if (list) list.push(it);
1069
- }
1070
- const html = sorted.map(s => {
1071
- const stageItems = itemsByStage[s.id] || [];
1072
- const itemsHtml = stageItems.length === 0
1073
- ? '<div class="empty">(empty)</div>'
1074
- : stageItems.map(it => {
1075
- const specName = matchSpec(it.description, __specs || []);
1076
- const specBtn = specName ? '<button class="spec-btn" data-spec="' + esc(specName) + '">spec</button>' : "";
1077
- return '<div class="item stage-' + esc(s.id) + '"><span class="item-id">' + esc(it.id) + '</span><span class="item-desc">' + esc(it.description) + '</span><span class="item-bottom">' + specBtn + '<span class="item-age">' + ageLabel(it.createdAt) + '</span></span></div>';
1078
- }).join("");
1079
- return '<div class="stage stage-' + esc(s.id) + '"><h2>' + esc(s.name) + ' <span class="count">' + stageItems.length + ' ' + (stageItems.length === 1 ? "item" : "items") + '</span></h2><div class="items">' + itemsHtml + '</div></div>';
1080
- }).join("\\n");
1081
- const board = document.getElementById("board");
1082
- board.classList.remove("board-fade");
1083
- board.innerHTML = html;
1084
- void board.offsetWidth;
1085
- board.classList.add("board-fade");
1086
- document.getElementById("projectDesc").querySelector("h1").textContent = wf.name || "Flow Board";
1087
- updateMeta(wf.updatedAt);
1088
- attachSpecButtons();
1089
- }
1090
- function updateMeta(updatedAt) {
1091
- const status = document.getElementById("status");
1092
- if (status) status.textContent = "connected" + (updatedAt ? " \xB7 updated " + new Date(updatedAt).toLocaleString() : "");
1093
- }
1094
- function attachSpecButtons() {
1095
- document.querySelectorAll(".spec-btn").forEach(btn => {
1096
- btn.addEventListener("click", () => openSpec(btn.dataset.spec));
1097
- });
1851
+ var TEMPLATES = {
1852
+ padrao: {
1853
+ name: "Padr\xE3o",
1854
+ stages: [
1855
+ { id: "backlog", name: "Backlog", zone: "todo" },
1856
+ { id: "design", name: "Design", zone: "doing" },
1857
+ { id: "code", name: "Code", zone: "doing" },
1858
+ { id: "review", name: "Review", zone: "doing" },
1859
+ { id: "done", name: "Done", zone: "done" }
1860
+ ]
1861
+ },
1862
+ kanban: {
1863
+ name: "Kanban",
1864
+ stages: [
1865
+ { id: "todo", name: "A Fazer", zone: "todo" },
1866
+ { id: "doing", name: "Fazendo", zone: "doing" },
1867
+ { id: "done", name: "Feito", zone: "done" }
1868
+ ]
1869
+ },
1870
+ agil: {
1871
+ name: "\xC1gil",
1872
+ stages: [
1873
+ { id: "product-backlog", name: "Product Backlog", zone: "todo" },
1874
+ { id: "sprint-backlog", name: "Sprint Backlog", zone: "todo" },
1875
+ { id: "in-progress", name: "In Progress", zone: "doing" },
1876
+ { id: "review", name: "Review", zone: "doing" },
1877
+ { id: "done", name: "Done", zone: "done" }
1878
+ ]
1879
+ }
1880
+ };
1881
+ function createWorkflowFromTemplate(root, templateId, options) {
1882
+ const t = TEMPLATES[templateId];
1883
+ if (!t) {
1884
+ throw new Error(
1885
+ `Template "${templateId}" not found. Available: ${Object.keys(TEMPLATES).join(", ")}`
1886
+ );
1887
+ }
1888
+ const stages = t.stages.map((s, i) => ({
1889
+ id: s.id,
1890
+ name: s.name,
1891
+ order: i,
1892
+ zone: s.zone
1893
+ }));
1894
+ const existing = loadWorkflow(root);
1895
+ return {
1896
+ version: "1.0",
1897
+ name: options?.name ?? detectProjectName(root) ?? t.name,
1898
+ createdAt: existing?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
1899
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1900
+ stages,
1901
+ items: existing?.items ?? [],
1902
+ specLinks: existing?.specLinks ?? void 0,
1903
+ tools: options?.tools ?? existing?.tools ?? []
1904
+ };
1098
1905
  }
1099
- function openSpec(name) {
1100
- const spec = (__specs || []).find(s => s.name === name);
1101
- if (!spec) {
1102
- document.getElementById("modalTitle").textContent = "Spec: " + name;
1103
- document.getElementById("modalBody").textContent = "Loading...";
1104
- document.getElementById("modal").classList.remove("hidden");
1105
- fetch("/api/specs").then(r => r.json()).then(all => {
1106
- __specs = all;
1107
- const s = all.find(x => x.name === name);
1108
- if (s) {
1109
- document.getElementById("modalTitle").textContent = "Spec: " + name;
1110
- document.getElementById("modalBody").textContent = s.content;
1906
+ var FlowServer = class {
1907
+ server;
1908
+ watcher;
1909
+ diagnosticsTimer;
1910
+ clients = /* @__PURE__ */ new Set();
1911
+ root;
1912
+ port;
1913
+ loadWorkflow;
1914
+ engine;
1915
+ constructor(root, port = DEFAULT_PORT) {
1916
+ this.root = root;
1917
+ this.port = port;
1918
+ this.loadWorkflow = () => loadWorkflow(root);
1919
+ this.engine = new DiagnosticEngine(root);
1920
+ }
1921
+ handleRequest = (req, res) => {
1922
+ const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
1923
+ const path = url.pathname;
1924
+ if (path === "/events") {
1925
+ res.writeHead(200, {
1926
+ "Content-Type": "text/event-stream",
1927
+ "Cache-Control": "no-cache",
1928
+ Connection: "keep-alive"
1929
+ });
1930
+ res.write("event: connected\ndata: {}\n\n");
1931
+ this.clients.add(res);
1932
+ req.on("close", () => this.clients.delete(res));
1933
+ return;
1934
+ }
1935
+ if (path === "/api/workflow") {
1936
+ const wf = this.loadWorkflow();
1937
+ res.writeHead(200, { "Content-Type": "application/json" });
1938
+ res.end(JSON.stringify(wf ?? { error: "No workflow found" }));
1939
+ return;
1940
+ }
1941
+ if (path === "/api/workflow/template" && req.method === "POST") {
1942
+ let body = "";
1943
+ req.on("data", (chunk) => {
1944
+ body += chunk;
1945
+ });
1946
+ req.on("end", () => {
1947
+ try {
1948
+ const data = JSON.parse(body);
1949
+ let wf;
1950
+ if (data.stages) {
1951
+ const stages = data.stages.map(
1952
+ (s, i) => ({
1953
+ id: s.id,
1954
+ name: s.name,
1955
+ order: i,
1956
+ zone: s.zone
1957
+ })
1958
+ );
1959
+ const existing = loadWorkflow(this.root);
1960
+ wf = {
1961
+ version: "1.0",
1962
+ name: data.name ?? detectProjectName(this.root) ?? "Personalizado",
1963
+ createdAt: existing?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
1964
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1965
+ stages,
1966
+ items: existing?.items ?? [],
1967
+ specLinks: existing?.specLinks ?? void 0,
1968
+ tools: data.tools ?? existing?.tools ?? []
1969
+ };
1970
+ } else {
1971
+ wf = createWorkflowFromTemplate(this.root, data.template, {
1972
+ name: data.name,
1973
+ tools: data.tools
1974
+ });
1975
+ }
1976
+ saveWorkflow(this.root, wf);
1977
+ res.writeHead(200, { "Content-Type": "application/json" });
1978
+ res.end(JSON.stringify(wf));
1979
+ } catch (e) {
1980
+ res.writeHead(400, { "Content-Type": "application/json" });
1981
+ res.end(JSON.stringify({ error: e.message }));
1982
+ }
1983
+ });
1984
+ return;
1985
+ }
1986
+ if (path === "/api/specs" && req.method === "GET") {
1987
+ try {
1988
+ const wf = this.loadWorkflow();
1989
+ const specs = loadSpecs(this.root, wf);
1990
+ res.writeHead(200, { "Content-Type": "application/json" });
1991
+ res.end(JSON.stringify(specs));
1992
+ } catch {
1993
+ res.writeHead(200, { "Content-Type": "application/json" });
1994
+ res.end(JSON.stringify([]));
1995
+ }
1996
+ return;
1997
+ }
1998
+ if (path === "/api/specs" && req.method === "POST") {
1999
+ let body = "";
2000
+ req.on("data", (chunk) => {
2001
+ body += chunk;
2002
+ });
2003
+ req.on("end", () => {
2004
+ try {
2005
+ const { id, content } = JSON.parse(body);
2006
+ if (!id || !content) {
2007
+ res.writeHead(400, { "Content-Type": "application/json" });
2008
+ res.end(JSON.stringify({ error: "id and content required" }));
2009
+ return;
2010
+ }
2011
+ const specDir = join17(this.root, ".letra", "specs", id);
2012
+ if (!existsSync16(specDir)) mkdirSync6(specDir, { recursive: true });
2013
+ writeFileSync8(join17(specDir, "spec.md"), content, "utf-8");
2014
+ const wf = this.loadWorkflow();
2015
+ if (wf) {
2016
+ if (!wf.specLinks) wf.specLinks = {};
2017
+ wf.specLinks[id] = { path: `.letra/specs/${id}/spec.md` };
2018
+ wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2019
+ saveWorkflow(this.root, wf);
2020
+ this.broadcast();
2021
+ }
2022
+ res.writeHead(200, { "Content-Type": "application/json" });
2023
+ res.end(JSON.stringify({ id, content }));
2024
+ } catch (e) {
2025
+ res.writeHead(400, { "Content-Type": "application/json" });
2026
+ res.end(JSON.stringify({ error: e.message }));
2027
+ }
2028
+ });
2029
+ return;
2030
+ }
2031
+ if (path.startsWith("/api/specs/") && req.method === "DELETE") {
2032
+ const specId = path.replace("/api/specs/", "").split("/")[0];
2033
+ if (!specId) {
2034
+ res.writeHead(400);
2035
+ res.end(JSON.stringify({ error: "spec id required" }));
2036
+ return;
2037
+ }
2038
+ const specDir = join17(this.root, ".letra", "specs", specId);
2039
+ if (existsSync16(specDir)) {
2040
+ writeFileSync8(join17(specDir, "spec.md"), "", "utf-8");
2041
+ }
2042
+ const wf = this.loadWorkflow();
2043
+ if (wf?.specLinks) {
2044
+ delete wf.specLinks[specId];
2045
+ wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2046
+ saveWorkflow(this.root, wf);
2047
+ this.broadcast();
2048
+ }
2049
+ res.writeHead(200, { "Content-Type": "application/json" });
2050
+ res.end(JSON.stringify({ deleted: specId }));
2051
+ return;
2052
+ }
2053
+ if (path.startsWith("/api/specs/") && req.method === "PUT") {
2054
+ const specId = path.replace("/api/specs/", "").split("/")[0];
2055
+ if (!specId) {
2056
+ res.writeHead(400);
2057
+ res.end(JSON.stringify({ error: "spec id required" }));
2058
+ return;
2059
+ }
2060
+ let body = "";
2061
+ req.on("data", (chunk) => {
2062
+ body += chunk;
2063
+ });
2064
+ req.on("end", () => {
2065
+ try {
2066
+ const { content } = JSON.parse(body);
2067
+ if (content === void 0) {
2068
+ res.writeHead(400);
2069
+ res.end(JSON.stringify({ error: "content required" }));
2070
+ return;
2071
+ }
2072
+ const specDir = join17(this.root, ".letra", "specs", specId);
2073
+ if (!existsSync16(specDir)) mkdirSync6(specDir, { recursive: true });
2074
+ writeFileSync8(join17(specDir, "spec.md"), content, "utf-8");
2075
+ const wf = this.loadWorkflow();
2076
+ if (wf) {
2077
+ wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2078
+ saveWorkflow(this.root, wf);
2079
+ this.broadcast();
2080
+ }
2081
+ res.writeHead(200, { "Content-Type": "application/json" });
2082
+ res.end(JSON.stringify({ id: specId, content }));
2083
+ } catch (e) {
2084
+ res.writeHead(400);
2085
+ res.end(JSON.stringify({ error: e.message }));
2086
+ }
2087
+ });
2088
+ return;
2089
+ }
2090
+ if (path.match(/^\/api\/specs\/[^/]+\/validate$/) && req.method === "POST") {
2091
+ const specId = path.replace("/api/specs/", "").split("/")[0];
2092
+ const specDir = join17(this.root, ".letra", "specs", specId);
2093
+ const specFile = join17(specDir, "spec.md");
2094
+ const issues = [];
2095
+ if (!existsSync16(specFile)) {
2096
+ res.writeHead(200, { "Content-Type": "application/json" });
2097
+ res.end(
2098
+ JSON.stringify({
2099
+ id: specId,
2100
+ issues: [{ type: "error", msg: "spec.md not found" }],
2101
+ valid: false
2102
+ })
2103
+ );
2104
+ return;
1111
2105
  }
1112
- }).catch(() => {
1113
- document.getElementById("modalBody").textContent = "Failed to load spec.";
1114
- });
1115
- return;
1116
- }
1117
- document.getElementById("modalTitle").textContent = "Spec: " + name;
1118
- document.getElementById("modalBody").textContent = spec.content;
1119
- document.getElementById("modal").classList.remove("hidden");
1120
- }
1121
- document.getElementById("modalClose").addEventListener("click", () => {
1122
- document.getElementById("modal").classList.add("hidden");
1123
- });
1124
- document.getElementById("modalBackdrop").addEventListener("click", () => {
1125
- document.getElementById("modal").classList.add("hidden");
1126
- });
1127
- document.addEventListener("keydown", (e) => {
1128
- if (e.key === "Escape") document.getElementById("modal").classList.add("hidden");
1129
- });
1130
- attachSpecButtons();
1131
- <${"/script"}>
1132
- </body>
1133
- </html>`;
1134
- }
1135
- function esc(s) {
1136
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1137
- }
1138
- var FlowServer = class {
1139
- server;
1140
- watcher;
1141
- clients = /* @__PURE__ */ new Set();
1142
- root;
1143
- port;
1144
- loadWorkflow;
1145
- constructor(root, port = DEFAULT_PORT) {
1146
- this.root = root;
1147
- this.port = port;
1148
- this.loadWorkflow = () => loadWorkflow(root);
1149
- }
1150
- handleRequest = (req, res) => {
1151
- const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
1152
- const path = url.pathname;
1153
- if (path === "/events") {
1154
- res.writeHead(200, {
1155
- "Content-Type": "text/event-stream",
1156
- "Cache-Control": "no-cache",
1157
- Connection: "keep-alive"
2106
+ const content = readFileSync12(specFile, "utf-8");
2107
+ const requiredSections = [
2108
+ "Outcome",
2109
+ "Constraints",
2110
+ "Exclusions",
2111
+ "Acceptance Criteria",
2112
+ "Context"
2113
+ ];
2114
+ for (const section of requiredSections) {
2115
+ const re = new RegExp(`## ${section}`);
2116
+ if (!re.test(content)) {
2117
+ issues.push({ type: "error", msg: `Missing section: ## ${section}` });
2118
+ }
2119
+ }
2120
+ const acMatch = content.match(/## Acceptance Criteria\s+([\s\S]*?)(?=\n## |$)/);
2121
+ if (acMatch) {
2122
+ const acSection = acMatch[1];
2123
+ const items = [...acSection.matchAll(/-\s+\[(\s|x)\]\s+/g)];
2124
+ if (items.length === 0) {
2125
+ issues.push({
2126
+ type: "warning",
2127
+ msg: "Acceptance Criteria section has no checklist items"
2128
+ });
2129
+ }
2130
+ }
2131
+ if (content.length > 3e3) {
2132
+ issues.push({ type: "warning", msg: "Spec exceeds 3000 chars (should be thin)" });
2133
+ }
2134
+ res.writeHead(200, { "Content-Type": "application/json" });
2135
+ res.end(
2136
+ JSON.stringify({
2137
+ id: specId,
2138
+ issues,
2139
+ valid: issues.filter((i) => i.type === "error").length === 0
2140
+ })
2141
+ );
2142
+ return;
2143
+ }
2144
+ if (path === "/api/items" && req.method === "POST") {
2145
+ let body = "";
2146
+ req.on("data", (chunk) => {
2147
+ body += chunk;
2148
+ });
2149
+ req.on("end", () => {
2150
+ try {
2151
+ const { id, description, stage } = JSON.parse(body);
2152
+ if (!id || !description || !stage) {
2153
+ res.writeHead(400, { "Content-Type": "application/json" });
2154
+ res.end(JSON.stringify({ error: "id, description, and stage required" }));
2155
+ return;
2156
+ }
2157
+ const wf = this.loadWorkflow();
2158
+ if (!wf) {
2159
+ res.writeHead(404, { "Content-Type": "application/json" });
2160
+ res.end(JSON.stringify({ error: "No workflow" }));
2161
+ return;
2162
+ }
2163
+ const item = {
2164
+ id,
2165
+ description,
2166
+ stage,
2167
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2168
+ tasks: []
2169
+ };
2170
+ wf.items.push(item);
2171
+ wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2172
+ saveWorkflow(this.root, wf);
2173
+ this.broadcast();
2174
+ res.writeHead(200, { "Content-Type": "application/json" });
2175
+ res.end(JSON.stringify(item));
2176
+ } catch (e) {
2177
+ res.writeHead(400, { "Content-Type": "application/json" });
2178
+ res.end(JSON.stringify({ error: e.message }));
2179
+ }
1158
2180
  });
1159
- res.write("event: connected\ndata: {}\n\n");
1160
- this.clients.add(res);
1161
- req.on("close", () => this.clients.delete(res));
1162
2181
  return;
1163
2182
  }
1164
- if (path === "/api/workflow") {
1165
- const wf2 = this.loadWorkflow();
2183
+ if (path.match(/^\/api\/items\/[^/]+$/) && req.method === "PATCH") {
2184
+ const itemId = path.replace("/api/items/", "");
2185
+ let body = "";
2186
+ req.on("data", (chunk) => {
2187
+ body += chunk;
2188
+ });
2189
+ req.on("end", () => {
2190
+ try {
2191
+ const data = JSON.parse(body);
2192
+ const wf = this.loadWorkflow();
2193
+ if (!wf) {
2194
+ res.writeHead(404, { "Content-Type": "application/json" });
2195
+ res.end(JSON.stringify({ error: "No workflow" }));
2196
+ return;
2197
+ }
2198
+ const item = wf.items.find((i) => i.id === itemId);
2199
+ if (!item) {
2200
+ res.writeHead(404, { "Content-Type": "application/json" });
2201
+ res.end(JSON.stringify({ error: "Item not found" }));
2202
+ return;
2203
+ }
2204
+ const oldStage = item.stage;
2205
+ if (data.stage !== void 0) item.stage = data.stage;
2206
+ if (data.description !== void 0) item.description = data.description;
2207
+ if (data.tasks !== void 0) item.tasks = data.tasks;
2208
+ wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2209
+ saveWorkflow(this.root, wf);
2210
+ this.broadcast();
2211
+ if (data.stage !== void 0 && data.stage !== oldStage) {
2212
+ this.fireWebhooks("item.moved", {
2213
+ itemId: item.id,
2214
+ itemDescription: item.description,
2215
+ sourceStage: oldStage,
2216
+ targetStage: data.stage
2217
+ });
2218
+ }
2219
+ res.writeHead(200, { "Content-Type": "application/json" });
2220
+ res.end(JSON.stringify(item));
2221
+ } catch (e) {
2222
+ res.writeHead(400, { "Content-Type": "application/json" });
2223
+ res.end(JSON.stringify({ error: e.message }));
2224
+ }
2225
+ });
2226
+ return;
2227
+ }
2228
+ if (path.match(/^\/api\/items\/[^/]+$/) && req.method === "DELETE") {
2229
+ const itemId = path.replace("/api/items/", "");
2230
+ const wf = this.loadWorkflow();
2231
+ if (!wf) {
2232
+ res.writeHead(404, { "Content-Type": "application/json" });
2233
+ res.end(JSON.stringify({ error: "No workflow" }));
2234
+ return;
2235
+ }
2236
+ const idx = wf.items.findIndex((i) => i.id === itemId);
2237
+ if (idx === -1) {
2238
+ res.writeHead(404, { "Content-Type": "application/json" });
2239
+ res.end(JSON.stringify({ error: "Item not found" }));
2240
+ return;
2241
+ }
2242
+ wf.items.splice(idx, 1);
2243
+ wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2244
+ saveWorkflow(this.root, wf);
2245
+ this.broadcast();
2246
+ res.writeHead(200, { "Content-Type": "application/json" });
2247
+ res.end(JSON.stringify({ deleted: itemId }));
2248
+ return;
2249
+ }
2250
+ if (path === "/api/workflow" && req.method === "PATCH") {
2251
+ let body = "";
2252
+ req.on("data", (chunk) => {
2253
+ body += chunk;
2254
+ });
2255
+ req.on("end", () => {
2256
+ try {
2257
+ const data = JSON.parse(body);
2258
+ const wf = this.loadWorkflow();
2259
+ if (!wf) {
2260
+ res.writeHead(404, { "Content-Type": "application/json" });
2261
+ res.end(JSON.stringify({ error: "No workflow" }));
2262
+ return;
2263
+ }
2264
+ if (data.stages !== void 0) wf.stages = data.stages;
2265
+ if (data.name !== void 0) wf.name = data.name;
2266
+ if (data.description !== void 0) wf.description = data.description;
2267
+ wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2268
+ saveWorkflow(this.root, wf);
2269
+ this.broadcast();
2270
+ res.writeHead(200, { "Content-Type": "application/json" });
2271
+ res.end(JSON.stringify(wf));
2272
+ } catch (e) {
2273
+ res.writeHead(400, { "Content-Type": "application/json" });
2274
+ res.end(JSON.stringify({ error: e.message }));
2275
+ }
2276
+ });
2277
+ return;
2278
+ }
2279
+ if (path === "/api/move") {
2280
+ const itemId = url.searchParams.get("item");
2281
+ const stage = url.searchParams.get("stage");
2282
+ if (itemId && stage) {
2283
+ const wf = this.loadWorkflow();
2284
+ if (wf) {
2285
+ const item = wf.items.find((i) => i.id === itemId);
2286
+ if (item) {
2287
+ item.stage = stage;
2288
+ wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2289
+ saveWorkflow(this.root, wf);
2290
+ this.broadcast();
2291
+ }
2292
+ }
2293
+ }
2294
+ res.writeHead(302, { Location: "/" });
2295
+ res.end();
2296
+ return;
2297
+ }
2298
+ if (path === "/api/focus") {
2299
+ const focusFile = join17(this.root, ".letra", "focus.md");
2300
+ if (existsSync16(focusFile)) {
2301
+ const content = readFileSync12(focusFile, "utf-8");
2302
+ res.writeHead(200, { "Content-Type": "application/json" });
2303
+ const lines = content.split("\n").filter((l) => l.trim());
2304
+ res.end(
2305
+ JSON.stringify({
2306
+ active: true,
2307
+ spec: lines[0]?.replace(/^#\s*/, "") || "",
2308
+ content
2309
+ })
2310
+ );
2311
+ } else {
2312
+ res.writeHead(200, { "Content-Type": "application/json" });
2313
+ res.end(JSON.stringify({ active: false }));
2314
+ }
2315
+ return;
2316
+ }
2317
+ if (path === "/api/context") {
2318
+ const file = url.searchParams.get("file") || "context.md";
2319
+ const letraDir = join17(this.root, ".letra");
2320
+ const allowedFiles = ["context.md", "constitution.md", "glossary.md"];
2321
+ if (file === "decisions") {
2322
+ const decisionsDir = join17(letraDir, "decisions");
2323
+ const files = [];
2324
+ if (existsSync16(decisionsDir)) {
2325
+ const names = readdirSync6(decisionsDir).filter((f) => f.endsWith(".md"));
2326
+ for (const name of names.sort().reverse()) {
2327
+ const content2 = readFileSync12(join17(decisionsDir, name), "utf-8");
2328
+ files.push({ name, content: content2 });
2329
+ }
2330
+ }
2331
+ res.writeHead(200, { "Content-Type": "application/json" });
2332
+ res.end(JSON.stringify(files));
2333
+ return;
2334
+ }
2335
+ if (!allowedFiles.includes(file)) {
2336
+ res.writeHead(400, { "Content-Type": "application/json" });
2337
+ res.end(JSON.stringify({ error: `Invalid file: ${file}` }));
2338
+ return;
2339
+ }
2340
+ const filePath = join17(letraDir, file);
2341
+ if (!existsSync16(filePath)) {
2342
+ res.writeHead(404, { "Content-Type": "application/json" });
2343
+ res.end(JSON.stringify({ error: `File not found: ${file}` }));
2344
+ return;
2345
+ }
2346
+ const content = readFileSync12(filePath, "utf-8");
2347
+ res.writeHead(200, { "Content-Type": "text/plain" });
2348
+ res.end(content);
2349
+ return;
2350
+ }
2351
+ if (path === "/api/diagnostics" && req.method === "GET") {
2352
+ const output = this.engine.getLastOutput();
1166
2353
  res.writeHead(200, { "Content-Type": "application/json" });
1167
- res.end(JSON.stringify(wf2 ?? { error: "No workflow found" }));
2354
+ res.end(JSON.stringify(output));
1168
2355
  return;
1169
2356
  }
1170
- if (path === "/api/specs") {
1171
- const specs2 = loadSpecs(this.root);
2357
+ if (path === "/api/diagnostics/snapshots" && req.method === "GET") {
2358
+ const snapshots = this.engine.listSnapshots();
1172
2359
  res.writeHead(200, { "Content-Type": "application/json" });
1173
- res.end(JSON.stringify(specs2));
2360
+ res.end(JSON.stringify({ snapshots }));
1174
2361
  return;
1175
2362
  }
1176
- const wf = this.loadWorkflow();
1177
- const specs = loadSpecs(this.root);
1178
- const html = boardHtml(wf, specs);
1179
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
1180
- res.end(html);
2363
+ if (path === "/api/diagnostics/scan" && req.method === "POST") {
2364
+ this.engine.runAll().then((output) => {
2365
+ this.broadcastDiagnostics(output);
2366
+ res.writeHead(200, { "Content-Type": "application/json" });
2367
+ res.end(JSON.stringify(output));
2368
+ }).catch((e) => {
2369
+ res.writeHead(500, { "Content-Type": "application/json" });
2370
+ res.end(JSON.stringify({ error: e.message }));
2371
+ });
2372
+ return;
2373
+ }
2374
+ if (path.match(/^\/api\/diagnostics\/undo\/[^/]+$/) && req.method === "POST") {
2375
+ const snapshotId = path.replace("/api/diagnostics/undo/", "");
2376
+ this.engine.undo(snapshotId).then((result) => {
2377
+ if (!result.ok) {
2378
+ res.writeHead(404, { "Content-Type": "application/json" });
2379
+ res.end(JSON.stringify({ error: "Snapshot not found" }));
2380
+ return;
2381
+ }
2382
+ this.broadcast();
2383
+ res.writeHead(200, { "Content-Type": "application/json" });
2384
+ res.end(JSON.stringify(result));
2385
+ }).catch((e) => {
2386
+ res.writeHead(500, { "Content-Type": "application/json" });
2387
+ res.end(JSON.stringify({ error: e.message }));
2388
+ });
2389
+ return;
2390
+ }
2391
+ this.serveClient(path, req, res);
1181
2392
  };
2393
+ clientDir = null;
2394
+ serveClient(path, req, res) {
2395
+ if (!this.clientDir) {
2396
+ const cliDir = dirname(fileURLToPath(import.meta.url));
2397
+ const builtIn = join17(cliDir, "client");
2398
+ const monorepoDev = join17(this.root, "packages", "client", "dist");
2399
+ const candidates = [builtIn, monorepoDev];
2400
+ for (const dir of candidates) {
2401
+ const idx = join17(dir, "index.html");
2402
+ if (existsSync16(idx)) {
2403
+ this.clientDir = dir;
2404
+ break;
2405
+ }
2406
+ }
2407
+ }
2408
+ if (!this.clientDir) {
2409
+ this.proxyToVite(req, res);
2410
+ return;
2411
+ }
2412
+ let filePath = join17(this.clientDir, path === "/" ? "index.html" : path);
2413
+ if (!existsSync16(filePath)) {
2414
+ filePath = join17(this.clientDir, "index.html");
2415
+ }
2416
+ const ext = extname(filePath);
2417
+ const mime = {
2418
+ ".html": "text/html; charset=utf-8",
2419
+ ".js": "application/javascript; charset=utf-8",
2420
+ ".css": "text/css; charset=utf-8",
2421
+ ".svg": "image/svg+xml",
2422
+ ".png": "image/png",
2423
+ ".ico": "image/x-icon",
2424
+ ".json": "application/json"
2425
+ };
2426
+ const contentType = mime[ext] ?? "application/octet-stream";
2427
+ res.writeHead(200, { "Content-Type": contentType });
2428
+ res.end(readFileSync12(filePath));
2429
+ }
2430
+ proxyToVite(req, res) {
2431
+ const proxyUrl = `http://localhost:5173${req.url}`;
2432
+ fetch(proxyUrl).then((proxyRes) => {
2433
+ res.writeHead(proxyRes.status, Object.fromEntries(proxyRes.headers));
2434
+ proxyRes.body?.pipeTo(
2435
+ new WritableStream({
2436
+ write(chunk) {
2437
+ res.write(chunk);
2438
+ },
2439
+ close() {
2440
+ res.end();
2441
+ }
2442
+ })
2443
+ );
2444
+ }).catch(() => {
2445
+ res.writeHead(502, { "Content-Type": "text/plain" });
2446
+ res.end("Vite dev server not running on http://localhost:5173");
2447
+ });
2448
+ }
1182
2449
  broadcast() {
1183
2450
  if (this.clients.size === 0) return;
1184
2451
  const data = "event: workflow-updated\ndata: {}\n\n";
@@ -1190,24 +2457,76 @@ var FlowServer = class {
1190
2457
  }
1191
2458
  }
1192
2459
  }
2460
+ broadcastDiagnostics(output) {
2461
+ if (this.clients.size === 0) return;
2462
+ const data = `event: diagnostics-updated
2463
+ data: ${JSON.stringify({ fixes: output.fixes.length, suggestions: output.suggestions.length, errors: output.errors.length })}
2464
+
2465
+ `;
2466
+ for (const client of this.clients) {
2467
+ try {
2468
+ client.write(data);
2469
+ } catch {
2470
+ this.clients.delete(client);
2471
+ }
2472
+ }
2473
+ }
2474
+ async fireWebhooks(event, payload) {
2475
+ const wf = this.loadWorkflow();
2476
+ if (!wf?.webhooks || wf.webhooks.length === 0) return;
2477
+ const matching = wf.webhooks.filter((wh) => wh.events.includes(event));
2478
+ if (matching.length === 0) return;
2479
+ const body = JSON.stringify({
2480
+ event,
2481
+ workflow: wf.name,
2482
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2483
+ ...payload
2484
+ });
2485
+ for (const wh of matching) {
2486
+ try {
2487
+ const res = await fetch(wh.url, {
2488
+ method: "POST",
2489
+ headers: { "Content-Type": "application/json" },
2490
+ body
2491
+ });
2492
+ wh.lastStatus = res.ok ? "ok" : "error";
2493
+ } catch {
2494
+ wh.lastStatus = "error";
2495
+ }
2496
+ wh.lastSentAt = (/* @__PURE__ */ new Date()).toISOString();
2497
+ }
2498
+ saveWorkflow(this.root, wf);
2499
+ }
1193
2500
  start() {
1194
- return new Promise((resolve16, reject) => {
2501
+ return new Promise((resolve18, reject) => {
1195
2502
  this.server = createServer(this.handleRequest);
1196
2503
  this.server.listen(this.port, () => {
1197
- const wfPath = join6(this.root, ".letra", "workflow.json");
1198
- if (existsSync6(wfPath)) {
2504
+ const wfPath = join17(this.root, ".letra", "workflow.json");
2505
+ if (existsSync16(wfPath)) {
1199
2506
  try {
1200
2507
  this.watcher = watch(wfPath, () => this.broadcast());
1201
2508
  } catch {
1202
2509
  }
1203
2510
  }
1204
- resolve16();
2511
+ this.engine.ensureDirs();
2512
+ this.engine.runAll().then((output) => {
2513
+ this.broadcastDiagnostics(output);
2514
+ }).catch(() => {
2515
+ });
2516
+ this.diagnosticsTimer = setInterval(() => {
2517
+ this.engine.runAll().then((output) => {
2518
+ this.broadcastDiagnostics(output);
2519
+ }).catch(() => {
2520
+ });
2521
+ }, 3e4);
2522
+ resolve18();
1205
2523
  });
1206
2524
  this.server.on("error", reject);
1207
2525
  });
1208
2526
  }
1209
2527
  stop() {
1210
2528
  if (this.watcher) this.watcher.close();
2529
+ if (this.diagnosticsTimer) clearInterval(this.diagnosticsTimer);
1211
2530
  if (this.server) this.server.close();
1212
2531
  for (const client of this.clients) {
1213
2532
  client.destroy();
@@ -1219,7 +2538,7 @@ var FlowServer = class {
1219
2538
  }
1220
2539
  };
1221
2540
  async function flowServeAction(targetPath, options) {
1222
- const root = resolve8(process.cwd(), targetPath ?? ".");
2541
+ const root = resolve9(process.cwd(), targetPath ?? ".");
1223
2542
  const port = options?.port ?? DEFAULT_PORT;
1224
2543
  const wf = loadWorkflow(root);
1225
2544
  if (!wf) {
@@ -1241,25 +2560,22 @@ async function flowServeAction(targetPath, options) {
1241
2560
  } catch {
1242
2561
  }
1243
2562
  }
1244
- await new Promise((resolve16) => {
2563
+ await new Promise((resolve18) => {
1245
2564
  process.on("SIGINT", () => {
1246
2565
  server.stop();
1247
- resolve16();
2566
+ resolve18();
1248
2567
  });
1249
2568
  });
1250
2569
  } catch (err) {
1251
- console.error(
1252
- `Failed to start server on port ${port}:`,
1253
- err.message
1254
- );
2570
+ console.error(`Failed to start server on port ${port}:`, err.message);
1255
2571
  process.exit(1);
1256
2572
  }
1257
2573
  }
1258
2574
 
1259
2575
  // src/commands/flow-visualize.ts
1260
- import { writeFileSync as writeFileSync6 } from "fs";
1261
- import { resolve as resolve9 } from "path";
1262
- import chalk8 from "chalk";
2576
+ import { writeFileSync as writeFileSync9 } from "fs";
2577
+ import { resolve as resolve10 } from "path";
2578
+ import chalk10 from "chalk";
1263
2579
  var MERMAID_LIVE = "https://mermaid.live/edit#";
1264
2580
  function generateMermaid(workflow) {
1265
2581
  const sorted = [...workflow.stages].sort((a, b) => a.order - b.order);
@@ -1281,9 +2597,7 @@ function generateMermaid(workflow) {
1281
2597
  ` ${sorted[0].id}["${labelFor(sorted[0])}"] --> ${sorted[1].id}["${labelFor(sorted[1])}"]`
1282
2598
  );
1283
2599
  for (let i = 1; i < sorted.length - 1; i++) {
1284
- lines.push(
1285
- ` ${sorted[i].id} --> ${sorted[i + 1].id}["${labelFor(sorted[i + 1])}"]`
1286
- );
2600
+ lines.push(` ${sorted[i].id} --> ${sorted[i + 1].id}["${labelFor(sorted[i + 1])}"]`);
1287
2601
  }
1288
2602
  return lines.join("\n");
1289
2603
  }
@@ -1311,14 +2625,12 @@ ${mermaid}
1311
2625
  function flowVisualize(root, options) {
1312
2626
  const workflow = loadWorkflow(root);
1313
2627
  if (!workflow) {
1314
- console.log(
1315
- chalk8.yellow("No workflow found. Run 'letra flow init --quick' first")
1316
- );
2628
+ console.log(chalk10.yellow("No workflow found. Run 'letra flow init --quick' first"));
1317
2629
  return;
1318
2630
  }
1319
2631
  const mermaid = generateMermaid(workflow);
1320
2632
  if (options?.output) {
1321
- const outputPath = resolve9(root, options.output);
2633
+ const outputPath = resolve10(root, options.output);
1322
2634
  const ext = options.output.toLowerCase().split(".").pop();
1323
2635
  let content;
1324
2636
  let label;
@@ -1336,16 +2648,16 @@ ${mermaid}
1336
2648
  `;
1337
2649
  label = "Diagram file";
1338
2650
  }
1339
- writeFileSync6(outputPath, content);
2651
+ writeFileSync9(outputPath, content);
1340
2652
  console.log(`${label} saved to ${options.output}`);
1341
2653
  } else {
1342
2654
  console.log(mermaid);
1343
- console.log(chalk8.dim(`
2655
+ console.log(chalk10.dim(`
1344
2656
  Copy to ${MERMAID_LIVE} to render`));
1345
2657
  }
1346
2658
  }
1347
2659
  function flowVisualizeAction(targetPath, options) {
1348
- const root = resolve9(process.cwd(), targetPath || ".");
2660
+ const root = resolve10(process.cwd(), targetPath || ".");
1349
2661
  flowVisualize(root, options);
1350
2662
  }
1351
2663
 
@@ -1362,6 +2674,13 @@ function flowCommand() {
1362
2674
  backlog.command("list").description("List all items with stage and age").action(() => {
1363
2675
  backlogActionList(void 0);
1364
2676
  });
2677
+ const importCmd = backlog.command("import").description("Import issues from external sources");
2678
+ importCmd.command("github <repo>").option("--label <label>", "Filter by label").option("--limit <number>", "Max issues to import", "50").description("Import open issues from a GitHub repository").action((repo, options) => {
2679
+ backlogImportGitHubAction(void 0, repo, options);
2680
+ });
2681
+ importCmd.command("linear <team>").option("--limit <number>", "Max issues to import", "50").description("Import issues from a Linear team").action((team, options) => {
2682
+ backlogImportLinearAction(void 0, team, options);
2683
+ });
1365
2684
  cmd.command("move <item-id>").requiredOption("--to <stage>", "Target stage id or name").description("Move item to another stage and regenerate adapters").action((itemId, options) => {
1366
2685
  flowMoveAction(void 0, itemId, options);
1367
2686
  });
@@ -1394,52 +2713,79 @@ function flowCommand() {
1394
2713
  }
1395
2714
 
1396
2715
  // src/commands/focus.ts
1397
- import { existsSync as existsSync7, readFileSync as readFileSync6, unlinkSync, writeFileSync as writeFileSync7 } from "fs";
1398
- import { join as join7, resolve as resolve10 } from "path";
1399
- import chalk9 from "chalk";
2716
+ import { existsSync as existsSync17, readFileSync as readFileSync13 } from "fs";
2717
+ import { join as join18, resolve as resolve11 } from "path";
2718
+ import chalk11 from "chalk";
1400
2719
  import { Command as Command3 } from "commander";
1401
- function extractOutcome(specDir) {
1402
- const specFile = join7(specDir, "spec.md");
1403
- if (!existsSync7(specFile)) return null;
1404
- const content = readFileSync6(specFile, "utf-8");
1405
- const match = content.match(/## Outcome\s+([\s\S]*?)(?=\n## |\n*$)/);
1406
- return match ? match[1].trim() : null;
1407
- }
1408
2720
  function focus_default() {
1409
2721
  return new Command3("focus").argument("[spec]", "Spec name to focus on").option("--clear", "Remove focus file").action((spec, options) => {
1410
- const root = resolve10(process.cwd());
1411
- const focusFile = join7(root, ".letra", "focus.md");
2722
+ const root = resolve11(process.cwd());
2723
+ const focusFile = join18(root, ".letra", "focus.md");
1412
2724
  if (options.clear) {
1413
- if (existsSync7(focusFile)) {
1414
- unlinkSync(focusFile);
1415
- console.log(chalk9.green("Focus removed."));
2725
+ if (existsSync17(focusFile)) {
2726
+ clearFocusFile(root);
2727
+ console.log(chalk11.green("Focus removed."));
1416
2728
  } else {
1417
- console.log(chalk9.yellow("No focus to remove."));
2729
+ console.log(chalk11.yellow("No focus to remove."));
2730
+ }
2731
+ const workflow = loadWorkflow(root);
2732
+ if (workflow) {
2733
+ const codeStage = workflow.stages.find(
2734
+ (s) => s.id === "code" || s.name.toLowerCase() === "code"
2735
+ );
2736
+ const activeStageId = codeStage ? codeStage.id : workflow.stages[0]?.id;
2737
+ generateAdapters(root, workflow.tools, {
2738
+ source: "focus",
2739
+ workflow: {
2740
+ name: workflow.name,
2741
+ stages: workflow.stages,
2742
+ items: workflow.items
2743
+ },
2744
+ activeStageId
2745
+ });
1418
2746
  }
1419
2747
  return;
1420
2748
  }
1421
2749
  if (spec) {
1422
- const specDir = join7(root, ".letra", "specs", spec);
1423
- const specFile = join7(specDir, "spec.md");
1424
- if (!existsSync7(specFile)) {
1425
- console.log(chalk9.red(`Spec "${spec}" not found`));
2750
+ const specDir = join18(root, ".letra", "specs", spec);
2751
+ const specFile = join18(specDir, "spec.md");
2752
+ if (!existsSync17(specFile)) {
2753
+ console.log(chalk11.red(`Spec "${spec}" not found`));
1426
2754
  process.exit(1);
1427
2755
  }
1428
- const outcome = extractOutcome(specDir);
1429
- const outcomeLine = `**Outcome**: ${outcome || spec}`;
1430
- const focusContent = [
1431
- `# Focus: ${spec}`,
1432
- "",
1433
- `**Path**: .letra/specs/${spec}/`,
1434
- outcomeLine,
1435
- ""
1436
- ].join("\n");
1437
- writeFileSync7(focusFile, focusContent);
1438
- console.log(chalk9.green(`Focus set to "${spec}".`));
2756
+ const workflow = loadWorkflow(root);
2757
+ let itemId = "";
2758
+ let activeStageId = "code";
2759
+ if (workflow) {
2760
+ const itemWithSpec = workflow.items.find((item) => item.spec === spec);
2761
+ if (itemWithSpec) {
2762
+ itemId = itemWithSpec.id;
2763
+ activeStageId = itemWithSpec.stage;
2764
+ } else {
2765
+ const codeStage = workflow.stages.find(
2766
+ (s) => s.id === "code" || s.name.toLowerCase() === "code"
2767
+ );
2768
+ activeStageId = codeStage ? codeStage.id : workflow.stages[0]?.id;
2769
+ }
2770
+ }
2771
+ writeFocusFile(root, spec, itemId);
2772
+ console.log(chalk11.green(`Focus set to "${spec}".`));
2773
+ if (workflow) {
2774
+ generateAdapters(root, workflow.tools, {
2775
+ source: "focus",
2776
+ workflow: {
2777
+ name: workflow.name,
2778
+ stages: workflow.stages,
2779
+ items: workflow.items
2780
+ },
2781
+ activeStageId,
2782
+ primaryItemId: itemId || void 0
2783
+ });
2784
+ }
1439
2785
  return;
1440
2786
  }
1441
- if (existsSync7(focusFile)) {
1442
- console.log(readFileSync6(focusFile, "utf-8"));
2787
+ if (existsSync17(focusFile)) {
2788
+ console.log(readFileSync13(focusFile, "utf-8"));
1443
2789
  } else {
1444
2790
  console.log("Nenhum foco definido.");
1445
2791
  }
@@ -1447,35 +2793,28 @@ function focus_default() {
1447
2793
  }
1448
2794
 
1449
2795
  // src/commands/init.ts
1450
- import {
1451
- copyFileSync,
1452
- existsSync as existsSync8,
1453
- mkdirSync as mkdirSync4,
1454
- writeFileSync as writeFileSync8
1455
- } from "fs";
1456
- import { join as join8, resolve as resolve11 } from "path";
2796
+ import { existsSync as existsSync18, mkdirSync as mkdirSync7, writeFileSync as writeFileSync10 } from "fs";
2797
+ import { join as join19, resolve as resolve12 } from "path";
1457
2798
  import { createInterface as createInterface2 } from "readline";
1458
- import { fileURLToPath } from "url";
1459
- import chalk10 from "chalk";
2799
+ import { fileURLToPath as fileURLToPath2 } from "url";
2800
+ import chalk12 from "chalk";
1460
2801
  import ora2 from "ora";
1461
- var __dirname = fileURLToPath(new URL(".", import.meta.url));
2802
+ var __dirname = fileURLToPath2(new URL(".", import.meta.url));
1462
2803
  function ask(query, options) {
1463
2804
  if (!process.stdin.isTTY) return Promise.resolve(options[0]);
1464
2805
  const rl = createInterface2({ input: process.stdin, output: process.stdout });
1465
- return new Promise((resolve16) => {
1466
- const formatted = `${chalk10.cyan(query)} ${options.map((o) => chalk10.gray(`(${o})`)).join(" ")}
2806
+ return new Promise((resolve18) => {
2807
+ const formatted = `${chalk12.cyan(query)} ${options.map((o) => chalk12.gray(`(${o})`)).join(" ")}
1467
2808
  > `;
1468
2809
  rl.question(formatted, (answer) => {
1469
2810
  rl.close();
1470
2811
  const trimmed = answer.trim().toLowerCase();
1471
2812
  if (trimmed && options.some((o) => o.toLowerCase().startsWith(trimmed))) {
1472
- resolve16(
1473
- options.find((o) => o.toLowerCase().startsWith(trimmed)) ?? options[0]
1474
- );
2813
+ resolve18(options.find((o) => o.toLowerCase().startsWith(trimmed)) ?? options[0]);
1475
2814
  } else if (trimmed && options.includes(trimmed)) {
1476
- resolve16(trimmed);
2815
+ resolve18(trimmed);
1477
2816
  } else {
1478
- resolve16(options[0]);
2817
+ resolve18(options[0]);
1479
2818
  }
1480
2819
  });
1481
2820
  });
@@ -1486,16 +2825,7 @@ function adaptConfig(projectType) {
1486
2825
  "consistencia-terminologia": { severity: "warning" },
1487
2826
  "detecao-tom": {
1488
2827
  severity: "warning",
1489
- blacklist: [
1490
- "tipo",
1491
- "t\xE1",
1492
- "pra",
1493
- "blz",
1494
- "kkk",
1495
- "eita",
1496
- "oi",
1497
- "oi pessoal"
1498
- ]
2828
+ blacklist: ["tipo", "t\xE1", "pra", "blz", "kkk", "eita", "oi", "oi pessoal"]
1499
2829
  },
1500
2830
  "drift-temporal": { severity: "warning", maxDays: 30 },
1501
2831
  "secoes-vazias": { severity: "warning" },
@@ -1546,51 +2876,56 @@ ${format === "at" ? "# Context\n@.letra/context.md\n@.letra/constitution.md\n@.l
1546
2876
  switch (tool) {
1547
2877
  case "cursor":
1548
2878
  adapters.push({
1549
- path: join8(root, ".cursorrules"),
2879
+ path: join19(root, ".cursorrules"),
1550
2880
  content: baseContent("Cursor", "at")
1551
2881
  });
1552
2882
  break;
1553
2883
  case "claude-code":
1554
2884
  adapters.push({
1555
- path: join8(root, "CLAUDE.md"),
2885
+ path: join19(root, "CLAUDE.md"),
1556
2886
  content: baseContent("Claude Code", "text")
1557
2887
  });
1558
2888
  break;
1559
2889
  case "windsurf":
1560
2890
  adapters.push({
1561
- path: join8(root, ".windsurfrules"),
2891
+ path: join19(root, ".windsurfrules"),
1562
2892
  content: baseContent("Windsurf", "at")
1563
2893
  });
1564
2894
  break;
1565
2895
  case "vscode":
1566
2896
  adapters.push({
1567
- path: join8(root, ".github", "copilot-instructions.md"),
2897
+ path: join19(root, ".github", "copilot-instructions.md"),
1568
2898
  content: baseContent("VSCode Copilot", "text")
1569
2899
  });
1570
2900
  break;
1571
2901
  case "opencode":
1572
2902
  adapters.push({
1573
- path: join8(root, "AGENTS.md"),
2903
+ path: join19(root, "AGENTS.md"),
1574
2904
  content: baseContent("OpenCode", "text")
1575
2905
  });
1576
2906
  break;
1577
2907
  }
1578
2908
  }
1579
2909
  for (const { path, content } of adapters) {
1580
- const dir = join8(path, "..");
1581
- if (!existsSync8(dir)) mkdirSync4(dir, { recursive: true });
1582
- writeFileSync8(path, content);
1583
- console.log(` ${chalk10.gray("Created")} ${path.replace(`${root}/`, "")}`);
2910
+ const dir = join19(path, "..");
2911
+ if (!existsSync18(dir)) mkdirSync7(dir, { recursive: true });
2912
+ writeFileSync10(path, content);
2913
+ console.log(` ${chalk12.gray("Created")} ${path.replace(`${root}/`, "")}`);
1584
2914
  }
1585
2915
  }
1586
2916
  async function init(targetPath, options) {
1587
- const root = resolve11(process.cwd(), targetPath || ".");
1588
- const letraDir = join8(root, ".letra");
1589
- const spinner = ora2("Initializing Letra...").start();
1590
- if (existsSync8(letraDir)) {
1591
- spinner.warn(chalk10.yellow(".letra/ already exists"));
2917
+ const root = resolve12(process.cwd(), targetPath || ".");
2918
+ const letraDir = join19(root, ".letra");
2919
+ if (existsSync18(letraDir)) {
2920
+ if (options?.serve) {
2921
+ console.log(chalk12.cyan(".letra/ already exists \u2014 starting UI..."));
2922
+ await flowServeAction(targetPath, { open: true });
2923
+ return;
2924
+ }
2925
+ console.log(chalk12.yellow(".letra/ already exists"));
1592
2926
  return;
1593
2927
  }
2928
+ const spinner = ora2("Initializing Letra...").start();
1594
2929
  try {
1595
2930
  let projectType = "web-app";
1596
2931
  let tool = "cursor";
@@ -1599,12 +2934,7 @@ async function init(targetPath, options) {
1599
2934
  tool = "todos";
1600
2935
  } else {
1601
2936
  spinner.stop();
1602
- projectType = await ask("Project type?", [
1603
- "web-app",
1604
- "cli",
1605
- "library",
1606
- "mobile"
1607
- ]);
2937
+ projectType = await ask("Project type?", ["web-app", "cli", "library", "mobile"]);
1608
2938
  const toolNames = [
1609
2939
  "Cursor",
1610
2940
  "Windsurf",
@@ -1617,24 +2947,91 @@ async function init(targetPath, options) {
1617
2947
  tool = answer.toLowerCase();
1618
2948
  spinner.start();
1619
2949
  }
1620
- mkdirSync4(join8(letraDir, "decisions"), { recursive: true });
1621
- mkdirSync4(join8(letraDir, "specs", "_template"), { recursive: true });
1622
- mkdirSync4(join8(letraDir, "adapters"), { recursive: true });
1623
- const templateDir = join8(__dirname, "..", "..", ".letra");
1624
- const templates = [
1625
- "context.md",
1626
- "constitution.md",
1627
- "glossary.md",
1628
- "lessons-learned.md"
1629
- ];
1630
- for (const file of templates) {
1631
- const src = join8(templateDir, file);
1632
- const dest = join8(letraDir, file);
1633
- if (existsSync8(src)) copyFileSync(src, dest);
2950
+ mkdirSync7(join19(letraDir, "decisions"), { recursive: true });
2951
+ mkdirSync7(join19(letraDir, "specs", "_template"), { recursive: true });
2952
+ mkdirSync7(join19(letraDir, "adapters"), { recursive: true });
2953
+ const templateFiles = {
2954
+ "context.md": `# Context
2955
+
2956
+ > Updated: 2026-05-01
2957
+ > Owner: letra-dev
2958
+
2959
+ ## Intent
2960
+
2961
+ Letra \xE9 um framework de Specification-Driven Development (SDD) agn\xF3stico a ferramentas.
2962
+ Captura dire\xE7\xE3o, inten\xE7\xE3o e contexto, enriquecendo prompts de agentes de c\xF3digo.
2963
+
2964
+ ## Dom\xEDnio
2965
+
2966
+ - **Produto**: CLI + adapters + formato de mem\xF3ria .letra/
2967
+ - **P\xFAblico**: 1. N\xE3o-devs
2968
+
2969
+ ## Restri\xE7\xF5es Reais
2970
+
2971
+ - Specs devem ser thin (m\xE1x 1 p\xE1gina por feature)
2972
+ - Sem lock-in de IDE
2973
+ - Drift detection deve funcionar para qualquer dom\xEDnio (n\xE3o s\xF3 c\xF3digo)
2974
+
2975
+ ## Porqu\xEAs
2976
+
2977
+ - Escolhemos TypeScript porque 82% dos novos pacotes npm s\xE3o TS em 2026
2978
+ - Escolhemos Markdown checklist porque n\xE3o-devs precisam ler e escrever specs
2979
+ `,
2980
+ "constitution.md": `# Constitution
2981
+
2982
+ ## Arquitetura
2983
+ - Adapter layer desde o dia 1 \u2014 nunca travar em uma IDE
2984
+ - Formato .letra/ \xE9 a fonte da verdade, n\xE3o o c\xF3digo
2985
+ - CLI deve ser extens\xEDvel via plugins
2986
+
2987
+ ## C\xF3digo
2988
+ - TypeScript estrito (strict: true)
2989
+ - Zero dependencies desnecess\xE1rias
2990
+
2991
+ ## Specs
2992
+ - Thin specs: m\xE1ximo 1 p\xE1gina por feature
2993
+ - Markdown checklist para acceptance criteria
2994
+ - Toda spec deve ter: Outcome, Constraints, Exclusions, Acceptance Criteria, Context
2995
+
2996
+ ## Seguran\xE7a
2997
+ - Nunca incluir secrets, tokens ou chaves no reposit\xF3rio
2998
+ `,
2999
+ "glossary.md": `# Glossary
3000
+
3001
+ | Termo | Defini\xE7\xE3o |
3002
+ |-------|-----------|
3003
+ | **Spec** | Especifica\xE7\xE3o thin que define o que deve ser constru\xEDdo. |
3004
+ | **Drift** | Diverg\xEAncia entre o que a spec diz e o que o artefato realmente entrega. |
3005
+ | **Adapter** | Tradutor que converte .letra/ para o formato que uma IDE/agent entende. |
3006
+ | **Context** | Documento que captura intent, dom\xEDnio, restri\xE7\xF5es reais e "porqu\xEAs" do projeto. |
3007
+ | **Constitution** | Regras n\xE3o-negoci\xE1veis de arquitetura, c\xF3digo e workflow. |
3008
+ | **Thin Spec** | Spec de no m\xE1ximo 1 p\xE1gina, focada em outcome. |
3009
+ `,
3010
+ "lessons-learned.md": `# Lessons Learned
3011
+
3012
+ ## O que funcionou
3013
+ - Pesquisar dores reais do SDD antes de definir arquitetura
3014
+ - Decidir por evid\xEAncias (m\xE9tricas, dados) e n\xE3o por intui\xE7\xE3o
3015
+
3016
+ ## O que aprendemos
3017
+ - Drift detection n\xE3o pode ser code-centric \u2014 p\xFAblico prim\xE1rio s\xE3o n\xE3o-devs
3018
+ - Obsidian nunca deve ser requisito \u2014 barreira de ado\xE7\xE3o
3019
+ - TypeScript domina CLIs em 2026 (82% dos novos pacotes npm)
3020
+
3021
+ ## Padr\xF5es a evitar
3022
+ - Specs gigantes (Markdown Madness)
3023
+ - Lock-in de IDE
3024
+ - Spec que vira pseudo-c\xF3digo
3025
+ `
3026
+ };
3027
+ for (const [file, content] of Object.entries(templateFiles)) {
3028
+ writeFileSync10(join19(letraDir, file), content, "utf-8");
1634
3029
  }
1635
- const specTemplate = join8(letraDir, "specs", "_template.md");
3030
+ const specTemplate = join19(letraDir, "specs", "_template.md");
1636
3031
  const specContent = `# Spec Template
1637
3032
 
3033
+ > Updated: YYYY-MM-DD
3034
+
1638
3035
  ## Outcome
1639
3036
  O que o usu\xE1rio consegue fazer quando isso estiver pronto.
1640
3037
 
@@ -1650,16 +3047,16 @@ O que explicitamente N\xC3O est\xE1 neste escopo.
1650
3047
  ## Context
1651
3048
  Por que estamos construindo isso.
1652
3049
  `;
1653
- writeFileSync8(specTemplate, specContent);
1654
- const configPath = join8(letraDir, "config.json");
1655
- writeFileSync8(configPath, adaptConfig(projectType));
1656
- console.log(` ${chalk10.gray("Created")} .letra/config.json`);
3050
+ writeFileSync10(specTemplate, specContent);
3051
+ const configPath = join19(letraDir, "config.json");
3052
+ writeFileSync10(configPath, adaptConfig(projectType));
3053
+ console.log(` ${chalk12.gray("Created")} .letra/config.json`);
1657
3054
  const tools = adaptersForTool(tool);
1658
3055
  generateAdapterFiles(root, tools);
1659
3056
  if (tool === "todos" || tool === "vscode") {
1660
- const vscodeDir = join8(root, ".vscode");
1661
- if (!existsSync8(vscodeDir)) mkdirSync4(vscodeDir, { recursive: true });
1662
- const vscodeSettingsPath = join8(vscodeDir, "settings.json");
3057
+ const vscodeDir = join19(root, ".vscode");
3058
+ if (!existsSync18(vscodeDir)) mkdirSync7(vscodeDir, { recursive: true });
3059
+ const vscodeSettingsPath = join19(vscodeDir, "settings.json");
1663
3060
  const vscodeSettingsContent = `{
1664
3061
  "editor.formatOnSave": true,
1665
3062
  "editor.defaultFormatter": "esbenp.prettier-vscode",
@@ -1669,26 +3066,32 @@ Por que estamos construindo isso.
1669
3066
  "files.autoSave": "onFocusChange"
1670
3067
  }
1671
3068
  `;
1672
- writeFileSync8(vscodeSettingsPath, vscodeSettingsContent);
1673
- console.log(` ${chalk10.gray("Created")} .vscode/settings.json`);
3069
+ writeFileSync10(vscodeSettingsPath, vscodeSettingsContent);
3070
+ console.log(` ${chalk12.gray("Created")} .vscode/settings.json`);
1674
3071
  }
1675
- spinner.succeed(chalk10.green(".letra/ initialized successfully"));
3072
+ spinner.succeed(chalk12.green(".letra/ initialized successfully"));
1676
3073
  console.log("");
1677
3074
  console.log(" Next steps:");
1678
- console.log(
1679
- ` ${chalk10.cyan("letra spec new <name>")} Create your first spec`
1680
- );
1681
- console.log(` ${chalk10.cyan("letra lint")} Validate specs`);
3075
+ console.log(` ${chalk12.cyan("letra spec new <name>")} Create your first spec`);
3076
+ console.log(` ${chalk12.cyan("letra lint")} Validate specs`);
3077
+ console.log(` ${chalk12.cyan("letra init --serve")} Open web UI to configure workflow`);
3078
+ if (options?.serve) {
3079
+ console.log(`
3080
+ ${chalk12.cyan("Opening web UI...")}
3081
+ `);
3082
+ await flowServeAction(targetPath, { open: true });
3083
+ return;
3084
+ }
1682
3085
  } catch (error) {
1683
- spinner.fail(chalk10.red("Failed to initialize Letra"));
3086
+ spinner.fail(chalk12.red("Failed to initialize Letra"));
1684
3087
  process.exit(1);
1685
3088
  }
1686
3089
  }
1687
3090
 
1688
3091
  // src/commands/lint.ts
1689
- import { existsSync as existsSync9, readFileSync as readFileSync7, readdirSync as readdirSync5 } from "fs";
1690
- import { join as join9, resolve as resolve12 } from "path";
1691
- import chalk11 from "chalk";
3092
+ import { existsSync as existsSync19, readFileSync as readFileSync14, readdirSync as readdirSync8 } from "fs";
3093
+ import { join as join20, resolve as resolve13 } from "path";
3094
+ import chalk13 from "chalk";
1692
3095
  var REQUIRED_SECTIONS = [
1693
3096
  "## Outcome",
1694
3097
  "## Constraints",
@@ -1697,27 +3100,25 @@ var REQUIRED_SECTIONS = [
1697
3100
  "## Context"
1698
3101
  ];
1699
3102
  async function lint(targetPath) {
1700
- const root = resolve12(process.cwd(), targetPath || ".");
1701
- const specsDir = join9(root, ".letra", "specs");
1702
- if (!existsSync9(specsDir)) {
1703
- console.log(
1704
- chalk11.red("Error: .letra/specs/ not found. Run 'letra init' first.")
1705
- );
3103
+ const root = resolve13(process.cwd(), targetPath || ".");
3104
+ const specsDir = join20(root, ".letra", "specs");
3105
+ if (!existsSync19(specsDir)) {
3106
+ console.log(chalk13.red("Error: .letra/specs/ not found. Run 'letra init' first."));
1706
3107
  process.exit(1);
1707
3108
  }
1708
3109
  const results = [];
1709
3110
  let totalErrors = 0;
1710
3111
  let totalWarnings = 0;
1711
- const entries = readdirSync5(specsDir, { withFileTypes: true });
3112
+ const entries = readdirSync8(specsDir, { withFileTypes: true });
1712
3113
  for (const entry of entries) {
1713
3114
  if (!entry.isDirectory() || entry.name.startsWith("_")) continue;
1714
- const specFile = join9(specsDir, entry.name, "spec.md");
3115
+ const specFile = join20(specsDir, entry.name, "spec.md");
1715
3116
  const errors = [];
1716
3117
  const warnings = [];
1717
- if (!existsSync9(specFile)) {
3118
+ if (!existsSync19(specFile)) {
1718
3119
  errors.push("Missing spec.md");
1719
3120
  } else {
1720
- const content = readFileSync7(specFile, "utf-8");
3121
+ const content = readFileSync14(specFile, "utf-8");
1721
3122
  for (const section of REQUIRED_SECTIONS) {
1722
3123
  if (!content.includes(section)) {
1723
3124
  errors.push(`Missing section: ${section}`);
@@ -1728,9 +3129,7 @@ async function lint(targetPath) {
1728
3129
  }
1729
3130
  const hasChecklist = /-\s*\[[ x]\]\s*\*\*/i.test(content);
1730
3131
  if (!hasChecklist && content.includes("## Acceptance Criteria")) {
1731
- errors.push(
1732
- "Acceptance Criteria section exists but has no checklist items"
1733
- );
3132
+ errors.push("Acceptance Criteria section exists but has no checklist items");
1734
3133
  }
1735
3134
  }
1736
3135
  if (errors.length > 0 || warnings.length > 0) {
@@ -1740,22 +3139,22 @@ async function lint(targetPath) {
1740
3139
  }
1741
3140
  }
1742
3141
  if (results.length === 0) {
1743
- console.log(chalk11.green("All specs are valid"));
3142
+ console.log(chalk13.green("All specs are valid"));
1744
3143
  process.exit(0);
1745
3144
  }
1746
3145
  console.log("");
1747
3146
  for (const result of results) {
1748
- console.log(chalk11.bold(`
3147
+ console.log(chalk13.bold(`
1749
3148
  Spec: ${result.file}`));
1750
3149
  for (const error of result.errors) {
1751
- console.log(chalk11.red(` \u2717 ${error}`));
3150
+ console.log(chalk13.red(` \u2717 ${error}`));
1752
3151
  }
1753
3152
  for (const warning of result.warnings) {
1754
- console.log(chalk11.yellow(` \u26A0 ${warning}`));
3153
+ console.log(chalk13.yellow(` \u26A0 ${warning}`));
1755
3154
  }
1756
3155
  }
1757
3156
  console.log(
1758
- chalk11.gray(
3157
+ chalk13.gray(
1759
3158
  `
1760
3159
  ${results.length} spec(s) with issues: ${totalErrors} error(s), ${totalWarnings} warning(s)`
1761
3160
  )
@@ -1764,20 +3163,16 @@ ${results.length} spec(s) with issues: ${totalErrors} error(s), ${totalWarnings}
1764
3163
  }
1765
3164
 
1766
3165
  // src/commands/spec.ts
1767
- import {
1768
- existsSync as existsSync10,
1769
- mkdirSync as mkdirSync5,
1770
- readFileSync as readFileSync8,
1771
- readdirSync as readdirSync6,
1772
- writeFileSync as writeFileSync9
1773
- } from "fs";
1774
- import { join as join10, resolve as resolve13 } from "path";
1775
- import chalk12 from "chalk";
3166
+ import { existsSync as existsSync20, mkdirSync as mkdirSync8, readFileSync as readFileSync15, readdirSync as readdirSync9, writeFileSync as writeFileSync11 } from "fs";
3167
+ import { join as join21, resolve as resolve14 } from "path";
3168
+ import chalk14 from "chalk";
1776
3169
  import ora3 from "ora";
1777
3170
  var builtInTemplates = {
1778
3171
  "web-api": {
1779
3172
  spec: `# Spec: {{name}}
1780
3173
 
3174
+ > Updated: {{date}}
3175
+
1781
3176
  ## Outcome
1782
3177
  Usu\xE1rio consegue fazer requisi\xE7\xF5es HTTP para a API e receber respostas padronizadas.
1783
3178
 
@@ -1811,6 +3206,8 @@ Template para APIs REST. Adaptado para o dom\xEDnio espec\xEDfico do projeto.`,
1811
3206
  "cli-tool": {
1812
3207
  spec: `# Spec: {{name}}
1813
3208
 
3209
+ > Updated: {{date}}
3210
+
1814
3211
  ## Outcome
1815
3212
  Usu\xE1rio instala e executa a CLI, recebendo output formatado no terminal.
1816
3213
 
@@ -1844,6 +3241,8 @@ Template para ferramentas de linha de comando. Adaptado para o escopo espec\xEDf
1844
3241
  "mobile-feature": {
1845
3242
  spec: `# Spec: {{name}}
1846
3243
 
3244
+ > Updated: {{date}}
3245
+
1847
3246
  ## Outcome
1848
3247
  Usu\xE1rio consegue acessar e interagir com a nova funcionalidade no aplicativo mobile.
1849
3248
 
@@ -1877,9 +3276,9 @@ Template para features mobile nativas. Adaptado para o framework espec\xEDfico (
1877
3276
  };
1878
3277
  function listTemplates(root) {
1879
3278
  const names = Object.keys(builtInTemplates);
1880
- const customDir = join10(root, ".letra", "templates");
1881
- if (existsSync10(customDir)) {
1882
- for (const file of readdirSync6(customDir)) {
3279
+ const customDir = join21(root, ".letra", "templates");
3280
+ if (existsSync20(customDir)) {
3281
+ for (const file of readdirSync9(customDir)) {
1883
3282
  if (file.endsWith(".md")) {
1884
3283
  const name = file.replace(/\.md$/, "");
1885
3284
  if (!names.includes(name)) names.push(name);
@@ -1891,16 +3290,11 @@ function listTemplates(root) {
1891
3290
  function findTemplate(root, type) {
1892
3291
  const lower = type.toLowerCase();
1893
3292
  if (builtInTemplates[lower]) return builtInTemplates[lower];
1894
- const customFile = join10(root, ".letra", "templates", `${type}.md`);
1895
- const customAcceptance = join10(
1896
- root,
1897
- ".letra",
1898
- "templates",
1899
- `${type}-acceptance.md`
1900
- );
1901
- if (existsSync10(customFile)) {
1902
- const spec = readFileSync8(customFile, "utf-8");
1903
- const acceptance = existsSync10(customAcceptance) ? readFileSync8(customAcceptance, "utf-8") : `# Acceptance Criteria \u2014 ${type}
3293
+ const customFile = join21(root, ".letra", "templates", `${type}.md`);
3294
+ const customAcceptance = join21(root, ".letra", "templates", `${type}-acceptance.md`);
3295
+ if (existsSync20(customFile)) {
3296
+ const spec = readFileSync15(customFile, "utf-8");
3297
+ const acceptance = existsSync20(customAcceptance) ? readFileSync15(customAcceptance, "utf-8") : `# Acceptance Criteria \u2014 ${type}
1904
3298
 
1905
3299
  - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
1906
3300
  `;
@@ -1908,43 +3302,42 @@ function findTemplate(root, type) {
1908
3302
  }
1909
3303
  return null;
1910
3304
  }
1911
- function applyPlaceholders(content, name) {
1912
- return content.replace(/\{\{name\}\}/g, name);
3305
+ function applyPlaceholders(content, name, date) {
3306
+ return content.replace(/\{\{name\}\}/g, name).replace(/\{\{date\}\}/g, date);
1913
3307
  }
1914
3308
  async function specNew(name, options) {
1915
- const root = resolve13(process.cwd());
1916
- const letraDir = join10(root, ".letra");
1917
- const specDir = join10(letraDir, "specs", name);
1918
- if (!existsSync10(letraDir)) {
1919
- console.log(chalk12.red(".letra/ not found. Run 'letra init' first."));
3309
+ const root = resolve14(process.cwd());
3310
+ const letraDir = join21(root, ".letra");
3311
+ const specDir = join21(letraDir, "specs", name);
3312
+ if (!existsSync20(letraDir)) {
3313
+ console.log(chalk14.red(".letra/ not found. Run 'letra init' first."));
1920
3314
  process.exit(1);
1921
3315
  }
1922
- if (existsSync10(specDir)) {
1923
- console.log(chalk12.yellow(`Spec "${name}" already exists`));
3316
+ if (existsSync20(specDir)) {
3317
+ console.log(chalk14.yellow(`Spec "${name}" already exists`));
1924
3318
  return;
1925
3319
  }
1926
3320
  const templateType = options?.template || "_default";
1927
3321
  const template = templateType === "_default" ? null : findTemplate(root, templateType);
1928
3322
  if (options?.template && !template) {
1929
3323
  const available = listTemplates(root).join(", ");
1930
- console.log(
1931
- chalk12.red(
1932
- `Template "${options.template}" not found. Available: ${available}`
1933
- )
1934
- );
3324
+ console.log(chalk14.red(`Template "${options.template}" not found. Available: ${available}`));
1935
3325
  process.exit(1);
1936
3326
  }
1937
3327
  const spinner = ora3(`Creating spec "${name}"...`).start();
1938
3328
  try {
1939
- mkdirSync5(specDir, { recursive: true });
3329
+ const today2 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
3330
+ mkdirSync8(specDir, { recursive: true });
1940
3331
  if (template) {
1941
- const specContent = applyPlaceholders(template.spec, name);
1942
- const acceptanceContent = applyPlaceholders(template.acceptance, name);
1943
- writeFileSync9(join10(specDir, "spec.md"), specContent);
1944
- writeFileSync9(join10(specDir, "acceptance.md"), acceptanceContent);
3332
+ const specContent = applyPlaceholders(template.spec, name, today2);
3333
+ const acceptanceContent = applyPlaceholders(template.acceptance, name, today2);
3334
+ writeFileSync11(join21(specDir, "spec.md"), specContent);
3335
+ writeFileSync11(join21(specDir, "acceptance.md"), acceptanceContent);
1945
3336
  } else {
1946
3337
  const specContent = `# Spec: ${name}
1947
3338
 
3339
+ > Updated: ${today2}
3340
+
1948
3341
  ## Outcome
1949
3342
  O que o usu\xE1rio consegue fazer quando isso estiver pronto.
1950
3343
 
@@ -1964,14 +3357,12 @@ Por que estamos construindo isso. Trade-offs considerados.
1964
3357
 
1965
3358
  - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
1966
3359
  `;
1967
- writeFileSync9(join10(specDir, "spec.md"), specContent);
1968
- writeFileSync9(join10(specDir, "acceptance.md"), acceptanceContent);
3360
+ writeFileSync11(join21(specDir, "spec.md"), specContent);
3361
+ writeFileSync11(join21(specDir, "acceptance.md"), acceptanceContent);
1969
3362
  }
1970
- spinner.succeed(
1971
- chalk12.green(`Spec "${name}" created at .letra/specs/${name}/`)
1972
- );
3363
+ spinner.succeed(chalk14.green(`Spec "${name}" created at .letra/specs/${name}/`));
1973
3364
  } catch (error) {
1974
- spinner.fail(chalk12.red("Failed to create spec"));
3365
+ spinner.fail(chalk14.red("Failed to create spec"));
1975
3366
  process.exit(1);
1976
3367
  }
1977
3368
  }
@@ -1979,21 +3370,21 @@ Por que estamos construindo isso. Trade-offs considerados.
1979
3370
  // src/commands/validate.ts
1980
3371
  import { execSync } from "child_process";
1981
3372
  import {
1982
- existsSync as existsSync12,
3373
+ existsSync as existsSync22,
1983
3374
  mkdtempSync,
1984
- readFileSync as readFileSync10,
1985
- readdirSync as readdirSync7,
1986
- rmSync,
3375
+ readFileSync as readFileSync17,
3376
+ readdirSync as readdirSync10,
3377
+ rmSync as rmSync2,
1987
3378
  statSync as statSync3,
1988
3379
  watch as watch2
1989
3380
  } from "fs";
1990
3381
  import { tmpdir } from "os";
1991
- import { join as join12, resolve as resolve14 } from "path";
1992
- import chalk13 from "chalk";
3382
+ import { join as join23, resolve as resolve15 } from "path";
3383
+ import chalk15 from "chalk";
1993
3384
 
1994
3385
  // src/config.ts
1995
- import { existsSync as existsSync11, readFileSync as readFileSync9 } from "fs";
1996
- import { join as join11 } from "path";
3386
+ import { existsSync as existsSync21, readFileSync as readFileSync16 } from "fs";
3387
+ import { join as join22 } from "path";
1997
3388
  var DEFAULT_HEURISTICS = {
1998
3389
  "conteudo-minimo": { severity: "warning", minChars: 50 },
1999
3390
  "consistencia-terminologia": { severity: "warning" },
@@ -2008,14 +3399,14 @@ var DEFAULT_HEURISTICS = {
2008
3399
  "validate-conflict": { severity: "warning" }
2009
3400
  };
2010
3401
  function loadConfig(root) {
2011
- const configPath = join11(root, ".letra", "config.json");
3402
+ const configPath = join22(root, ".letra", "config.json");
2012
3403
  const heuristics = {};
2013
3404
  for (const [key, value] of Object.entries(DEFAULT_HEURISTICS)) {
2014
3405
  heuristics[key] = { ...value };
2015
3406
  }
2016
- if (existsSync11(configPath)) {
3407
+ if (existsSync21(configPath)) {
2017
3408
  try {
2018
- const raw = JSON.parse(readFileSync9(configPath, "utf-8"));
3409
+ const raw = JSON.parse(readFileSync16(configPath, "utf-8"));
2019
3410
  if (raw.heuristics && typeof raw.heuristics === "object") {
2020
3411
  for (const [key, value] of Object.entries(raw.heuristics)) {
2021
3412
  if (heuristics[key]) {
@@ -2082,17 +3473,15 @@ var lowConfidenceMarkers = [
2082
3473
  "teoricamente"
2083
3474
  ];
2084
3475
  function checkSpecContent(specDir, label, description, config) {
2085
- const cfg = config ?? loadConfig(join12(specDir, "..", "..", ".."));
2086
- const specFile = join12(specDir, "spec.md");
2087
- const glossaryFile = join12(specDir, "..", "..", "glossary.md");
2088
- if (!existsSync12(specFile))
2089
- return { status: "FAIL", note: "(spec.md not found)" };
2090
- const specContent = readFileSync10(specFile, "utf-8");
2091
- const now6 = /* @__PURE__ */ new Date();
3476
+ const cfg = config ?? loadConfig(join23(specDir, "..", "..", ".."));
3477
+ const specFile = join23(specDir, "spec.md");
3478
+ const glossaryFile = join23(specDir, "..", "..", "glossary.md");
3479
+ if (!existsSync22(specFile)) return { status: "FAIL", note: "(spec.md not found)" };
3480
+ const specContent = readFileSync17(specFile, "utf-8");
3481
+ const now7 = /* @__PURE__ */ new Date();
2092
3482
  if (label.includes("Conte\xFAdo M\xEDnimo")) {
2093
3483
  const outcomeMatch = specContent.match(/## Outcome\s+([\s\S]*?)(?=\n## )/);
2094
- if (!outcomeMatch)
2095
- return { status: "FAIL", note: "(no Outcome section)" };
3484
+ if (!outcomeMatch) return { status: "FAIL", note: "(no Outcome section)" };
2096
3485
  const outcomeContent = outcomeMatch[1].trim();
2097
3486
  const heurConfig = getHeuristicConfig(cfg, label);
2098
3487
  const minChars = heurConfig.minChars ?? 50;
@@ -2108,13 +3497,13 @@ function checkSpecContent(specDir, label, description, config) {
2108
3497
  };
2109
3498
  }
2110
3499
  if (label.includes("Consist\xEAncia de Terminologia") || label.includes("Terminologia")) {
2111
- if (!existsSync12(glossaryFile)) {
3500
+ if (!existsSync22(glossaryFile)) {
2112
3501
  return {
2113
3502
  status: "PASS",
2114
3503
  note: "(no glossary to check against)"
2115
3504
  };
2116
3505
  }
2117
- const glossaryContent = readFileSync10(glossaryFile, "utf-8");
3506
+ const glossaryContent = readFileSync17(glossaryFile, "utf-8");
2118
3507
  const terms = glossaryContent.match(/\*\*(.+?)\*\*/g) || [];
2119
3508
  const extractedTerms = terms.map((t) => t.replace(/\*\*/g, "").trim()).filter((t) => t.length > 3);
2120
3509
  const missingTerms = extractedTerms.filter(
@@ -2153,9 +3542,7 @@ function checkSpecContent(specDir, label, description, config) {
2153
3542
  }
2154
3543
  if (label.includes("Drift Temporal") || label.includes("Temporal")) {
2155
3544
  const stat = statSync3(specFile);
2156
- const daysOld = Math.floor(
2157
- (now6.getTime() - stat.mtimeMs) / (1e3 * 60 * 60 * 24)
2158
- );
3545
+ const daysOld = Math.floor((now7.getTime() - stat.mtimeMs) / (1e3 * 60 * 60 * 24));
2159
3546
  const heurConfig = getHeuristicConfig(cfg, label);
2160
3547
  const maxDays = heurConfig.maxDays ?? 30;
2161
3548
  if (daysOld < maxDays) {
@@ -2207,9 +3594,7 @@ function checkEmptySections(specContent) {
2207
3594
  };
2208
3595
  }
2209
3596
  function checkBinaryCriteria(specContent) {
2210
- const acMatch = specContent.match(
2211
- /## Acceptance Criteria\s+([\s\S]*?)(?=\n## |\n*$)/
2212
- );
3597
+ const acMatch = specContent.match(/## Acceptance Criteria\s+([\s\S]*?)(?=\n## |\n*$)/);
2213
3598
  if (!acMatch) {
2214
3599
  return {
2215
3600
  status: "FAIL",
@@ -2224,9 +3609,7 @@ function checkBinaryCriteria(specContent) {
2224
3609
  for (const line of criteriaLines) {
2225
3610
  const description = line.replace(/- \[[ x]\] \*\*.+?\*\*:\s*/, "");
2226
3611
  const hasMetric = /\d+/.test(description);
2227
- const hasVagueVerb = vagueVerbs.some(
2228
- (v) => description.toLowerCase().includes(v)
2229
- );
3612
+ const hasVagueVerb = vagueVerbs.some((v) => description.toLowerCase().includes(v));
2230
3613
  if (!hasMetric && hasVagueVerb) {
2231
3614
  const labelMatch = line.match(/\*\*(.+?)\*\*/);
2232
3615
  if (labelMatch) nonBinary.push(labelMatch[1]);
@@ -2341,13 +3724,13 @@ function detectConflict(textA, textB) {
2341
3724
  }
2342
3725
  function checkConflicts(specsDir, config) {
2343
3726
  const results = [];
2344
- const entries = readdirSync7(specsDir, { withFileTypes: true });
3727
+ const entries = readdirSync10(specsDir, { withFileTypes: true });
2345
3728
  const specDirs = entries.filter((e) => e.isDirectory() && !e.name.startsWith("_")).map((e) => e.name);
2346
3729
  const specs = [];
2347
3730
  for (const dir of specDirs) {
2348
- const acceptanceFile = join12(specsDir, dir, "acceptance.md");
2349
- if (!existsSync12(acceptanceFile)) continue;
2350
- const content = readFileSync10(acceptanceFile, "utf-8");
3731
+ const acceptanceFile = join23(specsDir, dir, "acceptance.md");
3732
+ if (!existsSync22(acceptanceFile)) continue;
3733
+ const content = readFileSync17(acceptanceFile, "utf-8");
2351
3734
  const acLines = content.match(/- \[[ x]\] \*\*(.+?)\*\*: (.+)/g) || [];
2352
3735
  const acs = acLines.map((line) => {
2353
3736
  const m = line.match(/- \[[ x]\] \*\*(.+?)\*\*: (.+)/);
@@ -2397,13 +3780,11 @@ function out(format, level, spec, label, message, note) {
2397
3780
  if (format === "junit") {
2398
3781
  return;
2399
3782
  }
2400
- const icon = level === "pass" ? chalk13.green("\u2713") : level === "fail" ? chalk13.red("\u2717") : level === "warning" ? chalk13.yellow("\u26A0") : "";
3783
+ const icon = level === "pass" ? chalk15.green("\u2713") : level === "fail" ? chalk15.red("\u2717") : level === "warning" ? chalk15.yellow("\u26A0") : "";
2401
3784
  if (level === "info") {
2402
3785
  console.log(` ${message}`);
2403
3786
  } else {
2404
- console.log(
2405
- ` [${icon}] ${chalk13.cyan(label)}: ${message} ${chalk13.gray(note)}`
2406
- );
3787
+ console.log(` [${icon}] ${chalk15.cyan(label)}: ${message} ${chalk15.gray(note)}`);
2407
3788
  }
2408
3789
  }
2409
3790
  function buildJunitXml(results) {
@@ -2444,55 +3825,55 @@ function flushResults(results, format, specGroups, totalPass, totalFail, totalWa
2444
3825
  }
2445
3826
  }
2446
3827
  console.log(
2447
- chalk13.gray(
3828
+ chalk15.gray(
2448
3829
  `
2449
3830
  Results: ${totalPass} passed, ${totalFail} failed${totalWarning > 0 ? `, ${totalWarning} warnings` : ""}`
2450
3831
  )
2451
3832
  );
2452
3833
  }
2453
3834
  async function validate(targetPath, options) {
2454
- const root = resolve14(process.cwd(), targetPath || ".");
2455
- const specsDir = join12(root, ".letra", "specs");
3835
+ const root = resolve15(process.cwd(), targetPath || ".");
3836
+ const specsDir = join23(root, ".letra", "specs");
2456
3837
  const fmt = options?.format || "text";
2457
- if (!existsSync12(specsDir)) {
3838
+ if (!existsSync22(specsDir)) {
2458
3839
  const msg = "Error: .letra/specs/ not found. Run 'letra init' first.";
2459
3840
  if (fmt === "github-annotation") {
2460
3841
  console.log(`::error file=,title=Init Required::${msg}`);
2461
3842
  } else {
2462
- console.log(chalk13.red(msg));
3843
+ console.log(chalk15.red(msg));
2463
3844
  }
2464
3845
  process.exit(1);
2465
3846
  }
2466
3847
  async function runValidation() {
2467
3848
  const config = loadConfig(root);
2468
- const entries = readdirSync7(specsDir, { withFileTypes: true });
3849
+ const entries = readdirSync10(specsDir, { withFileTypes: true });
2469
3850
  let totalPass = 0;
2470
3851
  let totalFail = 0;
2471
3852
  let totalWarning = 0;
2472
3853
  const specGroups = /* @__PURE__ */ new Map();
2473
3854
  const allResults = [];
2474
- const entryPoint = join12(root, "src/index.ts");
3855
+ const entryPoint = join23(root, "src/index.ts");
2475
3856
  const opts = {
2476
3857
  stdio: "pipe",
2477
3858
  encoding: "utf-8",
2478
3859
  shell: process.platform === "win32" ? "cmd.exe" : true
2479
3860
  };
2480
- const ciFile = join12(root, ".github", "workflows", "ci.yml");
2481
- const cursorRulesFile = join12(root, ".cursorrules");
2482
- const copilotFile = join12(root, ".github", "copilot-instructions.md");
2483
- const vscodeSettingsFile = join12(root, ".vscode", "settings.json");
3861
+ const ciFile = join23(root, ".github", "workflows", "ci.yml");
3862
+ const cursorRulesFile = join23(root, ".cursorrules");
3863
+ const copilotFile = join23(root, ".github", "copilot-instructions.md");
3864
+ const vscodeSettingsFile = join23(root, ".vscode", "settings.json");
2484
3865
  if (fmt !== "junit") {
2485
3866
  out(fmt, "info", null, "", "\nLetra Validation\n", "");
2486
3867
  }
2487
3868
  for (const entry of entries) {
2488
3869
  if (!entry.isDirectory() || entry.name.startsWith("_")) continue;
2489
- const acceptanceFile = join12(specsDir, entry.name, "acceptance.md");
2490
- const specFile = join12(specsDir, entry.name, "spec.md");
3870
+ const acceptanceFile = join23(specsDir, entry.name, "acceptance.md");
3871
+ const specFile = join23(specsDir, entry.name, "spec.md");
2491
3872
  let content;
2492
- if (existsSync12(acceptanceFile)) {
2493
- content = readFileSync10(acceptanceFile, "utf-8");
2494
- } else if (existsSync12(specFile)) {
2495
- content = readFileSync10(specFile, "utf-8");
3873
+ if (existsSync22(acceptanceFile)) {
3874
+ content = readFileSync17(acceptanceFile, "utf-8");
3875
+ } else if (existsSync22(specFile)) {
3876
+ content = readFileSync17(specFile, "utf-8");
2496
3877
  } else {
2497
3878
  out(
2498
3879
  fmt,
@@ -2505,7 +3886,7 @@ async function validate(targetPath, options) {
2505
3886
  continue;
2506
3887
  }
2507
3888
  const criteriaLines = content.match(/- \[ \] \*\*(.+?)\*\*: (.+)/g) || [];
2508
- const specContent = existsSync12(specFile) ? readFileSync10(specFile, "utf-8") : null;
3889
+ const specContent = existsSync22(specFile) ? readFileSync17(specFile, "utf-8") : null;
2509
3890
  out(fmt, "info", entry.name, "", `Spec: ${entry.name}`, "");
2510
3891
  if (criteriaLines.length === 0) {
2511
3892
  out(fmt, "info", entry.name, "", "No criteria found", "");
@@ -2522,7 +3903,7 @@ async function validate(targetPath, options) {
2522
3903
  let intelligenceResult = null;
2523
3904
  try {
2524
3905
  intelligenceResult = checkSpecContent(
2525
- join12(specsDir, entry.name),
3906
+ join23(specsDir, entry.name),
2526
3907
  label,
2527
3908
  description,
2528
3909
  config
@@ -2531,45 +3912,42 @@ async function validate(targetPath, options) {
2531
3912
  status = intelligenceResult.status;
2532
3913
  note = intelligenceResult.note;
2533
3914
  } else if (label.includes("letra init")) {
2534
- const tmp = mkdtempSync(join12(tmpdir(), "letra-test-"));
3915
+ const tmp = mkdtempSync(join23(tmpdir(), "letra-test-"));
2535
3916
  execSync(`npx tsx "${entryPoint}" init "${tmp}"`, { ...opts });
2536
- if (existsSync12(join12(tmp, ".letra", "context.md")))
2537
- status = "PASS";
2538
- rmSync(tmp, { recursive: true });
3917
+ if (existsSync22(join23(tmp, ".letra", "context.md"))) status = "PASS";
3918
+ rmSync2(tmp, { recursive: true });
2539
3919
  } else if (label.includes("letra spec")) {
2540
- const tmp = mkdtempSync(join12(tmpdir(), "letra-test-"));
3920
+ const tmp = mkdtempSync(join23(tmpdir(), "letra-test-"));
2541
3921
  execSync(`npx tsx "${entryPoint}" init "${tmp}"`, { ...opts });
2542
3922
  execSync(`npx tsx "${entryPoint}" spec smoke-test`, {
2543
3923
  ...opts,
2544
3924
  cwd: tmp
2545
3925
  });
2546
- if (existsSync12(
2547
- join12(tmp, ".letra", "specs", "smoke-test", "spec.md")
2548
- ))
3926
+ if (existsSync22(join23(tmp, ".letra", "specs", "smoke-test", "spec.md")))
2549
3927
  status = "PASS";
2550
- rmSync(tmp, { recursive: true });
3928
+ rmSync2(tmp, { recursive: true });
2551
3929
  } else if (label.includes("letra lint")) {
2552
3930
  execSync(`npx tsx "${entryPoint}" lint`, { ...opts });
2553
3931
  status = "PASS";
2554
3932
  } else if (label.includes("letra validate")) {
2555
3933
  status = "PASS";
2556
- } else if (label.includes("Workflow Ativo") || label.includes("CI") && existsSync12(ciFile)) {
3934
+ } else if (label.includes("Workflow Ativo") || label.includes("CI") && existsSync22(ciFile)) {
2557
3935
  status = "PASS";
2558
3936
  } else if (label.includes("Lint Gate") || label.includes("Lint")) {
2559
- const ciContent = readFileSync10(ciFile, "utf-8");
3937
+ const ciContent = readFileSync17(ciFile, "utf-8");
2560
3938
  if (ciContent.includes("letra lint") || ciContent.includes("lint"))
2561
3939
  status = "PASS";
2562
3940
  } else if (label.includes("Test Gate") || label.includes("Test")) {
2563
- const ciContent = readFileSync10(ciFile, "utf-8");
3941
+ const ciContent = readFileSync17(ciFile, "utf-8");
2564
3942
  if (ciContent.includes("npm test") || ciContent.includes("vitest") || ciContent.includes("test"))
2565
3943
  status = "PASS";
2566
3944
  } else if (label.includes("Valida\xE7\xE3o de Formato") || label.includes("Formato")) {
2567
- const ciContent = readFileSync10(ciFile, "utf-8");
3945
+ const ciContent = readFileSync17(ciFile, "utf-8");
2568
3946
  if (ciContent.includes("tsc") || ciContent.includes("typecheck"))
2569
3947
  status = "PASS";
2570
3948
  } else if (label.includes("Distribui\xE7\xE3o npm") || label.includes("npm")) {
2571
3949
  const pkgJson = JSON.parse(
2572
- readFileSync10(join12(root, "package.json"), "utf-8")
3950
+ readFileSync17(join23(root, "package.json"), "utf-8")
2573
3951
  );
2574
3952
  if (pkgJson.bin && pkgJson.name) {
2575
3953
  status = "PASS";
@@ -2581,50 +3959,47 @@ async function validate(targetPath, options) {
2581
3959
  status = "PASS";
2582
3960
  note = "(npm distribution preferred)";
2583
3961
  } else if (label.includes("Gera\xE7\xE3o de Regras") || label.includes("Gera\xE7\xE3o")) {
2584
- if (existsSync12(cursorRulesFile)) {
2585
- const rulesContent = readFileSync10(cursorRulesFile, "utf-8");
3962
+ if (existsSync22(cursorRulesFile)) {
3963
+ const rulesContent = readFileSync17(cursorRulesFile, "utf-8");
2586
3964
  if (rulesContent.includes(".letra/context.md") && rulesContent.includes(".letra/constitution.md")) {
2587
3965
  status = "PASS";
2588
3966
  }
2589
3967
  }
2590
3968
  } else if (label.includes("Inje\xE7\xE3o de Contexto")) {
2591
- if (existsSync12(cursorRulesFile)) {
2592
- const rulesContent = readFileSync10(cursorRulesFile, "utf-8");
3969
+ if (existsSync22(cursorRulesFile)) {
3970
+ const rulesContent = readFileSync17(cursorRulesFile, "utf-8");
2593
3971
  if (rulesContent.includes("@.letra/")) status = "PASS";
2594
- } else if (existsSync12(copilotFile)) {
2595
- const copilotContent = readFileSync10(copilotFile, "utf-8");
3972
+ } else if (existsSync22(copilotFile)) {
3973
+ const copilotContent = readFileSync17(copilotFile, "utf-8");
2596
3974
  if (copilotContent.includes(".letra/")) status = "PASS";
2597
3975
  }
2598
3976
  } else if (label.includes("Acesso a Valida\xE7\xE3o")) {
2599
- if (existsSync12(cursorRulesFile)) {
2600
- const rulesContent = readFileSync10(cursorRulesFile, "utf-8");
3977
+ if (existsSync22(cursorRulesFile)) {
3978
+ const rulesContent = readFileSync17(cursorRulesFile, "utf-8");
2601
3979
  if (rulesContent.includes("letra validate")) status = "PASS";
2602
3980
  }
2603
3981
  } else if (label.includes("N\xE3o-intrusivo")) {
2604
- if (existsSync12(cursorRulesFile) || existsSync12(copilotFile)) {
3982
+ if (existsSync22(cursorRulesFile) || existsSync22(copilotFile)) {
2605
3983
  status = "PASS";
2606
3984
  }
2607
3985
  } else if (label.includes("Gera\xE7\xE3o de Instru\xE7\xF5es")) {
2608
- if (existsSync12(copilotFile)) {
2609
- const copilotContent = readFileSync10(copilotFile, "utf-8");
3986
+ if (existsSync22(copilotFile)) {
3987
+ const copilotContent = readFileSync17(copilotFile, "utf-8");
2610
3988
  if (copilotContent.includes(".letra/context.md") && copilotContent.includes(".letra/constitution.md")) {
2611
3989
  status = "PASS";
2612
3990
  }
2613
3991
  }
2614
3992
  } else if (label.includes("Settings do Editor")) {
2615
- if (existsSync12(vscodeSettingsFile)) {
2616
- const settingsContent = readFileSync10(
2617
- vscodeSettingsFile,
2618
- "utf-8"
2619
- );
3993
+ if (existsSync22(vscodeSettingsFile)) {
3994
+ const settingsContent = readFileSync17(vscodeSettingsFile, "utf-8");
2620
3995
  if (settingsContent.includes("editor.formatOnSave")) {
2621
3996
  status = "PASS";
2622
3997
  }
2623
3998
  }
2624
3999
  } else if (label.includes("Arquivo de Config")) {
2625
- const configFile = join12(root, ".letra", "config.json");
2626
- if (existsSync12(configFile)) {
2627
- const cfgContent = readFileSync10(configFile, "utf-8");
4000
+ const configFile = join23(root, ".letra", "config.json");
4001
+ if (existsSync22(configFile)) {
4002
+ const cfgContent = readFileSync17(configFile, "utf-8");
2628
4003
  try {
2629
4004
  const parsed = JSON.parse(cfgContent);
2630
4005
  if (parsed.heuristics) {
@@ -2651,14 +4026,7 @@ async function validate(targetPath, options) {
2651
4026
  note = `(error: ${err.message?.split("\n")[0] || "unknown"})`;
2652
4027
  }
2653
4028
  if (status === "PASS") {
2654
- collectResult(
2655
- allResults,
2656
- "pass",
2657
- entry.name,
2658
- label,
2659
- description,
2660
- note
2661
- );
4029
+ collectResult(allResults, "pass", entry.name, label, description, note);
2662
4030
  totalPass++;
2663
4031
  specPass++;
2664
4032
  } else if (intelligenceResult) {
@@ -2675,37 +4043,16 @@ async function validate(targetPath, options) {
2675
4043
  totalWarning++;
2676
4044
  specWarning++;
2677
4045
  } else {
2678
- collectResult(
2679
- allResults,
2680
- "fail",
2681
- entry.name,
2682
- label,
2683
- description,
2684
- note
2685
- );
4046
+ collectResult(allResults, "fail", entry.name, label, description, note);
2686
4047
  totalFail++;
2687
4048
  specFail++;
2688
4049
  }
2689
4050
  } else if (note.includes("manual check needed")) {
2690
- collectResult(
2691
- allResults,
2692
- "warning",
2693
- entry.name,
2694
- label,
2695
- description,
2696
- note
2697
- );
4051
+ collectResult(allResults, "warning", entry.name, label, description, note);
2698
4052
  totalWarning++;
2699
4053
  specWarning++;
2700
4054
  } else {
2701
- collectResult(
2702
- allResults,
2703
- "fail",
2704
- entry.name,
2705
- label,
2706
- description,
2707
- note
2708
- );
4055
+ collectResult(allResults, "fail", entry.name, label, description, note);
2709
4056
  totalFail++;
2710
4057
  specFail++;
2711
4058
  }
@@ -2812,14 +4159,7 @@ async function validate(targetPath, options) {
2812
4159
  for (const cr of conflictResults) {
2813
4160
  if (cr.passed) continue;
2814
4161
  const level = conflictCfg.severity === "warning" ? "warning" : "fail";
2815
- collectResult(
2816
- allResults,
2817
- level,
2818
- "(cross-spec)",
2819
- cr.label,
2820
- cr.message,
2821
- ""
2822
- );
4162
+ collectResult(allResults, level, "(cross-spec)", cr.label, cr.message, "");
2823
4163
  if (level === "warning") {
2824
4164
  totalWarning++;
2825
4165
  } else {
@@ -2832,27 +4172,20 @@ async function validate(targetPath, options) {
2832
4172
  out(fmt, r.level, r.spec, r.label, r.message, r.note);
2833
4173
  }
2834
4174
  }
2835
- flushResults(
2836
- allResults,
2837
- fmt,
2838
- specGroups,
2839
- totalPass,
2840
- totalFail,
2841
- totalWarning
2842
- );
4175
+ flushResults(allResults, fmt, specGroups, totalPass, totalFail, totalWarning);
2843
4176
  return totalFail;
2844
4177
  }
2845
4178
  const exitCode = await runValidation();
2846
4179
  if (options?.watch) {
2847
4180
  let timer = null;
2848
- console.log(chalk13.gray("\nWatching for changes... (Ctrl+C to stop)"));
4181
+ console.log(chalk15.gray("\nWatching for changes... (Ctrl+C to stop)"));
2849
4182
  const watcher = watch2(specsDir, { recursive: true });
2850
4183
  watcher.on("change", () => {
2851
4184
  if (timer) clearTimeout(timer);
2852
4185
  timer = setTimeout(async () => {
2853
4186
  console.clear();
2854
4187
  const code = await runValidation();
2855
- console.log(chalk13.gray("\nWatching for changes... (Ctrl+C to stop)"));
4188
+ console.log(chalk15.gray("\nWatching for changes... (Ctrl+C to stop)"));
2856
4189
  }, 300);
2857
4190
  });
2858
4191
  process.on("SIGINT", () => {
@@ -2870,21 +4203,68 @@ async function validate(targetPath, options) {
2870
4203
  }
2871
4204
  }
2872
4205
 
4206
+ // src/commands/diagnose.ts
4207
+ import { resolve as resolve16 } from "path";
4208
+ async function diagnose(targetPath) {
4209
+ const root = resolve16(process.cwd(), targetPath ?? ".");
4210
+ const engine = new DiagnosticEngine(root);
4211
+ engine.ensureDirs();
4212
+ console.log("\n\u{1F50D} Auto-diagn\xF3stico do Letra\n");
4213
+ const output = await engine.runAll();
4214
+ if (output.fixes.length > 0) {
4215
+ console.log(`\u2705 ${output.fixes.length} auto-corre\xE7\xE3o(\xF5es) aplicada(s):
4216
+ `);
4217
+ for (const fix of output.fixes) {
4218
+ console.log(` \u2022 ${fix.title}`);
4219
+ }
4220
+ console.log();
4221
+ }
4222
+ if (output.suggestions.length > 0) {
4223
+ console.log(`\u{1F4A1} ${output.suggestions.length} sugest\xE3o(\xF5es):
4224
+ `);
4225
+ for (const s of output.suggestions) {
4226
+ console.log(` \u2022 [${s.type}] ${s.title}`);
4227
+ console.log(` ${s.description}`);
4228
+ }
4229
+ console.log();
4230
+ }
4231
+ if (output.errors.length > 0) {
4232
+ console.log(`\u274C ${output.errors.length} erro(s) nos detectores:
4233
+ `);
4234
+ for (const err of output.errors) {
4235
+ console.log(` \u2022 ${err}`);
4236
+ }
4237
+ console.log();
4238
+ }
4239
+ if (output.fixes.length === 0 && output.suggestions.length === 0 && output.errors.length === 0) {
4240
+ console.log(" Nenhum problema detectado. Tudo ok.\n");
4241
+ }
4242
+ const snapshots = engine.listSnapshots();
4243
+ if (snapshots.length > 0) {
4244
+ console.log(`\u{1F4E6} ${snapshots.length} snapshots dispon\xEDveis para undo:`);
4245
+ for (const snap of snapshots.slice(0, 5)) {
4246
+ console.log(
4247
+ ` \u2022 ${snap.id} \u2014 ${snap.diagnosticTitle} (${new Date(snap.timestamp).toLocaleString()})`
4248
+ );
4249
+ }
4250
+ if (snapshots.length > 5) {
4251
+ console.log(` ... e mais ${snapshots.length - 5}`);
4252
+ }
4253
+ console.log();
4254
+ }
4255
+ }
4256
+
2873
4257
  // src/index.ts
2874
- var __dirname2 = fileURLToPath2(new URL(".", import.meta.url));
2875
- var pkg = JSON.parse(
2876
- readFileSync11(join13(resolve15(__dirname2, ".."), "package.json"), "utf-8")
2877
- );
4258
+ var __dirname2 = fileURLToPath3(new URL(".", import.meta.url));
4259
+ var pkg = JSON.parse(readFileSync18(join24(resolve17(__dirname2, ".."), "package.json"), "utf-8"));
2878
4260
  var program = new Command4();
2879
4261
  program.name("letra").description("SDD-agnostic memory framework for AI coding agents").version(pkg.version);
2880
- program.command("init [path]").option("--yes", "Skip prompts and use defaults").description("Initialize .letra/ directory with templates").action((path, options) => init(path, { ...options }));
4262
+ program.command("init [path]").option("--yes", "Skip prompts and use defaults").option("--serve", "Open web UI after init (starts flow serve)").description("Initialize .letra/ directory with templates").action((path, options) => init(path, { ...options }));
2881
4263
  var specCmd = program.command("spec").description("Manage specs");
2882
- specCmd.command("new <name>").option(
2883
- "--template <type>",
2884
- "Template type: web-api, cli-tool, mobile-feature"
2885
- ).description("Create a new spec from template").action((name, options) => specNew(name, { ...options }));
4264
+ specCmd.command("new <name>").option("--template <type>", "Template type: web-api, cli-tool, mobile-feature").description("Create a new spec from template").action((name, options) => specNew(name, { ...options }));
2886
4265
  program.command("lint [path]").description("Validate spec format and completeness").action(lint);
2887
4266
  program.command("validate [path]").option("--watch", "Watch specs and re-validate on change").option("--format <type>", "Output format: text, github-annotation, junit").description("Check if artifacts meet acceptance criteria").action((path, options) => validate(path, { ...options }));
4267
+ program.command("diagnose [path]").description("Detect and fix drifts between specs, code, and workflow").action((path) => diagnose(path));
2888
4268
  program.addCommand(decisionCommand());
2889
4269
  program.addCommand(flowCommand());
2890
4270
  program.addCommand(focus_default());