@letra-ai/cli 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/client/assets/index-BDvDDvsh.css +1 -0
  2. package/dist/client/assets/index-CUvZ9Y9b.js +84 -0
  3. package/dist/client/index.html +13 -0
  4. package/dist/index.js +1255 -437
  5. package/package.json +28 -61
  6. package/.letra/adapters/opencode.json +0 -21
  7. package/.letra/constitution.md +0 -35
  8. package/.letra/context.md +0 -29
  9. package/.letra/decisions/flow-mvp-escopo-enxuto-3-comandos-valor-imediato.md +0 -35
  10. package/.letra/glossary.md +0 -21
  11. package/.letra/lessons-learned.md +0 -20
  12. package/.letra/specs/_template.md +0 -27
  13. package/.letra/specs/adapter-claude-code/acceptance.md +0 -6
  14. package/.letra/specs/adapter-claude-code/spec.md +0 -27
  15. package/.letra/specs/adapter-codex-cli/acceptance.md +0 -6
  16. package/.letra/specs/adapter-codex-cli/spec.md +0 -27
  17. package/.letra/specs/adapter-cursor/acceptance.md +0 -6
  18. package/.letra/specs/adapter-cursor/spec.md +0 -29
  19. package/.letra/specs/adapter-opencode/acceptance.md +0 -6
  20. package/.letra/specs/adapter-opencode/spec.md +0 -35
  21. package/.letra/specs/adapter-vscode/acceptance.md +0 -6
  22. package/.letra/specs/adapter-vscode/spec.md +0 -29
  23. package/.letra/specs/adapter-windsurf/acceptance.md +0 -6
  24. package/.letra/specs/adapter-windsurf/spec.md +0 -27
  25. package/.letra/specs/ci-cd-pipeline/acceptance.md +0 -6
  26. package/.letra/specs/ci-cd-pipeline/spec.md +0 -30
  27. package/.letra/specs/cli-skeleton/acceptance.md +0 -7
  28. package/.letra/specs/cli-skeleton/spec.md +0 -30
  29. package/.letra/specs/decision-new/acceptance.md +0 -7
  30. package/.letra/specs/decision-new/spec.md +0 -29
  31. package/.letra/specs/flow-edit-diff/acceptance.md +0 -7
  32. package/.letra/specs/flow-edit-diff/spec.md +0 -30
  33. package/.letra/specs/flow-export-import/acceptance.md +0 -7
  34. package/.letra/specs/flow-export-import/spec.md +0 -27
  35. package/.letra/specs/flow-mvp/roadmap.md +0 -40
  36. package/.letra/specs/flow-mvp/spec.md +0 -40
  37. package/.letra/specs/flow-visualize/acceptance.md +0 -7
  38. package/.letra/specs/flow-visualize/spec.md +0 -28
  39. package/.letra/specs/init-interactive/acceptance.md +0 -7
  40. package/.letra/specs/init-interactive/spec.md +0 -29
  41. package/.letra/specs/session-focus/acceptance.md +0 -7
  42. package/.letra/specs/session-focus/spec.md +0 -30
  43. package/.letra/specs/spec-templates-domain/acceptance.md +0 -7
  44. package/.letra/specs/spec-templates-domain/spec.md +0 -29
  45. package/.letra/specs/validate-config/acceptance.md +0 -9
  46. package/.letra/specs/validate-config/spec.md +0 -32
  47. package/.letra/specs/validate-conflict/acceptance.md +0 -7
  48. package/.letra/specs/validate-conflict/spec.md +0 -29
  49. package/.letra/specs/validate-format-pr/acceptance.md +0 -7
  50. package/.letra/specs/validate-format-pr/spec.md +0 -28
  51. package/.letra/specs/validate-intelligence/acceptance.md +0 -9
  52. package/.letra/specs/validate-intelligence/spec.md +0 -30
  53. package/.letra/specs/validate-watch/acceptance.md +0 -7
  54. package/.letra/specs/validate-watch/spec.md +0 -29
  55. package/.letra/workspace.schema.json +0 -32
  56. package/LICENSE +0 -21
  57. package/README.md +0 -240
package/dist/index.js CHANGED
@@ -1,19 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/index.ts
4
- import { readFileSync as readFileSync10 } from "fs";
5
- import { join as join12, resolve as resolve14 } from "path";
6
- import { fileURLToPath as fileURLToPath2 } from "url";
4
+ import { readFileSync as readFileSync11 } from "fs";
5
+ import { join as join13, resolve as resolve16 } from "path";
6
+ import { fileURLToPath as fileURLToPath3 } from "url";
7
7
  import { Command as Command4 } from "commander";
8
8
 
9
9
  // src/commands/decision.ts
10
- import {
11
- existsSync,
12
- mkdirSync,
13
- readFileSync,
14
- readdirSync,
15
- writeFileSync
16
- } from "fs";
10
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "fs";
17
11
  import { join, resolve } from "path";
18
12
  import chalk from "chalk";
19
13
  import { Command } from "commander";
@@ -35,9 +29,7 @@ function decisionCommand() {
35
29
  }
36
30
  if (existsSync(filePath)) {
37
31
  console.log(
38
- chalk.red(
39
- `Decision "${slug}" already exists at .letra/decisions/${slug}.md`
40
- )
32
+ chalk.red(`Decision "${slug}" already exists at .letra/decisions/${slug}.md`)
41
33
  );
42
34
  return;
43
35
  }
@@ -59,19 +51,13 @@ What was decided?
59
51
  What are the trade-offs? What does this enable or prevent?
60
52
  `;
61
53
  writeFileSync(filePath, content);
62
- console.log(
63
- chalk.green(
64
- `Decision "${slug}" created at .letra/decisions/${slug}.md`
65
- )
66
- );
54
+ console.log(chalk.green(`Decision "${slug}" created at .letra/decisions/${slug}.md`));
67
55
  });
68
56
  cmd.command("list").description("Lista todos os Architecture Decision Records").action(() => {
69
57
  const root = resolve(process.cwd());
70
58
  const decisionsDir = join(root, ".letra", "decisions");
71
59
  if (!existsSync(decisionsDir)) {
72
- console.log(
73
- chalk.yellow("No decisions directory found at .letra/decisions/")
74
- );
60
+ console.log(chalk.yellow("No decisions directory found at .letra/decisions/"));
75
61
  return;
76
62
  }
77
63
  const files = readdirSync(decisionsDir).filter((f) => f.endsWith(".md")).sort();
@@ -104,12 +90,12 @@ import ora from "ora";
104
90
  function askText(query, defaultValue) {
105
91
  if (!process.stdin.isTTY) return Promise.resolve(defaultValue);
106
92
  const rl = createInterface({ input: process.stdin, output: process.stdout });
107
- return new Promise((resolve15) => {
93
+ return new Promise((resolve17) => {
108
94
  const formatted = `${chalk2.cyan(query)} ${chalk2.gray(`(default: ${defaultValue})`)}
109
95
  > `;
110
96
  rl.question(formatted, (answer) => {
111
97
  rl.close();
112
- resolve15(answer.trim() || defaultValue);
98
+ resolve17(answer.trim() || defaultValue);
113
99
  });
114
100
  });
115
101
  }
@@ -119,8 +105,7 @@ function detectExistingTools(root) {
119
105
  if (existsSync2(join2(root, "CLAUDE.md"))) tools.push("claude-code");
120
106
  if (existsSync2(join2(root, ".windsurfrules"))) tools.push("windsurf");
121
107
  if (existsSync2(join2(root, "AGENTS.md"))) tools.push("opencode");
122
- if (existsSync2(join2(root, ".github", "copilot-instructions.md")))
123
- tools.push("vscode");
108
+ if (existsSync2(join2(root, ".github", "copilot-instructions.md"))) tools.push("vscode");
124
109
  return tools;
125
110
  }
126
111
  function detectProjectName(root) {
@@ -163,13 +148,23 @@ function loadWorkflow(root) {
163
148
  function saveWorkflow(root, workflow) {
164
149
  const dir = join2(root, ".letra");
165
150
  if (!existsSync2(dir)) mkdirSync2(dir, { recursive: true });
166
- writeFileSync2(workflowFilePath(root), JSON.stringify(workflow, null, 2));
151
+ const filePath = workflowFilePath(root);
152
+ if (existsSync2(filePath)) {
153
+ const backupDir = join2(root, ".letra", "backups");
154
+ if (!existsSync2(backupDir)) mkdirSync2(backupDir, { recursive: true });
155
+ const ts = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
156
+ const backupPath = join2(backupDir, `workflow-${ts}.json`);
157
+ try {
158
+ const existing = readFileSync2(filePath, "utf-8");
159
+ writeFileSync2(backupPath, existing, "utf-8");
160
+ } catch {
161
+ }
162
+ }
163
+ writeFileSync2(filePath, JSON.stringify(workflow, null, 2));
167
164
  }
168
165
  async function flowInit(root, options) {
169
166
  if (!process.stdin.isTTY && !options?.quick) {
170
- console.log(
171
- chalk2.yellow("Non-TTY: usando defaults. Passe --quick para confirmar.")
172
- );
167
+ console.log(chalk2.yellow("Non-TTY: usando defaults. Passe --quick para confirmar."));
173
168
  return flowInitQuick(root);
174
169
  }
175
170
  if (options?.quick) {
@@ -202,10 +197,7 @@ async function flowInitQuick(root) {
202
197
  const detected = detectExistingTools(root);
203
198
  const defaultTools = detected.length > 0 ? detected.join(", ") : "cursor, opencode";
204
199
  const name = await askText("Workflow name?", defaultName);
205
- const stagesInput = await askText(
206
- "Stages (comma-separated)?",
207
- defaultStagesList
208
- );
200
+ const stagesInput = await askText("Stages (comma-separated)?", defaultStagesList);
209
201
  const stages = stagesFromInput(stagesInput);
210
202
  const toolsInput = await askText("Tools (comma-separated)?", defaultTools);
211
203
  const tools = toolsInput.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
@@ -224,9 +216,7 @@ async function flowInitAction(targetPath, options) {
224
216
  const root = resolve2(process.cwd(), targetPath || ".");
225
217
  const filePath = workflowFilePath(root);
226
218
  if (existsSync2(filePath)) {
227
- console.log(
228
- chalk2.yellow("Workflow already exists at .letra/workflow.json")
229
- );
219
+ console.log(chalk2.yellow("Workflow already exists at .letra/workflow.json"));
230
220
  return;
231
221
  }
232
222
  const spinner = ora("Setting up workflow...").start();
@@ -238,18 +228,14 @@ async function flowInitAction(targetPath, options) {
238
228
  spinner.succeed(chalk2.green("Workflow created at .letra/workflow.json"));
239
229
  console.log("");
240
230
  console.log(` Name: ${chalk2.cyan(workflow.name)}`);
241
- console.log(
242
- ` Stages: ${chalk2.cyan(workflow.stages.map((s) => s.name).join(" \u2192 "))}`
243
- );
231
+ console.log(` Stages: ${chalk2.cyan(workflow.stages.map((s) => s.name).join(" \u2192 "))}`);
244
232
  console.log(` Tools: ${chalk2.cyan(workflow.tools.join(", "))}`);
245
233
  console.log("");
246
234
  console.log(" Next steps:");
247
235
  console.log(
248
236
  ` ${chalk2.cyan("letra flow backlog add <desc>")} Add items to your backlog`
249
237
  );
250
- console.log(
251
- ` ${chalk2.cyan("letra flow board")} View your board`
252
- );
238
+ console.log(` ${chalk2.cyan("letra flow board")} View your board`);
253
239
  } catch (error) {
254
240
  spinner.fail(chalk2.red("Failed to create workflow"));
255
241
  process.exit(1);
@@ -281,9 +267,7 @@ function backlogAdd(root, description) {
281
267
  }
282
268
  const workflow = workflowExists(root);
283
269
  if (!workflow) {
284
- console.log(
285
- chalk3.red("No workflow found. Run 'letra flow init --quick' first")
286
- );
270
+ console.log(chalk3.red("No workflow found. Run 'letra flow init --quick' first"));
287
271
  process.exit(1);
288
272
  }
289
273
  if (workflow.stages.length === 0) {
@@ -307,9 +291,7 @@ function backlogAdd(root, description) {
307
291
  function backlogList(root) {
308
292
  const workflow = workflowExists(root);
309
293
  if (!workflow) {
310
- console.log(
311
- chalk3.yellow("No workflow found. Run 'letra flow init --quick' first")
312
- );
294
+ console.log(chalk3.yellow("No workflow found. Run 'letra flow init --quick' first"));
313
295
  return;
314
296
  }
315
297
  if (workflow.items.length === 0) {
@@ -325,9 +307,7 @@ function backlogList(root) {
325
307
  for (const item of workflow.items) {
326
308
  const stageName2 = stageNames.get(item.stage) || item.stage;
327
309
  const created = new Date(item.createdAt);
328
- const age = Math.floor(
329
- (Date.now() - created.getTime()) / (1e3 * 60 * 60 * 24)
330
- );
310
+ const age = Math.floor((Date.now() - created.getTime()) / (1e3 * 60 * 60 * 24));
331
311
  const ageStr = age === 0 ? "today" : `${age}d`;
332
312
  const desc = item.description.length > 28 ? `${item.description.slice(0, 27)}\u2026` : item.description.padEnd(30);
333
313
  console.log(
@@ -350,17 +330,13 @@ import { resolve as resolve4 } from "path";
350
330
  import chalk4 from "chalk";
351
331
  function ageLabel(createdAt) {
352
332
  const created = new Date(createdAt);
353
- const age = Math.floor(
354
- (Date.now() - created.getTime()) / (1e3 * 60 * 60 * 24)
355
- );
333
+ const age = Math.floor((Date.now() - created.getTime()) / (1e3 * 60 * 60 * 24));
356
334
  return age === 0 ? "today" : `${age}d`;
357
335
  }
358
336
  function flowBoard(root) {
359
337
  const workflow = loadWorkflow(root);
360
338
  if (!workflow) {
361
- console.log(
362
- chalk4.yellow("No workflow found. Run 'letra flow init --quick' first")
363
- );
339
+ console.log(chalk4.yellow("No workflow found. Run 'letra flow init --quick' first"));
364
340
  return;
365
341
  }
366
342
  console.log(`
