@letra-ai/cli 0.1.14 → 0.3.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 (30) hide show
  1. package/.letra/brand/logo-01-terminal.svg +6 -0
  2. package/.letra/brand/logo-02-bookmark.svg +6 -0
  3. package/.letra/brand/logo-03-diamond.svg +7 -0
  4. package/.letra/decisions/flow-mvp-escopo-enxuto-3-comandos-valor-imediato.md +35 -0
  5. package/.letra/glossary.md +5 -0
  6. package/.letra/specs/adapter-claude-code/acceptance.md +6 -0
  7. package/.letra/specs/adapter-claude-code/spec.md +4 -4
  8. package/.letra/specs/adapter-codex-cli/acceptance.md +6 -0
  9. package/.letra/specs/adapter-cursor/acceptance.md +4 -4
  10. package/.letra/specs/adapter-vscode/acceptance.md +4 -4
  11. package/.letra/specs/adapter-windsurf/acceptance.md +6 -0
  12. package/.letra/specs/adapter-windsurf/spec.md +4 -4
  13. package/.letra/specs/ci-cd-pipeline/acceptance.md +4 -4
  14. package/.letra/specs/ci-cd-pipeline/spec.md +5 -2
  15. package/.letra/specs/cli-skeleton/acceptance.md +5 -5
  16. package/.letra/specs/flow-edit-diff/acceptance.md +7 -0
  17. package/.letra/specs/flow-edit-diff/spec.md +30 -0
  18. package/.letra/specs/flow-export-import/acceptance.md +7 -0
  19. package/.letra/specs/flow-export-import/spec.md +27 -0
  20. package/.letra/specs/flow-mvp/roadmap.md +40 -0
  21. package/.letra/specs/flow-mvp/spec.md +40 -0
  22. package/.letra/specs/flow-serve/spec.md +47 -0
  23. package/.letra/specs/flow-visualize/acceptance.md +7 -0
  24. package/.letra/specs/flow-visualize/spec.md +28 -0
  25. package/.letra/specs/validate-config/acceptance.md +9 -0
  26. package/.letra/specs/validate-intelligence/acceptance.md +3 -0
  27. package/.letra/workflow.json +47 -0
  28. package/README.md +42 -0
  29. package/dist/index.js +1514 -209
  30. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/index.ts
4
- import { readFileSync as readFileSync7 } from "fs";
5
- import { join as join8, resolve as resolve7 } from "path";
4
+ import { readFileSync as readFileSync11 } from "fs";
5
+ import { join as join13, resolve as resolve15 } from "path";
6
6
  import { fileURLToPath as fileURLToPath2 } from "url";
7
- import { Command as Command3 } from "commander";
7
+ import { Command as Command4 } from "commander";
8
8
 
9
9
  // src/commands/decision.ts
10
10
  import {
@@ -88,36 +88,1341 @@ What are the trade-offs? What does this enable or prevent?
88
88
  return cmd;
89
89
  }
90
90
 
91
- // src/commands/focus.ts
92
- import { existsSync as existsSync2, readFileSync as readFileSync2, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
91
+ // src/commands/flow.ts
92
+ import { Command as Command2 } from "commander";
93
+
94
+ // src/commands/flow-backlog.ts
95
+ import { resolve as resolve3 } from "path";
96
+ import chalk3 from "chalk";
97
+
98
+ // src/commands/flow-init.ts
99
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
93
100
  import { join as join2, resolve as resolve2 } from "path";
101
+ import { createInterface } from "readline";
94
102
  import chalk2 from "chalk";
95
- import { Command as Command2 } from "commander";
103
+ import ora from "ora";
104
+ function askText(query, defaultValue) {
105
+ if (!process.stdin.isTTY) return Promise.resolve(defaultValue);
106
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
107
+ return new Promise((resolve16) => {
108
+ const formatted = `${chalk2.cyan(query)} ${chalk2.gray(`(default: ${defaultValue})`)}
109
+ > `;
110
+ rl.question(formatted, (answer) => {
111
+ rl.close();
112
+ resolve16(answer.trim() || defaultValue);
113
+ });
114
+ });
115
+ }
116
+ function detectExistingTools(root) {
117
+ const tools = [];
118
+ if (existsSync2(join2(root, ".cursorrules"))) tools.push("cursor");
119
+ if (existsSync2(join2(root, "CLAUDE.md"))) tools.push("claude-code");
120
+ if (existsSync2(join2(root, ".windsurfrules"))) tools.push("windsurf");
121
+ if (existsSync2(join2(root, "AGENTS.md"))) tools.push("opencode");
122
+ if (existsSync2(join2(root, ".github", "copilot-instructions.md")))
123
+ tools.push("vscode");
124
+ return tools;
125
+ }
126
+ function detectProjectName(root) {
127
+ const pkgPath = join2(root, "package.json");
128
+ if (existsSync2(pkgPath)) {
129
+ try {
130
+ const pkg2 = JSON.parse(readFileSync2(pkgPath, "utf-8"));
131
+ if (pkg2.name) return pkg2.name.replace(/^@[^/]+\//, "");
132
+ } catch {
133
+ }
134
+ }
135
+ return resolve2(root).split(/[\\/]/).pop() || "meu-projeto";
136
+ }
137
+ function stagesFromInput(input) {
138
+ return input.split(",").map((s, i) => {
139
+ const trimmed = s.trim();
140
+ if (!trimmed) return null;
141
+ return {
142
+ id: trimmed.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, ""),
143
+ name: trimmed.charAt(0).toUpperCase() + trimmed.slice(1),
144
+ order: i
145
+ };
146
+ }).filter((s) => s !== null);
147
+ }
148
+ function now() {
149
+ return (/* @__PURE__ */ new Date()).toISOString();
150
+ }
151
+ function workflowFilePath(root) {
152
+ return join2(root, ".letra", "workflow.json");
153
+ }
154
+ function loadWorkflow(root) {
155
+ const filePath = workflowFilePath(root);
156
+ if (!existsSync2(filePath)) return null;
157
+ try {
158
+ return JSON.parse(readFileSync2(filePath, "utf-8"));
159
+ } catch {
160
+ return null;
161
+ }
162
+ }
163
+ function saveWorkflow(root, workflow) {
164
+ const dir = join2(root, ".letra");
165
+ if (!existsSync2(dir)) mkdirSync2(dir, { recursive: true });
166
+ writeFileSync2(workflowFilePath(root), JSON.stringify(workflow, null, 2));
167
+ }
168
+ async function flowInit(root, options) {
169
+ if (!process.stdin.isTTY && !options?.quick) {
170
+ console.log(
171
+ chalk2.yellow("Non-TTY: usando defaults. Passe --quick para confirmar.")
172
+ );
173
+ return flowInitQuick(root);
174
+ }
175
+ if (options?.quick) {
176
+ return flowInitQuick(root);
177
+ }
178
+ const name = await askText("Workflow name?", detectProjectName(root));
179
+ const stagesInput = await askText(
180
+ "Stages (comma-separated)?",
181
+ "backlog, design, code, review, done"
182
+ );
183
+ const stages = stagesFromInput(stagesInput);
184
+ const detected = detectExistingTools(root);
185
+ const defaultTools = detected.length > 0 ? detected.join(", ") : "cursor, opencode";
186
+ const toolsInput = await askText("Tools (comma-separated)?", defaultTools);
187
+ const tools = toolsInput.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
188
+ const workflow = {
189
+ version: "1.0",
190
+ name,
191
+ createdAt: now(),
192
+ updatedAt: now(),
193
+ stages,
194
+ items: [],
195
+ tools
196
+ };
197
+ return workflow;
198
+ }
199
+ async function flowInitQuick(root) {
200
+ const defaultName = detectProjectName(root);
201
+ const defaultStagesList = "backlog, design, code, review, done";
202
+ const detected = detectExistingTools(root);
203
+ const defaultTools = detected.length > 0 ? detected.join(", ") : "cursor, opencode";
204
+ const name = await askText("Workflow name?", defaultName);
205
+ const stagesInput = await askText(
206
+ "Stages (comma-separated)?",
207
+ defaultStagesList
208
+ );
209
+ const stages = stagesFromInput(stagesInput);
210
+ const toolsInput = await askText("Tools (comma-separated)?", defaultTools);
211
+ const tools = toolsInput.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
212
+ const workflow = {
213
+ version: "1.0",
214
+ name,
215
+ createdAt: now(),
216
+ updatedAt: now(),
217
+ stages,
218
+ items: [],
219
+ tools
220
+ };
221
+ return workflow;
222
+ }
223
+ async function flowInitAction(targetPath, options) {
224
+ const root = resolve2(process.cwd(), targetPath || ".");
225
+ const filePath = workflowFilePath(root);
226
+ if (existsSync2(filePath)) {
227
+ console.log(
228
+ chalk2.yellow("Workflow already exists at .letra/workflow.json")
229
+ );
230
+ return;
231
+ }
232
+ const spinner = ora("Setting up workflow...").start();
233
+ try {
234
+ spinner.stop();
235
+ const workflow = await flowInit(root, options);
236
+ spinner.start();
237
+ saveWorkflow(root, workflow);
238
+ spinner.succeed(chalk2.green("Workflow created at .letra/workflow.json"));
239
+ console.log("");
240
+ console.log(` Name: ${chalk2.cyan(workflow.name)}`);
241
+ console.log(
242
+ ` Stages: ${chalk2.cyan(workflow.stages.map((s) => s.name).join(" \u2192 "))}`
243
+ );
244
+ console.log(` Tools: ${chalk2.cyan(workflow.tools.join(", "))}`);
245
+ console.log("");
246
+ console.log(" Next steps:");
247
+ console.log(
248
+ ` ${chalk2.cyan("letra flow backlog add <desc>")} Add items to your backlog`
249
+ );
250
+ console.log(
251
+ ` ${chalk2.cyan("letra flow board")} View your board`
252
+ );
253
+ } catch (error) {
254
+ spinner.fail(chalk2.red("Failed to create workflow"));
255
+ process.exit(1);
256
+ }
257
+ }
258
+
259
+ // src/commands/flow-backlog.ts
260
+ function now2() {
261
+ return (/* @__PURE__ */ new Date()).toISOString();
262
+ }
263
+ function nextItemId(workflow) {
264
+ let max = 0;
265
+ for (const item of workflow.items) {
266
+ const match = item.id.match(/^ITEM-(\d+)$/);
267
+ if (match) {
268
+ const num = Number.parseInt(match[1], 10);
269
+ if (num > max) max = num;
270
+ }
271
+ }
272
+ return `ITEM-${max + 1}`;
273
+ }
274
+ function workflowExists(root) {
275
+ return loadWorkflow(root);
276
+ }
277
+ function backlogAdd(root, description) {
278
+ if (!description) {
279
+ console.log(chalk3.red("Description is required"));
280
+ process.exit(1);
281
+ }
282
+ const workflow = workflowExists(root);
283
+ if (!workflow) {
284
+ console.log(
285
+ chalk3.red("No workflow found. Run 'letra flow init --quick' first")
286
+ );
287
+ process.exit(1);
288
+ }
289
+ if (workflow.stages.length === 0) {
290
+ console.log(chalk3.red("Workflow has no stages defined"));
291
+ process.exit(1);
292
+ }
293
+ const firstStage = workflow.stages[0].id;
294
+ const item = {
295
+ id: nextItemId(workflow),
296
+ description,
297
+ stage: firstStage,
298
+ createdAt: now2()
299
+ };
300
+ workflow.items.push(item);
301
+ workflow.updatedAt = now2();
302
+ saveWorkflow(root, workflow);
303
+ console.log(
304
+ ` ${chalk3.green("\u2713")} Item ${chalk3.cyan(item.id)} added to ${chalk3.cyan(workflow.stages[0].name)}`
305
+ );
306
+ }
307
+ function backlogList(root) {
308
+ const workflow = workflowExists(root);
309
+ if (!workflow) {
310
+ console.log(
311
+ chalk3.yellow("No workflow found. Run 'letra flow init --quick' first")
312
+ );
313
+ return;
314
+ }
315
+ if (workflow.items.length === 0) {
316
+ console.log(chalk3.yellow("No items in backlog"));
317
+ return;
318
+ }
319
+ const stageNames = new Map(workflow.stages.map((s) => [s.id, s.name]));
320
+ console.log("");
321
+ console.log(
322
+ ` ${chalk3.bold("ID")} ${chalk3.bold("Description".padEnd(30))} ${chalk3.bold("Stage".padEnd(15))} ${chalk3.bold("Age")}`
323
+ );
324
+ console.log(` ${"\u2500".repeat(70)}`);
325
+ for (const item of workflow.items) {
326
+ const stageName2 = stageNames.get(item.stage) || item.stage;
327
+ const created = new Date(item.createdAt);
328
+ const age = Math.floor(
329
+ (Date.now() - created.getTime()) / (1e3 * 60 * 60 * 24)
330
+ );
331
+ const ageStr = age === 0 ? "today" : `${age}d`;
332
+ const desc = item.description.length > 28 ? `${item.description.slice(0, 27)}\u2026` : item.description.padEnd(30);
333
+ console.log(
334
+ ` ${chalk3.cyan(item.id.padEnd(7))} ${desc} ${chalk3.yellow(stageName2.padEnd(15))} ${chalk3.gray(ageStr)}`
335
+ );
336
+ }
337
+ console.log("");
338
+ }
339
+ function backlogActionAdd(targetPath, description) {
340
+ const root = resolve3(process.cwd(), targetPath || ".");
341
+ backlogAdd(root, description);
342
+ }
343
+ function backlogActionList(targetPath) {
344
+ const root = resolve3(process.cwd(), targetPath || ".");
345
+ backlogList(root);
346
+ }
347
+
348
+ // src/commands/flow-board.ts
349
+ import { resolve as resolve4 } from "path";
350
+ import chalk4 from "chalk";
351
+ function ageLabel(createdAt) {
352
+ const created = new Date(createdAt);
353
+ const age = Math.floor(
354
+ (Date.now() - created.getTime()) / (1e3 * 60 * 60 * 24)
355
+ );
356
+ return age === 0 ? "today" : `${age}d`;
357
+ }
358
+ function flowBoard(root) {
359
+ const workflow = loadWorkflow(root);
360
+ if (!workflow) {
361
+ console.log(
362
+ chalk4.yellow("No workflow found. Run 'letra flow init --quick' first")
363
+ );
364
+ return;
365
+ }
366
+ console.log(`
367
+ ${chalk4.bold("Board")} \u2014 ${chalk4.cyan(workflow.name)}
368
+ `);
369
+ const stageMap = new Map(workflow.stages.map((s) => [s.id, s]));
370
+ const itemsByStage = /* @__PURE__ */ new Map();
371
+ for (const stage of workflow.stages) {
372
+ itemsByStage.set(stage.id, []);
373
+ }
374
+ for (const item of workflow.items) {
375
+ const list = itemsByStage.get(item.stage);
376
+ if (list) list.push(item);
377
+ }
378
+ for (const stage of workflow.stages) {
379
+ const items = itemsByStage.get(stage.id) || [];
380
+ const count = items.length;
381
+ const countLabel = count === 0 ? chalk4.gray("(empty)") : count === 1 ? chalk4.white(`${count} item`) : chalk4.white(`${count} items`);
382
+ console.log(` ${chalk4.bold(stage.name)} ${countLabel}`);
383
+ for (const item of items) {
384
+ const desc = item.description.length > 50 ? `${item.description.slice(0, 49)}\u2026` : item.description;
385
+ console.log(
386
+ ` ${chalk4.cyan(item.id.padEnd(7))} ${desc} ${chalk4.gray(ageLabel(item.createdAt))}`
387
+ );
388
+ }
389
+ if (items.length > 0) console.log("");
390
+ }
391
+ }
392
+ function flowBoardAction(targetPath) {
393
+ const root = resolve4(process.cwd(), targetPath || ".");
394
+ flowBoard(root);
395
+ }
396
+
397
+ // src/commands/flow-edit-diff.ts
398
+ import { existsSync as existsSync3, readFileSync as readFileSync3, readdirSync as readdirSync2, writeFileSync as writeFileSync3 } from "fs";
399
+ import { join as join3, resolve as resolve5 } from "path";
400
+ import chalk5 from "chalk";
401
+ function now3() {
402
+ return (/* @__PURE__ */ new Date()).toISOString();
403
+ }
404
+ function normalizeVersion(v) {
405
+ const parts = v.split(".");
406
+ if (parts.length === 2) return `${v}.0`;
407
+ return v;
408
+ }
409
+ function incrementVersion(v) {
410
+ const parts = normalizeVersion(v).split(".").map(Number);
411
+ parts[1] += 1;
412
+ parts[2] = 0;
413
+ return parts.join(".");
414
+ }
415
+ function loadBackup(root, version) {
416
+ const path = join3(root, ".letra", `workflow.v${version}.json`);
417
+ if (!existsSync3(path)) return null;
418
+ try {
419
+ return JSON.parse(readFileSync3(path, "utf-8"));
420
+ } catch {
421
+ return null;
422
+ }
423
+ }
424
+ function loadVersion(root, version) {
425
+ const backup = loadBackup(root, version);
426
+ if (backup) return backup;
427
+ const current = loadWorkflow(root);
428
+ if (current && normalizeVersion(current.version) === version) return current;
429
+ return null;
430
+ }
431
+ function getLatestBackupVersion(root) {
432
+ const dir = join3(root, ".letra");
433
+ if (!existsSync3(dir)) return null;
434
+ const files = readdirSync2(dir).filter(
435
+ (f) => f.startsWith("workflow.v") && f.endsWith(".json")
436
+ );
437
+ if (files.length === 0) return null;
438
+ const versions = files.map(
439
+ (f) => f.replace("workflow.v", "").replace(".json", "")
440
+ );
441
+ versions.sort((a, b) => {
442
+ const pa = a.split(".").map(Number);
443
+ const pb = b.split(".").map(Number);
444
+ for (let i = 0; i < 3; i++) {
445
+ if ((pa[i] || 0) !== (pb[i] || 0)) return (pa[i] || 0) - (pb[i] || 0);
446
+ }
447
+ return 0;
448
+ });
449
+ return versions[versions.length - 1];
450
+ }
451
+ function backupFilePath(root, version) {
452
+ return join3(root, ".letra", `workflow.v${version}.json`);
453
+ }
454
+ function flowEdit(root, options) {
455
+ const workflow = loadWorkflow(root);
456
+ if (!workflow) {
457
+ console.log(
458
+ chalk5.yellow("No workflow found. Run 'letra flow init --quick' first")
459
+ );
460
+ return;
461
+ }
462
+ const currentVersion = normalizeVersion(workflow.version);
463
+ const backupPath = backupFilePath(root, currentVersion);
464
+ if (!existsSync3(backupPath)) {
465
+ writeFileSync3(backupPath, JSON.stringify(workflow, null, 2));
466
+ }
467
+ if (options.name !== void 0) {
468
+ workflow.name = options.name;
469
+ }
470
+ if (options.desc !== void 0) {
471
+ workflow.description = options.desc;
472
+ }
473
+ workflow.version = incrementVersion(workflow.version);
474
+ workflow.updatedAt = now3();
475
+ saveWorkflow(root, workflow);
476
+ console.log(` ${chalk5.green("\u2713")} Workflow updated to v${workflow.version}`);
477
+ if (options.name !== void 0) {
478
+ console.log(` Name: ${chalk5.cyan(options.name)}`);
479
+ }
480
+ if (options.desc !== void 0) {
481
+ console.log(` Description: ${chalk5.cyan(options.desc)}`);
482
+ }
483
+ }
484
+ function stageName(workflow, stageId) {
485
+ return workflow.stages.find((s) => s.id === stageId)?.name || stageId;
486
+ }
487
+ function computeDiff(oldWf, newWf) {
488
+ const nameDiff = oldWf.name !== newWf.name ? `"${oldWf.name}" \u2192 "${newWf.name}"` : null;
489
+ const oldStageNames = new Set(oldWf.stages.map((s) => s.name));
490
+ const newStageNames = new Set(newWf.stages.map((s) => s.name));
491
+ const stagesAdded = newWf.stages.filter((s) => !oldStageNames.has(s.name)).map((s) => s.name);
492
+ const stagesRemoved = oldWf.stages.filter((s) => !newStageNames.has(s.name)).map((s) => s.name);
493
+ const oldItemMap = new Map(oldWf.items.map((i) => [i.id, i]));
494
+ const newItemMap = new Map(newWf.items.map((i) => [i.id, i]));
495
+ const itemsNew = [];
496
+ const itemsMoved = [];
497
+ const itemsRemoved = [];
498
+ for (const [id, item] of newItemMap) {
499
+ if (!oldItemMap.has(id)) {
500
+ itemsNew.push({ id, stage: stageName(newWf, item.stage) });
501
+ } else {
502
+ const oldItem = oldItemMap.get(id);
503
+ if (oldItem && oldItem.stage !== item.stage) {
504
+ itemsMoved.push({
505
+ id,
506
+ from: stageName(oldWf, oldItem.stage),
507
+ to: stageName(newWf, item.stage)
508
+ });
509
+ }
510
+ }
511
+ }
512
+ for (const [id, item] of oldItemMap) {
513
+ if (!newItemMap.has(id)) {
514
+ itemsRemoved.push({ id, stage: stageName(oldWf, item.stage) });
515
+ }
516
+ }
517
+ return {
518
+ name: nameDiff,
519
+ stagesAdded,
520
+ stagesRemoved,
521
+ itemsNew,
522
+ itemsMoved,
523
+ itemsRemoved
524
+ };
525
+ }
526
+ function formatDiff(wfName, diff) {
527
+ const lines = [];
528
+ lines.push(`Workflow: ${wfName}`);
529
+ if (diff.name) {
530
+ lines.push(` Name: ${diff.name}`);
531
+ }
532
+ if (diff.stagesAdded.length > 0 || diff.stagesRemoved.length > 0) {
533
+ const parts = [];
534
+ for (const s of diff.stagesAdded) parts.push(`+${s}`);
535
+ for (const s of diff.stagesRemoved) parts.push(`-${s}`);
536
+ lines.push(` Stages: ${parts.join(", ")}`);
537
+ }
538
+ const itemParts = [];
539
+ for (const item of diff.itemsNew) {
540
+ itemParts.push(`+${item.id} (${item.stage})`);
541
+ }
542
+ for (const item of diff.itemsMoved) {
543
+ itemParts.push(`${item.id} moved: ${item.from} \u2192 ${item.to}`);
544
+ }
545
+ for (const item of diff.itemsRemoved) {
546
+ itemParts.push(`-${item.id} (${item.stage})`);
547
+ }
548
+ if (itemParts.length > 0) {
549
+ lines.push(` Items: ${itemParts.join(", ")}`);
550
+ }
551
+ return lines;
552
+ }
553
+ function stripVPrefix(v) {
554
+ return v.replace(/^v/, "");
555
+ }
556
+ function flowDiff(root, v1, v2) {
557
+ const current = loadWorkflow(root);
558
+ if (!current) {
559
+ console.log(chalk5.yellow("No workflow found"));
560
+ return;
561
+ }
562
+ if (v1 && v2) {
563
+ const wf1 = loadVersion(root, stripVPrefix(v1));
564
+ const wf2 = loadVersion(root, stripVPrefix(v2));
565
+ if (!wf1 && !wf2) {
566
+ console.log(
567
+ chalk5.yellow(`No backups found for versions ${v1} and ${v2}`)
568
+ );
569
+ return;
570
+ }
571
+ if (!wf1) {
572
+ console.log(chalk5.yellow(`No backup found for version ${v1}`));
573
+ return;
574
+ }
575
+ if (!wf2) {
576
+ console.log(chalk5.yellow(`No backup found for version ${v2}`));
577
+ return;
578
+ }
579
+ const diff = computeDiff(wf1, wf2);
580
+ const lines = formatDiff(wf2.name, diff);
581
+ for (const line of lines) console.log(line);
582
+ } else {
583
+ const latestVersion = getLatestBackupVersion(root);
584
+ if (!latestVersion) {
585
+ console.log(chalk5.yellow("No backup versions found to compare"));
586
+ return;
587
+ }
588
+ const backup = loadBackup(root, latestVersion);
589
+ if (!backup) {
590
+ console.log(
591
+ chalk5.yellow(`Failed to load backup version ${latestVersion}`)
592
+ );
593
+ return;
594
+ }
595
+ const diff = computeDiff(backup, current);
596
+ const lines = formatDiff(current.name, diff);
597
+ for (const line of lines) console.log(line);
598
+ }
599
+ }
600
+ function flowEditAction(targetPath, options) {
601
+ const root = resolve5(process.cwd(), targetPath || ".");
602
+ flowEdit(root, options);
603
+ }
604
+ function flowDiffAction(targetPath, v1, v2) {
605
+ const root = resolve5(process.cwd(), targetPath || ".");
606
+ flowDiff(root, v1, v2);
607
+ }
608
+
609
+ // src/commands/flow-export-import.ts
610
+ import { existsSync as existsSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync4 } from "fs";
611
+ import { join as join4, resolve as resolve6 } from "path";
612
+ import chalk6 from "chalk";
613
+ function flowExport(root, options) {
614
+ const workflow = loadWorkflow(root);
615
+ if (!workflow) {
616
+ console.log(chalk6.yellow("No workflow found"));
617
+ return;
618
+ }
619
+ const json = JSON.stringify(workflow, null, options?.minified ? 0 : 2);
620
+ console.log(json);
621
+ }
622
+ function flowExportAction(targetPath, options) {
623
+ const root = resolve6(process.cwd(), targetPath || ".");
624
+ flowExport(root, options);
625
+ }
626
+ function now4() {
627
+ return (/* @__PURE__ */ new Date()).toISOString();
628
+ }
629
+ function flowImport(root, filePath) {
630
+ if (!existsSync4(filePath)) {
631
+ console.log(chalk6.red(`File not found: ${filePath}`));
632
+ process.exit(1);
633
+ }
634
+ let parsed;
635
+ try {
636
+ const content = readFileSync4(filePath, "utf-8");
637
+ parsed = JSON.parse(content);
638
+ } catch {
639
+ console.log(chalk6.red("Invalid JSON file"));
640
+ process.exit(1);
641
+ }
642
+ const obj = parsed;
643
+ if (!obj.name || typeof obj.name !== "string" || !obj.name.trim()) {
644
+ console.log(chalk6.red("Missing required field: name (non-empty string)"));
645
+ process.exit(1);
646
+ }
647
+ if (!obj.stages || !Array.isArray(obj.stages) || obj.stages.length === 0) {
648
+ console.log(chalk6.red("Missing required field: stages (non-empty array)"));
649
+ process.exit(1);
650
+ }
651
+ const imported = parsed;
652
+ const existingWorkflow = loadWorkflow(root);
653
+ if (existingWorkflow) {
654
+ const backup = join4(
655
+ root,
656
+ ".letra",
657
+ `workflow.v${existingWorkflow.version}.json`
658
+ );
659
+ if (!existsSync4(backup)) {
660
+ writeFileSync4(backup, JSON.stringify(existingWorkflow, null, 2));
661
+ console.log(
662
+ chalk6.gray(
663
+ `Backup saved: .letra/workflow.v${existingWorkflow.version}.json`
664
+ )
665
+ );
666
+ }
667
+ }
668
+ imported.createdAt = now4();
669
+ imported.updatedAt = now4();
670
+ saveWorkflow(root, imported);
671
+ console.log(
672
+ chalk6.green(`Workflow imported: ${imported.name} (${imported.version})`)
673
+ );
674
+ }
675
+ function flowImportAction(targetPath, filePath) {
676
+ const root = resolve6(process.cwd(), targetPath || ".");
677
+ flowImport(root, filePath);
678
+ }
679
+
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";
683
+ import chalk7 from "chalk";
684
+ function now5() {
685
+ return (/* @__PURE__ */ new Date()).toISOString();
686
+ }
687
+ function resolveStage(workflow, input) {
688
+ const lower = input.toLowerCase();
689
+ for (const stage of workflow.stages) {
690
+ if (stage.id === lower) return stage.id;
691
+ if (stage.name.toLowerCase() === lower) return stage.id;
692
+ }
693
+ return null;
694
+ }
695
+ function adapterContent(workflowName, currentStageName, items, stageNames) {
696
+ const stageItems = items.filter(
697
+ (item) => item.stage === currentStageName.toLowerCase().replace(/[^a-z0-9]+/g, "-") || stageNames.get(item.stage) === currentStageName
698
+ );
699
+ const itemsBlock = stageItems.length > 0 ? stageItems.map((item) => `- ${item.id}: ${item.description}`).join("\n") : "(nenhum item ativo neste estagio)";
700
+ return `# Letra Context \u2014 ${workflowName}
701
+
702
+ ## Workflow
703
+
704
+ **Estagio atual:** ${currentStageName}
705
+
706
+ ### Itens neste estagio
707
+
708
+ ${itemsBlock}
709
+
710
+ ### Regras
711
+
712
+ - Leia as specs em .letra/specs/ antes de codificar
713
+ - Execute \`letra validate\` para verificar acceptance criteria
714
+ - Siga a constitution.md rigorosamente
715
+ - Ao concluir, mova o item com \`letra flow move <id> --to <proximo_estagio>\`
716
+ `;
717
+ }
718
+ function generateAdapters(root, tools, content) {
719
+ const adapters = [];
720
+ const header = `# Gerado por letra flow move. Nao edite manualmente.
721
+ `;
722
+ for (const tool of tools) {
723
+ switch (tool) {
724
+ case "cursor":
725
+ adapters.push({
726
+ path: join5(root, ".cursorrules"),
727
+ content: header + content
728
+ });
729
+ break;
730
+ case "claude-code":
731
+ adapters.push({
732
+ path: join5(root, "CLAUDE.md"),
733
+ content: header + content
734
+ });
735
+ break;
736
+ case "windsurf":
737
+ adapters.push({
738
+ path: join5(root, ".windsurfrules"),
739
+ content: header + content
740
+ });
741
+ break;
742
+ case "vscode": {
743
+ const dir = join5(root, ".github");
744
+ if (!existsSync5(dir)) mkdirSync3(dir, { recursive: true });
745
+ adapters.push({
746
+ path: join5(dir, "copilot-instructions.md"),
747
+ content: header + content
748
+ });
749
+ break;
750
+ }
751
+ case "opencode":
752
+ adapters.push({
753
+ path: join5(root, "AGENTS.md"),
754
+ content: header + content
755
+ });
756
+ break;
757
+ }
758
+ }
759
+ for (const { path, content: fileContent } of adapters) {
760
+ const dir = join5(path, "..");
761
+ if (!existsSync5(dir)) mkdirSync3(dir, { recursive: true });
762
+ writeFileSync5(path, fileContent);
763
+ console.log(` ${chalk7.gray("Updated")} ${path.replace(`${root}/`, "")}`);
764
+ }
765
+ }
766
+ function flowMove(root, itemId, targetStageInput) {
767
+ const workflow = loadWorkflow(root);
768
+ if (!workflow) {
769
+ console.log(
770
+ chalk7.red("No workflow found. Run 'letra flow init --quick' first")
771
+ );
772
+ process.exit(1);
773
+ }
774
+ const item = workflow.items.find((i) => i.id === itemId) || workflow.items.find((i) => i.description === itemId);
775
+ if (!item) {
776
+ console.log(chalk7.red(`Item "${itemId}" not found`));
777
+ process.exit(1);
778
+ }
779
+ const targetStageId = resolveStage(workflow, targetStageInput);
780
+ if (!targetStageId) {
781
+ 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
+ );
787
+ process.exit(1);
788
+ }
789
+ if (item.stage === targetStageId) {
790
+ console.log(
791
+ chalk7.yellow(`Item ${itemId} is already in stage "${targetStageId}"`)
792
+ );
793
+ return;
794
+ }
795
+ const fromStage = workflow.stages.find((s) => s.id === item.stage)?.name || item.stage;
796
+ const toStage = workflow.stages.find((s) => s.id === targetStageId)?.name || targetStageId;
797
+ item.stage = targetStageId;
798
+ workflow.updatedAt = now5();
799
+ saveWorkflow(root, workflow);
800
+ const stageNames = new Map(workflow.stages.map((s) => [s.id, s.name]));
801
+ const currentStageName = stageNames.get(targetStageId) || targetStageId;
802
+ const content = adapterContent(
803
+ workflow.name,
804
+ currentStageName,
805
+ workflow.items,
806
+ stageNames
807
+ );
808
+ generateAdapters(root, workflow.tools, content);
809
+ console.log(
810
+ ` ${chalk7.green("\u2713")} Item ${chalk7.cyan(itemId)} moved: ${chalk7.yellow(fromStage)} \u2192 ${chalk7.green(toStage)}`
811
+ );
812
+ console.log(
813
+ ` ${chalk7.gray("Adapters regenerated for:")} ${workflow.tools.join(", ")}`
814
+ );
815
+ }
816
+ function flowMoveAction(targetPath, itemId, options) {
817
+ const root = resolve7(process.cwd(), targetPath || ".");
818
+ flowMove(root, itemId, options.to);
819
+ }
820
+
821
+ // src/commands/flow-serve.ts
822
+ import {
823
+ existsSync as existsSync6,
824
+ readFileSync as readFileSync5,
825
+ readdirSync as readdirSync3,
826
+ statSync,
827
+ watch
828
+ } from "fs";
829
+ import {
830
+ createServer
831
+ } from "http";
832
+ import { join as join6, resolve as resolve8 } from "path";
833
+ var DEFAULT_PORT = 3e3;
834
+ function loadSpecs(root) {
835
+ const specsDir = join6(root, ".letra", "specs");
836
+ if (!existsSync6(specsDir)) return [];
837
+ return readdirSync3(specsDir).filter((entry) => {
838
+ const specFile = join6(specsDir, entry, "spec.md");
839
+ return statSync(join6(specsDir, entry)).isDirectory() && existsSync6(specFile);
840
+ }).map((entry) => {
841
+ const content = readFileSync5(join6(specsDir, entry, "spec.md"), "utf-8");
842
+ return { name: entry, content };
843
+ });
844
+ }
845
+ function findItemSpec(item, specs) {
846
+ const desc = item.description.toLowerCase();
847
+ return specs.find(
848
+ (s) => desc.includes(s.name.toLowerCase().replace(/-/g, " ")) || desc.includes(s.name.toLowerCase())
849
+ );
850
+ }
851
+ function boardHtml(workflow, specs = []) {
852
+ const stages = workflow?.stages ?? [];
853
+ const items = workflow?.items ?? [];
854
+ const itemsByStage = /* @__PURE__ */ new Map();
855
+ for (const s of stages) itemsByStage.set(s.id, []);
856
+ for (const it of items) {
857
+ const list = itemsByStage.get(it.stage);
858
+ if (list) list.push(it);
859
+ }
860
+ function ageLabel2(createdAt) {
861
+ const age = Math.floor(
862
+ (Date.now() - new Date(createdAt).getTime()) / (1e3 * 60 * 60 * 24)
863
+ );
864
+ if (age === 0) return "today";
865
+ if (age === 1) return "1d ago";
866
+ return `${age}d ago`;
867
+ }
868
+ const stageCards = stages.map((s) => {
869
+ const stageItems = itemsByStage.get(s.id) ?? [];
870
+ const itemsHtml = stageItems.length === 0 ? '<div class="empty">(empty)</div>' : stageItems.map((it) => {
871
+ const spec = findItemSpec(it, specs);
872
+ const specBtn = spec ? `<button class="spec-btn" data-spec="${esc(spec.name)}">spec</button>` : "";
873
+ return `<div class="item stage-${esc(s.id)}"><span class="item-id">${it.id}</span><span class="item-desc">${esc(it.description)}</span><span class="item-bottom">${specBtn}<span class="item-age">${ageLabel2(it.createdAt)}</span></span></div>`;
874
+ }).join("");
875
+ const count = stageItems.length;
876
+ return `<div class="stage stage-${esc(s.id)}"><h2>${esc(s.name)} <span class="count">${count} ${count === 1 ? "item" : "items"}</span></h2><div class="items">${itemsHtml}</div></div>`;
877
+ }).join("\n");
878
+ const name = workflow ? esc(workflow.name) : "No workflow";
879
+ const updatedAt = workflow ? new Date(workflow.updatedAt).toLocaleString() : "-";
880
+ return `<!DOCTYPE html>
881
+ <html lang="en">
882
+ <head>
883
+ <meta charset="UTF-8">
884
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
885
+ <title>${name} \u2014 Flow Board</title>
886
+ <style>
887
+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
888
+ body {
889
+ font-family: system-ui, -apple-system, sans-serif;
890
+ background: #0f1117; color: #e1e4e8;
891
+ padding: 2rem 1rem; max-width: 1200px; margin: 0 auto;
892
+ }
893
+ header {
894
+ display: flex; justify-content: space-between; align-items: center;
895
+ }
896
+ .brand {
897
+ display: flex; align-items: center; gap: 0.625rem;
898
+ }
899
+ .brand svg { width: 36px; height: 36px; flex-shrink: 0; }
900
+ .brand-text { font-weight: 600; font-size: 1rem; color: #e1e4e8; }
901
+ .brand-text span { color: #8b949e; font-weight: 300; }
902
+ .header-status { color: #8b949e; font-size: 0.75rem; }
903
+ .live { color: #3fb950; }
904
+ .live::before { content: "\u25CF"; margin-right: 0.3rem; }
905
+ .project-desc { margin: 15px 0 1.5rem; }
906
+ .project-desc h1 { font-size: 1.4rem; font-weight: 700; margin-bottom: 0.25rem; }
907
+ .project-desc p { color: #8b949e; font-size: 0.9rem; line-height: 1.4; }
908
+ .board-scroll { overflow-x: auto; padding-bottom: 0.5rem; }
909
+ .board { display: flex; gap: 1rem; }
910
+ .stage {
911
+ flex: 0 0 280px; width: 280px;
912
+ background: #161b22; border: 1px solid #30363d; border-top: 3px solid #30363d;
913
+ border-radius: 10px; padding: 1rem; display: flex; flex-direction: column; gap: 0.5rem;
914
+ transition: border-top-color .2s;
915
+ }
916
+ .stage.stage-backlog { border-top-color: #8b949e; }
917
+ .stage.stage-design { border-top-color: #d29922; }
918
+ .stage.stage-code { border-top-color: #58a6ff; }
919
+ .stage.stage-review { border-top-color: #bc8cff; }
920
+ .stage.stage-done { border-top-color: #3fb950; }
921
+ .stage h2 { font-size: 1rem; font-weight: 600; display: flex; justify-content: space-between; align-items: center; }
922
+ .count { font-size: 0.7rem; color: #8b949e; font-weight: 400; background: rgba(139,148,158,0.1); padding: 0.15rem 0.5rem; border-radius: 10px; }
923
+ .items { display: flex; flex-direction: column; gap: 0.5rem; min-height: 2rem; }
924
+ .empty { color: #484f58; font-size: 0.8rem; padding: 0.75rem 0; text-align: center; border: 1px dashed #21262d; border-radius: 6px; }
925
+ .item {
926
+ background: #0f1117; border-radius: 8px; padding: 0.625rem 0.75rem;
927
+ display: flex; flex-direction: column; gap: 0.3rem;
928
+ border-left: 3px solid #30363d; box-shadow: 0 1px 2px rgba(0,0,0,0.2);
929
+ transition: border-color .15s, transform .15s, box-shadow .15s;
930
+ }
931
+ .item:hover { transform: translateY(-1px); box-shadow: 0 3px 8px rgba(0,0,0,0.3); }
932
+ .item.stage-backlog { border-left-color: #8b949e; }
933
+ .item.stage-design { border-left-color: #d29922; }
934
+ .item.stage-code { border-left-color: #58a6ff; }
935
+ .item.stage-review { border-left-color: #bc8cff; }
936
+ .item.stage-done { border-left-color: #3fb950; }
937
+ .item-id {
938
+ font-family: monospace; font-size: 0.65rem; color: #58a6ff; font-weight: 600;
939
+ background: rgba(88,166,255,0.1); padding: 0.1rem 0.4rem; border-radius: 4px;
940
+ display: inline-block; width: fit-content;
941
+ }
942
+ .item-desc { font-size: 0.85rem; color: #e1e4e8; line-height: 1.35; margin-top: 0.1rem; }
943
+ .item-bottom { display: flex; justify-content: space-between; align-items: center; margin-top: 0.2rem; }
944
+ .item-age { font-size: 0.65rem; color: #8b949e; }
945
+ .spec-btn {
946
+ background: none; border: 1px solid #30363d; border-radius: 4px;
947
+ color: #8b949e; font-size: 0.6rem; padding: 0.1rem 0.4rem;
948
+ cursor: pointer; font-family: monospace; transition: .15s;
949
+ }
950
+ .spec-btn:hover { border-color: #58a6ff; color: #58a6ff; background: rgba(88,166,255,0.08); }
951
+ .board-fade { animation: fadeIn .3s ease; }
952
+ @keyframes fadeIn { from { opacity: 0.5; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } }
953
+ .modal { position: fixed; inset: 0; z-index: 100; display: flex; align-items: center; justify-content: center; }
954
+ .modal.hidden { display: none; }
955
+ .modal-backdrop { position: absolute; inset: 0; background: rgba(0,0,0,0.7); }
956
+ .modal-content {
957
+ position: relative; background: #161b22; border: 1px solid #30363d;
958
+ border-radius: 12px; max-width: 700px; width: 90%; max-height: 80vh;
959
+ display: flex; flex-direction: column;
960
+ }
961
+ .modal-header {
962
+ display: flex; justify-content: space-between; align-items: center;
963
+ padding: 1rem 1.25rem; border-bottom: 1px solid #30363d;
964
+ }
965
+ .modal-header h2 { font-size: 1rem; font-weight: 600; }
966
+ .modal-close {
967
+ background: none; border: none; color: #8b949e; font-size: 1.5rem;
968
+ cursor: pointer; line-height: 1; padding: 0;
969
+ }
970
+ .modal-close:hover { color: #e1e4e8; }
971
+ .modal-body {
972
+ padding: 1.25rem; overflow-y: auto; font-size: 0.875rem; line-height: 1.6;
973
+ white-space: pre-wrap; font-family: monospace; color: #e1e4e8;
974
+ }
975
+ .modal-body h1, .modal-body h2, .modal-body h3 { font-family: system-ui; margin: 1rem 0 0.5rem; }
976
+ .modal-body h1 { font-size: 1.2rem; }
977
+ .modal-body h2 { font-size: 1rem; color: #58a6ff; }
978
+ .modal-body h3 { font-size: 0.9rem; color: #d29922; }
979
+ .modal-body ul, .modal-body ol { padding-left: 1.5rem; margin: 0.5rem 0; }
980
+ .modal-body li { margin-bottom: 0.25rem; }
981
+ .modal-body code { background: #0f1117; padding: 0.1rem 0.3rem; border-radius: 3px; font-size: 0.8rem; }
982
+ .modal-body pre { background: #0f1117; padding: 0.75rem; border-radius: 6px; overflow-x: auto; margin: 0.5rem 0; }
983
+ .modal-body pre code { background: none; padding: 0; }
984
+ @media (max-width: 600px) {
985
+ .board { grid-template-columns: 1fr; }
986
+ body { padding: 1rem 0.5rem; }
987
+ }
988
+ </style>
989
+ </head>
990
+ <body>
991
+ <header>
992
+ <div class="brand">
993
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40" fill="none">
994
+ <rect width="40" height="40" rx="8" fill="#d29922"/>
995
+ <path d="M20 10l10 14-10 14-10-14L20 10z" fill="#0f1117"/>
996
+ <circle cx="20" cy="24" r="3" fill="#d29922"/>
997
+ </svg>
998
+ <div class="brand-text">letra<span>.dev</span></div>
999
+ </div>
1000
+ <div class="header-status">
1001
+ <span class="live"></span>
1002
+ <span id="status">connected</span>
1003
+ <span>&middot; updated ${updatedAt}</span>
1004
+ </div>
1005
+ </header>
1006
+ <div class="project-desc" id="projectDesc">
1007
+ <h1>${name}</h1>
1008
+ ${workflow?.description ? `<p>${esc(workflow.description)}</p>` : ""}
1009
+ </div>
1010
+ <div class="board-scroll">
1011
+ <div class="board" id="board">
1012
+ ${stageCards}
1013
+ </div>
1014
+ </div>
1015
+ <div id="modal" class="modal hidden">
1016
+ <div class="modal-backdrop" id="modalBackdrop"></div>
1017
+ <div class="modal-content">
1018
+ <div class="modal-header">
1019
+ <h2 id="modalTitle"></h2>
1020
+ <button class="modal-close" id="modalClose">&times;</button>
1021
+ </div>
1022
+ <div class="modal-body" id="modalBody"></div>
1023
+ </div>
1024
+ </div>
1025
+ <script>
1026
+ var __specs = null;
1027
+ fetch("/api/specs").then(r => r.json()).then(s => { __specs = s; attachSpecButtons(); }).catch(() => {});
1028
+ const evtSource = new EventSource("/events");
1029
+ evtSource.addEventListener("workflow-updated", () => {
1030
+ document.getElementById("status").textContent = "refreshing...";
1031
+ fetch("/api/workflow")
1032
+ .then(r => r.json())
1033
+ .then(data => {
1034
+ document.getElementById("status").textContent = "updated " + new Date().toLocaleTimeString();
1035
+ renderBoard(data);
1036
+ })
1037
+ .catch(() => {
1038
+ document.getElementById("status").textContent = "update failed";
1039
+ });
1040
+ });
1041
+ evtSource.onerror = () => {
1042
+ document.getElementById("status").textContent = "disconnected";
1043
+ };
1044
+ function esc(s) {
1045
+ const d = document.createElement("div");
1046
+ d.textContent = s;
1047
+ return d.innerHTML;
1048
+ }
1049
+ function ageLabel(createdAt) {
1050
+ const age = Math.floor((Date.now() - new Date(createdAt).getTime()) / (1000 * 60 * 60 * 24));
1051
+ if (age === 0) return "today";
1052
+ if (age === 1) return "1d ago";
1053
+ return age + "d ago";
1054
+ }
1055
+ function matchSpec(desc, specs) {
1056
+ const lower = desc.toLowerCase();
1057
+ for (const s of specs) {
1058
+ if (lower.includes(s.name.replace(/-/g, " ")) || lower.includes(s.name)) return s.name;
1059
+ }
1060
+ return null;
1061
+ }
1062
+ function renderBoard(wf) {
1063
+ const sorted = (wf.stages || []).sort((a, b) => a.order - b.order);
1064
+ const itemsByStage = {};
1065
+ for (const s of sorted) itemsByStage[s.id] = [];
1066
+ for (const it of (wf.items || [])) {
1067
+ const list = itemsByStage[it.stage];
1068
+ if (list) list.push(it);
1069
+ }
1070
+ const html = sorted.map(s => {
1071
+ const stageItems = itemsByStage[s.id] || [];
1072
+ const itemsHtml = stageItems.length === 0
1073
+ ? '<div class="empty">(empty)</div>'
1074
+ : stageItems.map(it => {
1075
+ const specName = matchSpec(it.description, __specs || []);
1076
+ const specBtn = specName ? '<button class="spec-btn" data-spec="' + esc(specName) + '">spec</button>' : "";
1077
+ return '<div class="item stage-' + esc(s.id) + '"><span class="item-id">' + esc(it.id) + '</span><span class="item-desc">' + esc(it.description) + '</span><span class="item-bottom">' + specBtn + '<span class="item-age">' + ageLabel(it.createdAt) + '</span></span></div>';
1078
+ }).join("");
1079
+ return '<div class="stage stage-' + esc(s.id) + '"><h2>' + esc(s.name) + ' <span class="count">' + stageItems.length + ' ' + (stageItems.length === 1 ? "item" : "items") + '</span></h2><div class="items">' + itemsHtml + '</div></div>';
1080
+ }).join("\\n");
1081
+ const board = document.getElementById("board");
1082
+ board.classList.remove("board-fade");
1083
+ board.innerHTML = html;
1084
+ void board.offsetWidth;
1085
+ board.classList.add("board-fade");
1086
+ document.getElementById("projectDesc").querySelector("h1").textContent = wf.name || "Flow Board";
1087
+ updateMeta(wf.updatedAt);
1088
+ attachSpecButtons();
1089
+ }
1090
+ function updateMeta(updatedAt) {
1091
+ const status = document.getElementById("status");
1092
+ if (status) status.textContent = "connected" + (updatedAt ? " \xB7 updated " + new Date(updatedAt).toLocaleString() : "");
1093
+ }
1094
+ function attachSpecButtons() {
1095
+ document.querySelectorAll(".spec-btn").forEach(btn => {
1096
+ btn.addEventListener("click", () => openSpec(btn.dataset.spec));
1097
+ });
1098
+ }
1099
+ function openSpec(name) {
1100
+ const spec = (__specs || []).find(s => s.name === name);
1101
+ if (!spec) {
1102
+ document.getElementById("modalTitle").textContent = "Spec: " + name;
1103
+ document.getElementById("modalBody").textContent = "Loading...";
1104
+ document.getElementById("modal").classList.remove("hidden");
1105
+ fetch("/api/specs").then(r => r.json()).then(all => {
1106
+ __specs = all;
1107
+ const s = all.find(x => x.name === name);
1108
+ if (s) {
1109
+ document.getElementById("modalTitle").textContent = "Spec: " + name;
1110
+ document.getElementById("modalBody").textContent = s.content;
1111
+ }
1112
+ }).catch(() => {
1113
+ document.getElementById("modalBody").textContent = "Failed to load spec.";
1114
+ });
1115
+ return;
1116
+ }
1117
+ document.getElementById("modalTitle").textContent = "Spec: " + name;
1118
+ document.getElementById("modalBody").textContent = spec.content;
1119
+ document.getElementById("modal").classList.remove("hidden");
1120
+ }
1121
+ document.getElementById("modalClose").addEventListener("click", () => {
1122
+ document.getElementById("modal").classList.add("hidden");
1123
+ });
1124
+ document.getElementById("modalBackdrop").addEventListener("click", () => {
1125
+ document.getElementById("modal").classList.add("hidden");
1126
+ });
1127
+ document.addEventListener("keydown", (e) => {
1128
+ if (e.key === "Escape") document.getElementById("modal").classList.add("hidden");
1129
+ });
1130
+ attachSpecButtons();
1131
+ <${"/script"}>
1132
+ </body>
1133
+ </html>`;
1134
+ }
1135
+ function esc(s) {
1136
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1137
+ }
1138
+ var FlowServer = class {
1139
+ server;
1140
+ watcher;
1141
+ clients = /* @__PURE__ */ new Set();
1142
+ root;
1143
+ port;
1144
+ loadWorkflow;
1145
+ constructor(root, port = DEFAULT_PORT) {
1146
+ this.root = root;
1147
+ this.port = port;
1148
+ this.loadWorkflow = () => loadWorkflow(root);
1149
+ }
1150
+ handleRequest = (req, res) => {
1151
+ const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
1152
+ const path = url.pathname;
1153
+ if (path === "/events") {
1154
+ res.writeHead(200, {
1155
+ "Content-Type": "text/event-stream",
1156
+ "Cache-Control": "no-cache",
1157
+ Connection: "keep-alive"
1158
+ });
1159
+ res.write("event: connected\ndata: {}\n\n");
1160
+ this.clients.add(res);
1161
+ req.on("close", () => this.clients.delete(res));
1162
+ return;
1163
+ }
1164
+ if (path === "/api/workflow") {
1165
+ const wf2 = this.loadWorkflow();
1166
+ res.writeHead(200, { "Content-Type": "application/json" });
1167
+ res.end(JSON.stringify(wf2 ?? { error: "No workflow found" }));
1168
+ return;
1169
+ }
1170
+ if (path === "/api/specs") {
1171
+ const specs2 = loadSpecs(this.root);
1172
+ res.writeHead(200, { "Content-Type": "application/json" });
1173
+ res.end(JSON.stringify(specs2));
1174
+ return;
1175
+ }
1176
+ const wf = this.loadWorkflow();
1177
+ const specs = loadSpecs(this.root);
1178
+ const html = boardHtml(wf, specs);
1179
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
1180
+ res.end(html);
1181
+ };
1182
+ broadcast() {
1183
+ if (this.clients.size === 0) return;
1184
+ const data = "event: workflow-updated\ndata: {}\n\n";
1185
+ for (const client of this.clients) {
1186
+ try {
1187
+ client.write(data);
1188
+ } catch {
1189
+ this.clients.delete(client);
1190
+ }
1191
+ }
1192
+ }
1193
+ start() {
1194
+ return new Promise((resolve16, reject) => {
1195
+ this.server = createServer(this.handleRequest);
1196
+ this.server.listen(this.port, () => {
1197
+ const wfPath = join6(this.root, ".letra", "workflow.json");
1198
+ if (existsSync6(wfPath)) {
1199
+ try {
1200
+ this.watcher = watch(wfPath, () => this.broadcast());
1201
+ } catch {
1202
+ }
1203
+ }
1204
+ resolve16();
1205
+ });
1206
+ this.server.on("error", reject);
1207
+ });
1208
+ }
1209
+ stop() {
1210
+ if (this.watcher) this.watcher.close();
1211
+ if (this.server) this.server.close();
1212
+ for (const client of this.clients) {
1213
+ client.destroy();
1214
+ }
1215
+ this.clients.clear();
1216
+ }
1217
+ getPort() {
1218
+ return this.port;
1219
+ }
1220
+ };
1221
+ async function flowServeAction(targetPath, options) {
1222
+ const root = resolve8(process.cwd(), targetPath ?? ".");
1223
+ const port = options?.port ?? DEFAULT_PORT;
1224
+ const wf = loadWorkflow(root);
1225
+ if (!wf) {
1226
+ console.log("No workflow found. Run 'letra flow init --quick' first");
1227
+ return;
1228
+ }
1229
+ const server = new FlowServer(root, port);
1230
+ try {
1231
+ await server.start();
1232
+ console.log(`
1233
+ Flow Board \u2192 http://localhost:${port}
1234
+ `);
1235
+ console.log(" Press Ctrl+C to stop\n");
1236
+ if (options?.open) {
1237
+ const { execSync: execSync2 } = await import("child_process");
1238
+ const cmd = process.platform === "win32" ? "start" : process.platform === "darwin" ? "open" : "xdg-open";
1239
+ try {
1240
+ execSync2(`${cmd} http://localhost:${port}`, { stdio: "ignore" });
1241
+ } catch {
1242
+ }
1243
+ }
1244
+ await new Promise((resolve16) => {
1245
+ process.on("SIGINT", () => {
1246
+ server.stop();
1247
+ resolve16();
1248
+ });
1249
+ });
1250
+ } catch (err) {
1251
+ console.error(
1252
+ `Failed to start server on port ${port}:`,
1253
+ err.message
1254
+ );
1255
+ process.exit(1);
1256
+ }
1257
+ }
1258
+
1259
+ // src/commands/flow-visualize.ts
1260
+ import { writeFileSync as writeFileSync6 } from "fs";
1261
+ import { resolve as resolve9 } from "path";
1262
+ import chalk8 from "chalk";
1263
+ var MERMAID_LIVE = "https://mermaid.live/edit#";
1264
+ function generateMermaid(workflow) {
1265
+ const sorted = [...workflow.stages].sort((a, b) => a.order - b.order);
1266
+ const itemsByStage = /* @__PURE__ */ new Map();
1267
+ for (const item of workflow.items) {
1268
+ itemsByStage.set(item.stage, (itemsByStage.get(item.stage) ?? 0) + 1);
1269
+ }
1270
+ function labelFor(stage) {
1271
+ const count = itemsByStage.get(stage.id) ?? 0;
1272
+ return `${stage.name} (${count} ${count === 1 ? "item" : "items"})`;
1273
+ }
1274
+ const lines = ["flowchart LR"];
1275
+ if (sorted.length === 0) return lines.join("\n");
1276
+ if (sorted.length === 1) {
1277
+ lines.push(` ${sorted[0].id}["${labelFor(sorted[0])}"]`);
1278
+ return lines.join("\n");
1279
+ }
1280
+ lines.push(
1281
+ ` ${sorted[0].id}["${labelFor(sorted[0])}"] --> ${sorted[1].id}["${labelFor(sorted[1])}"]`
1282
+ );
1283
+ for (let i = 1; i < sorted.length - 1; i++) {
1284
+ lines.push(
1285
+ ` ${sorted[i].id} --> ${sorted[i + 1].id}["${labelFor(sorted[i + 1])}"]`
1286
+ );
1287
+ }
1288
+ return lines.join("\n");
1289
+ }
1290
+ function buildHtml(mermaid) {
1291
+ return `<!DOCTYPE html>
1292
+ <html lang="en">
1293
+ <head>
1294
+ <meta charset="UTF-8">
1295
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1296
+ <title>Workflow Diagram</title>
1297
+ <script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script>
1298
+ <style>
1299
+ body { font-family: system-ui, sans-serif; max-width: 960px; margin: 2rem auto; padding: 0 1rem; }
1300
+ .mermaid { text-align: center; }
1301
+ </style>
1302
+ </head>
1303
+ <body>
1304
+ <pre class="mermaid">
1305
+ ${mermaid}
1306
+ </pre>
1307
+ <script>mermaid.initialize({ startOnLoad: true });</script>
1308
+ </body>
1309
+ </html>`;
1310
+ }
1311
+ function flowVisualize(root, options) {
1312
+ const workflow = loadWorkflow(root);
1313
+ if (!workflow) {
1314
+ console.log(
1315
+ chalk8.yellow("No workflow found. Run 'letra flow init --quick' first")
1316
+ );
1317
+ return;
1318
+ }
1319
+ const mermaid = generateMermaid(workflow);
1320
+ if (options?.output) {
1321
+ const outputPath = resolve9(root, options.output);
1322
+ const ext = options.output.toLowerCase().split(".").pop();
1323
+ let content;
1324
+ let label;
1325
+ if (ext === "html") {
1326
+ content = buildHtml(mermaid);
1327
+ label = "HTML page";
1328
+ } else if (ext === "md") {
1329
+ content = `\`\`\`mermaid
1330
+ ${mermaid}
1331
+ \`\`\`
1332
+ `;
1333
+ label = "Markdown file";
1334
+ } else {
1335
+ content = `${mermaid}
1336
+ `;
1337
+ label = "Diagram file";
1338
+ }
1339
+ writeFileSync6(outputPath, content);
1340
+ console.log(`${label} saved to ${options.output}`);
1341
+ } else {
1342
+ console.log(mermaid);
1343
+ console.log(chalk8.dim(`
1344
+ Copy to ${MERMAID_LIVE} to render`));
1345
+ }
1346
+ }
1347
+ function flowVisualizeAction(targetPath, options) {
1348
+ const root = resolve9(process.cwd(), targetPath || ".");
1349
+ flowVisualize(root, options);
1350
+ }
1351
+
1352
+ // src/commands/flow.ts
1353
+ function flowCommand() {
1354
+ const cmd = new Command2("flow");
1355
+ cmd.command("init [path]").option("--quick", "Quick setup with 3 questions only").description("Initialize workflow in .letra/workflow.json").action((path, options) => {
1356
+ flowInitAction(path, { quick: options.quick });
1357
+ });
1358
+ const backlog = cmd.command("backlog").description("Manage backlog items");
1359
+ backlog.command("add <description>").description("Add item to the first stage").action((description) => {
1360
+ backlogActionAdd(void 0, description);
1361
+ });
1362
+ backlog.command("list").description("List all items with stage and age").action(() => {
1363
+ backlogActionList(void 0);
1364
+ });
1365
+ cmd.command("move <item-id>").requiredOption("--to <stage>", "Target stage id or name").description("Move item to another stage and regenerate adapters").action((itemId, options) => {
1366
+ flowMoveAction(void 0, itemId, options);
1367
+ });
1368
+ cmd.command("board").description("Show board with all stages and items").action(() => {
1369
+ flowBoardAction(void 0);
1370
+ });
1371
+ cmd.command("export").option("--minified", "Output JSON without indentation").description("Export workflow to stdout").action((options) => {
1372
+ flowExportAction(void 0, options);
1373
+ });
1374
+ cmd.command("import <file>").description("Import workflow from a JSON file").action((file) => {
1375
+ flowImportAction(void 0, file);
1376
+ });
1377
+ 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) => {
1378
+ flowServeAction(void 0, {
1379
+ port: options.port ? Number(options.port) : void 0,
1380
+ open: options.open
1381
+ });
1382
+ });
1383
+ cmd.command("visualize").option("--output <file>", "Save diagram to file").description("Generate Mermaid diagram of workflow").action((options) => {
1384
+ flowVisualizeAction(void 0, options);
1385
+ });
1386
+ cmd.command("edit").option("--name <name>", "New workflow name").option("--desc <desc>", "New workflow description").description("Edit workflow metadata").action((options) => {
1387
+ flowEditAction(void 0, options);
1388
+ });
1389
+ cmd.command("diff [v1] [v2]").description("Show diff between workflow versions").action((...args) => {
1390
+ const strings = args.filter((a) => typeof a === "string");
1391
+ flowDiffAction(void 0, strings[0], strings[1]);
1392
+ });
1393
+ return cmd;
1394
+ }
1395
+
1396
+ // src/commands/focus.ts
1397
+ import { existsSync as existsSync7, readFileSync as readFileSync6, unlinkSync, writeFileSync as writeFileSync7 } from "fs";
1398
+ import { join as join7, resolve as resolve10 } from "path";
1399
+ import chalk9 from "chalk";
1400
+ import { Command as Command3 } from "commander";
96
1401
  function extractOutcome(specDir) {
97
- const specFile = join2(specDir, "spec.md");
98
- if (!existsSync2(specFile)) return null;
99
- const content = readFileSync2(specFile, "utf-8");
1402
+ const specFile = join7(specDir, "spec.md");
1403
+ if (!existsSync7(specFile)) return null;
1404
+ const content = readFileSync6(specFile, "utf-8");
100
1405
  const match = content.match(/## Outcome\s+([\s\S]*?)(?=\n## |\n*$)/);
101
1406
  return match ? match[1].trim() : null;
102
1407
  }
103
1408
  function focus_default() {
104
- return new Command2("focus").argument("[spec]", "Spec name to focus on").option("--clear", "Remove focus file").action((spec, options) => {
105
- const root = resolve2(process.cwd());
106
- const focusFile = join2(root, ".letra", "focus.md");
1409
+ return new Command3("focus").argument("[spec]", "Spec name to focus on").option("--clear", "Remove focus file").action((spec, options) => {
1410
+ const root = resolve10(process.cwd());
1411
+ const focusFile = join7(root, ".letra", "focus.md");
107
1412
  if (options.clear) {
108
- if (existsSync2(focusFile)) {
1413
+ if (existsSync7(focusFile)) {
109
1414
  unlinkSync(focusFile);
110
- console.log(chalk2.green("Focus removed."));
1415
+ console.log(chalk9.green("Focus removed."));
111
1416
  } else {
112
- console.log(chalk2.yellow("No focus to remove."));
1417
+ console.log(chalk9.yellow("No focus to remove."));
113
1418
  }
114
1419
  return;
115
1420
  }
116
1421
  if (spec) {
117
- const specDir = join2(root, ".letra", "specs", spec);
118
- const specFile = join2(specDir, "spec.md");
119
- if (!existsSync2(specFile)) {
120
- console.log(chalk2.red(`Spec "${spec}" not found`));
1422
+ const specDir = join7(root, ".letra", "specs", spec);
1423
+ const specFile = join7(specDir, "spec.md");
1424
+ if (!existsSync7(specFile)) {
1425
+ console.log(chalk9.red(`Spec "${spec}" not found`));
121
1426
  process.exit(1);
122
1427
  }
123
1428
  const outcome = extractOutcome(specDir);
@@ -129,12 +1434,12 @@ function focus_default() {
129
1434
  outcomeLine,
130
1435
  ""
131
1436
  ].join("\n");
132
- writeFileSync2(focusFile, focusContent);
133
- console.log(chalk2.green(`Focus set to "${spec}".`));
1437
+ writeFileSync7(focusFile, focusContent);
1438
+ console.log(chalk9.green(`Focus set to "${spec}".`));
134
1439
  return;
135
1440
  }
136
- if (existsSync2(focusFile)) {
137
- console.log(readFileSync2(focusFile, "utf-8"));
1441
+ if (existsSync7(focusFile)) {
1442
+ console.log(readFileSync6(focusFile, "utf-8"));
138
1443
  } else {
139
1444
  console.log("Nenhum foco definido.");
140
1445
  }
@@ -144,33 +1449,33 @@ function focus_default() {
144
1449
  // src/commands/init.ts
145
1450
  import {
146
1451
  copyFileSync,
147
- existsSync as existsSync3,
148
- mkdirSync as mkdirSync2,
149
- writeFileSync as writeFileSync3
1452
+ existsSync as existsSync8,
1453
+ mkdirSync as mkdirSync4,
1454
+ writeFileSync as writeFileSync8
150
1455
  } from "fs";
151
- import { join as join3, resolve as resolve3 } from "path";
152
- import { createInterface } from "readline";
1456
+ import { join as join8, resolve as resolve11 } from "path";
1457
+ import { createInterface as createInterface2 } from "readline";
153
1458
  import { fileURLToPath } from "url";
154
- import chalk3 from "chalk";
155
- import ora from "ora";
1459
+ import chalk10 from "chalk";
1460
+ import ora2 from "ora";
156
1461
  var __dirname = fileURLToPath(new URL(".", import.meta.url));
157
1462
  function ask(query, options) {
158
1463
  if (!process.stdin.isTTY) return Promise.resolve(options[0]);
159
- const rl = createInterface({ input: process.stdin, output: process.stdout });
160
- return new Promise((resolve8) => {
161
- const formatted = `${chalk3.cyan(query)} ${options.map((o) => chalk3.gray(`(${o})`)).join(" ")}
1464
+ const rl = createInterface2({ input: process.stdin, output: process.stdout });
1465
+ return new Promise((resolve16) => {
1466
+ const formatted = `${chalk10.cyan(query)} ${options.map((o) => chalk10.gray(`(${o})`)).join(" ")}
162
1467
  > `;
163
1468
  rl.question(formatted, (answer) => {
164
1469
  rl.close();
165
1470
  const trimmed = answer.trim().toLowerCase();
166
1471
  if (trimmed && options.some((o) => o.toLowerCase().startsWith(trimmed))) {
167
- resolve8(
1472
+ resolve16(
168
1473
  options.find((o) => o.toLowerCase().startsWith(trimmed)) ?? options[0]
169
1474
  );
170
1475
  } else if (trimmed && options.includes(trimmed)) {
171
- resolve8(trimmed);
1476
+ resolve16(trimmed);
172
1477
  } else {
173
- resolve8(options[0]);
1478
+ resolve16(options[0]);
174
1479
  }
175
1480
  });
176
1481
  });
@@ -241,49 +1546,49 @@ ${format === "at" ? "# Context\n@.letra/context.md\n@.letra/constitution.md\n@.l
241
1546
  switch (tool) {
242
1547
  case "cursor":
243
1548
  adapters.push({
244
- path: join3(root, ".cursorrules"),
1549
+ path: join8(root, ".cursorrules"),
245
1550
  content: baseContent("Cursor", "at")
246
1551
  });
247
1552
  break;
248
1553
  case "claude-code":
249
1554
  adapters.push({
250
- path: join3(root, "CLAUDE.md"),
1555
+ path: join8(root, "CLAUDE.md"),
251
1556
  content: baseContent("Claude Code", "text")
252
1557
  });
253
1558
  break;
254
1559
  case "windsurf":
255
1560
  adapters.push({
256
- path: join3(root, ".windsurfrules"),
1561
+ path: join8(root, ".windsurfrules"),
257
1562
  content: baseContent("Windsurf", "at")
258
1563
  });
259
1564
  break;
260
1565
  case "vscode":
261
1566
  adapters.push({
262
- path: join3(root, ".github", "copilot-instructions.md"),
1567
+ path: join8(root, ".github", "copilot-instructions.md"),
263
1568
  content: baseContent("VSCode Copilot", "text")
264
1569
  });
265
1570
  break;
266
1571
  case "opencode":
267
1572
  adapters.push({
268
- path: join3(root, "AGENTS.md"),
1573
+ path: join8(root, "AGENTS.md"),
269
1574
  content: baseContent("OpenCode", "text")
270
1575
  });
271
1576
  break;
272
1577
  }
273
1578
  }
274
1579
  for (const { path, content } of adapters) {
275
- const dir = join3(path, "..");
276
- if (!existsSync3(dir)) mkdirSync2(dir, { recursive: true });
277
- writeFileSync3(path, content);
278
- console.log(` ${chalk3.gray("Created")} ${path.replace(`${root}/`, "")}`);
1580
+ const dir = join8(path, "..");
1581
+ if (!existsSync8(dir)) mkdirSync4(dir, { recursive: true });
1582
+ writeFileSync8(path, content);
1583
+ console.log(` ${chalk10.gray("Created")} ${path.replace(`${root}/`, "")}`);
279
1584
  }
280
1585
  }
281
1586
  async function init(targetPath, options) {
282
- const root = resolve3(process.cwd(), targetPath || ".");
283
- const letraDir = join3(root, ".letra");
284
- const spinner = ora("Initializing Letra...").start();
285
- if (existsSync3(letraDir)) {
286
- spinner.warn(chalk3.yellow(".letra/ already exists"));
1587
+ const root = resolve11(process.cwd(), targetPath || ".");
1588
+ const letraDir = join8(root, ".letra");
1589
+ const spinner = ora2("Initializing Letra...").start();
1590
+ if (existsSync8(letraDir)) {
1591
+ spinner.warn(chalk10.yellow(".letra/ already exists"));
287
1592
  return;
288
1593
  }
289
1594
  try {
@@ -312,10 +1617,10 @@ async function init(targetPath, options) {
312
1617
  tool = answer.toLowerCase();
313
1618
  spinner.start();
314
1619
  }
315
- mkdirSync2(join3(letraDir, "decisions"), { recursive: true });
316
- mkdirSync2(join3(letraDir, "specs", "_template"), { recursive: true });
317
- mkdirSync2(join3(letraDir, "adapters"), { recursive: true });
318
- const templateDir = join3(__dirname, "..", "..", ".letra");
1620
+ mkdirSync4(join8(letraDir, "decisions"), { recursive: true });
1621
+ mkdirSync4(join8(letraDir, "specs", "_template"), { recursive: true });
1622
+ mkdirSync4(join8(letraDir, "adapters"), { recursive: true });
1623
+ const templateDir = join8(__dirname, "..", "..", ".letra");
319
1624
  const templates = [
320
1625
  "context.md",
321
1626
  "constitution.md",
@@ -323,11 +1628,11 @@ async function init(targetPath, options) {
323
1628
  "lessons-learned.md"
324
1629
  ];
325
1630
  for (const file of templates) {
326
- const src = join3(templateDir, file);
327
- const dest = join3(letraDir, file);
328
- if (existsSync3(src)) copyFileSync(src, dest);
1631
+ const src = join8(templateDir, file);
1632
+ const dest = join8(letraDir, file);
1633
+ if (existsSync8(src)) copyFileSync(src, dest);
329
1634
  }
330
- const specTemplate = join3(letraDir, "specs", "_template.md");
1635
+ const specTemplate = join8(letraDir, "specs", "_template.md");
331
1636
  const specContent = `# Spec Template
332
1637
 
333
1638
  ## Outcome
@@ -345,16 +1650,16 @@ O que explicitamente N\xC3O est\xE1 neste escopo.
345
1650
  ## Context
346
1651
  Por que estamos construindo isso.
347
1652
  `;
348
- writeFileSync3(specTemplate, specContent);
349
- const configPath = join3(letraDir, "config.json");
350
- writeFileSync3(configPath, adaptConfig(projectType));
351
- console.log(` ${chalk3.gray("Created")} .letra/config.json`);
1653
+ writeFileSync8(specTemplate, specContent);
1654
+ const configPath = join8(letraDir, "config.json");
1655
+ writeFileSync8(configPath, adaptConfig(projectType));
1656
+ console.log(` ${chalk10.gray("Created")} .letra/config.json`);
352
1657
  const tools = adaptersForTool(tool);
353
1658
  generateAdapterFiles(root, tools);
354
1659
  if (tool === "todos" || tool === "vscode") {
355
- const vscodeDir = join3(root, ".vscode");
356
- if (!existsSync3(vscodeDir)) mkdirSync2(vscodeDir, { recursive: true });
357
- const vscodeSettingsPath = join3(vscodeDir, "settings.json");
1660
+ const vscodeDir = join8(root, ".vscode");
1661
+ if (!existsSync8(vscodeDir)) mkdirSync4(vscodeDir, { recursive: true });
1662
+ const vscodeSettingsPath = join8(vscodeDir, "settings.json");
358
1663
  const vscodeSettingsContent = `{
359
1664
  "editor.formatOnSave": true,
360
1665
  "editor.defaultFormatter": "esbenp.prettier-vscode",
@@ -364,26 +1669,26 @@ Por que estamos construindo isso.
364
1669
  "files.autoSave": "onFocusChange"
365
1670
  }
366
1671
  `;
367
- writeFileSync3(vscodeSettingsPath, vscodeSettingsContent);
368
- console.log(` ${chalk3.gray("Created")} .vscode/settings.json`);
1672
+ writeFileSync8(vscodeSettingsPath, vscodeSettingsContent);
1673
+ console.log(` ${chalk10.gray("Created")} .vscode/settings.json`);
369
1674
  }
370
- spinner.succeed(chalk3.green(".letra/ initialized successfully"));
1675
+ spinner.succeed(chalk10.green(".letra/ initialized successfully"));
371
1676
  console.log("");
372
1677
  console.log(" Next steps:");
373
1678
  console.log(
374
- ` ${chalk3.cyan("letra spec new <name>")} Create your first spec`
1679
+ ` ${chalk10.cyan("letra spec new <name>")} Create your first spec`
375
1680
  );
376
- console.log(` ${chalk3.cyan("letra lint")} Validate specs`);
1681
+ console.log(` ${chalk10.cyan("letra lint")} Validate specs`);
377
1682
  } catch (error) {
378
- spinner.fail(chalk3.red("Failed to initialize Letra"));
1683
+ spinner.fail(chalk10.red("Failed to initialize Letra"));
379
1684
  process.exit(1);
380
1685
  }
381
1686
  }
382
1687
 
383
1688
  // src/commands/lint.ts
384
- import { existsSync as existsSync4, readFileSync as readFileSync3, readdirSync as readdirSync3 } from "fs";
385
- import { join as join4, resolve as resolve4 } from "path";
386
- import chalk4 from "chalk";
1689
+ import { existsSync as existsSync9, readFileSync as readFileSync7, readdirSync as readdirSync5 } from "fs";
1690
+ import { join as join9, resolve as resolve12 } from "path";
1691
+ import chalk11 from "chalk";
387
1692
  var REQUIRED_SECTIONS = [
388
1693
  "## Outcome",
389
1694
  "## Constraints",
@@ -392,27 +1697,27 @@ var REQUIRED_SECTIONS = [
392
1697
  "## Context"
393
1698
  ];
394
1699
  async function lint(targetPath) {
395
- const root = resolve4(process.cwd(), targetPath || ".");
396
- const specsDir = join4(root, ".letra", "specs");
397
- if (!existsSync4(specsDir)) {
1700
+ const root = resolve12(process.cwd(), targetPath || ".");
1701
+ const specsDir = join9(root, ".letra", "specs");
1702
+ if (!existsSync9(specsDir)) {
398
1703
  console.log(
399
- chalk4.red("Error: .letra/specs/ not found. Run 'letra init' first.")
1704
+ chalk11.red("Error: .letra/specs/ not found. Run 'letra init' first.")
400
1705
  );
401
1706
  process.exit(1);
402
1707
  }
403
1708
  const results = [];
404
1709
  let totalErrors = 0;
405
1710
  let totalWarnings = 0;
406
- const entries = readdirSync3(specsDir, { withFileTypes: true });
1711
+ const entries = readdirSync5(specsDir, { withFileTypes: true });
407
1712
  for (const entry of entries) {
408
1713
  if (!entry.isDirectory() || entry.name.startsWith("_")) continue;
409
- const specFile = join4(specsDir, entry.name, "spec.md");
1714
+ const specFile = join9(specsDir, entry.name, "spec.md");
410
1715
  const errors = [];
411
1716
  const warnings = [];
412
- if (!existsSync4(specFile)) {
1717
+ if (!existsSync9(specFile)) {
413
1718
  errors.push("Missing spec.md");
414
1719
  } else {
415
- const content = readFileSync3(specFile, "utf-8");
1720
+ const content = readFileSync7(specFile, "utf-8");
416
1721
  for (const section of REQUIRED_SECTIONS) {
417
1722
  if (!content.includes(section)) {
418
1723
  errors.push(`Missing section: ${section}`);
@@ -435,22 +1740,22 @@ async function lint(targetPath) {
435
1740
  }
436
1741
  }
437
1742
  if (results.length === 0) {
438
- console.log(chalk4.green("All specs are valid"));
1743
+ console.log(chalk11.green("All specs are valid"));
439
1744
  process.exit(0);
440
1745
  }
441
1746
  console.log("");
442
1747
  for (const result of results) {
443
- console.log(chalk4.bold(`
1748
+ console.log(chalk11.bold(`
444
1749
  Spec: ${result.file}`));
445
1750
  for (const error of result.errors) {
446
- console.log(chalk4.red(` \u2717 ${error}`));
1751
+ console.log(chalk11.red(` \u2717 ${error}`));
447
1752
  }
448
1753
  for (const warning of result.warnings) {
449
- console.log(chalk4.yellow(` \u26A0 ${warning}`));
1754
+ console.log(chalk11.yellow(` \u26A0 ${warning}`));
450
1755
  }
451
1756
  }
452
1757
  console.log(
453
- chalk4.gray(
1758
+ chalk11.gray(
454
1759
  `
455
1760
  ${results.length} spec(s) with issues: ${totalErrors} error(s), ${totalWarnings} warning(s)`
456
1761
  )
@@ -460,15 +1765,15 @@ ${results.length} spec(s) with issues: ${totalErrors} error(s), ${totalWarnings}
460
1765
 
461
1766
  // src/commands/spec.ts
462
1767
  import {
463
- existsSync as existsSync5,
464
- mkdirSync as mkdirSync3,
465
- readFileSync as readFileSync4,
466
- readdirSync as readdirSync4,
467
- writeFileSync as writeFileSync4
1768
+ existsSync as existsSync10,
1769
+ mkdirSync as mkdirSync5,
1770
+ readFileSync as readFileSync8,
1771
+ readdirSync as readdirSync6,
1772
+ writeFileSync as writeFileSync9
468
1773
  } from "fs";
469
- import { join as join5, resolve as resolve5 } from "path";
470
- import chalk5 from "chalk";
471
- import ora2 from "ora";
1774
+ import { join as join10, resolve as resolve13 } from "path";
1775
+ import chalk12 from "chalk";
1776
+ import ora3 from "ora";
472
1777
  var builtInTemplates = {
473
1778
  "web-api": {
474
1779
  spec: `# Spec: {{name}}
@@ -572,9 +1877,9 @@ Template para features mobile nativas. Adaptado para o framework espec\xEDfico (
572
1877
  };
573
1878
  function listTemplates(root) {
574
1879
  const names = Object.keys(builtInTemplates);
575
- const customDir = join5(root, ".letra", "templates");
576
- if (existsSync5(customDir)) {
577
- for (const file of readdirSync4(customDir)) {
1880
+ const customDir = join10(root, ".letra", "templates");
1881
+ if (existsSync10(customDir)) {
1882
+ for (const file of readdirSync6(customDir)) {
578
1883
  if (file.endsWith(".md")) {
579
1884
  const name = file.replace(/\.md$/, "");
580
1885
  if (!names.includes(name)) names.push(name);
@@ -586,16 +1891,16 @@ function listTemplates(root) {
586
1891
  function findTemplate(root, type) {
587
1892
  const lower = type.toLowerCase();
588
1893
  if (builtInTemplates[lower]) return builtInTemplates[lower];
589
- const customFile = join5(root, ".letra", "templates", `${type}.md`);
590
- const customAcceptance = join5(
1894
+ const customFile = join10(root, ".letra", "templates", `${type}.md`);
1895
+ const customAcceptance = join10(
591
1896
  root,
592
1897
  ".letra",
593
1898
  "templates",
594
1899
  `${type}-acceptance.md`
595
1900
  );
596
- if (existsSync5(customFile)) {
597
- const spec = readFileSync4(customFile, "utf-8");
598
- const acceptance = existsSync5(customAcceptance) ? readFileSync4(customAcceptance, "utf-8") : `# Acceptance Criteria \u2014 ${type}
1901
+ if (existsSync10(customFile)) {
1902
+ const spec = readFileSync8(customFile, "utf-8");
1903
+ const acceptance = existsSync10(customAcceptance) ? readFileSync8(customAcceptance, "utf-8") : `# Acceptance Criteria \u2014 ${type}
599
1904
 
600
1905
  - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
601
1906
  `;
@@ -607,15 +1912,15 @@ function applyPlaceholders(content, name) {
607
1912
  return content.replace(/\{\{name\}\}/g, name);
608
1913
  }
609
1914
  async function specNew(name, options) {
610
- const root = resolve5(process.cwd());
611
- const letraDir = join5(root, ".letra");
612
- const specDir = join5(letraDir, "specs", name);
613
- if (!existsSync5(letraDir)) {
614
- console.log(chalk5.red(".letra/ not found. Run 'letra init' first."));
1915
+ const root = resolve13(process.cwd());
1916
+ const letraDir = join10(root, ".letra");
1917
+ const specDir = join10(letraDir, "specs", name);
1918
+ if (!existsSync10(letraDir)) {
1919
+ console.log(chalk12.red(".letra/ not found. Run 'letra init' first."));
615
1920
  process.exit(1);
616
1921
  }
617
- if (existsSync5(specDir)) {
618
- console.log(chalk5.yellow(`Spec "${name}" already exists`));
1922
+ if (existsSync10(specDir)) {
1923
+ console.log(chalk12.yellow(`Spec "${name}" already exists`));
619
1924
  return;
620
1925
  }
621
1926
  const templateType = options?.template || "_default";
@@ -623,20 +1928,20 @@ async function specNew(name, options) {
623
1928
  if (options?.template && !template) {
624
1929
  const available = listTemplates(root).join(", ");
625
1930
  console.log(
626
- chalk5.red(
1931
+ chalk12.red(
627
1932
  `Template "${options.template}" not found. Available: ${available}`
628
1933
  )
629
1934
  );
630
1935
  process.exit(1);
631
1936
  }
632
- const spinner = ora2(`Creating spec "${name}"...`).start();
1937
+ const spinner = ora3(`Creating spec "${name}"...`).start();
633
1938
  try {
634
- mkdirSync3(specDir, { recursive: true });
1939
+ mkdirSync5(specDir, { recursive: true });
635
1940
  if (template) {
636
1941
  const specContent = applyPlaceholders(template.spec, name);
637
1942
  const acceptanceContent = applyPlaceholders(template.acceptance, name);
638
- writeFileSync4(join5(specDir, "spec.md"), specContent);
639
- writeFileSync4(join5(specDir, "acceptance.md"), acceptanceContent);
1943
+ writeFileSync9(join10(specDir, "spec.md"), specContent);
1944
+ writeFileSync9(join10(specDir, "acceptance.md"), acceptanceContent);
640
1945
  } else {
641
1946
  const specContent = `# Spec: ${name}
642
1947
 
@@ -659,14 +1964,14 @@ Por que estamos construindo isso. Trade-offs considerados.
659
1964
 
660
1965
  - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
661
1966
  `;
662
- writeFileSync4(join5(specDir, "spec.md"), specContent);
663
- writeFileSync4(join5(specDir, "acceptance.md"), acceptanceContent);
1967
+ writeFileSync9(join10(specDir, "spec.md"), specContent);
1968
+ writeFileSync9(join10(specDir, "acceptance.md"), acceptanceContent);
664
1969
  }
665
1970
  spinner.succeed(
666
- chalk5.green(`Spec "${name}" created at .letra/specs/${name}/`)
1971
+ chalk12.green(`Spec "${name}" created at .letra/specs/${name}/`)
667
1972
  );
668
1973
  } catch (error) {
669
- spinner.fail(chalk5.red("Failed to create spec"));
1974
+ spinner.fail(chalk12.red("Failed to create spec"));
670
1975
  process.exit(1);
671
1976
  }
672
1977
  }
@@ -674,21 +1979,21 @@ Por que estamos construindo isso. Trade-offs considerados.
674
1979
  // src/commands/validate.ts
675
1980
  import { execSync } from "child_process";
676
1981
  import {
677
- existsSync as existsSync7,
1982
+ existsSync as existsSync12,
678
1983
  mkdtempSync,
679
- readFileSync as readFileSync6,
680
- readdirSync as readdirSync5,
1984
+ readFileSync as readFileSync10,
1985
+ readdirSync as readdirSync7,
681
1986
  rmSync,
682
- statSync as statSync2,
683
- watch
1987
+ statSync as statSync3,
1988
+ watch as watch2
684
1989
  } from "fs";
685
1990
  import { tmpdir } from "os";
686
- import { join as join7, resolve as resolve6 } from "path";
687
- import chalk6 from "chalk";
1991
+ import { join as join12, resolve as resolve14 } from "path";
1992
+ import chalk13 from "chalk";
688
1993
 
689
1994
  // src/config.ts
690
- import { existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
691
- import { join as join6 } from "path";
1995
+ import { existsSync as existsSync11, readFileSync as readFileSync9 } from "fs";
1996
+ import { join as join11 } from "path";
692
1997
  var DEFAULT_HEURISTICS = {
693
1998
  "conteudo-minimo": { severity: "warning", minChars: 50 },
694
1999
  "consistencia-terminologia": { severity: "warning" },
@@ -703,14 +2008,14 @@ var DEFAULT_HEURISTICS = {
703
2008
  "validate-conflict": { severity: "warning" }
704
2009
  };
705
2010
  function loadConfig(root) {
706
- const configPath = join6(root, ".letra", "config.json");
2011
+ const configPath = join11(root, ".letra", "config.json");
707
2012
  const heuristics = {};
708
2013
  for (const [key, value] of Object.entries(DEFAULT_HEURISTICS)) {
709
2014
  heuristics[key] = { ...value };
710
2015
  }
711
- if (existsSync6(configPath)) {
2016
+ if (existsSync11(configPath)) {
712
2017
  try {
713
- const raw = JSON.parse(readFileSync5(configPath, "utf-8"));
2018
+ const raw = JSON.parse(readFileSync9(configPath, "utf-8"));
714
2019
  if (raw.heuristics && typeof raw.heuristics === "object") {
715
2020
  for (const [key, value] of Object.entries(raw.heuristics)) {
716
2021
  if (heuristics[key]) {
@@ -732,20 +2037,18 @@ function getHeuristicConfig(config, label) {
732
2037
  const key = heuristicKey(label);
733
2038
  return config.heuristics[key] ?? { severity: "warning" };
734
2039
  }
2040
+ function normalize(str) {
2041
+ return str.normalize("NFD").replace(/\p{M}/gu, "");
2042
+ }
735
2043
  function heuristicKey(label) {
736
- const lower = label.toLowerCase();
737
- if (lower.includes("conteudo m\xEDnimo") || lower.includes("conteudo minimo"))
738
- return "conteudo-minimo";
2044
+ const lower = normalize(label.toLowerCase());
2045
+ if (lower.includes("conteudo minimo")) return "conteudo-minimo";
739
2046
  if (lower.includes("terminologia")) return "consistencia-terminologia";
740
2047
  if (lower.includes("tom")) return "detecao-tom";
741
- if (lower.includes("drift temporal") || lower.includes("temporal"))
742
- return "drift-temporal";
743
- if (lower.includes("se\xE7\xF5es vazias") || lower.includes("secoes vazias"))
744
- return "secoes-vazias";
745
- if (lower.includes("acs sem m\xE9trica") || lower.includes("acs sem metrica"))
746
- return "acs-sem-metrica";
747
- if (lower.includes("baixa confian\xE7a") || lower.includes("baixa confianca"))
748
- return "baixa-confianca";
2048
+ if (lower.includes("drift temporal")) return "drift-temporal";
2049
+ if (lower.includes("secoes vazias")) return "secoes-vazias";
2050
+ if (lower.includes("acs sem metrica")) return "acs-sem-metrica";
2051
+ if (lower.includes("baixa confianca")) return "baixa-confianca";
749
2052
  if (lower.includes("validate conflict")) return "validate-conflict";
750
2053
  return lower.replace(/\s+/g, "-");
751
2054
  }
@@ -779,13 +2082,13 @@ var lowConfidenceMarkers = [
779
2082
  "teoricamente"
780
2083
  ];
781
2084
  function checkSpecContent(specDir, label, description, config) {
782
- const cfg = config ?? loadConfig(join7(specDir, "..", "..", ".."));
783
- const specFile = join7(specDir, "spec.md");
784
- const glossaryFile = join7(specDir, "..", "..", "glossary.md");
785
- if (!existsSync7(specFile))
2085
+ const cfg = config ?? loadConfig(join12(specDir, "..", "..", ".."));
2086
+ const specFile = join12(specDir, "spec.md");
2087
+ const glossaryFile = join12(specDir, "..", "..", "glossary.md");
2088
+ if (!existsSync12(specFile))
786
2089
  return { status: "FAIL", note: "(spec.md not found)" };
787
- const specContent = readFileSync6(specFile, "utf-8");
788
- const now = /* @__PURE__ */ new Date();
2090
+ const specContent = readFileSync10(specFile, "utf-8");
2091
+ const now6 = /* @__PURE__ */ new Date();
789
2092
  if (label.includes("Conte\xFAdo M\xEDnimo")) {
790
2093
  const outcomeMatch = specContent.match(/## Outcome\s+([\s\S]*?)(?=\n## )/);
791
2094
  if (!outcomeMatch)
@@ -805,13 +2108,13 @@ function checkSpecContent(specDir, label, description, config) {
805
2108
  };
806
2109
  }
807
2110
  if (label.includes("Consist\xEAncia de Terminologia") || label.includes("Terminologia")) {
808
- if (!existsSync7(glossaryFile)) {
2111
+ if (!existsSync12(glossaryFile)) {
809
2112
  return {
810
2113
  status: "PASS",
811
2114
  note: "(no glossary to check against)"
812
2115
  };
813
2116
  }
814
- const glossaryContent = readFileSync6(glossaryFile, "utf-8");
2117
+ const glossaryContent = readFileSync10(glossaryFile, "utf-8");
815
2118
  const terms = glossaryContent.match(/\*\*(.+?)\*\*/g) || [];
816
2119
  const extractedTerms = terms.map((t) => t.replace(/\*\*/g, "").trim()).filter((t) => t.length > 3);
817
2120
  const missingTerms = extractedTerms.filter(
@@ -849,9 +2152,9 @@ function checkSpecContent(specDir, label, description, config) {
849
2152
  };
850
2153
  }
851
2154
  if (label.includes("Drift Temporal") || label.includes("Temporal")) {
852
- const stat = statSync2(specFile);
2155
+ const stat = statSync3(specFile);
853
2156
  const daysOld = Math.floor(
854
- (now.getTime() - stat.mtimeMs) / (1e3 * 60 * 60 * 24)
2157
+ (now6.getTime() - stat.mtimeMs) / (1e3 * 60 * 60 * 24)
855
2158
  );
856
2159
  const heurConfig = getHeuristicConfig(cfg, label);
857
2160
  const maxDays = heurConfig.maxDays ?? 30;
@@ -1038,13 +2341,13 @@ function detectConflict(textA, textB) {
1038
2341
  }
1039
2342
  function checkConflicts(specsDir, config) {
1040
2343
  const results = [];
1041
- const entries = readdirSync5(specsDir, { withFileTypes: true });
2344
+ const entries = readdirSync7(specsDir, { withFileTypes: true });
1042
2345
  const specDirs = entries.filter((e) => e.isDirectory() && !e.name.startsWith("_")).map((e) => e.name);
1043
2346
  const specs = [];
1044
2347
  for (const dir of specDirs) {
1045
- const acceptanceFile = join7(specsDir, dir, "acceptance.md");
1046
- if (!existsSync7(acceptanceFile)) continue;
1047
- const content = readFileSync6(acceptanceFile, "utf-8");
2348
+ const acceptanceFile = join12(specsDir, dir, "acceptance.md");
2349
+ if (!existsSync12(acceptanceFile)) continue;
2350
+ const content = readFileSync10(acceptanceFile, "utf-8");
1048
2351
  const acLines = content.match(/- \[[ x]\] \*\*(.+?)\*\*: (.+)/g) || [];
1049
2352
  const acs = acLines.map((line) => {
1050
2353
  const m = line.match(/- \[[ x]\] \*\*(.+?)\*\*: (.+)/);
@@ -1094,12 +2397,12 @@ function out(format, level, spec, label, message, note) {
1094
2397
  if (format === "junit") {
1095
2398
  return;
1096
2399
  }
1097
- const icon = level === "pass" ? chalk6.green("\u2713") : level === "fail" ? chalk6.red("\u2717") : level === "warning" ? chalk6.yellow("\u26A0") : "";
2400
+ const icon = level === "pass" ? chalk13.green("\u2713") : level === "fail" ? chalk13.red("\u2717") : level === "warning" ? chalk13.yellow("\u26A0") : "";
1098
2401
  if (level === "info") {
1099
2402
  console.log(` ${message}`);
1100
2403
  } else {
1101
2404
  console.log(
1102
- ` [${icon}] ${chalk6.cyan(label)}: ${message} ${chalk6.gray(note)}`
2405
+ ` [${icon}] ${chalk13.cyan(label)}: ${message} ${chalk13.gray(note)}`
1103
2406
  );
1104
2407
  }
1105
2408
  }
@@ -1141,55 +2444,55 @@ function flushResults(results, format, specGroups, totalPass, totalFail, totalWa
1141
2444
  }
1142
2445
  }
1143
2446
  console.log(
1144
- chalk6.gray(
2447
+ chalk13.gray(
1145
2448
  `
1146
2449
  Results: ${totalPass} passed, ${totalFail} failed${totalWarning > 0 ? `, ${totalWarning} warnings` : ""}`
1147
2450
  )
1148
2451
  );
1149
2452
  }
1150
2453
  async function validate(targetPath, options) {
1151
- const root = resolve6(process.cwd(), targetPath || ".");
1152
- const specsDir = join7(root, ".letra", "specs");
2454
+ const root = resolve14(process.cwd(), targetPath || ".");
2455
+ const specsDir = join12(root, ".letra", "specs");
1153
2456
  const fmt = options?.format || "text";
1154
- if (!existsSync7(specsDir)) {
2457
+ if (!existsSync12(specsDir)) {
1155
2458
  const msg = "Error: .letra/specs/ not found. Run 'letra init' first.";
1156
2459
  if (fmt === "github-annotation") {
1157
2460
  console.log(`::error file=,title=Init Required::${msg}`);
1158
2461
  } else {
1159
- console.log(chalk6.red(msg));
2462
+ console.log(chalk13.red(msg));
1160
2463
  }
1161
2464
  process.exit(1);
1162
2465
  }
1163
2466
  async function runValidation() {
1164
2467
  const config = loadConfig(root);
1165
- const entries = readdirSync5(specsDir, { withFileTypes: true });
2468
+ const entries = readdirSync7(specsDir, { withFileTypes: true });
1166
2469
  let totalPass = 0;
1167
2470
  let totalFail = 0;
1168
2471
  let totalWarning = 0;
1169
2472
  const specGroups = /* @__PURE__ */ new Map();
1170
2473
  const allResults = [];
1171
- const entryPoint = join7(root, "src/index.ts");
2474
+ const entryPoint = join12(root, "src/index.ts");
1172
2475
  const opts = {
1173
2476
  stdio: "pipe",
1174
2477
  encoding: "utf-8",
1175
2478
  shell: process.platform === "win32" ? "cmd.exe" : true
1176
2479
  };
1177
- const ciFile = join7(root, ".github", "workflows", "ci.yml");
1178
- const cursorRulesFile = join7(root, ".cursorrules");
1179
- const copilotFile = join7(root, ".github", "copilot-instructions.md");
1180
- const vscodeSettingsFile = join7(root, ".vscode", "settings.json");
2480
+ const ciFile = join12(root, ".github", "workflows", "ci.yml");
2481
+ const cursorRulesFile = join12(root, ".cursorrules");
2482
+ const copilotFile = join12(root, ".github", "copilot-instructions.md");
2483
+ const vscodeSettingsFile = join12(root, ".vscode", "settings.json");
1181
2484
  if (fmt !== "junit") {
1182
2485
  out(fmt, "info", null, "", "\nLetra Validation\n", "");
1183
2486
  }
1184
2487
  for (const entry of entries) {
1185
2488
  if (!entry.isDirectory() || entry.name.startsWith("_")) continue;
1186
- const acceptanceFile = join7(specsDir, entry.name, "acceptance.md");
1187
- const specFile = join7(specsDir, entry.name, "spec.md");
2489
+ const acceptanceFile = join12(specsDir, entry.name, "acceptance.md");
2490
+ const specFile = join12(specsDir, entry.name, "spec.md");
1188
2491
  let content;
1189
- if (existsSync7(acceptanceFile)) {
1190
- content = readFileSync6(acceptanceFile, "utf-8");
1191
- } else if (existsSync7(specFile)) {
1192
- content = readFileSync6(specFile, "utf-8");
2492
+ if (existsSync12(acceptanceFile)) {
2493
+ content = readFileSync10(acceptanceFile, "utf-8");
2494
+ } else if (existsSync12(specFile)) {
2495
+ content = readFileSync10(specFile, "utf-8");
1193
2496
  } else {
1194
2497
  out(
1195
2498
  fmt,
@@ -1202,7 +2505,7 @@ async function validate(targetPath, options) {
1202
2505
  continue;
1203
2506
  }
1204
2507
  const criteriaLines = content.match(/- \[ \] \*\*(.+?)\*\*: (.+)/g) || [];
1205
- const specContent = existsSync7(specFile) ? readFileSync6(specFile, "utf-8") : null;
2508
+ const specContent = existsSync12(specFile) ? readFileSync10(specFile, "utf-8") : null;
1206
2509
  out(fmt, "info", entry.name, "", `Spec: ${entry.name}`, "");
1207
2510
  if (criteriaLines.length === 0) {
1208
2511
  out(fmt, "info", entry.name, "", "No criteria found", "");
@@ -1219,7 +2522,7 @@ async function validate(targetPath, options) {
1219
2522
  let intelligenceResult = null;
1220
2523
  try {
1221
2524
  intelligenceResult = checkSpecContent(
1222
- join7(specsDir, entry.name),
2525
+ join12(specsDir, entry.name),
1223
2526
  label,
1224
2527
  description,
1225
2528
  config
@@ -1228,20 +2531,20 @@ async function validate(targetPath, options) {
1228
2531
  status = intelligenceResult.status;
1229
2532
  note = intelligenceResult.note;
1230
2533
  } else if (label.includes("letra init")) {
1231
- const tmp = mkdtempSync(join7(tmpdir(), "letra-test-"));
2534
+ const tmp = mkdtempSync(join12(tmpdir(), "letra-test-"));
1232
2535
  execSync(`npx tsx "${entryPoint}" init "${tmp}"`, { ...opts });
1233
- if (existsSync7(join7(tmp, ".letra", "context.md")))
2536
+ if (existsSync12(join12(tmp, ".letra", "context.md")))
1234
2537
  status = "PASS";
1235
2538
  rmSync(tmp, { recursive: true });
1236
2539
  } else if (label.includes("letra spec")) {
1237
- const tmp = mkdtempSync(join7(tmpdir(), "letra-test-"));
2540
+ const tmp = mkdtempSync(join12(tmpdir(), "letra-test-"));
1238
2541
  execSync(`npx tsx "${entryPoint}" init "${tmp}"`, { ...opts });
1239
2542
  execSync(`npx tsx "${entryPoint}" spec smoke-test`, {
1240
2543
  ...opts,
1241
2544
  cwd: tmp
1242
2545
  });
1243
- if (existsSync7(
1244
- join7(tmp, ".letra", "specs", "smoke-test", "spec.md")
2546
+ if (existsSync12(
2547
+ join12(tmp, ".letra", "specs", "smoke-test", "spec.md")
1245
2548
  ))
1246
2549
  status = "PASS";
1247
2550
  rmSync(tmp, { recursive: true });
@@ -1250,23 +2553,23 @@ async function validate(targetPath, options) {
1250
2553
  status = "PASS";
1251
2554
  } else if (label.includes("letra validate")) {
1252
2555
  status = "PASS";
1253
- } else if (label.includes("Workflow Ativo") || label.includes("CI") && existsSync7(ciFile)) {
2556
+ } else if (label.includes("Workflow Ativo") || label.includes("CI") && existsSync12(ciFile)) {
1254
2557
  status = "PASS";
1255
2558
  } else if (label.includes("Lint Gate") || label.includes("Lint")) {
1256
- const ciContent = readFileSync6(ciFile, "utf-8");
2559
+ const ciContent = readFileSync10(ciFile, "utf-8");
1257
2560
  if (ciContent.includes("letra lint") || ciContent.includes("lint"))
1258
2561
  status = "PASS";
1259
2562
  } else if (label.includes("Test Gate") || label.includes("Test")) {
1260
- const ciContent = readFileSync6(ciFile, "utf-8");
2563
+ const ciContent = readFileSync10(ciFile, "utf-8");
1261
2564
  if (ciContent.includes("npm test") || ciContent.includes("vitest") || ciContent.includes("test"))
1262
2565
  status = "PASS";
1263
2566
  } else if (label.includes("Valida\xE7\xE3o de Formato") || label.includes("Formato")) {
1264
- const ciContent = readFileSync6(ciFile, "utf-8");
2567
+ const ciContent = readFileSync10(ciFile, "utf-8");
1265
2568
  if (ciContent.includes("tsc") || ciContent.includes("typecheck"))
1266
2569
  status = "PASS";
1267
2570
  } else if (label.includes("Distribui\xE7\xE3o npm") || label.includes("npm")) {
1268
2571
  const pkgJson = JSON.parse(
1269
- readFileSync6(join7(root, "package.json"), "utf-8")
2572
+ readFileSync10(join12(root, "package.json"), "utf-8")
1270
2573
  );
1271
2574
  if (pkgJson.bin && pkgJson.name) {
1272
2575
  status = "PASS";
@@ -1278,39 +2581,39 @@ async function validate(targetPath, options) {
1278
2581
  status = "PASS";
1279
2582
  note = "(npm distribution preferred)";
1280
2583
  } else if (label.includes("Gera\xE7\xE3o de Regras") || label.includes("Gera\xE7\xE3o")) {
1281
- if (existsSync7(cursorRulesFile)) {
1282
- const rulesContent = readFileSync6(cursorRulesFile, "utf-8");
2584
+ if (existsSync12(cursorRulesFile)) {
2585
+ const rulesContent = readFileSync10(cursorRulesFile, "utf-8");
1283
2586
  if (rulesContent.includes(".letra/context.md") && rulesContent.includes(".letra/constitution.md")) {
1284
2587
  status = "PASS";
1285
2588
  }
1286
2589
  }
1287
2590
  } else if (label.includes("Inje\xE7\xE3o de Contexto")) {
1288
- if (existsSync7(cursorRulesFile)) {
1289
- const rulesContent = readFileSync6(cursorRulesFile, "utf-8");
2591
+ if (existsSync12(cursorRulesFile)) {
2592
+ const rulesContent = readFileSync10(cursorRulesFile, "utf-8");
1290
2593
  if (rulesContent.includes("@.letra/")) status = "PASS";
1291
- } else if (existsSync7(copilotFile)) {
1292
- const copilotContent = readFileSync6(copilotFile, "utf-8");
2594
+ } else if (existsSync12(copilotFile)) {
2595
+ const copilotContent = readFileSync10(copilotFile, "utf-8");
1293
2596
  if (copilotContent.includes(".letra/")) status = "PASS";
1294
2597
  }
1295
2598
  } else if (label.includes("Acesso a Valida\xE7\xE3o")) {
1296
- if (existsSync7(cursorRulesFile)) {
1297
- const rulesContent = readFileSync6(cursorRulesFile, "utf-8");
2599
+ if (existsSync12(cursorRulesFile)) {
2600
+ const rulesContent = readFileSync10(cursorRulesFile, "utf-8");
1298
2601
  if (rulesContent.includes("letra validate")) status = "PASS";
1299
2602
  }
1300
2603
  } else if (label.includes("N\xE3o-intrusivo")) {
1301
- if (existsSync7(cursorRulesFile) || existsSync7(copilotFile)) {
2604
+ if (existsSync12(cursorRulesFile) || existsSync12(copilotFile)) {
1302
2605
  status = "PASS";
1303
2606
  }
1304
2607
  } else if (label.includes("Gera\xE7\xE3o de Instru\xE7\xF5es")) {
1305
- if (existsSync7(copilotFile)) {
1306
- const copilotContent = readFileSync6(copilotFile, "utf-8");
2608
+ if (existsSync12(copilotFile)) {
2609
+ const copilotContent = readFileSync10(copilotFile, "utf-8");
1307
2610
  if (copilotContent.includes(".letra/context.md") && copilotContent.includes(".letra/constitution.md")) {
1308
2611
  status = "PASS";
1309
2612
  }
1310
2613
  }
1311
2614
  } else if (label.includes("Settings do Editor")) {
1312
- if (existsSync7(vscodeSettingsFile)) {
1313
- const settingsContent = readFileSync6(
2615
+ if (existsSync12(vscodeSettingsFile)) {
2616
+ const settingsContent = readFileSync10(
1314
2617
  vscodeSettingsFile,
1315
2618
  "utf-8"
1316
2619
  );
@@ -1319,9 +2622,9 @@ async function validate(targetPath, options) {
1319
2622
  }
1320
2623
  }
1321
2624
  } else if (label.includes("Arquivo de Config")) {
1322
- const configFile = join7(root, ".letra", "config.json");
1323
- if (existsSync7(configFile)) {
1324
- const cfgContent = readFileSync6(configFile, "utf-8");
2625
+ const configFile = join12(root, ".letra", "config.json");
2626
+ if (existsSync12(configFile)) {
2627
+ const cfgContent = readFileSync10(configFile, "utf-8");
1325
2628
  try {
1326
2629
  const parsed = JSON.parse(cfgContent);
1327
2630
  if (parsed.heuristics) {
@@ -1542,14 +2845,14 @@ async function validate(targetPath, options) {
1542
2845
  const exitCode = await runValidation();
1543
2846
  if (options?.watch) {
1544
2847
  let timer = null;
1545
- console.log(chalk6.gray("\nWatching for changes... (Ctrl+C to stop)"));
1546
- const watcher = watch(specsDir, { recursive: true });
2848
+ console.log(chalk13.gray("\nWatching for changes... (Ctrl+C to stop)"));
2849
+ const watcher = watch2(specsDir, { recursive: true });
1547
2850
  watcher.on("change", () => {
1548
2851
  if (timer) clearTimeout(timer);
1549
2852
  timer = setTimeout(async () => {
1550
2853
  console.clear();
1551
2854
  const code = await runValidation();
1552
- console.log(chalk6.gray("\nWatching for changes... (Ctrl+C to stop)"));
2855
+ console.log(chalk13.gray("\nWatching for changes... (Ctrl+C to stop)"));
1553
2856
  }, 300);
1554
2857
  });
1555
2858
  process.on("SIGINT", () => {
@@ -1570,17 +2873,19 @@ async function validate(targetPath, options) {
1570
2873
  // src/index.ts
1571
2874
  var __dirname2 = fileURLToPath2(new URL(".", import.meta.url));
1572
2875
  var pkg = JSON.parse(
1573
- readFileSync7(join8(resolve7(__dirname2, ".."), "package.json"), "utf-8")
2876
+ readFileSync11(join13(resolve15(__dirname2, ".."), "package.json"), "utf-8")
1574
2877
  );
1575
- var program = new Command3();
2878
+ var program = new Command4();
1576
2879
  program.name("letra").description("SDD-agnostic memory framework for AI coding agents").version(pkg.version);
1577
2880
  program.command("init [path]").option("--yes", "Skip prompts and use defaults").description("Initialize .letra/ directory with templates").action((path, options) => init(path, { ...options }));
1578
- program.command("spec <name>").option(
2881
+ var specCmd = program.command("spec").description("Manage specs");
2882
+ specCmd.command("new <name>").option(
1579
2883
  "--template <type>",
1580
2884
  "Template type: web-api, cli-tool, mobile-feature"
1581
2885
  ).description("Create a new spec from template").action((name, options) => specNew(name, { ...options }));
1582
2886
  program.command("lint [path]").description("Validate spec format and completeness").action(lint);
1583
2887
  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 }));
1584
2888
  program.addCommand(decisionCommand());
2889
+ program.addCommand(flowCommand());
1585
2890
  program.addCommand(focus_default());
1586
2891
  program.parse();