@@ -431,13 +407,9 @@ function loadVersion(root, version) {
431
407
  function getLatestBackupVersion(root) {
432
408
  const dir = join3(root, ".letra");
433
409
  if (!existsSync3(dir)) return null;
434
- const files = readdirSync2(dir).filter(
435
- (f) => f.startsWith("workflow.v") && f.endsWith(".json")
436
- );
410
+ const files = readdirSync2(dir).filter((f) => f.startsWith("workflow.v") && f.endsWith(".json"));
437
411
  if (files.length === 0) return null;
438
- const versions = files.map(
439
- (f) => f.replace("workflow.v", "").replace(".json", "")
440
- );
412
+ const versions = files.map((f) => f.replace("workflow.v", "").replace(".json", ""));
441
413
  versions.sort((a, b) => {
442
414
  const pa = a.split(".").map(Number);
443
415
  const pb = b.split(".").map(Number);
@@ -454,9 +426,7 @@ function backupFilePath(root, version) {
454
426
  function flowEdit(root, options) {
455
427
  const workflow = loadWorkflow(root);
456
428
  if (!workflow) {
457
- console.log(
458
- chalk5.yellow("No workflow found. Run 'letra flow init --quick' first")
459
- );
429
+ console.log(chalk5.yellow("No workflow found. Run 'letra flow init --quick' first"));
460
430
  return;
461
431
  }
462
432
  const currentVersion = normalizeVersion(workflow.version);
@@ -563,9 +533,7 @@ function flowDiff(root, v1, v2) {
563
533
  const wf1 = loadVersion(root, stripVPrefix(v1));
564
534
  const wf2 = loadVersion(root, stripVPrefix(v2));
565
535
  if (!wf1 && !wf2) {
566
- console.log(
567
- chalk5.yellow(`No backups found for versions ${v1} and ${v2}`)
568
- );
536
+ console.log(chalk5.yellow(`No backups found for versions ${v1} and ${v2}`));
569
537
  return;
570
538
  }
571
539
  if (!wf1) {
@@ -587,9 +555,7 @@ function flowDiff(root, v1, v2) {
587
555
  }
588
556
  const backup = loadBackup(root, latestVersion);
589
557
  if (!backup) {
590
- console.log(
591
- chalk5.yellow(`Failed to load backup version ${latestVersion}`)
592
- );
558
+ console.log(chalk5.yellow(`Failed to load backup version ${latestVersion}`));
593
559
  return;
594
560
  }
595
561
  const diff = computeDiff(backup, current);
@@ -651,39 +617,229 @@ function flowImport(root, filePath) {
651
617
  const imported = parsed;
652
618
  const existingWorkflow = loadWorkflow(root);
653
619
  if (existingWorkflow) {
654
- const backup = join4(
655
- root,
656
- ".letra",
657
- `workflow.v${existingWorkflow.version}.json`
658
- );
620
+ const backup = join4(root, ".letra", `workflow.v${existingWorkflow.version}.json`);
659
621
  if (!existsSync4(backup)) {
660
622
  writeFileSync4(backup, JSON.stringify(existingWorkflow, null, 2));
661
623
  console.log(
662
- chalk6.gray(
663
- `Backup saved: .letra/workflow.v${existingWorkflow.version}.json`
664
- )
624
+ chalk6.gray(`Backup saved: .letra/workflow.v${existingWorkflow.version}.json`)
665
625
  );
666
626
  }
667
627
  }
668
628
  imported.createdAt = now4();
669
629
  imported.updatedAt = now4();
670
630
  saveWorkflow(root, imported);
671
- console.log(
672
- chalk6.green(`Workflow imported: ${imported.name} (${imported.version})`)
673
- );
631
+ console.log(chalk6.green(`Workflow imported: ${imported.name} (${imported.version})`));
674
632
  }
675
633
  function flowImportAction(targetPath, filePath) {
676
634
  const root = resolve6(process.cwd(), targetPath || ".");
677
635
  flowImport(root, filePath);
678
636
  }
679
637
 
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";
638
+ // src/commands/flow-import-issues.ts
639
+ import { resolve as resolve7 } from "path";
683
640
  import chalk7 from "chalk";
684
641
  function now5() {
685
642
  return (/* @__PURE__ */ new Date()).toISOString();
686
643
  }
644
+ function nextItemId2(workflow) {
645
+ let max = 0;
646
+ for (const item of workflow.items) {
647
+ const match = item.id.match(/^ITEM-(\d+)$/);
648
+ if (match) {
649
+ const num = Number.parseInt(match[1], 10);
650
+ if (num > max) max = num;
651
+ }
652
+ }
653
+ return `ITEM-${max + 1}`;
654
+ }
655
+ function ensureWorkflow(root) {
656
+ const workflow = loadWorkflow(root);
657
+ if (!workflow) {
658
+ console.log(chalk7.red("No workflow found. Run 'letra flow init --quick' first"));
659
+ process.exit(1);
660
+ }
661
+ if (workflow.stages.length === 0) {
662
+ console.log(chalk7.red("Workflow has no stages defined"));
663
+ process.exit(1);
664
+ }
665
+ return workflow;
666
+ }
667
+ async function backlogImportGitHub(root, repo, options) {
668
+ const workflow = ensureWorkflow(root);
669
+ const limit = options?.limit ?? 50;
670
+ const token = process.env.GITHUB_TOKEN;
671
+ const url = new URL(`https://api.github.com/repos/${repo}/issues`);
672
+ url.searchParams.set("state", "open");
673
+ url.searchParams.set("per_page", String(limit));
674
+ if (options?.label) {
675
+ url.searchParams.set("labels", options.label);
676
+ }
677
+ const headers = {
678
+ Accept: "application/vnd.github.v3+json",
679
+ "User-Agent": "letra-cli"
680
+ };
681
+ if (token) {
682
+ headers.Authorization = `Bearer ${token}`;
683
+ }
684
+ let response;
685
+ try {
686
+ response = await fetch(url.toString(), { headers });
687
+ } catch (err) {
688
+ const msg = err instanceof Error ? err.message : String(err);
689
+ console.log(chalk7.red(`Failed to fetch issues: ${msg}`));
690
+ process.exit(1);
691
+ }
692
+ if (!response.ok) {
693
+ const text = await response.text().catch(() => "unknown error");
694
+ if (response.status === 404) {
695
+ console.log(chalk7.red(`Repository "${repo}" not found or is private`));
696
+ } else if (response.status === 401 || response.status === 403) {
697
+ console.log(chalk7.red(`GitHub API error (${response.status}). Check GITHUB_TOKEN`));
698
+ } else {
699
+ console.log(chalk7.red(`GitHub API error (${response.status}): ${text}`));
700
+ }
701
+ process.exit(1);
702
+ }
703
+ let issues;
704
+ try {
705
+ issues = await response.json();
706
+ } catch {
707
+ console.log(chalk7.red("Failed to parse GitHub response"));
708
+ process.exit(1);
709
+ }
710
+ issues = issues.filter((i) => !("pull_request" in i));
711
+ if (issues.length === 0) {
712
+ console.log(chalk7.yellow("No open issues found"));
713
+ return { imported: 0, total: 0 };
714
+ }
715
+ const firstStage = workflow.stages[0].id;
716
+ let imported = 0;
717
+ for (const issue of issues) {
718
+ const labels = issue.labels?.map((l) => l.name).join(", ") || "";
719
+ const description = labels ? `[${issue.number}] ${issue.title} (${labels})` : `[${issue.number}] ${issue.title}`;
720
+ const item = {
721
+ id: nextItemId2(workflow),
722
+ description,
723
+ stage: firstStage,
724
+ createdAt: now5(),
725
+ source: "github",
726
+ sourceUrl: issue.html_url
727
+ };
728
+ workflow.items.push(item);
729
+ imported++;
730
+ }
731
+ workflow.updatedAt = now5();
732
+ saveWorkflow(root, workflow);
733
+ console.log(
734
+ ` ${chalk7.green("\u2713")} Imported ${chalk7.cyan(String(imported))} issue${imported !== 1 ? "s" : ""} from ${chalk7.cyan(repo)}`
735
+ );
736
+ return { imported, total: issues.length };
737
+ }
738
+ async function backlogImportLinear(root, team, options) {
739
+ const apiKey = process.env.LINEAR_API_KEY;
740
+ if (!apiKey) {
741
+ console.log(chalk7.red("LINEAR_API_KEY environment variable is required for Linear import"));
742
+ process.exit(1);
743
+ }
744
+ const workflow = ensureWorkflow(root);
745
+ const limit = options?.limit ?? 50;
746
+ const query = `
747
+ query($team: String!, $limit: Int!) {
748
+ team(key: $team) {
749
+ issues(first: $limit, filter: { state: { type: { in: [todo, inProgress] } } }) {
750
+ nodes {
751
+ id
752
+ title
753
+ url
754
+ identifier
755
+ }
756
+ }
757
+ }
758
+ }`;
759
+ let response;
760
+ try {
761
+ response = await fetch("https://api.linear.app/graphql", {
762
+ method: "POST",
763
+ headers: {
764
+ "Content-Type": "application/json",
765
+ Authorization: apiKey
766
+ },
767
+ body: JSON.stringify({ query, variables: { team, limit } })
768
+ });
769
+ } catch (err) {
770
+ const msg = err instanceof Error ? err.message : String(err);
771
+ console.log(chalk7.red(`Failed to fetch Linear issues: ${msg}`));
772
+ process.exit(1);
773
+ }
774
+ if (!response.ok) {
775
+ const text = await response.text().catch(() => "unknown error");
776
+ if (response.status === 401) {
777
+ console.log(chalk7.red("Invalid Linear API key. Check LINEAR_API_KEY"));
778
+ } else {
779
+ console.log(chalk7.red(`Linear API error (${response.status}): ${text}`));
780
+ }
781
+ process.exit(1);
782
+ }
783
+ let data;
784
+ try {
785
+ data = await response.json();
786
+ } catch {
787
+ console.log(chalk7.red("Failed to parse Linear response"));
788
+ process.exit(1);
789
+ }
790
+ if (data.data?.team?.issues?.nodes == null) {
791
+ const errMsg = data?.data?.team == null ? `Team "${team}" not found` : "Failed to fetch Linear issues";
792
+ console.log(chalk7.red(errMsg));
793
+ process.exit(1);
794
+ }
795
+ const issues = data.data.team.issues.nodes;
796
+ if (issues.length === 0) {
797
+ console.log(chalk7.yellow(`No open issues found for team "${team}"`));
798
+ return { imported: 0, total: 0 };
799
+ }
800
+ const firstStage = workflow.stages[0].id;
801
+ let imported = 0;
802
+ for (const issue of issues) {
803
+ const description = `${issue.identifier} ${issue.title}`;
804
+ const item = {
805
+ id: nextItemId2(workflow),
806
+ description,
807
+ stage: firstStage,
808
+ createdAt: now5(),
809
+ source: "linear",
810
+ sourceUrl: issue.url
811
+ };
812
+ workflow.items.push(item);
813
+ imported++;
814
+ }
815
+ workflow.updatedAt = now5();
816
+ saveWorkflow(root, workflow);
817
+ console.log(
818
+ ` ${chalk7.green("\u2713")} Imported ${chalk7.cyan(String(imported))} issue${imported !== 1 ? "s" : ""} from Linear team ${chalk7.cyan(team)}`
819
+ );
820
+ return { imported, total: issues.length };
821
+ }
822
+ async function backlogImportGitHubAction(targetPath, repo, options) {
823
+ const root = resolve7(process.cwd(), targetPath || ".");
824
+ await backlogImportGitHub(root, repo, {
825
+ label: options.label,
826
+ limit: options.limit ? Number(options.limit) : void 0
827
+ });
828
+ }
829
+ async function backlogImportLinearAction(targetPath, team, options) {
830
+ const root = resolve7(process.cwd(), targetPath || ".");
831
+ await backlogImportLinear(root, team, {
832
+ limit: options.limit ? Number(options.limit) : void 0
833
+ });
834
+ }
835
+
836
+ // src/commands/flow-move.ts
837
+ import { existsSync as existsSync5, mkdirSync as mkdirSync3, writeFileSync as writeFileSync5 } from "fs";
838
+ import { join as join5, resolve as resolve8 } from "path";
839
+ import chalk8 from "chalk";
840
+ function now6() {
841
+ return (/* @__PURE__ */ new Date()).toISOString();
842
+ }
687
843
  function resolveStage(workflow, input) {
688
844
  const lower = input.toLowerCase();
689
845
  for (const stage of workflow.stages) {
@@ -760,68 +916,738 @@ function generateAdapters(root, tools, content) {
760
916
  const dir = join5(path, "..");
761
917
  if (!existsSync5(dir)) mkdirSync3(dir, { recursive: true });
762
918
  writeFileSync5(path, fileContent);
763
- console.log(` ${chalk7.gray("Updated")} ${path.replace(`${root}/`, "")}`);
919
+ console.log(` ${chalk8.gray("Updated")} ${path.replace(`${root}/`, "")}`);
764
920
  }
765
921
  }
766
922
  function flowMove(root, itemId, targetStageInput) {
767
923
  const workflow = loadWorkflow(root);
768
924
  if (!workflow) {
769
- console.log(
770
- chalk7.red("No workflow found. Run 'letra flow init --quick' first")
771
- );
925
+ console.log(chalk8.red("No workflow found. Run 'letra flow init --quick' first"));
772
926
  process.exit(1);
773
927
  }
774
928
  const item = workflow.items.find((i) => i.id === itemId) || workflow.items.find((i) => i.description === itemId);
775
929
  if (!item) {
776
- console.log(chalk7.red(`Item "${itemId}" not found`));
930
+ console.log(chalk8.red(`Item "${itemId}" not found`));
777
931
  process.exit(1);
778
932
  }
779
933
  const targetStageId = resolveStage(workflow, targetStageInput);
780
934
  if (!targetStageId) {
781
935
  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
- );
936
+ console.log(chalk8.red(`Stage "${targetStageInput}" not found. Valid stages: ${valid}`));
787
937
  process.exit(1);
788
938
  }
789
939
  if (item.stage === targetStageId) {
790
- console.log(
791
- chalk7.yellow(`Item ${itemId} is already in stage "${targetStageId}"`)
792
- );
940
+ console.log(chalk8.yellow(`Item ${itemId} is already in stage "${targetStageId}"`));
793
941
  return;
794
942
  }
795
943
  const fromStage = workflow.stages.find((s) => s.id === item.stage)?.name || item.stage;
796
944
  const toStage = workflow.stages.find((s) => s.id === targetStageId)?.name || targetStageId;
797
945
  item.stage = targetStageId;
798
- workflow.updatedAt = now5();
946
+ workflow.updatedAt = now6();
799
947
  saveWorkflow(root, workflow);
800
948
  const stageNames = new Map(workflow.stages.map((s) => [s.id, s.name]));
801
949
  const currentStageName = stageNames.get(targetStageId) || targetStageId;
802
- const content = adapterContent(
803
- workflow.name,
804
- currentStageName,
805
- workflow.items,
806
- stageNames
807
- );
950
+ const content = adapterContent(workflow.name, currentStageName, workflow.items, stageNames);
808
951
  generateAdapters(root, workflow.tools, content);
809
952
  console.log(
810
- ` ${chalk7.green("\u2713")} Item ${chalk7.cyan(itemId)} moved: ${chalk7.yellow(fromStage)} \u2192 ${chalk7.green(toStage)}`
811
- );
812
- console.log(
813
- ` ${chalk7.gray("Adapters regenerated for:")} ${workflow.tools.join(", ")}`
953
+ ` ${chalk8.green("\u2713")} Item ${chalk8.cyan(itemId)} moved: ${chalk8.yellow(fromStage)} \u2192 ${chalk8.green(toStage)}`
814
954
  );
955
+ console.log(` ${chalk8.gray("Adapters regenerated for:")} ${workflow.tools.join(", ")}`);
815
956
  }
816
957
  function flowMoveAction(targetPath, itemId, options) {
817
- const root = resolve7(process.cwd(), targetPath || ".");
958
+ const root = resolve8(process.cwd(), targetPath || ".");
818
959
  flowMove(root, itemId, options.to);
819
960
  }
820
961
 
962
+ // src/commands/flow-serve.ts
963
+ import { existsSync as existsSync6, mkdirSync as mkdirSync4, readFileSync as readFileSync5, readdirSync as readdirSync3, watch, writeFileSync as writeFileSync6 } from "fs";
964
+ import { createServer } from "http";
965
+ import { dirname, extname, join as join6, resolve as resolve9 } from "path";
966
+ import { fileURLToPath } from "url";
967
+ var DEFAULT_PORT = 3e3;
968
+ function loadSpecs(root, workflow) {
969
+ const result = [];
970
+ if (workflow?.specLinks) {
971
+ for (const [id, link] of Object.entries(workflow.specLinks)) {
972
+ const filePath = join6(root, link.path);
973
+ if (existsSync6(filePath)) {
974
+ result.push({ id, content: readFileSync5(filePath, "utf-8") });
975
+ }
976
+ }
977
+ }
978
+ const specsDir = join6(root, ".letra", "specs");
979
+ const registered = new Set(result.map((s) => s.id));
980
+ if (existsSync6(specsDir)) {
981
+ for (const entry of readdirSync3(specsDir, { withFileTypes: true })) {
982
+ if (entry.isDirectory() && !registered.has(entry.name)) {
983
+ const specPath = join6(specsDir, entry.name, "spec.md");
984
+ if (existsSync6(specPath)) {
985
+ result.push({ id: entry.name, content: readFileSync5(specPath, "utf-8") });
986
+ }
987
+ }
988
+ }
989
+ }
990
+ return result;
991
+ }
992
+ var TEMPLATES = {
993
+ padrao: {
994
+ name: "Padr\xE3o",
995
+ stages: [
996
+ { id: "backlog", name: "Backlog", zone: "todo" },
997
+ { id: "design", name: "Design", zone: "doing" },
998
+ { id: "code", name: "Code", zone: "doing" },
999
+ { id: "review", name: "Review", zone: "doing" },
1000
+ { id: "done", name: "Done", zone: "done" }
1001
+ ]
1002
+ },
1003
+ kanban: {
1004
+ name: "Kanban",
1005
+ stages: [
1006
+ { id: "todo", name: "A Fazer", zone: "todo" },
1007
+ { id: "doing", name: "Fazendo", zone: "doing" },
1008
+ { id: "done", name: "Feito", zone: "done" }
1009
+ ]
1010
+ },
1011
+ agil: {
1012
+ name: "\xC1gil",
1013
+ stages: [
1014
+ { id: "product-backlog", name: "Product Backlog", zone: "todo" },
1015
+ { id: "sprint-backlog", name: "Sprint Backlog", zone: "todo" },
1016
+ { id: "in-progress", name: "In Progress", zone: "doing" },
1017
+ { id: "review", name: "Review", zone: "doing" },
1018
+ { id: "done", name: "Done", zone: "done" }
1019
+ ]
1020
+ }
1021
+ };
1022
+ function createWorkflowFromTemplate(root, templateId, options) {
1023
+ const t = TEMPLATES[templateId];
1024
+ if (!t) {
1025
+ throw new Error(
1026
+ `Template "${templateId}" not found. Available: ${Object.keys(TEMPLATES).join(", ")}`
1027
+ );
1028
+ }
1029
+ const stages = t.stages.map((s, i) => ({
1030
+ id: s.id,
1031
+ name: s.name,
1032
+ order: i,
1033
+ zone: s.zone
1034
+ }));
1035
+ const existing = loadWorkflow(root);
1036
+ return {
1037
+ version: "1.0",
1038
+ name: options?.name ?? detectProjectName(root) ?? t.name,
1039
+ createdAt: existing?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
1040
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1041
+ stages,
1042
+ items: existing?.items ?? [],
1043
+ specLinks: existing?.specLinks ?? void 0,
1044
+ tools: options?.tools ?? existing?.tools ?? []
1045
+ };
1046
+ }
1047
+ var FlowServer = class {
1048
+ server;
1049
+ watcher;
1050
+ clients = /* @__PURE__ */ new Set();
1051
+ root;
1052
+ port;
1053
+ loadWorkflow;
1054
+ constructor(root, port = DEFAULT_PORT) {
1055
+ this.root = root;
1056
+ this.port = port;
1057
+ this.loadWorkflow = () => loadWorkflow(root);
1058
+ }
1059
+ handleRequest = (req, res) => {
1060
+ const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
1061
+ const path = url.pathname;
1062
+ if (path === "/events") {
1063
+ res.writeHead(200, {
1064
+ "Content-Type": "text/event-stream",
1065
+ "Cache-Control": "no-cache",
1066
+ Connection: "keep-alive"
1067
+ });
1068
+ res.write("event: connected\ndata: {}\n\n");
1069
+ this.clients.add(res);
1070
+ req.on("close", () => this.clients.delete(res));
1071
+ return;
1072
+ }
1073
+ if (path === "/api/workflow") {
1074
+ const wf = this.loadWorkflow();
1075
+ res.writeHead(200, { "Content-Type": "application/json" });
1076
+ res.end(JSON.stringify(wf ?? { error: "No workflow found" }));
1077
+ return;
1078
+ }
1079
+ if (path === "/api/workflow/template" && req.method === "POST") {
1080
+ let body = "";
1081
+ req.on("data", (chunk) => {
1082
+ body += chunk;
1083
+ });
1084
+ req.on("end", () => {
1085
+ try {
1086
+ const data = JSON.parse(body);
1087
+ let wf;
1088
+ if (data.stages) {
1089
+ const stages = data.stages.map(
1090
+ (s, i) => ({
1091
+ id: s.id,
1092
+ name: s.name,
1093
+ order: i,
1094
+ zone: s.zone
1095
+ })
1096
+ );
1097
+ const existing = loadWorkflow(this.root);
1098
+ wf = {
1099
+ version: "1.0",
1100
+ name: data.name ?? detectProjectName(this.root) ?? "Personalizado",
1101
+ createdAt: existing?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
1102
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1103
+ stages,
1104
+ items: existing?.items ?? [],
1105
+ specLinks: existing?.specLinks ?? void 0,
1106
+ tools: data.tools ?? existing?.tools ?? []
1107
+ };
1108
+ } else {
1109
+ wf = createWorkflowFromTemplate(this.root, data.template, {
1110
+ name: data.name,
1111
+ tools: data.tools
1112
+ });
1113
+ }
1114
+ saveWorkflow(this.root, wf);
1115
+ res.writeHead(200, { "Content-Type": "application/json" });
1116
+ res.end(JSON.stringify(wf));
1117
+ } catch (e) {
1118
+ res.writeHead(400, { "Content-Type": "application/json" });
1119
+ res.end(JSON.stringify({ error: e.message }));
1120
+ }
1121
+ });
1122
+ return;
1123
+ }
1124
+ if (path === "/api/specs" && req.method === "GET") {
1125
+ try {
1126
+ const wf = this.loadWorkflow();
1127
+ const specs = loadSpecs(this.root, wf);
1128
+ res.writeHead(200, { "Content-Type": "application/json" });
1129
+ res.end(JSON.stringify(specs));
1130
+ } catch {
1131
+ res.writeHead(200, { "Content-Type": "application/json" });
1132
+ res.end(JSON.stringify([]));
1133
+ }
1134
+ return;
1135
+ }
1136
+ if (path === "/api/specs" && req.method === "POST") {
1137
+ let body = "";
1138
+ req.on("data", (chunk) => {
1139
+ body += chunk;
1140
+ });
1141
+ req.on("end", () => {
1142
+ try {
1143
+ const { id, content } = JSON.parse(body);
1144
+ if (!id || !content) {
1145
+ res.writeHead(400, { "Content-Type": "application/json" });
1146
+ res.end(JSON.stringify({ error: "id and content required" }));
1147
+ return;
1148
+ }
1149
+ const specDir = join6(this.root, ".letra", "specs", id);
1150
+ if (!existsSync6(specDir)) mkdirSync4(specDir, { recursive: true });
1151
+ writeFileSync6(join6(specDir, "spec.md"), content, "utf-8");
1152
+ const wf = this.loadWorkflow();
1153
+ if (wf) {
1154
+ if (!wf.specLinks) wf.specLinks = {};
1155
+ wf.specLinks[id] = { path: `.letra/specs/${id}/spec.md` };
1156
+ wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1157
+ saveWorkflow(this.root, wf);
1158
+ this.broadcast();
1159
+ }
1160
+ res.writeHead(200, { "Content-Type": "application/json" });
1161
+ res.end(JSON.stringify({ id, content }));
1162
+ } catch (e) {
1163
+ res.writeHead(400, { "Content-Type": "application/json" });
1164
+ res.end(JSON.stringify({ error: e.message }));
1165
+ }
1166
+ });
1167
+ return;
1168
+ }
1169
+ if (path.startsWith("/api/specs/") && req.method === "DELETE") {
1170
+ const specId = path.replace("/api/specs/", "").split("/")[0];
1171
+ if (!specId) {
1172
+ res.writeHead(400);
1173
+ res.end(JSON.stringify({ error: "spec id required" }));
1174
+ return;
1175
+ }
1176
+ const specDir = join6(this.root, ".letra", "specs", specId);
1177
+ if (existsSync6(specDir)) {
1178
+ writeFileSync6(join6(specDir, "spec.md"), "", "utf-8");
1179
+ }
1180
+ const wf = this.loadWorkflow();
1181
+ if (wf?.specLinks) {
1182
+ delete wf.specLinks[specId];
1183
+ wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1184
+ saveWorkflow(this.root, wf);
1185
+ this.broadcast();
1186
+ }
1187
+ res.writeHead(200, { "Content-Type": "application/json" });
1188
+ res.end(JSON.stringify({ deleted: specId }));
1189
+ return;
1190
+ }
1191
+ if (path.startsWith("/api/specs/") && req.method === "PUT") {
1192
+ const specId = path.replace("/api/specs/", "").split("/")[0];
1193
+ if (!specId) {
1194
+ res.writeHead(400);
1195
+ res.end(JSON.stringify({ error: "spec id required" }));
1196
+ return;
1197
+ }
1198
+ let body = "";
1199
+ req.on("data", (chunk) => {
1200
+ body += chunk;
1201
+ });
1202
+ req.on("end", () => {
1203
+ try {
1204
+ const { content } = JSON.parse(body);
1205
+ if (content === void 0) {
1206
+ res.writeHead(400);
1207
+ res.end(JSON.stringify({ error: "content required" }));
1208
+ return;
1209
+ }
1210
+ const specDir = join6(this.root, ".letra", "specs", specId);
1211
+ if (!existsSync6(specDir)) mkdirSync4(specDir, { recursive: true });
1212
+ writeFileSync6(join6(specDir, "spec.md"), content, "utf-8");
1213
+ const wf = this.loadWorkflow();
1214
+ if (wf) {
1215
+ wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1216
+ saveWorkflow(this.root, wf);
1217
+ this.broadcast();
1218
+ }
1219
+ res.writeHead(200, { "Content-Type": "application/json" });
1220
+ res.end(JSON.stringify({ id: specId, content }));
1221
+ } catch (e) {
1222
+ res.writeHead(400);
1223
+ res.end(JSON.stringify({ error: e.message }));
1224
+ }
1225
+ });
1226
+ return;
1227
+ }
1228
+ if (path.match(/^\/api\/specs\/[^/]+\/validate$/) && req.method === "POST") {
1229
+ const specId = path.replace("/api/specs/", "").split("/")[0];
1230
+ const specDir = join6(this.root, ".letra", "specs", specId);
1231
+ const specFile = join6(specDir, "spec.md");
1232
+ const issues = [];
1233
+ if (!existsSync6(specFile)) {
1234
+ res.writeHead(200, { "Content-Type": "application/json" });
1235
+ res.end(
1236
+ JSON.stringify({
1237
+ id: specId,
1238
+ issues: [{ type: "error", msg: "spec.md not found" }],
1239
+ valid: false
1240
+ })
1241
+ );
1242
+ return;
1243
+ }
1244
+ const content = readFileSync5(specFile, "utf-8");
1245
+ const requiredSections = [
1246
+ "Outcome",
1247
+ "Constraints",
1248
+ "Exclusions",
1249
+ "Acceptance Criteria",
1250
+ "Context"
1251
+ ];
1252
+ for (const section of requiredSections) {
1253
+ const re = new RegExp(`## ${section}`);
1254
+ if (!re.test(content)) {
1255
+ issues.push({ type: "error", msg: `Missing section: ## ${section}` });
1256
+ }
1257
+ }
1258
+ const acMatch = content.match(/## Acceptance Criteria\s+([\s\S]*?)(?=\n## |$)/);
1259
+ if (acMatch) {
1260
+ const acSection = acMatch[1];
1261
+ const items = [...acSection.matchAll(/-\s+\[(\s|x)\]\s+/g)];
1262
+ if (items.length === 0) {
1263
+ issues.push({
1264
+ type: "warning",
1265
+ msg: "Acceptance Criteria section has no checklist items"
1266
+ });
1267
+ }
1268
+ }
1269
+ if (content.length > 3e3) {
1270
+ issues.push({ type: "warning", msg: "Spec exceeds 3000 chars (should be thin)" });
1271
+ }
1272
+ res.writeHead(200, { "Content-Type": "application/json" });
1273
+ res.end(
1274
+ JSON.stringify({
1275
+ id: specId,
1276
+ issues,
1277
+ valid: issues.filter((i) => i.type === "error").length === 0
1278
+ })
1279
+ );
1280
+ return;
1281
+ }
1282
+ if (path === "/api/items" && req.method === "POST") {
1283
+ let body = "";
1284
+ req.on("data", (chunk) => {
1285
+ body += chunk;
1286
+ });
1287
+ req.on("end", () => {
1288
+ try {
1289
+ const { id, description, stage } = JSON.parse(body);
1290
+ if (!id || !description || !stage) {
1291
+ res.writeHead(400, { "Content-Type": "application/json" });
1292
+ res.end(JSON.stringify({ error: "id, description, and stage required" }));
1293
+ return;
1294
+ }
1295
+ const wf = this.loadWorkflow();
1296
+ if (!wf) {
1297
+ res.writeHead(404, { "Content-Type": "application/json" });
1298
+ res.end(JSON.stringify({ error: "No workflow" }));
1299
+ return;
1300
+ }
1301
+ const item = {
1302
+ id,
1303
+ description,
1304
+ stage,
1305
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1306
+ tasks: []
1307
+ };
1308
+ wf.items.push(item);
1309
+ wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1310
+ saveWorkflow(this.root, wf);
1311
+ this.broadcast();
1312
+ res.writeHead(200, { "Content-Type": "application/json" });
1313
+ res.end(JSON.stringify(item));
1314
+ } catch (e) {
1315
+ res.writeHead(400, { "Content-Type": "application/json" });
1316
+ res.end(JSON.stringify({ error: e.message }));
1317
+ }
1318
+ });
1319
+ return;
1320
+ }
1321
+ if (path.match(/^\/api\/items\/[^/]+$/) && req.method === "PATCH") {
1322
+ const itemId = path.replace("/api/items/", "");
1323
+ let body = "";
1324
+ req.on("data", (chunk) => {
1325
+ body += chunk;
1326
+ });
1327
+ req.on("end", () => {
1328
+ try {
1329
+ const data = JSON.parse(body);
1330
+ const wf = this.loadWorkflow();
1331
+ if (!wf) {
1332
+ res.writeHead(404, { "Content-Type": "application/json" });
1333
+ res.end(JSON.stringify({ error: "No workflow" }));
1334
+ return;
1335
+ }
1336
+ const item = wf.items.find((i) => i.id === itemId);
1337
+ if (!item) {
1338
+ res.writeHead(404, { "Content-Type": "application/json" });
1339
+ res.end(JSON.stringify({ error: "Item not found" }));
1340
+ return;
1341
+ }
1342
+ const oldStage = item.stage;
1343
+ if (data.stage !== void 0) item.stage = data.stage;
1344
+ if (data.description !== void 0) item.description = data.description;
1345
+ if (data.tasks !== void 0) item.tasks = data.tasks;
1346
+ wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1347
+ saveWorkflow(this.root, wf);
1348
+ this.broadcast();
1349
+ if (data.stage !== void 0 && data.stage !== oldStage) {
1350
+ this.fireWebhooks("item.moved", {
1351
+ itemId: item.id,
1352
+ itemDescription: item.description,
1353
+ sourceStage: oldStage,
1354
+ targetStage: data.stage
1355
+ });
1356
+ }
1357
+ res.writeHead(200, { "Content-Type": "application/json" });
1358
+ res.end(JSON.stringify(item));
1359
+ } catch (e) {
1360
+ res.writeHead(400, { "Content-Type": "application/json" });
1361
+ res.end(JSON.stringify({ error: e.message }));
1362
+ }
1363
+ });
1364
+ return;
1365
+ }
1366
+ if (path.match(/^\/api\/items\/[^/]+$/) && req.method === "DELETE") {
1367
+ const itemId = path.replace("/api/items/", "");
1368
+ const wf = this.loadWorkflow();
1369
+ if (!wf) {
1370
+ res.writeHead(404, { "Content-Type": "application/json" });
1371
+ res.end(JSON.stringify({ error: "No workflow" }));
1372
+ return;
1373
+ }
1374
+ const idx = wf.items.findIndex((i) => i.id === itemId);
1375
+ if (idx === -1) {
1376
+ res.writeHead(404, { "Content-Type": "application/json" });
1377
+ res.end(JSON.stringify({ error: "Item not found" }));
1378
+ return;
1379
+ }
1380
+ wf.items.splice(idx, 1);
1381
+ wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1382
+ saveWorkflow(this.root, wf);
1383
+ this.broadcast();
1384
+ res.writeHead(200, { "Content-Type": "application/json" });
1385
+ res.end(JSON.stringify({ deleted: itemId }));
1386
+ return;
1387
+ }
1388
+ if (path === "/api/workflow" && req.method === "PATCH") {
1389
+ let body = "";
1390
+ req.on("data", (chunk) => {
1391
+ body += chunk;
1392
+ });
1393
+ req.on("end", () => {
1394
+ try {
1395
+ const data = JSON.parse(body);
1396
+ const wf = this.loadWorkflow();
1397
+ if (!wf) {
1398
+ res.writeHead(404, { "Content-Type": "application/json" });
1399
+ res.end(JSON.stringify({ error: "No workflow" }));
1400
+ return;
1401
+ }
1402
+ if (data.stages !== void 0) wf.stages = data.stages;
1403
+ if (data.name !== void 0) wf.name = data.name;
1404
+ if (data.description !== void 0) wf.description = data.description;
1405
+ wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1406
+ saveWorkflow(this.root, wf);
1407
+ this.broadcast();
1408
+ res.writeHead(200, { "Content-Type": "application/json" });
1409
+ res.end(JSON.stringify(wf));
1410
+ } catch (e) {
1411
+ res.writeHead(400, { "Content-Type": "application/json" });
1412
+ res.end(JSON.stringify({ error: e.message }));
1413
+ }
1414
+ });
1415
+ return;
1416
+ }
1417
+ if (path === "/api/move") {
1418
+ const itemId = url.searchParams.get("item");
1419
+ const stage = url.searchParams.get("stage");
1420
+ if (itemId && stage) {
1421
+ const wf = this.loadWorkflow();
1422
+ if (wf) {
1423
+ const item = wf.items.find((i) => i.id === itemId);
1424
+ if (item) {
1425
+ item.stage = stage;
1426
+ wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1427
+ saveWorkflow(this.root, wf);
1428
+ this.broadcast();
1429
+ }
1430
+ }
1431
+ }
1432
+ res.writeHead(302, { Location: "/" });
1433
+ res.end();
1434
+ return;
1435
+ }
1436
+ if (path === "/api/focus") {
1437
+ const focusFile = join6(this.root, ".letra", "focus.md");
1438
+ if (existsSync6(focusFile)) {
1439
+ const content = readFileSync5(focusFile, "utf-8");
1440
+ res.writeHead(200, { "Content-Type": "application/json" });
1441
+ const lines = content.split("\n").filter((l) => l.trim());
1442
+ res.end(
1443
+ JSON.stringify({
1444
+ active: true,
1445
+ spec: lines[0]?.replace(/^#\s*/, "") || "",
1446
+ content
1447
+ })
1448
+ );
1449
+ } else {
1450
+ res.writeHead(200, { "Content-Type": "application/json" });
1451
+ res.end(JSON.stringify({ active: false }));
1452
+ }
1453
+ return;
1454
+ }
1455
+ if (path === "/api/context") {
1456
+ const file = url.searchParams.get("file") || "context.md";
1457
+ const letraDir = join6(this.root, ".letra");
1458
+ const allowedFiles = ["context.md", "constitution.md", "glossary.md"];
1459
+ if (file === "decisions") {
1460
+ const decisionsDir = join6(letraDir, "decisions");
1461
+ const files = [];
1462
+ if (existsSync6(decisionsDir)) {
1463
+ const names = readdirSync3(decisionsDir).filter((f) => f.endsWith(".md"));
1464
+ for (const name of names.sort().reverse()) {
1465
+ const content2 = readFileSync5(join6(decisionsDir, name), "utf-8");
1466
+ files.push({ name, content: content2 });
1467
+ }
1468
+ }
1469
+ res.writeHead(200, { "Content-Type": "application/json" });
1470
+ res.end(JSON.stringify(files));
1471
+ return;
1472
+ }
1473
+ if (!allowedFiles.includes(file)) {
1474
+ res.writeHead(400, { "Content-Type": "application/json" });
1475
+ res.end(JSON.stringify({ error: `Invalid file: ${file}` }));
1476
+ return;
1477
+ }
1478
+ const filePath = join6(letraDir, file);
1479
+ if (!existsSync6(filePath)) {
1480
+ res.writeHead(404, { "Content-Type": "application/json" });
1481
+ res.end(JSON.stringify({ error: `File not found: ${file}` }));
1482
+ return;
1483
+ }
1484
+ const content = readFileSync5(filePath, "utf-8");
1485
+ res.writeHead(200, { "Content-Type": "text/plain" });
1486
+ res.end(content);
1487
+ return;
1488
+ }
1489
+ this.serveClient(path, req, res);
1490
+ };
1491
+ clientDir = null;
1492
+ serveClient(path, req, res) {
1493
+ if (!this.clientDir) {
1494
+ const cliDir = dirname(fileURLToPath(import.meta.url));
1495
+ const builtIn = join6(cliDir, "client");
1496
+ const monorepoDev = join6(this.root, "packages", "client", "dist");
1497
+ const candidates = [builtIn, monorepoDev];
1498
+ for (const dir of candidates) {
1499
+ const idx = join6(dir, "index.html");
1500
+ if (existsSync6(idx)) {
1501
+ this.clientDir = dir;
1502
+ break;
1503
+ }
1504
+ }
1505
+ }
1506
+ if (!this.clientDir) {
1507
+ this.proxyToVite(req, res);
1508
+ return;
1509
+ }
1510
+ let filePath = join6(this.clientDir, path === "/" ? "index.html" : path);
1511
+ if (!existsSync6(filePath)) {
1512
+ filePath = join6(this.clientDir, "index.html");
1513
+ }
1514
+ const ext = extname(filePath);
1515
+ const mime = {
1516
+ ".html": "text/html; charset=utf-8",
1517
+ ".js": "application/javascript; charset=utf-8",
1518
+ ".css": "text/css; charset=utf-8",
1519
+ ".svg": "image/svg+xml",
1520
+ ".png": "image/png",
1521
+ ".ico": "image/x-icon",
1522
+ ".json": "application/json"
1523
+ };
1524
+ const contentType = mime[ext] ?? "application/octet-stream";
1525
+ res.writeHead(200, { "Content-Type": contentType });
1526
+ res.end(readFileSync5(filePath));
1527
+ }
1528
+ proxyToVite(req, res) {
1529
+ const proxyUrl = `http://localhost:5173${req.url}`;
1530
+ fetch(proxyUrl).then((proxyRes) => {
1531
+ res.writeHead(proxyRes.status, Object.fromEntries(proxyRes.headers));
1532
+ proxyRes.body?.pipeTo(
1533
+ new WritableStream({
1534
+ write(chunk) {
1535
+ res.write(chunk);
1536
+ },
1537
+ close() {
1538
+ res.end();
1539
+ }
1540
+ })
1541
+ );
1542
+ }).catch(() => {
1543
+ res.writeHead(502, { "Content-Type": "text/plain" });
1544
+ res.end("Vite dev server not running on http://localhost:5173");
1545
+ });
1546
+ }
1547
+ broadcast() {
1548
+ if (this.clients.size === 0) return;
1549
+ const data = "event: workflow-updated\ndata: {}\n\n";
1550
+ for (const client of this.clients) {
1551
+ try {
1552
+ client.write(data);
1553
+ } catch {
1554
+ this.clients.delete(client);
1555
+ }
1556
+ }
1557
+ }
1558
+ async fireWebhooks(event, payload) {
1559
+ const wf = this.loadWorkflow();
1560
+ if (!wf?.webhooks || wf.webhooks.length === 0) return;
1561
+ const matching = wf.webhooks.filter((wh) => wh.events.includes(event));
1562
+ if (matching.length === 0) return;
1563
+ const body = JSON.stringify({
1564
+ event,
1565
+ workflow: wf.name,
1566
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1567
+ ...payload
1568
+ });
1569
+ for (const wh of matching) {
1570
+ try {
1571
+ const res = await fetch(wh.url, {
1572
+ method: "POST",
1573
+ headers: { "Content-Type": "application/json" },
1574
+ body
1575
+ });
1576
+ wh.lastStatus = res.ok ? "ok" : "error";
1577
+ } catch {
1578
+ wh.lastStatus = "error";
1579
+ }
1580
+ wh.lastSentAt = (/* @__PURE__ */ new Date()).toISOString();
1581
+ }
1582
+ saveWorkflow(this.root, wf);
1583
+ }
1584
+ start() {
1585
+ return new Promise((resolve17, reject) => {
1586
+ this.server = createServer(this.handleRequest);
1587
+ this.server.listen(this.port, () => {
1588
+ const wfPath = join6(this.root, ".letra", "workflow.json");
1589
+ if (existsSync6(wfPath)) {
1590
+ try {
1591
+ this.watcher = watch(wfPath, () => this.broadcast());
1592
+ } catch {
1593
+ }
1594
+ }
1595
+ resolve17();
1596
+ });
1597
+ this.server.on("error", reject);
1598
+ });
1599
+ }
1600
+ stop() {
1601
+ if (this.watcher) this.watcher.close();
1602
+ if (this.server) this.server.close();
1603
+ for (const client of this.clients) {
1604
+ client.destroy();
1605
+ }
1606
+ this.clients.clear();
1607
+ }
1608
+ getPort() {
1609
+ return this.port;
1610
+ }
1611
+ };
1612
+ async function flowServeAction(targetPath, options) {
1613
+ const root = resolve9(process.cwd(), targetPath ?? ".");
1614
+ const port = options?.port ?? DEFAULT_PORT;
1615
+ const wf = loadWorkflow(root);
1616
+ if (!wf) {
1617
+ console.log("No workflow found. Run 'letra flow init --quick' first");
1618
+ return;
1619
+ }
1620
+ const server = new FlowServer(root, port);
1621
+ try {
1622
+ await server.start();
1623
+ console.log(`
1624
+ Flow Board \u2192 http://localhost:${port}
1625
+ `);
1626
+ console.log(" Press Ctrl+C to stop\n");
1627
+ if (options?.open) {
1628
+ const { execSync: execSync2 } = await import("child_process");
1629
+ const cmd = process.platform === "win32" ? "start" : process.platform === "darwin" ? "open" : "xdg-open";
1630
+ try {
1631
+ execSync2(`${cmd} http://localhost:${port}`, { stdio: "ignore" });
1632
+ } catch {
1633
+ }
1634
+ }
1635
+ await new Promise((resolve17) => {
1636
+ process.on("SIGINT", () => {
1637
+ server.stop();
1638
+ resolve17();
1639
+ });
1640
+ });
1641
+ } catch (err) {
1642
+ console.error(`Failed to start server on port ${port}:`, err.message);
1643
+ process.exit(1);
1644
+ }
1645
+ }
1646
+
821
1647
  // src/commands/flow-visualize.ts
822
- import { writeFileSync as writeFileSync6 } from "fs";
823
- import { resolve as resolve8 } from "path";
824
- import chalk8 from "chalk";
1648
+ import { writeFileSync as writeFileSync7 } from "fs";
1649
+ import { resolve as resolve10 } from "path";
1650
+ import chalk9 from "chalk";
825
1651
  var MERMAID_LIVE = "https://mermaid.live/edit#";
826
1652
  function generateMermaid(workflow) {
827
1653
  const sorted = [...workflow.stages].sort((a, b) => a.order - b.order);
@@ -843,9 +1669,7 @@ function generateMermaid(workflow) {
843
1669
  ` ${sorted[0].id}["${labelFor(sorted[0])}"] --> ${sorted[1].id}["${labelFor(sorted[1])}"]`
844
1670
  );
845
1671
  for (let i = 1; i < sorted.length - 1; i++) {
846
- lines.push(
847
- ` ${sorted[i].id} --> ${sorted[i + 1].id}["${labelFor(sorted[i + 1])}"]`
848
- );
1672
+ lines.push(` ${sorted[i].id} --> ${sorted[i + 1].id}["${labelFor(sorted[i + 1])}"]`);
849
1673
  }
850
1674
  return lines.join("\n");
851
1675
  }
@@ -873,14 +1697,12 @@ ${mermaid}
873
1697
  function flowVisualize(root, options) {
874
1698
  const workflow = loadWorkflow(root);
875
1699
  if (!workflow) {
876
- console.log(
877
- chalk8.yellow("No workflow found. Run 'letra flow init --quick' first")
878
- );
1700
+ console.log(chalk9.yellow("No workflow found. Run 'letra flow init --quick' first"));
879
1701
  return;
880
1702
  }
881
1703
  const mermaid = generateMermaid(workflow);
882
1704
  if (options?.output) {
883
- const outputPath = resolve8(root, options.output);
1705
+ const outputPath = resolve10(root, options.output);
884
1706
  const ext = options.output.toLowerCase().split(".").pop();
885
1707
  let content;
886
1708
  let label;
@@ -898,16 +1720,16 @@ ${mermaid}
898
1720
  `;
899
1721
  label = "Diagram file";
900
1722
  }
901
- writeFileSync6(outputPath, content);
1723
+ writeFileSync7(outputPath, content);
902
1724
  console.log(`${label} saved to ${options.output}`);
903
1725
  } else {
904
1726
  console.log(mermaid);
905
- console.log(chalk8.dim(`
1727
+ console.log(chalk9.dim(`
906
1728
  Copy to ${MERMAID_LIVE} to render`));
907
1729
  }
908
1730
  }
909
1731
  function flowVisualizeAction(targetPath, options) {
910
- const root = resolve8(process.cwd(), targetPath || ".");
1732
+ const root = resolve10(process.cwd(), targetPath || ".");
911
1733
  flowVisualize(root, options);
912
1734
  }
913
1735
 
@@ -924,6 +1746,13 @@ function flowCommand() {
924
1746
  backlog.command("list").description("List all items with stage and age").action(() => {
925
1747
  backlogActionList(void 0);
926
1748
  });
1749
+ const importCmd = backlog.command("import").description("Import issues from external sources");
1750
+ 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) => {
1751
+ backlogImportGitHubAction(void 0, repo, options);
1752
+ });
1753
+ importCmd.command("linear <team>").option("--limit <number>", "Max issues to import", "50").description("Import issues from a Linear team").action((team, options) => {
1754
+ backlogImportLinearAction(void 0, team, options);
1755
+ });
927
1756
  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) => {
928
1757
  flowMoveAction(void 0, itemId, options);
929
1758
  });
@@ -936,6 +1765,12 @@ function flowCommand() {
936
1765
  cmd.command("import <file>").description("Import workflow from a JSON file").action((file) => {
937
1766
  flowImportAction(void 0, file);
938
1767
  });
1768
+ cmd.command("serve").option("--port <number>", "Port to listen on", "3000").option("--open", "Open browser automatically").description("Start local web server with live board").action((options) => {
1769
+ flowServeAction(void 0, {
1770
+ port: options.port ? Number(options.port) : void 0,
1771
+ open: options.open
1772
+ });
1773
+ });
939
1774
  cmd.command("visualize").option("--output <file>", "Save diagram to file").description("Generate Mermaid diagram of workflow").action((options) => {
940
1775
  flowVisualizeAction(void 0, options);
941
1776
  });
@@ -950,35 +1785,35 @@ function flowCommand() {
950
1785
  }
951
1786
 
952
1787
  // src/commands/focus.ts
953
- import { existsSync as existsSync6, readFileSync as readFileSync5, unlinkSync, writeFileSync as writeFileSync7 } from "fs";
954
- import { join as join6, resolve as resolve9 } from "path";
955
- import chalk9 from "chalk";
1788
+ import { existsSync as existsSync7, readFileSync as readFileSync6, unlinkSync, writeFileSync as writeFileSync8 } from "fs";
1789
+ import { join as join7, resolve as resolve11 } from "path";
1790
+ import chalk10 from "chalk";
956
1791
  import { Command as Command3 } from "commander";
957
1792
  function extractOutcome(specDir) {
958
- const specFile = join6(specDir, "spec.md");
959
- if (!existsSync6(specFile)) return null;
960
- const content = readFileSync5(specFile, "utf-8");
1793
+ const specFile = join7(specDir, "spec.md");
1794
+ if (!existsSync7(specFile)) return null;
1795
+ const content = readFileSync6(specFile, "utf-8");
961
1796
  const match = content.match(/## Outcome\s+([\s\S]*?)(?=\n## |\n*$)/);
962
1797
  return match ? match[1].trim() : null;
963
1798
  }
964
1799
  function focus_default() {
965
1800
  return new Command3("focus").argument("[spec]", "Spec name to focus on").option("--clear", "Remove focus file").action((spec, options) => {
966
- const root = resolve9(process.cwd());
967
- const focusFile = join6(root, ".letra", "focus.md");
1801
+ const root = resolve11(process.cwd());
1802
+ const focusFile = join7(root, ".letra", "focus.md");
968
1803
  if (options.clear) {
969
- if (existsSync6(focusFile)) {
1804
+ if (existsSync7(focusFile)) {
970
1805
  unlinkSync(focusFile);
971
- console.log(chalk9.green("Focus removed."));
1806
+ console.log(chalk10.green("Focus removed."));
972
1807
  } else {
973
- console.log(chalk9.yellow("No focus to remove."));
1808
+ console.log(chalk10.yellow("No focus to remove."));
974
1809
  }
975
1810
  return;
976
1811
  }
977
1812
  if (spec) {
978
- const specDir = join6(root, ".letra", "specs", spec);
979
- const specFile = join6(specDir, "spec.md");
980
- if (!existsSync6(specFile)) {
981
- console.log(chalk9.red(`Spec "${spec}" not found`));
1813
+ const specDir = join7(root, ".letra", "specs", spec);
1814
+ const specFile = join7(specDir, "spec.md");
1815
+ if (!existsSync7(specFile)) {
1816
+ console.log(chalk10.red(`Spec "${spec}" not found`));
982
1817
  process.exit(1);
983
1818
  }
984
1819
  const outcome = extractOutcome(specDir);
@@ -990,12 +1825,12 @@ function focus_default() {
990
1825
  outcomeLine,
991
1826
  ""
992
1827
  ].join("\n");
993
- writeFileSync7(focusFile, focusContent);
994
- console.log(chalk9.green(`Focus set to "${spec}".`));
1828
+ writeFileSync8(focusFile, focusContent);
1829
+ console.log(chalk10.green(`Focus set to "${spec}".`));
995
1830
  return;
996
1831
  }
997
- if (existsSync6(focusFile)) {
998
- console.log(readFileSync5(focusFile, "utf-8"));
1832
+ if (existsSync7(focusFile)) {
1833
+ console.log(readFileSync6(focusFile, "utf-8"));
999
1834
  } else {
1000
1835
  console.log("Nenhum foco definido.");
1001
1836
  }
@@ -1003,35 +1838,28 @@ function focus_default() {
1003
1838
  }
1004
1839
 
1005
1840
  // src/commands/init.ts
1006
- import {
1007
- copyFileSync,
1008
- existsSync as existsSync7,
1009
- mkdirSync as mkdirSync4,
1010
- writeFileSync as writeFileSync8
1011
- } from "fs";
1012
- import { join as join7, resolve as resolve10 } from "path";
1841
+ import { existsSync as existsSync8, mkdirSync as mkdirSync5, writeFileSync as writeFileSync9 } from "fs";
1842
+ import { join as join8, resolve as resolve12 } from "path";
1013
1843
  import { createInterface as createInterface2 } from "readline";
1014
- import { fileURLToPath } from "url";
1015
- import chalk10 from "chalk";
1844
+ import { fileURLToPath as fileURLToPath2 } from "url";
1845
+ import chalk11 from "chalk";
1016
1846
  import ora2 from "ora";
1017
- var __dirname = fileURLToPath(new URL(".", import.meta.url));
1847
+ var __dirname = fileURLToPath2(new URL(".", import.meta.url));
1018
1848
  function ask(query, options) {
1019
1849
  if (!process.stdin.isTTY) return Promise.resolve(options[0]);
1020
1850
  const rl = createInterface2({ input: process.stdin, output: process.stdout });
1021
- return new Promise((resolve15) => {
1022
- const formatted = `${chalk10.cyan(query)} ${options.map((o) => chalk10.gray(`(${o})`)).join(" ")}
1851
+ return new Promise((resolve17) => {
1852
+ const formatted = `${chalk11.cyan(query)} ${options.map((o) => chalk11.gray(`(${o})`)).join(" ")}
1023
1853
  > `;
1024
1854
  rl.question(formatted, (answer) => {
1025
1855
  rl.close();
1026
1856
  const trimmed = answer.trim().toLowerCase();
1027
1857
  if (trimmed && options.some((o) => o.toLowerCase().startsWith(trimmed))) {
1028
- resolve15(
1029
- options.find((o) => o.toLowerCase().startsWith(trimmed)) ?? options[0]
1030
- );
1858
+ resolve17(options.find((o) => o.toLowerCase().startsWith(trimmed)) ?? options[0]);
1031
1859
  } else if (trimmed && options.includes(trimmed)) {
1032
- resolve15(trimmed);
1860
+ resolve17(trimmed);
1033
1861
  } else {
1034
- resolve15(options[0]);
1862
+ resolve17(options[0]);
1035
1863
  }
1036
1864
  });
1037
1865
  });
@@ -1042,16 +1870,7 @@ function adaptConfig(projectType) {
1042
1870
  "consistencia-terminologia": { severity: "warning" },
1043
1871
  "detecao-tom": {
1044
1872
  severity: "warning",
1045
- blacklist: [
1046
- "tipo",
1047
- "t\xE1",
1048
- "pra",
1049
- "blz",
1050
- "kkk",
1051
- "eita",
1052
- "oi",
1053
- "oi pessoal"
1054
- ]
1873
+ blacklist: ["tipo", "t\xE1", "pra", "blz", "kkk", "eita", "oi", "oi pessoal"]
1055
1874
  },
1056
1875
  "drift-temporal": { severity: "warning", maxDays: 30 },
1057
1876
  "secoes-vazias": { severity: "warning" },
@@ -1102,51 +1921,56 @@ ${format === "at" ? "# Context\n@.letra/context.md\n@.letra/constitution.md\n@.l
1102
1921
  switch (tool) {
1103
1922
  case "cursor":
1104
1923
  adapters.push({
1105
- path: join7(root, ".cursorrules"),
1924
+ path: join8(root, ".cursorrules"),
1106
1925
  content: baseContent("Cursor", "at")
1107
1926
  });
1108
1927
  break;
1109
1928
  case "claude-code":
1110
1929
  adapters.push({
1111
- path: join7(root, "CLAUDE.md"),
1930
+ path: join8(root, "CLAUDE.md"),
1112
1931
  content: baseContent("Claude Code", "text")
1113
1932
  });
1114
1933
  break;
1115
1934
  case "windsurf":
1116
1935
  adapters.push({
1117
- path: join7(root, ".windsurfrules"),
1936
+ path: join8(root, ".windsurfrules"),
1118
1937
  content: baseContent("Windsurf", "at")
1119
1938
  });
1120
1939
  break;
1121
1940
  case "vscode":
1122
1941
  adapters.push({
1123
- path: join7(root, ".github", "copilot-instructions.md"),
1942
+ path: join8(root, ".github", "copilot-instructions.md"),
1124
1943
  content: baseContent("VSCode Copilot", "text")
1125
1944
  });
1126
1945
  break;
1127
1946
  case "opencode":
1128
1947
  adapters.push({
1129
- path: join7(root, "AGENTS.md"),
1948
+ path: join8(root, "AGENTS.md"),
1130
1949
  content: baseContent("OpenCode", "text")
1131
1950
  });
1132
1951
  break;
1133
1952
  }
1134
1953
  }
1135
1954
  for (const { path, content } of adapters) {
1136
- const dir = join7(path, "..");
1137
- if (!existsSync7(dir)) mkdirSync4(dir, { recursive: true });
1138
- writeFileSync8(path, content);
1139
- console.log(` ${chalk10.gray("Created")} ${path.replace(`${root}/`, "")}`);
1955
+ const dir = join8(path, "..");
1956
+ if (!existsSync8(dir)) mkdirSync5(dir, { recursive: true });
1957
+ writeFileSync9(path, content);
1958
+ console.log(` ${chalk11.gray("Created")} ${path.replace(`${root}/`, "")}`);
1140
1959
  }
1141
1960
  }
1142
1961
  async function init(targetPath, options) {
1143
- const root = resolve10(process.cwd(), targetPath || ".");
1144
- const letraDir = join7(root, ".letra");
1145
- const spinner = ora2("Initializing Letra...").start();
1146
- if (existsSync7(letraDir)) {
1147
- spinner.warn(chalk10.yellow(".letra/ already exists"));
1962
+ const root = resolve12(process.cwd(), targetPath || ".");
1963
+ const letraDir = join8(root, ".letra");
1964
+ if (existsSync8(letraDir)) {
1965
+ if (options?.serve) {
1966
+ console.log(chalk11.cyan(".letra/ already exists \u2014 starting UI..."));
1967
+ await flowServeAction(targetPath, { open: true });
1968
+ return;
1969
+ }
1970
+ console.log(chalk11.yellow(".letra/ already exists"));
1148
1971
  return;
1149
1972
  }
1973
+ const spinner = ora2("Initializing Letra...").start();
1150
1974
  try {
1151
1975
  let projectType = "web-app";
1152
1976
  let tool = "cursor";
@@ -1155,12 +1979,7 @@ async function init(targetPath, options) {
1155
1979
  tool = "todos";
1156
1980
  } else {
1157
1981
  spinner.stop();
1158
- projectType = await ask("Project type?", [
1159
- "web-app",
1160
- "cli",
1161
- "library",
1162
- "mobile"
1163
- ]);
1982
+ projectType = await ask("Project type?", ["web-app", "cli", "library", "mobile"]);
1164
1983
  const toolNames = [
1165
1984
  "Cursor",
1166
1985
  "Windsurf",
@@ -1173,24 +1992,91 @@ async function init(targetPath, options) {
1173
1992
  tool = answer.toLowerCase();
1174
1993
  spinner.start();
1175
1994
  }
1176
- mkdirSync4(join7(letraDir, "decisions"), { recursive: true });
1177
- mkdirSync4(join7(letraDir, "specs", "_template"), { recursive: true });
1178
- mkdirSync4(join7(letraDir, "adapters"), { recursive: true });
1179
- const templateDir = join7(__dirname, "..", "..", ".letra");
1180
- const templates = [
1181
- "context.md",
1182
- "constitution.md",
1183
- "glossary.md",
1184
- "lessons-learned.md"
1185
- ];
1186
- for (const file of templates) {
1187
- const src = join7(templateDir, file);
1188
- const dest = join7(letraDir, file);
1189
- if (existsSync7(src)) copyFileSync(src, dest);
1995
+ mkdirSync5(join8(letraDir, "decisions"), { recursive: true });
1996
+ mkdirSync5(join8(letraDir, "specs", "_template"), { recursive: true });
1997
+ mkdirSync5(join8(letraDir, "adapters"), { recursive: true });
1998
+ const templateFiles = {
1999
+ "context.md": `# Context
2000
+
2001
+ > Updated: 2026-05-01
2002
+ > Owner: letra-dev
2003
+
2004
+ ## Intent
2005
+
2006
+ Letra \xE9 um framework de Specification-Driven Development (SDD) agn\xF3stico a ferramentas.
2007
+ Captura dire\xE7\xE3o, inten\xE7\xE3o e contexto, enriquecendo prompts de agentes de c\xF3digo.
2008
+
2009
+ ## Dom\xEDnio
2010
+
2011
+ - **Produto**: CLI + adapters + formato de mem\xF3ria .letra/
2012
+ - **P\xFAblico**: 1. N\xE3o-devs
2013
+
2014
+ ## Restri\xE7\xF5es Reais
2015
+
2016
+ - Specs devem ser thin (m\xE1x 1 p\xE1gina por feature)
2017
+ - Sem lock-in de IDE
2018
+ - Drift detection deve funcionar para qualquer dom\xEDnio (n\xE3o s\xF3 c\xF3digo)
2019
+
2020
+ ## Porqu\xEAs
2021
+
2022
+ - Escolhemos TypeScript porque 82% dos novos pacotes npm s\xE3o TS em 2026
2023
+ - Escolhemos Markdown checklist porque n\xE3o-devs precisam ler e escrever specs
2024
+ `,
2025
+ "constitution.md": `# Constitution
2026
+
2027
+ ## Arquitetura
2028
+ - Adapter layer desde o dia 1 \u2014 nunca travar em uma IDE
2029
+ - Formato .letra/ \xE9 a fonte da verdade, n\xE3o o c\xF3digo
2030
+ - CLI deve ser extens\xEDvel via plugins
2031
+
2032
+ ## C\xF3digo
2033
+ - TypeScript estrito (strict: true)
2034
+ - Zero dependencies desnecess\xE1rias
2035
+
2036
+ ## Specs
2037
+ - Thin specs: m\xE1ximo 1 p\xE1gina por feature
2038
+ - Markdown checklist para acceptance criteria
2039
+ - Toda spec deve ter: Outcome, Constraints, Exclusions, Acceptance Criteria, Context
2040
+
2041
+ ## Seguran\xE7a
2042
+ - Nunca incluir secrets, tokens ou chaves no reposit\xF3rio
2043
+ `,
2044
+ "glossary.md": `# Glossary
2045
+
2046
+ | Termo | Defini\xE7\xE3o |
2047
+ |-------|-----------|
2048
+ | **Spec** | Especifica\xE7\xE3o thin que define o que deve ser constru\xEDdo. |
2049
+ | **Drift** | Diverg\xEAncia entre o que a spec diz e o que o artefato realmente entrega. |
2050
+ | **Adapter** | Tradutor que converte .letra/ para o formato que uma IDE/agent entende. |
2051
+ | **Context** | Documento que captura intent, dom\xEDnio, restri\xE7\xF5es reais e "porqu\xEAs" do projeto. |
2052
+ | **Constitution** | Regras n\xE3o-negoci\xE1veis de arquitetura, c\xF3digo e workflow. |
2053
+ | **Thin Spec** | Spec de no m\xE1ximo 1 p\xE1gina, focada em outcome. |
2054
+ `,
2055
+ "lessons-learned.md": `# Lessons Learned
2056
+
2057
+ ## O que funcionou
2058
+ - Pesquisar dores reais do SDD antes de definir arquitetura
2059
+ - Decidir por evid\xEAncias (m\xE9tricas, dados) e n\xE3o por intui\xE7\xE3o
2060
+
2061
+ ## O que aprendemos
2062
+ - Drift detection n\xE3o pode ser code-centric \u2014 p\xFAblico prim\xE1rio s\xE3o n\xE3o-devs
2063
+ - Obsidian nunca deve ser requisito \u2014 barreira de ado\xE7\xE3o
2064
+ - TypeScript domina CLIs em 2026 (82% dos novos pacotes npm)
2065
+
2066
+ ## Padr\xF5es a evitar
2067
+ - Specs gigantes (Markdown Madness)
2068
+ - Lock-in de IDE
2069
+ - Spec que vira pseudo-c\xF3digo
2070
+ `
2071
+ };
2072
+ for (const [file, content] of Object.entries(templateFiles)) {
2073
+ writeFileSync9(join8(letraDir, file), content, "utf-8");
1190
2074
  }
1191
- const specTemplate = join7(letraDir, "specs", "_template.md");
2075
+ const specTemplate = join8(letraDir, "specs", "_template.md");
1192
2076
  const specContent = `# Spec Template
1193
2077
 
2078
+ > Updated: YYYY-MM-DD
2079
+
1194
2080
  ## Outcome
1195
2081
  O que o usu\xE1rio consegue fazer quando isso estiver pronto.
1196
2082
 
@@ -1206,16 +2092,16 @@ O que explicitamente N\xC3O est\xE1 neste escopo.
1206
2092
  ## Context
1207
2093
  Por que estamos construindo isso.
1208
2094
  `;
1209
- writeFileSync8(specTemplate, specContent);
1210
- const configPath = join7(letraDir, "config.json");
1211
- writeFileSync8(configPath, adaptConfig(projectType));
1212
- console.log(` ${chalk10.gray("Created")} .letra/config.json`);
2095
+ writeFileSync9(specTemplate, specContent);
2096
+ const configPath = join8(letraDir, "config.json");
2097
+ writeFileSync9(configPath, adaptConfig(projectType));
2098
+ console.log(` ${chalk11.gray("Created")} .letra/config.json`);
1213
2099
  const tools = adaptersForTool(tool);
1214
2100
  generateAdapterFiles(root, tools);
1215
2101
  if (tool === "todos" || tool === "vscode") {
1216
- const vscodeDir = join7(root, ".vscode");
1217
- if (!existsSync7(vscodeDir)) mkdirSync4(vscodeDir, { recursive: true });
1218
- const vscodeSettingsPath = join7(vscodeDir, "settings.json");
2102
+ const vscodeDir = join8(root, ".vscode");
2103
+ if (!existsSync8(vscodeDir)) mkdirSync5(vscodeDir, { recursive: true });
2104
+ const vscodeSettingsPath = join8(vscodeDir, "settings.json");
1219
2105
  const vscodeSettingsContent = `{
1220
2106
  "editor.formatOnSave": true,
1221
2107
  "editor.defaultFormatter": "esbenp.prettier-vscode",
@@ -1225,26 +2111,32 @@ Por que estamos construindo isso.
1225
2111
  "files.autoSave": "onFocusChange"
1226
2112
  }
1227
2113
  `;
1228
- writeFileSync8(vscodeSettingsPath, vscodeSettingsContent);
1229
- console.log(` ${chalk10.gray("Created")} .vscode/settings.json`);
2114
+ writeFileSync9(vscodeSettingsPath, vscodeSettingsContent);
2115
+ console.log(` ${chalk11.gray("Created")} .vscode/settings.json`);
1230
2116
  }
1231
- spinner.succeed(chalk10.green(".letra/ initialized successfully"));
2117
+ spinner.succeed(chalk11.green(".letra/ initialized successfully"));
1232
2118
  console.log("");
1233
2119
  console.log(" Next steps:");
1234
- console.log(
1235
- ` ${chalk10.cyan("letra spec new <name>")} Create your first spec`
1236
- );
1237
- console.log(` ${chalk10.cyan("letra lint")} Validate specs`);
2120
+ console.log(` ${chalk11.cyan("letra spec new <name>")} Create your first spec`);
2121
+ console.log(` ${chalk11.cyan("letra lint")} Validate specs`);
2122
+ console.log(` ${chalk11.cyan("letra init --serve")} Open web UI to configure workflow`);
2123
+ if (options?.serve) {
2124
+ console.log(`
2125
+ ${chalk11.cyan("Opening web UI...")}
2126
+ `);
2127
+ await flowServeAction(targetPath, { open: true });
2128
+ return;
2129
+ }
1238
2130
  } catch (error) {
1239
- spinner.fail(chalk10.red("Failed to initialize Letra"));
2131
+ spinner.fail(chalk11.red("Failed to initialize Letra"));
1240
2132
  process.exit(1);
1241
2133
  }
1242
2134
  }
1243
2135
 
1244
2136
  // src/commands/lint.ts
1245
- import { existsSync as existsSync8, readFileSync as readFileSync6, readdirSync as readdirSync4 } from "fs";
1246
- import { join as join8, resolve as resolve11 } from "path";
1247
- import chalk11 from "chalk";
2137
+ import { existsSync as existsSync9, readFileSync as readFileSync7, readdirSync as readdirSync5 } from "fs";
2138
+ import { join as join9, resolve as resolve13 } from "path";
2139
+ import chalk12 from "chalk";
1248
2140
  var REQUIRED_SECTIONS = [
1249
2141
  "## Outcome",
1250
2142
  "## Constraints",
@@ -1253,27 +2145,25 @@ var REQUIRED_SECTIONS = [
1253
2145
  "## Context"
1254
2146
  ];
1255
2147
  async function lint(targetPath) {
1256
- const root = resolve11(process.cwd(), targetPath || ".");
1257
- const specsDir = join8(root, ".letra", "specs");
1258
- if (!existsSync8(specsDir)) {
1259
- console.log(
1260
- chalk11.red("Error: .letra/specs/ not found. Run 'letra init' first.")
1261
- );
2148
+ const root = resolve13(process.cwd(), targetPath || ".");
2149
+ const specsDir = join9(root, ".letra", "specs");
2150
+ if (!existsSync9(specsDir)) {
2151
+ console.log(chalk12.red("Error: .letra/specs/ not found. Run 'letra init' first."));
1262
2152
  process.exit(1);
1263
2153
  }
1264
2154
  const results = [];
1265
2155
  let totalErrors = 0;
1266
2156
  let totalWarnings = 0;
1267
- const entries = readdirSync4(specsDir, { withFileTypes: true });
2157
+ const entries = readdirSync5(specsDir, { withFileTypes: true });
1268
2158
  for (const entry of entries) {
1269
2159
  if (!entry.isDirectory() || entry.name.startsWith("_")) continue;
1270
- const specFile = join8(specsDir, entry.name, "spec.md");
2160
+ const specFile = join9(specsDir, entry.name, "spec.md");
1271
2161
  const errors = [];
1272
2162
  const warnings = [];
1273
- if (!existsSync8(specFile)) {
2163
+ if (!existsSync9(specFile)) {
1274
2164
  errors.push("Missing spec.md");
1275
2165
  } else {
1276
- const content = readFileSync6(specFile, "utf-8");
2166
+ const content = readFileSync7(specFile, "utf-8");
1277
2167
  for (const section of REQUIRED_SECTIONS) {
1278
2168
  if (!content.includes(section)) {
1279
2169
  errors.push(`Missing section: ${section}`);
@@ -1284,9 +2174,7 @@ async function lint(targetPath) {
1284
2174
  }
1285
2175
  const hasChecklist = /-\s*\[[ x]\]\s*\*\*/i.test(content);
1286
2176
  if (!hasChecklist && content.includes("## Acceptance Criteria")) {
1287
- errors.push(
1288
- "Acceptance Criteria section exists but has no checklist items"
1289
- );
2177
+ errors.push("Acceptance Criteria section exists but has no checklist items");
1290
2178
  }
1291
2179
  }
1292
2180
  if (errors.length > 0 || warnings.length > 0) {
@@ -1296,22 +2184,22 @@ async function lint(targetPath) {
1296
2184
  }
1297
2185
  }
1298
2186
  if (results.length === 0) {
1299
- console.log(chalk11.green("All specs are valid"));
2187
+ console.log(chalk12.green("All specs are valid"));
1300
2188
  process.exit(0);
1301
2189
  }
1302
2190
  console.log("");
1303
2191
  for (const result of results) {
1304
- console.log(chalk11.bold(`
2192
+ console.log(chalk12.bold(`
1305
2193
  Spec: ${result.file}`));
1306
2194
  for (const error of result.errors) {
1307
- console.log(chalk11.red(` \u2717 ${error}`));
2195
+ console.log(chalk12.red(` \u2717 ${error}`));
1308
2196
  }
1309
2197
  for (const warning of result.warnings) {
1310
- console.log(chalk11.yellow(` \u26A0 ${warning}`));
2198
+ console.log(chalk12.yellow(` \u26A0 ${warning}`));
1311
2199
  }
1312
2200
  }
1313
2201
  console.log(
1314
- chalk11.gray(
2202
+ chalk12.gray(
1315
2203
  `
1316
2204
  ${results.length} spec(s) with issues: ${totalErrors} error(s), ${totalWarnings} warning(s)`
1317
2205
  )
@@ -1320,20 +2208,16 @@ ${results.length} spec(s) with issues: ${totalErrors} error(s), ${totalWarnings}
1320
2208
  }
1321
2209
 
1322
2210
  // src/commands/spec.ts
1323
- import {
1324
- existsSync as existsSync9,
1325
- mkdirSync as mkdirSync5,
1326
- readFileSync as readFileSync7,
1327
- readdirSync as readdirSync5,
1328
- writeFileSync as writeFileSync9
1329
- } from "fs";
1330
- import { join as join9, resolve as resolve12 } from "path";
1331
- import chalk12 from "chalk";
2211
+ import { existsSync as existsSync10, mkdirSync as mkdirSync6, readFileSync as readFileSync8, readdirSync as readdirSync6, writeFileSync as writeFileSync10 } from "fs";
2212
+ import { join as join10, resolve as resolve14 } from "path";
2213
+ import chalk13 from "chalk";
1332
2214
  import ora3 from "ora";
1333
2215
  var builtInTemplates = {
1334
2216
  "web-api": {
1335
2217
  spec: `# Spec: {{name}}
1336
2218
 
2219
+ > Updated: {{date}}
2220
+
1337
2221
  ## Outcome
1338
2222
  Usu\xE1rio consegue fazer requisi\xE7\xF5es HTTP para a API e receber respostas padronizadas.
1339
2223
 
@@ -1367,6 +2251,8 @@ Template para APIs REST. Adaptado para o dom\xEDnio espec\xEDfico do projeto.`,
1367
2251
  "cli-tool": {
1368
2252
  spec: `# Spec: {{name}}
1369
2253
 
2254
+ > Updated: {{date}}
2255
+
1370
2256
  ## Outcome
1371
2257
  Usu\xE1rio instala e executa a CLI, recebendo output formatado no terminal.
1372
2258
 
@@ -1400,6 +2286,8 @@ Template para ferramentas de linha de comando. Adaptado para o escopo espec\xEDf
1400
2286
  "mobile-feature": {
1401
2287
  spec: `# Spec: {{name}}
1402
2288
 
2289
+ > Updated: {{date}}
2290
+
1403
2291
  ## Outcome
1404
2292
  Usu\xE1rio consegue acessar e interagir com a nova funcionalidade no aplicativo mobile.
1405
2293
 
@@ -1433,9 +2321,9 @@ Template para features mobile nativas. Adaptado para o framework espec\xEDfico (
1433
2321
  };
1434
2322
  function listTemplates(root) {
1435
2323
  const names = Object.keys(builtInTemplates);
1436
- const customDir = join9(root, ".letra", "templates");
1437
- if (existsSync9(customDir)) {
1438
- for (const file of readdirSync5(customDir)) {
2324
+ const customDir = join10(root, ".letra", "templates");
2325
+ if (existsSync10(customDir)) {
2326
+ for (const file of readdirSync6(customDir)) {
1439
2327
  if (file.endsWith(".md")) {
1440
2328
  const name = file.replace(/\.md$/, "");
1441
2329
  if (!names.includes(name)) names.push(name);
@@ -1447,16 +2335,11 @@ function listTemplates(root) {
1447
2335
  function findTemplate(root, type) {
1448
2336
  const lower = type.toLowerCase();
1449
2337
  if (builtInTemplates[lower]) return builtInTemplates[lower];
1450
- const customFile = join9(root, ".letra", "templates", `${type}.md`);
1451
- const customAcceptance = join9(
1452
- root,
1453
- ".letra",
1454
- "templates",
1455
- `${type}-acceptance.md`
1456
- );
1457
- if (existsSync9(customFile)) {
1458
- const spec = readFileSync7(customFile, "utf-8");
1459
- const acceptance = existsSync9(customAcceptance) ? readFileSync7(customAcceptance, "utf-8") : `# Acceptance Criteria \u2014 ${type}
2338
+ const customFile = join10(root, ".letra", "templates", `${type}.md`);
2339
+ const customAcceptance = join10(root, ".letra", "templates", `${type}-acceptance.md`);
2340
+ if (existsSync10(customFile)) {
2341
+ const spec = readFileSync8(customFile, "utf-8");
2342
+ const acceptance = existsSync10(customAcceptance) ? readFileSync8(customAcceptance, "utf-8") : `# Acceptance Criteria \u2014 ${type}
1460
2343
 
1461
2344
  - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
1462
2345
  `;
@@ -1464,43 +2347,42 @@ function findTemplate(root, type) {
1464
2347
  }
1465
2348
  return null;
1466
2349
  }
1467
- function applyPlaceholders(content, name) {
1468
- return content.replace(/\{\{name\}\}/g, name);
2350
+ function applyPlaceholders(content, name, date) {
2351
+ return content.replace(/\{\{name\}\}/g, name).replace(/\{\{date\}\}/g, date);
1469
2352
  }
1470
2353
  async function specNew(name, options) {
1471
- const root = resolve12(process.cwd());
1472
- const letraDir = join9(root, ".letra");
1473
- const specDir = join9(letraDir, "specs", name);
1474
- if (!existsSync9(letraDir)) {
1475
- console.log(chalk12.red(".letra/ not found. Run 'letra init' first."));
2354
+ const root = resolve14(process.cwd());
2355
+ const letraDir = join10(root, ".letra");
2356
+ const specDir = join10(letraDir, "specs", name);
2357
+ if (!existsSync10(letraDir)) {
2358
+ console.log(chalk13.red(".letra/ not found. Run 'letra init' first."));
1476
2359
  process.exit(1);
1477
2360
  }
1478
- if (existsSync9(specDir)) {
1479
- console.log(chalk12.yellow(`Spec "${name}" already exists`));
2361
+ if (existsSync10(specDir)) {
2362
+ console.log(chalk13.yellow(`Spec "${name}" already exists`));
1480
2363
  return;
1481
2364
  }
1482
2365
  const templateType = options?.template || "_default";
1483
2366
  const template = templateType === "_default" ? null : findTemplate(root, templateType);
1484
2367
  if (options?.template && !template) {
1485
2368
  const available = listTemplates(root).join(", ");
1486
- console.log(
1487
- chalk12.red(
1488
- `Template "${options.template}" not found. Available: ${available}`
1489
- )
1490
- );
2369
+ console.log(chalk13.red(`Template "${options.template}" not found. Available: ${available}`));
1491
2370
  process.exit(1);
1492
2371
  }
1493
2372
  const spinner = ora3(`Creating spec "${name}"...`).start();
1494
2373
  try {
1495
- mkdirSync5(specDir, { recursive: true });
2374
+ const today2 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
2375
+ mkdirSync6(specDir, { recursive: true });
1496
2376
  if (template) {
1497
- const specContent = applyPlaceholders(template.spec, name);
1498
- const acceptanceContent = applyPlaceholders(template.acceptance, name);
1499
- writeFileSync9(join9(specDir, "spec.md"), specContent);
1500
- writeFileSync9(join9(specDir, "acceptance.md"), acceptanceContent);
2377
+ const specContent = applyPlaceholders(template.spec, name, today2);
2378
+ const acceptanceContent = applyPlaceholders(template.acceptance, name, today2);
2379
+ writeFileSync10(join10(specDir, "spec.md"), specContent);
2380
+ writeFileSync10(join10(specDir, "acceptance.md"), acceptanceContent);
1501
2381
  } else {
1502
2382
  const specContent = `# Spec: ${name}
1503
2383
 
2384
+ > Updated: ${today2}
2385
+
1504
2386
  ## Outcome
1505
2387
  O que o usu\xE1rio consegue fazer quando isso estiver pronto.
1506
2388
 
@@ -1520,14 +2402,12 @@ Por que estamos construindo isso. Trade-offs considerados.
1520
2402
 
1521
2403
  - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
1522
2404
  `;
1523
- writeFileSync9(join9(specDir, "spec.md"), specContent);
1524
- writeFileSync9(join9(specDir, "acceptance.md"), acceptanceContent);
2405
+ writeFileSync10(join10(specDir, "spec.md"), specContent);
2406
+ writeFileSync10(join10(specDir, "acceptance.md"), acceptanceContent);
1525
2407
  }
1526
- spinner.succeed(
1527
- chalk12.green(`Spec "${name}" created at .letra/specs/${name}/`)
1528
- );
2408
+ spinner.succeed(chalk13.green(`Spec "${name}" created at .letra/specs/${name}/`));
1529
2409
  } catch (error) {
1530
- spinner.fail(chalk12.red("Failed to create spec"));
2410
+ spinner.fail(chalk13.red("Failed to create spec"));
1531
2411
  process.exit(1);
1532
2412
  }
1533
2413
  }
@@ -1535,21 +2415,21 @@ Por que estamos construindo isso. Trade-offs considerados.
1535
2415
  // src/commands/validate.ts
1536
2416
  import { execSync } from "child_process";
1537
2417
  import {
1538
- existsSync as existsSync11,
2418
+ existsSync as existsSync12,
1539
2419
  mkdtempSync,
1540
- readFileSync as readFileSync9,
1541
- readdirSync as readdirSync6,
2420
+ readFileSync as readFileSync10,
2421
+ readdirSync as readdirSync7,
1542
2422
  rmSync,
1543
2423
  statSync as statSync2,
1544
- watch
2424
+ watch as watch2
1545
2425
  } from "fs";
1546
2426
  import { tmpdir } from "os";
1547
- import { join as join11, resolve as resolve13 } from "path";
1548
- import chalk13 from "chalk";
2427
+ import { join as join12, resolve as resolve15 } from "path";
2428
+ import chalk14 from "chalk";
1549
2429
 
1550
2430
  // src/config.ts
1551
- import { existsSync as existsSync10, readFileSync as readFileSync8 } from "fs";
1552
- import { join as join10 } from "path";
2431
+ import { existsSync as existsSync11, readFileSync as readFileSync9 } from "fs";
2432
+ import { join as join11 } from "path";
1553
2433
  var DEFAULT_HEURISTICS = {
1554
2434
  "conteudo-minimo": { severity: "warning", minChars: 50 },
1555
2435
  "consistencia-terminologia": { severity: "warning" },
@@ -1564,14 +2444,14 @@ var DEFAULT_HEURISTICS = {
1564
2444
  "validate-conflict": { severity: "warning" }
1565
2445
  };
1566
2446
  function loadConfig(root) {
1567
- const configPath = join10(root, ".letra", "config.json");
2447
+ const configPath = join11(root, ".letra", "config.json");
1568
2448
  const heuristics = {};
1569
2449
  for (const [key, value] of Object.entries(DEFAULT_HEURISTICS)) {
1570
2450
  heuristics[key] = { ...value };
1571
2451
  }
1572
- if (existsSync10(configPath)) {
2452
+ if (existsSync11(configPath)) {
1573
2453
  try {
1574
- const raw = JSON.parse(readFileSync8(configPath, "utf-8"));
2454
+ const raw = JSON.parse(readFileSync9(configPath, "utf-8"));
1575
2455
  if (raw.heuristics && typeof raw.heuristics === "object") {
1576
2456
  for (const [key, value] of Object.entries(raw.heuristics)) {
1577
2457
  if (heuristics[key]) {
@@ -1638,17 +2518,15 @@ var lowConfidenceMarkers = [
1638
2518
  "teoricamente"
1639
2519
  ];
1640
2520
  function checkSpecContent(specDir, label, description, config) {
1641
- const cfg = config ?? loadConfig(join11(specDir, "..", "..", ".."));
1642
- const specFile = join11(specDir, "spec.md");
1643
- const glossaryFile = join11(specDir, "..", "..", "glossary.md");
1644
- if (!existsSync11(specFile))
1645
- return { status: "FAIL", note: "(spec.md not found)" };
1646
- const specContent = readFileSync9(specFile, "utf-8");
1647
- const now6 = /* @__PURE__ */ new Date();
2521
+ const cfg = config ?? loadConfig(join12(specDir, "..", "..", ".."));
2522
+ const specFile = join12(specDir, "spec.md");
2523
+ const glossaryFile = join12(specDir, "..", "..", "glossary.md");
2524
+ if (!existsSync12(specFile)) return { status: "FAIL", note: "(spec.md not found)" };
2525
+ const specContent = readFileSync10(specFile, "utf-8");
2526
+ const now7 = /* @__PURE__ */ new Date();
1648
2527
  if (label.includes("Conte\xFAdo M\xEDnimo")) {
1649
2528
  const outcomeMatch = specContent.match(/## Outcome\s+([\s\S]*?)(?=\n## )/);
1650
- if (!outcomeMatch)
1651
- return { status: "FAIL", note: "(no Outcome section)" };
2529
+ if (!outcomeMatch) return { status: "FAIL", note: "(no Outcome section)" };
1652
2530
  const outcomeContent = outcomeMatch[1].trim();
1653
2531
  const heurConfig = getHeuristicConfig(cfg, label);
1654
2532
  const minChars = heurConfig.minChars ?? 50;
@@ -1664,13 +2542,13 @@ function checkSpecContent(specDir, label, description, config) {
1664
2542
  };
1665
2543
  }
1666
2544
  if (label.includes("Consist\xEAncia de Terminologia") || label.includes("Terminologia")) {
1667
- if (!existsSync11(glossaryFile)) {
2545
+ if (!existsSync12(glossaryFile)) {
1668
2546
  return {
1669
2547
  status: "PASS",
1670
2548
  note: "(no glossary to check against)"
1671
2549
  };
1672
2550
  }
1673
- const glossaryContent = readFileSync9(glossaryFile, "utf-8");
2551
+ const glossaryContent = readFileSync10(glossaryFile, "utf-8");
1674
2552
  const terms = glossaryContent.match(/\*\*(.+?)\*\*/g) || [];
1675
2553
  const extractedTerms = terms.map((t) => t.replace(/\*\*/g, "").trim()).filter((t) => t.length > 3);
1676
2554
  const missingTerms = extractedTerms.filter(
@@ -1709,9 +2587,7 @@ function checkSpecContent(specDir, label, description, config) {
1709
2587
  }
1710
2588
  if (label.includes("Drift Temporal") || label.includes("Temporal")) {
1711
2589
  const stat = statSync2(specFile);
1712
- const daysOld = Math.floor(
1713
- (now6.getTime() - stat.mtimeMs) / (1e3 * 60 * 60 * 24)
1714
- );
2590
+ const daysOld = Math.floor((now7.getTime() - stat.mtimeMs) / (1e3 * 60 * 60 * 24));
1715
2591
  const heurConfig = getHeuristicConfig(cfg, label);
1716
2592
  const maxDays = heurConfig.maxDays ?? 30;
1717
2593
  if (daysOld < maxDays) {
@@ -1763,9 +2639,7 @@ function checkEmptySections(specContent) {
1763
2639
  };
1764
2640
  }
1765
2641
  function checkBinaryCriteria(specContent) {
1766
- const acMatch = specContent.match(
1767
- /## Acceptance Criteria\s+([\s\S]*?)(?=\n## |\n*$)/
1768
- );
2642
+ const acMatch = specContent.match(/## Acceptance Criteria\s+([\s\S]*?)(?=\n## |\n*$)/);
1769
2643
  if (!acMatch) {
1770
2644
  return {
1771
2645
  status: "FAIL",
@@ -1780,9 +2654,7 @@ function checkBinaryCriteria(specContent) {
1780
2654
  for (const line of criteriaLines) {
1781
2655
  const description = line.replace(/- \[[ x]\] \*\*.+?\*\*:\s*/, "");
1782
2656
  const hasMetric = /\d+/.test(description);
1783
- const hasVagueVerb = vagueVerbs.some(
1784
- (v) => description.toLowerCase().includes(v)
1785
- );
2657
+ const hasVagueVerb = vagueVerbs.some((v) => description.toLowerCase().includes(v));
1786
2658
  if (!hasMetric && hasVagueVerb) {
1787
2659
  const labelMatch = line.match(/\*\*(.+?)\*\*/);
1788
2660
  if (labelMatch) nonBinary.push(labelMatch[1]);
@@ -1897,13 +2769,13 @@ function detectConflict(textA, textB) {
1897
2769
  }
1898
2770
  function checkConflicts(specsDir, config) {
1899
2771
  const results = [];
1900
- const entries = readdirSync6(specsDir, { withFileTypes: true });
2772
+ const entries = readdirSync7(specsDir, { withFileTypes: true });
1901
2773
  const specDirs = entries.filter((e) => e.isDirectory() && !e.name.startsWith("_")).map((e) => e.name);
1902
2774
  const specs = [];
1903
2775
  for (const dir of specDirs) {
1904
- const acceptanceFile = join11(specsDir, dir, "acceptance.md");
1905
- if (!existsSync11(acceptanceFile)) continue;
1906
- const content = readFileSync9(acceptanceFile, "utf-8");
2776
+ const acceptanceFile = join12(specsDir, dir, "acceptance.md");
2777
+ if (!existsSync12(acceptanceFile)) continue;
2778
+ const content = readFileSync10(acceptanceFile, "utf-8");
1907
2779
  const acLines = content.match(/- \[[ x]\] \*\*(.+?)\*\*: (.+)/g) || [];
1908
2780
  const acs = acLines.map((line) => {
1909
2781
  const m = line.match(/- \[[ x]\] \*\*(.+?)\*\*: (.+)/);
@@ -1953,13 +2825,11 @@ function out(format, level, spec, label, message, note) {
1953
2825
  if (format === "junit") {
1954
2826
  return;
1955
2827
  }
1956
- const icon = level === "pass" ? chalk13.green("\u2713") : level === "fail" ? chalk13.red("\u2717") : level === "warning" ? chalk13.yellow("\u26A0") : "";
2828
+ const icon = level === "pass" ? chalk14.green("\u2713") : level === "fail" ? chalk14.red("\u2717") : level === "warning" ? chalk14.yellow("\u26A0") : "";
1957
2829
  if (level === "info") {
1958
2830
  console.log(` ${message}`);
1959
2831
  } else {
1960
- console.log(
1961
- ` [${icon}] ${chalk13.cyan(label)}: ${message} ${chalk13.gray(note)}`
1962
- );
2832
+ console.log(` [${icon}] ${chalk14.cyan(label)}: ${message} ${chalk14.gray(note)}`);
1963
2833
  }
1964
2834
  }
1965
2835
  function buildJunitXml(results) {
@@ -2000,55 +2870,55 @@ function flushResults(results, format, specGroups, totalPass, totalFail, totalWa
2000
2870
  }
2001
2871
  }
2002
2872
  console.log(
2003
- chalk13.gray(
2873
+ chalk14.gray(
2004
2874
  `
2005
2875
  Results: ${totalPass} passed, ${totalFail} failed${totalWarning > 0 ? `, ${totalWarning} warnings` : ""}`
2006
2876
  )
2007
2877
  );
2008
2878
  }
2009
2879
  async function validate(targetPath, options) {
2010
- const root = resolve13(process.cwd(), targetPath || ".");
2011
- const specsDir = join11(root, ".letra", "specs");
2880
+ const root = resolve15(process.cwd(), targetPath || ".");
2881
+ const specsDir = join12(root, ".letra", "specs");
2012
2882
  const fmt = options?.format || "text";
2013
- if (!existsSync11(specsDir)) {
2883
+ if (!existsSync12(specsDir)) {
2014
2884
  const msg = "Error: .letra/specs/ not found. Run 'letra init' first.";
2015
2885
  if (fmt === "github-annotation") {
2016
2886
  console.log(`::error file=,title=Init Required::${msg}`);
2017
2887
  } else {
2018
- console.log(chalk13.red(msg));
2888
+ console.log(chalk14.red(msg));
2019
2889
  }
2020
2890
  process.exit(1);
2021
2891
  }
2022
2892
  async function runValidation() {
2023
2893
  const config = loadConfig(root);
2024
- const entries = readdirSync6(specsDir, { withFileTypes: true });
2894
+ const entries = readdirSync7(specsDir, { withFileTypes: true });
2025
2895
  let totalPass = 0;
2026
2896
  let totalFail = 0;
2027
2897
  let totalWarning = 0;
2028
2898
  const specGroups = /* @__PURE__ */ new Map();
2029
2899
  const allResults = [];
2030
- const entryPoint = join11(root, "src/index.ts");
2900
+ const entryPoint = join12(root, "src/index.ts");
2031
2901
  const opts = {
2032
2902
  stdio: "pipe",
2033
2903
  encoding: "utf-8",
2034
2904
  shell: process.platform === "win32" ? "cmd.exe" : true
2035
2905
  };
2036
- const ciFile = join11(root, ".github", "workflows", "ci.yml");
2037
- const cursorRulesFile = join11(root, ".cursorrules");
2038
- const copilotFile = join11(root, ".github", "copilot-instructions.md");
2039
- const vscodeSettingsFile = join11(root, ".vscode", "settings.json");
2906
+ const ciFile = join12(root, ".github", "workflows", "ci.yml");
2907
+ const cursorRulesFile = join12(root, ".cursorrules");
2908
+ const copilotFile = join12(root, ".github", "copilot-instructions.md");
2909
+ const vscodeSettingsFile = join12(root, ".vscode", "settings.json");
2040
2910
  if (fmt !== "junit") {
2041
2911
  out(fmt, "info", null, "", "\nLetra Validation\n", "");
2042
2912
  }
2043
2913
  for (const entry of entries) {
2044
2914
  if (!entry.isDirectory() || entry.name.startsWith("_")) continue;
2045
- const acceptanceFile = join11(specsDir, entry.name, "acceptance.md");
2046
- const specFile = join11(specsDir, entry.name, "spec.md");
2915
+ const acceptanceFile = join12(specsDir, entry.name, "acceptance.md");
2916
+ const specFile = join12(specsDir, entry.name, "spec.md");
2047
2917
  let content;
2048
- if (existsSync11(acceptanceFile)) {
2049
- content = readFileSync9(acceptanceFile, "utf-8");
2050
- } else if (existsSync11(specFile)) {
2051
- content = readFileSync9(specFile, "utf-8");
2918
+ if (existsSync12(acceptanceFile)) {
2919
+ content = readFileSync10(acceptanceFile, "utf-8");
2920
+ } else if (existsSync12(specFile)) {
2921
+ content = readFileSync10(specFile, "utf-8");
2052
2922
  } else {
2053
2923
  out(
2054
2924
  fmt,
@@ -2061,7 +2931,7 @@ async function validate(targetPath, options) {
2061
2931
  continue;
2062
2932
  }
2063
2933
  const criteriaLines = content.match(/- \[ \] \*\*(.+?)\*\*: (.+)/g) || [];
2064
- const specContent = existsSync11(specFile) ? readFileSync9(specFile, "utf-8") : null;
2934
+ const specContent = existsSync12(specFile) ? readFileSync10(specFile, "utf-8") : null;
2065
2935
  out(fmt, "info", entry.name, "", `Spec: ${entry.name}`, "");
2066
2936
  if (criteriaLines.length === 0) {
2067
2937
  out(fmt, "info", entry.name, "", "No criteria found", "");
@@ -2078,7 +2948,7 @@ async function validate(targetPath, options) {
2078
2948
  let intelligenceResult = null;
2079
2949
  try {
2080
2950
  intelligenceResult = checkSpecContent(
2081
- join11(specsDir, entry.name),
2951
+ join12(specsDir, entry.name),
2082
2952
  label,
2083
2953
  description,
2084
2954
  config
@@ -2087,21 +2957,18 @@ async function validate(targetPath, options) {
2087
2957
  status = intelligenceResult.status;
2088
2958
  note = intelligenceResult.note;
2089
2959
  } else if (label.includes("letra init")) {
2090
- const tmp = mkdtempSync(join11(tmpdir(), "letra-test-"));
2960
+ const tmp = mkdtempSync(join12(tmpdir(), "letra-test-"));
2091
2961
  execSync(`npx tsx "${entryPoint}" init "${tmp}"`, { ...opts });
2092
- if (existsSync11(join11(tmp, ".letra", "context.md")))
2093
- status = "PASS";
2962
+ if (existsSync12(join12(tmp, ".letra", "context.md"))) status = "PASS";
2094
2963
  rmSync(tmp, { recursive: true });
2095
2964
  } else if (label.includes("letra spec")) {
2096
- const tmp = mkdtempSync(join11(tmpdir(), "letra-test-"));
2965
+ const tmp = mkdtempSync(join12(tmpdir(), "letra-test-"));
2097
2966
  execSync(`npx tsx "${entryPoint}" init "${tmp}"`, { ...opts });
2098
2967
  execSync(`npx tsx "${entryPoint}" spec smoke-test`, {
2099
2968
  ...opts,
2100
2969
  cwd: tmp
2101
2970
  });
2102
- if (existsSync11(
2103
- join11(tmp, ".letra", "specs", "smoke-test", "spec.md")
2104
- ))
2971
+ if (existsSync12(join12(tmp, ".letra", "specs", "smoke-test", "spec.md")))
2105
2972
  status = "PASS";
2106
2973
  rmSync(tmp, { recursive: true });
2107
2974
  } else if (label.includes("letra lint")) {
@@ -2109,23 +2976,23 @@ async function validate(targetPath, options) {
2109
2976
  status = "PASS";
2110
2977
  } else if (label.includes("letra validate")) {
2111
2978
  status = "PASS";
2112
- } else if (label.includes("Workflow Ativo") || label.includes("CI") && existsSync11(ciFile)) {
2979
+ } else if (label.includes("Workflow Ativo") || label.includes("CI") && existsSync12(ciFile)) {
2113
2980
  status = "PASS";
2114
2981
  } else if (label.includes("Lint Gate") || label.includes("Lint")) {
2115
- const ciContent = readFileSync9(ciFile, "utf-8");
2982
+ const ciContent = readFileSync10(ciFile, "utf-8");
2116
2983
  if (ciContent.includes("letra lint") || ciContent.includes("lint"))
2117
2984
  status = "PASS";
2118
2985
  } else if (label.includes("Test Gate") || label.includes("Test")) {
2119
- const ciContent = readFileSync9(ciFile, "utf-8");
2986
+ const ciContent = readFileSync10(ciFile, "utf-8");
2120
2987
  if (ciContent.includes("npm test") || ciContent.includes("vitest") || ciContent.includes("test"))
2121
2988
  status = "PASS";
2122
2989
  } else if (label.includes("Valida\xE7\xE3o de Formato") || label.includes("Formato")) {
2123
- const ciContent = readFileSync9(ciFile, "utf-8");
2990
+ const ciContent = readFileSync10(ciFile, "utf-8");
2124
2991
  if (ciContent.includes("tsc") || ciContent.includes("typecheck"))
2125
2992
  status = "PASS";
2126
2993
  } else if (label.includes("Distribui\xE7\xE3o npm") || label.includes("npm")) {
2127
2994
  const pkgJson = JSON.parse(
2128
- readFileSync9(join11(root, "package.json"), "utf-8")
2995
+ readFileSync10(join12(root, "package.json"), "utf-8")
2129
2996
  );
2130
2997
  if (pkgJson.bin && pkgJson.name) {
2131
2998
  status = "PASS";
@@ -2137,50 +3004,47 @@ async function validate(targetPath, options) {
2137
3004
  status = "PASS";
2138
3005
  note = "(npm distribution preferred)";
2139
3006
  } else if (label.includes("Gera\xE7\xE3o de Regras") || label.includes("Gera\xE7\xE3o")) {
2140
- if (existsSync11(cursorRulesFile)) {
2141
- const rulesContent = readFileSync9(cursorRulesFile, "utf-8");
3007
+ if (existsSync12(cursorRulesFile)) {
3008
+ const rulesContent = readFileSync10(cursorRulesFile, "utf-8");
2142
3009
  if (rulesContent.includes(".letra/context.md") && rulesContent.includes(".letra/constitution.md")) {
2143
3010
  status = "PASS";
2144
3011
  }
2145
3012
  }
2146
3013
  } else if (label.includes("Inje\xE7\xE3o de Contexto")) {
2147
- if (existsSync11(cursorRulesFile)) {
2148
- const rulesContent = readFileSync9(cursorRulesFile, "utf-8");
3014
+ if (existsSync12(cursorRulesFile)) {
3015
+ const rulesContent = readFileSync10(cursorRulesFile, "utf-8");
2149
3016
  if (rulesContent.includes("@.letra/")) status = "PASS";
2150
- } else if (existsSync11(copilotFile)) {
2151
- const copilotContent = readFileSync9(copilotFile, "utf-8");
3017
+ } else if (existsSync12(copilotFile)) {
3018
+ const copilotContent = readFileSync10(copilotFile, "utf-8");
2152
3019
  if (copilotContent.includes(".letra/")) status = "PASS";
2153
3020
  }
2154
3021
  } else if (label.includes("Acesso a Valida\xE7\xE3o")) {
2155
- if (existsSync11(cursorRulesFile)) {
2156
- const rulesContent = readFileSync9(cursorRulesFile, "utf-8");
3022
+ if (existsSync12(cursorRulesFile)) {
3023
+ const rulesContent = readFileSync10(cursorRulesFile, "utf-8");
2157
3024
  if (rulesContent.includes("letra validate")) status = "PASS";
2158
3025
  }
2159
3026
  } else if (label.includes("N\xE3o-intrusivo")) {
2160
- if (existsSync11(cursorRulesFile) || existsSync11(copilotFile)) {
3027
+ if (existsSync12(cursorRulesFile) || existsSync12(copilotFile)) {
2161
3028
  status = "PASS";
2162
3029
  }
2163
3030
  } else if (label.includes("Gera\xE7\xE3o de Instru\xE7\xF5es")) {
2164
- if (existsSync11(copilotFile)) {
2165
- const copilotContent = readFileSync9(copilotFile, "utf-8");
3031
+ if (existsSync12(copilotFile)) {
3032
+ const copilotContent = readFileSync10(copilotFile, "utf-8");
2166
3033
  if (copilotContent.includes(".letra/context.md") && copilotContent.includes(".letra/constitution.md")) {
2167
3034
  status = "PASS";
2168
3035
  }
2169
3036
  }
2170
3037
  } else if (label.includes("Settings do Editor")) {
2171
- if (existsSync11(vscodeSettingsFile)) {
2172
- const settingsContent = readFileSync9(
2173
- vscodeSettingsFile,
2174
- "utf-8"
2175
- );
3038
+ if (existsSync12(vscodeSettingsFile)) {
3039
+ const settingsContent = readFileSync10(vscodeSettingsFile, "utf-8");
2176
3040
  if (settingsContent.includes("editor.formatOnSave")) {
2177
3041
  status = "PASS";
2178
3042
  }
2179
3043
  }
2180
3044
  } else if (label.includes("Arquivo de Config")) {
2181
- const configFile = join11(root, ".letra", "config.json");
2182
- if (existsSync11(configFile)) {
2183
- const cfgContent = readFileSync9(configFile, "utf-8");
3045
+ const configFile = join12(root, ".letra", "config.json");
3046
+ if (existsSync12(configFile)) {
3047
+ const cfgContent = readFileSync10(configFile, "utf-8");
2184
3048
  try {
2185
3049
  const parsed = JSON.parse(cfgContent);
2186
3050
  if (parsed.heuristics) {
@@ -2207,14 +3071,7 @@ async function validate(targetPath, options) {
2207
3071
  note = `(error: ${err.message?.split("\n")[0] || "unknown"})`;
2208
3072
  }
2209
3073
  if (status === "PASS") {
2210
- collectResult(
2211
- allResults,
2212
- "pass",
2213
- entry.name,
2214
- label,
2215
- description,
2216
- note
2217
- );
3074
+ collectResult(allResults, "pass", entry.name, label, description, note);
2218
3075
  totalPass++;
2219
3076
  specPass++;
2220
3077
  } else if (intelligenceResult) {
@@ -2231,37 +3088,16 @@ async function validate(targetPath, options) {
2231
3088
  totalWarning++;
2232
3089
  specWarning++;
2233
3090
  } else {
2234
- collectResult(
2235
- allResults,
2236
- "fail",
2237
- entry.name,
2238
- label,
2239
- description,
2240
- note
2241
- );
3091
+ collectResult(allResults, "fail", entry.name, label, description, note);
2242
3092
  totalFail++;
2243
3093
  specFail++;
2244
3094
  }
2245
3095
  } else if (note.includes("manual check needed")) {
2246
- collectResult(
2247
- allResults,
2248
- "warning",
2249
- entry.name,
2250
- label,
2251
- description,
2252
- note
2253
- );
3096
+ collectResult(allResults, "warning", entry.name, label, description, note);
2254
3097
  totalWarning++;
2255
3098
  specWarning++;
2256
3099
  } else {
2257
- collectResult(
2258
- allResults,
2259
- "fail",
2260
- entry.name,
2261
- label,
2262
- description,
2263
- note
2264
- );
3100
+ collectResult(allResults, "fail", entry.name, label, description, note);
2265
3101
  totalFail++;
2266
3102
  specFail++;
2267
3103
  }
@@ -2368,14 +3204,7 @@ async function validate(targetPath, options) {
2368
3204
  for (const cr of conflictResults) {
2369
3205
  if (cr.passed) continue;
2370
3206
  const level = conflictCfg.severity === "warning" ? "warning" : "fail";
2371
- collectResult(
2372
- allResults,
2373
- level,
2374
- "(cross-spec)",
2375
- cr.label,
2376
- cr.message,
2377
- ""
2378
- );
3207
+ collectResult(allResults, level, "(cross-spec)", cr.label, cr.message, "");
2379
3208
  if (level === "warning") {
2380
3209
  totalWarning++;
2381
3210
  } else {
@@ -2388,27 +3217,20 @@ async function validate(targetPath, options) {
2388
3217
  out(fmt, r.level, r.spec, r.label, r.message, r.note);
2389
3218
  }
2390
3219
  }
2391
- flushResults(
2392
- allResults,
2393
- fmt,
2394
- specGroups,
2395
- totalPass,
2396
- totalFail,
2397
- totalWarning
2398
- );
3220
+ flushResults(allResults, fmt, specGroups, totalPass, totalFail, totalWarning);
2399
3221
  return totalFail;
2400
3222
  }
2401
3223
  const exitCode = await runValidation();
2402
3224
  if (options?.watch) {
2403
3225
  let timer = null;
2404
- console.log(chalk13.gray("\nWatching for changes... (Ctrl+C to stop)"));
2405
- const watcher = watch(specsDir, { recursive: true });
3226
+ console.log(chalk14.gray("\nWatching for changes... (Ctrl+C to stop)"));
3227
+ const watcher = watch2(specsDir, { recursive: true });
2406
3228
  watcher.on("change", () => {
2407
3229
  if (timer) clearTimeout(timer);
2408
3230
  timer = setTimeout(async () => {
2409
3231
  console.clear();
2410
3232
  const code = await runValidation();
2411
- console.log(chalk13.gray("\nWatching for changes... (Ctrl+C to stop)"));
3233
+ console.log(chalk14.gray("\nWatching for changes... (Ctrl+C to stop)"));
2412
3234
  }, 300);
2413
3235
  });
2414
3236
  process.on("SIGINT", () => {
@@ -2427,17 +3249,13 @@ async function validate(targetPath, options) {
2427
3249
  }
2428
3250
 
2429
3251
  // src/index.ts
2430
- var __dirname2 = fileURLToPath2(new URL(".", import.meta.url));
2431
- var pkg = JSON.parse(
2432
- readFileSync10(join12(resolve14(__dirname2, ".."), "package.json"), "utf-8")
2433
- );
3252
+ var __dirname2 = fileURLToPath3(new URL(".", import.meta.url));
3253
+ var pkg = JSON.parse(readFileSync11(join13(resolve16(__dirname2, ".."), "package.json"), "utf-8"));
2434
3254
  var program = new Command4();
2435
3255
  program.name("letra").description("SDD-agnostic memory framework for AI coding agents").version(pkg.version);
2436
- program.command("init [path]").option("--yes", "Skip prompts and use defaults").description("Initialize .letra/ directory with templates").action((path, options) => init(path, { ...options }));
2437
- program.command("spec <name>").option(
2438
- "--template <type>",
2439
- "Template type: web-api, cli-tool, mobile-feature"
2440
- ).description("Create a new spec from template").action((name, options) => specNew(name, { ...options }));
3256
+ 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 }));
3257
+ var specCmd = program.command("spec").description("Manage specs");
3258
+ 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 }));
2441
3259
  program.command("lint [path]").description("Validate spec format and completeness").action(lint);
2442
3260
  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 }));
2443
3261
  program.addCommand(decisionCommand());