@letra-ai/cli 0.1.13 → 0.2.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 (39) hide show
  1. package/.letra/constitution.md +35 -35
  2. package/.letra/context.md +29 -29
  3. package/.letra/decisions/flow-mvp-escopo-enxuto-3-comandos-valor-imediato.md +35 -0
  4. package/.letra/glossary.md +21 -16
  5. package/.letra/lessons-learned.md +20 -20
  6. package/.letra/specs/_template.md +27 -27
  7. package/.letra/specs/adapter-claude-code/acceptance.md +6 -0
  8. package/.letra/specs/adapter-claude-code/spec.md +27 -27
  9. package/.letra/specs/adapter-codex-cli/acceptance.md +6 -0
  10. package/.letra/specs/adapter-cursor/acceptance.md +6 -6
  11. package/.letra/specs/adapter-cursor/spec.md +29 -29
  12. package/.letra/specs/adapter-opencode/acceptance.md +6 -6
  13. package/.letra/specs/adapter-opencode/spec.md +35 -35
  14. package/.letra/specs/adapter-vscode/acceptance.md +6 -6
  15. package/.letra/specs/adapter-vscode/spec.md +29 -29
  16. package/.letra/specs/adapter-windsurf/acceptance.md +6 -0
  17. package/.letra/specs/adapter-windsurf/spec.md +27 -27
  18. package/.letra/specs/ci-cd-pipeline/acceptance.md +6 -6
  19. package/.letra/specs/ci-cd-pipeline/spec.md +30 -27
  20. package/.letra/specs/cli-skeleton/acceptance.md +7 -7
  21. package/.letra/specs/cli-skeleton/spec.md +30 -30
  22. package/.letra/specs/flow-edit-diff/acceptance.md +7 -0
  23. package/.letra/specs/flow-edit-diff/spec.md +30 -0
  24. package/.letra/specs/flow-export-import/acceptance.md +7 -0
  25. package/.letra/specs/flow-export-import/spec.md +27 -0
  26. package/.letra/specs/flow-mvp/roadmap.md +40 -0
  27. package/.letra/specs/flow-mvp/spec.md +40 -0
  28. package/.letra/specs/flow-visualize/acceptance.md +7 -0
  29. package/.letra/specs/flow-visualize/spec.md +28 -0
  30. package/.letra/specs/validate-config/acceptance.md +9 -0
  31. package/.letra/specs/validate-intelligence/acceptance.md +9 -6
  32. package/.letra/specs/validate-intelligence/spec.md +30 -30
  33. package/LICENSE +21 -21
  34. package/README.md +240 -198
  35. package/dist/index.js +1071 -202
  36. package/package.json +61 -57
  37. package/tsup.config.ts +11 -0
  38. package/dist/index.cjs +0 -1577
  39. package/dist/index.d.cts +0 -2
package/dist/index.js CHANGED
@@ -1,5 +1,10 @@
1
+ #!/usr/bin/env node
2
+
1
3
  // src/index.ts
2
- import { Command as Command3 } from "commander";
4
+ import { readFileSync as readFileSync10 } from "fs";
5
+ import { join as join12, resolve as resolve14 } from "path";
6
+ import { fileURLToPath as fileURLToPath2 } from "url";
7
+ import { Command as Command4 } from "commander";
3
8
 
4
9
  // src/commands/decision.ts
5
10
  import {
@@ -83,36 +88,897 @@ What are the trade-offs? What does this enable or prevent?
83
88
  return cmd;
84
89
  }
85
90
 
86
- // src/commands/focus.ts
87
- 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";
88
100
  import { join as join2, resolve as resolve2 } from "path";
101
+ import { createInterface } from "readline";
89
102
  import chalk2 from "chalk";
90
- 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((resolve15) => {
108
+ const formatted = `${chalk2.cyan(query)} ${chalk2.gray(`(default: ${defaultValue})`)}
109
+ > `;
110
+ rl.question(formatted, (answer) => {
111
+ rl.close();
112
+ resolve15(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-visualize.ts
822
+ import { writeFileSync as writeFileSync6 } from "fs";
823
+ import { resolve as resolve8 } from "path";
824
+ import chalk8 from "chalk";
825
+ var MERMAID_LIVE = "https://mermaid.live/edit#";
826
+ function generateMermaid(workflow) {
827
+ const sorted = [...workflow.stages].sort((a, b) => a.order - b.order);
828
+ const itemsByStage = /* @__PURE__ */ new Map();
829
+ for (const item of workflow.items) {
830
+ itemsByStage.set(item.stage, (itemsByStage.get(item.stage) ?? 0) + 1);
831
+ }
832
+ function labelFor(stage) {
833
+ const count = itemsByStage.get(stage.id) ?? 0;
834
+ return `${stage.name} (${count} ${count === 1 ? "item" : "items"})`;
835
+ }
836
+ const lines = ["flowchart LR"];
837
+ if (sorted.length === 0) return lines.join("\n");
838
+ if (sorted.length === 1) {
839
+ lines.push(` ${sorted[0].id}["${labelFor(sorted[0])}"]`);
840
+ return lines.join("\n");
841
+ }
842
+ lines.push(
843
+ ` ${sorted[0].id}["${labelFor(sorted[0])}"] --> ${sorted[1].id}["${labelFor(sorted[1])}"]`
844
+ );
845
+ for (let i = 1; i < sorted.length - 1; i++) {
846
+ lines.push(
847
+ ` ${sorted[i].id} --> ${sorted[i + 1].id}["${labelFor(sorted[i + 1])}"]`
848
+ );
849
+ }
850
+ return lines.join("\n");
851
+ }
852
+ function buildHtml(mermaid) {
853
+ return `<!DOCTYPE html>
854
+ <html lang="en">
855
+ <head>
856
+ <meta charset="UTF-8">
857
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
858
+ <title>Workflow Diagram</title>
859
+ <script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script>
860
+ <style>
861
+ body { font-family: system-ui, sans-serif; max-width: 960px; margin: 2rem auto; padding: 0 1rem; }
862
+ .mermaid { text-align: center; }
863
+ </style>
864
+ </head>
865
+ <body>
866
+ <pre class="mermaid">
867
+ ${mermaid}
868
+ </pre>
869
+ <script>mermaid.initialize({ startOnLoad: true });</script>
870
+ </body>
871
+ </html>`;
872
+ }
873
+ function flowVisualize(root, options) {
874
+ const workflow = loadWorkflow(root);
875
+ if (!workflow) {
876
+ console.log(
877
+ chalk8.yellow("No workflow found. Run 'letra flow init --quick' first")
878
+ );
879
+ return;
880
+ }
881
+ const mermaid = generateMermaid(workflow);
882
+ if (options?.output) {
883
+ const outputPath = resolve8(root, options.output);
884
+ const ext = options.output.toLowerCase().split(".").pop();
885
+ let content;
886
+ let label;
887
+ if (ext === "html") {
888
+ content = buildHtml(mermaid);
889
+ label = "HTML page";
890
+ } else if (ext === "md") {
891
+ content = `\`\`\`mermaid
892
+ ${mermaid}
893
+ \`\`\`
894
+ `;
895
+ label = "Markdown file";
896
+ } else {
897
+ content = `${mermaid}
898
+ `;
899
+ label = "Diagram file";
900
+ }
901
+ writeFileSync6(outputPath, content);
902
+ console.log(`${label} saved to ${options.output}`);
903
+ } else {
904
+ console.log(mermaid);
905
+ console.log(chalk8.dim(`
906
+ Copy to ${MERMAID_LIVE} to render`));
907
+ }
908
+ }
909
+ function flowVisualizeAction(targetPath, options) {
910
+ const root = resolve8(process.cwd(), targetPath || ".");
911
+ flowVisualize(root, options);
912
+ }
913
+
914
+ // src/commands/flow.ts
915
+ function flowCommand() {
916
+ const cmd = new Command2("flow");
917
+ cmd.command("init [path]").option("--quick", "Quick setup with 3 questions only").description("Initialize workflow in .letra/workflow.json").action((path, options) => {
918
+ flowInitAction(path, { quick: options.quick });
919
+ });
920
+ const backlog = cmd.command("backlog").description("Manage backlog items");
921
+ backlog.command("add <description>").description("Add item to the first stage").action((description) => {
922
+ backlogActionAdd(void 0, description);
923
+ });
924
+ backlog.command("list").description("List all items with stage and age").action(() => {
925
+ backlogActionList(void 0);
926
+ });
927
+ cmd.command("move <item-id>").requiredOption("--to <stage>", "Target stage id or name").description("Move item to another stage and regenerate adapters").action((itemId, options) => {
928
+ flowMoveAction(void 0, itemId, options);
929
+ });
930
+ cmd.command("board").description("Show board with all stages and items").action(() => {
931
+ flowBoardAction(void 0);
932
+ });
933
+ cmd.command("export").option("--minified", "Output JSON without indentation").description("Export workflow to stdout").action((options) => {
934
+ flowExportAction(void 0, options);
935
+ });
936
+ cmd.command("import <file>").description("Import workflow from a JSON file").action((file) => {
937
+ flowImportAction(void 0, file);
938
+ });
939
+ cmd.command("visualize").option("--output <file>", "Save diagram to file").description("Generate Mermaid diagram of workflow").action((options) => {
940
+ flowVisualizeAction(void 0, options);
941
+ });
942
+ cmd.command("edit").option("--name <name>", "New workflow name").option("--desc <desc>", "New workflow description").description("Edit workflow metadata").action((options) => {
943
+ flowEditAction(void 0, options);
944
+ });
945
+ cmd.command("diff [v1] [v2]").description("Show diff between workflow versions").action((...args) => {
946
+ const strings = args.filter((a) => typeof a === "string");
947
+ flowDiffAction(void 0, strings[0], strings[1]);
948
+ });
949
+ return cmd;
950
+ }
951
+
952
+ // src/commands/focus.ts
953
+ import { existsSync as existsSync6, readFileSync as readFileSync5, unlinkSync, writeFileSync as writeFileSync7 } from "fs";
954
+ import { join as join6, resolve as resolve9 } from "path";
955
+ import chalk9 from "chalk";
956
+ import { Command as Command3 } from "commander";
91
957
  function extractOutcome(specDir) {
92
- const specFile = join2(specDir, "spec.md");
93
- if (!existsSync2(specFile)) return null;
94
- const content = readFileSync2(specFile, "utf-8");
958
+ const specFile = join6(specDir, "spec.md");
959
+ if (!existsSync6(specFile)) return null;
960
+ const content = readFileSync5(specFile, "utf-8");
95
961
  const match = content.match(/## Outcome\s+([\s\S]*?)(?=\n## |\n*$)/);
96
962
  return match ? match[1].trim() : null;
97
963
  }
98
964
  function focus_default() {
99
- return new Command2("focus").argument("[spec]", "Spec name to focus on").option("--clear", "Remove focus file").action((spec, options) => {
100
- const root = resolve2(process.cwd());
101
- const focusFile = join2(root, ".letra", "focus.md");
965
+ return new Command3("focus").argument("[spec]", "Spec name to focus on").option("--clear", "Remove focus file").action((spec, options) => {
966
+ const root = resolve9(process.cwd());
967
+ const focusFile = join6(root, ".letra", "focus.md");
102
968
  if (options.clear) {
103
- if (existsSync2(focusFile)) {
969
+ if (existsSync6(focusFile)) {
104
970
  unlinkSync(focusFile);
105
- console.log(chalk2.green("Focus removed."));
971
+ console.log(chalk9.green("Focus removed."));
106
972
  } else {
107
- console.log(chalk2.yellow("No focus to remove."));
973
+ console.log(chalk9.yellow("No focus to remove."));
108
974
  }
109
975
  return;
110
976
  }
111
977
  if (spec) {
112
- const specDir = join2(root, ".letra", "specs", spec);
113
- const specFile = join2(specDir, "spec.md");
114
- if (!existsSync2(specFile)) {
115
- console.log(chalk2.red(`Spec "${spec}" not found`));
978
+ const specDir = join6(root, ".letra", "specs", spec);
979
+ const specFile = join6(specDir, "spec.md");
980
+ if (!existsSync6(specFile)) {
981
+ console.log(chalk9.red(`Spec "${spec}" not found`));
116
982
  process.exit(1);
117
983
  }
118
984
  const outcome = extractOutcome(specDir);
@@ -124,12 +990,12 @@ function focus_default() {
124
990
  outcomeLine,
125
991
  ""
126
992
  ].join("\n");
127
- writeFileSync2(focusFile, focusContent);
128
- console.log(chalk2.green(`Focus set to "${spec}".`));
993
+ writeFileSync7(focusFile, focusContent);
994
+ console.log(chalk9.green(`Focus set to "${spec}".`));
129
995
  return;
130
996
  }
131
- if (existsSync2(focusFile)) {
132
- console.log(readFileSync2(focusFile, "utf-8"));
997
+ if (existsSync6(focusFile)) {
998
+ console.log(readFileSync5(focusFile, "utf-8"));
133
999
  } else {
134
1000
  console.log("Nenhum foco definido.");
135
1001
  }
@@ -139,33 +1005,33 @@ function focus_default() {
139
1005
  // src/commands/init.ts
140
1006
  import {
141
1007
  copyFileSync,
142
- existsSync as existsSync3,
143
- mkdirSync as mkdirSync2,
144
- writeFileSync as writeFileSync3
1008
+ existsSync as existsSync7,
1009
+ mkdirSync as mkdirSync4,
1010
+ writeFileSync as writeFileSync8
145
1011
  } from "fs";
146
- import { join as join3, resolve as resolve3 } from "path";
147
- import { createInterface } from "readline";
1012
+ import { join as join7, resolve as resolve10 } from "path";
1013
+ import { createInterface as createInterface2 } from "readline";
148
1014
  import { fileURLToPath } from "url";
149
- import chalk3 from "chalk";
150
- import ora from "ora";
1015
+ import chalk10 from "chalk";
1016
+ import ora2 from "ora";
151
1017
  var __dirname = fileURLToPath(new URL(".", import.meta.url));
152
1018
  function ask(query, options) {
153
1019
  if (!process.stdin.isTTY) return Promise.resolve(options[0]);
154
- const rl = createInterface({ input: process.stdin, output: process.stdout });
155
- return new Promise((resolve7) => {
156
- const formatted = `${chalk3.cyan(query)} ${options.map((o) => chalk3.gray(`(${o})`)).join(" ")}
1020
+ const rl = createInterface2({ input: process.stdin, output: process.stdout });
1021
+ return new Promise((resolve15) => {
1022
+ const formatted = `${chalk10.cyan(query)} ${options.map((o) => chalk10.gray(`(${o})`)).join(" ")}
157
1023
  > `;
158
1024
  rl.question(formatted, (answer) => {
159
1025
  rl.close();
160
1026
  const trimmed = answer.trim().toLowerCase();
161
1027
  if (trimmed && options.some((o) => o.toLowerCase().startsWith(trimmed))) {
162
- resolve7(
1028
+ resolve15(
163
1029
  options.find((o) => o.toLowerCase().startsWith(trimmed)) ?? options[0]
164
1030
  );
165
1031
  } else if (trimmed && options.includes(trimmed)) {
166
- resolve7(trimmed);
1032
+ resolve15(trimmed);
167
1033
  } else {
168
- resolve7(options[0]);
1034
+ resolve15(options[0]);
169
1035
  }
170
1036
  });
171
1037
  });
@@ -236,49 +1102,49 @@ ${format === "at" ? "# Context\n@.letra/context.md\n@.letra/constitution.md\n@.l
236
1102
  switch (tool) {
237
1103
  case "cursor":
238
1104
  adapters.push({
239
- path: join3(root, ".cursorrules"),
1105
+ path: join7(root, ".cursorrules"),
240
1106
  content: baseContent("Cursor", "at")
241
1107
  });
242
1108
  break;
243
1109
  case "claude-code":
244
1110
  adapters.push({
245
- path: join3(root, "CLAUDE.md"),
1111
+ path: join7(root, "CLAUDE.md"),
246
1112
  content: baseContent("Claude Code", "text")
247
1113
  });
248
1114
  break;
249
1115
  case "windsurf":
250
1116
  adapters.push({
251
- path: join3(root, ".windsurfrules"),
1117
+ path: join7(root, ".windsurfrules"),
252
1118
  content: baseContent("Windsurf", "at")
253
1119
  });
254
1120
  break;
255
1121
  case "vscode":
256
1122
  adapters.push({
257
- path: join3(root, ".github", "copilot-instructions.md"),
1123
+ path: join7(root, ".github", "copilot-instructions.md"),
258
1124
  content: baseContent("VSCode Copilot", "text")
259
1125
  });
260
1126
  break;
261
1127
  case "opencode":
262
1128
  adapters.push({
263
- path: join3(root, "AGENTS.md"),
1129
+ path: join7(root, "AGENTS.md"),
264
1130
  content: baseContent("OpenCode", "text")
265
1131
  });
266
1132
  break;
267
1133
  }
268
1134
  }
269
1135
  for (const { path, content } of adapters) {
270
- const dir = join3(path, "..");
271
- if (!existsSync3(dir)) mkdirSync2(dir, { recursive: true });
272
- writeFileSync3(path, content);
273
- console.log(` ${chalk3.gray("Created")} ${path.replace(`${root}/`, "")}`);
1136
+ const dir = join7(path, "..");
1137
+ if (!existsSync7(dir)) mkdirSync4(dir, { recursive: true });
1138
+ writeFileSync8(path, content);
1139
+ console.log(` ${chalk10.gray("Created")} ${path.replace(`${root}/`, "")}`);
274
1140
  }
275
1141
  }
276
1142
  async function init(targetPath, options) {
277
- const root = resolve3(process.cwd(), targetPath || ".");
278
- const letraDir = join3(root, ".letra");
279
- const spinner = ora("Initializing Letra...").start();
280
- if (existsSync3(letraDir)) {
281
- spinner.warn(chalk3.yellow(".letra/ already exists"));
1143
+ const root = resolve10(process.cwd(), targetPath || ".");
1144
+ const letraDir = join7(root, ".letra");
1145
+ const spinner = ora2("Initializing Letra...").start();
1146
+ if (existsSync7(letraDir)) {
1147
+ spinner.warn(chalk10.yellow(".letra/ already exists"));
282
1148
  return;
283
1149
  }
284
1150
  try {
@@ -307,10 +1173,10 @@ async function init(targetPath, options) {
307
1173
  tool = answer.toLowerCase();
308
1174
  spinner.start();
309
1175
  }
310
- mkdirSync2(join3(letraDir, "decisions"), { recursive: true });
311
- mkdirSync2(join3(letraDir, "specs", "_template"), { recursive: true });
312
- mkdirSync2(join3(letraDir, "adapters"), { recursive: true });
313
- const templateDir = join3(__dirname, "..", "..", ".letra");
1176
+ mkdirSync4(join7(letraDir, "decisions"), { recursive: true });
1177
+ mkdirSync4(join7(letraDir, "specs", "_template"), { recursive: true });
1178
+ mkdirSync4(join7(letraDir, "adapters"), { recursive: true });
1179
+ const templateDir = join7(__dirname, "..", "..", ".letra");
314
1180
  const templates = [
315
1181
  "context.md",
316
1182
  "constitution.md",
@@ -318,11 +1184,11 @@ async function init(targetPath, options) {
318
1184
  "lessons-learned.md"
319
1185
  ];
320
1186
  for (const file of templates) {
321
- const src = join3(templateDir, file);
322
- const dest = join3(letraDir, file);
323
- if (existsSync3(src)) copyFileSync(src, dest);
1187
+ const src = join7(templateDir, file);
1188
+ const dest = join7(letraDir, file);
1189
+ if (existsSync7(src)) copyFileSync(src, dest);
324
1190
  }
325
- const specTemplate = join3(letraDir, "specs", "_template.md");
1191
+ const specTemplate = join7(letraDir, "specs", "_template.md");
326
1192
  const specContent = `# Spec Template
327
1193
 
328
1194
  ## Outcome
@@ -340,16 +1206,16 @@ O que explicitamente N\xC3O est\xE1 neste escopo.
340
1206
  ## Context
341
1207
  Por que estamos construindo isso.
342
1208
  `;
343
- writeFileSync3(specTemplate, specContent);
344
- const configPath = join3(letraDir, "config.json");
345
- writeFileSync3(configPath, adaptConfig(projectType));
346
- console.log(` ${chalk3.gray("Created")} .letra/config.json`);
1209
+ writeFileSync8(specTemplate, specContent);
1210
+ const configPath = join7(letraDir, "config.json");
1211
+ writeFileSync8(configPath, adaptConfig(projectType));
1212
+ console.log(` ${chalk10.gray("Created")} .letra/config.json`);
347
1213
  const tools = adaptersForTool(tool);
348
1214
  generateAdapterFiles(root, tools);
349
1215
  if (tool === "todos" || tool === "vscode") {
350
- const vscodeDir = join3(root, ".vscode");
351
- if (!existsSync3(vscodeDir)) mkdirSync2(vscodeDir, { recursive: true });
352
- const vscodeSettingsPath = join3(vscodeDir, "settings.json");
1216
+ const vscodeDir = join7(root, ".vscode");
1217
+ if (!existsSync7(vscodeDir)) mkdirSync4(vscodeDir, { recursive: true });
1218
+ const vscodeSettingsPath = join7(vscodeDir, "settings.json");
353
1219
  const vscodeSettingsContent = `{
354
1220
  "editor.formatOnSave": true,
355
1221
  "editor.defaultFormatter": "esbenp.prettier-vscode",
@@ -359,26 +1225,26 @@ Por que estamos construindo isso.
359
1225
  "files.autoSave": "onFocusChange"
360
1226
  }
361
1227
  `;
362
- writeFileSync3(vscodeSettingsPath, vscodeSettingsContent);
363
- console.log(` ${chalk3.gray("Created")} .vscode/settings.json`);
1228
+ writeFileSync8(vscodeSettingsPath, vscodeSettingsContent);
1229
+ console.log(` ${chalk10.gray("Created")} .vscode/settings.json`);
364
1230
  }
365
- spinner.succeed(chalk3.green(".letra/ initialized successfully"));
1231
+ spinner.succeed(chalk10.green(".letra/ initialized successfully"));
366
1232
  console.log("");
367
1233
  console.log(" Next steps:");
368
1234
  console.log(
369
- ` ${chalk3.cyan("letra spec new <name>")} Create your first spec`
1235
+ ` ${chalk10.cyan("letra spec new <name>")} Create your first spec`
370
1236
  );
371
- console.log(` ${chalk3.cyan("letra lint")} Validate specs`);
1237
+ console.log(` ${chalk10.cyan("letra lint")} Validate specs`);
372
1238
  } catch (error) {
373
- spinner.fail(chalk3.red("Failed to initialize Letra"));
1239
+ spinner.fail(chalk10.red("Failed to initialize Letra"));
374
1240
  process.exit(1);
375
1241
  }
376
1242
  }
377
1243
 
378
1244
  // src/commands/lint.ts
379
- import { existsSync as existsSync4, readFileSync as readFileSync3, readdirSync as readdirSync3 } from "fs";
380
- import { join as join4, resolve as resolve4 } from "path";
381
- import chalk4 from "chalk";
1245
+ import { existsSync as existsSync8, readFileSync as readFileSync6, readdirSync as readdirSync4 } from "fs";
1246
+ import { join as join8, resolve as resolve11 } from "path";
1247
+ import chalk11 from "chalk";
382
1248
  var REQUIRED_SECTIONS = [
383
1249
  "## Outcome",
384
1250
  "## Constraints",
@@ -387,27 +1253,27 @@ var REQUIRED_SECTIONS = [
387
1253
  "## Context"
388
1254
  ];
389
1255
  async function lint(targetPath) {
390
- const root = resolve4(process.cwd(), targetPath || ".");
391
- const specsDir = join4(root, ".letra", "specs");
392
- if (!existsSync4(specsDir)) {
1256
+ const root = resolve11(process.cwd(), targetPath || ".");
1257
+ const specsDir = join8(root, ".letra", "specs");
1258
+ if (!existsSync8(specsDir)) {
393
1259
  console.log(
394
- chalk4.red("Error: .letra/specs/ not found. Run 'letra init' first.")
1260
+ chalk11.red("Error: .letra/specs/ not found. Run 'letra init' first.")
395
1261
  );
396
1262
  process.exit(1);
397
1263
  }
398
1264
  const results = [];
399
1265
  let totalErrors = 0;
400
1266
  let totalWarnings = 0;
401
- const entries = readdirSync3(specsDir, { withFileTypes: true });
1267
+ const entries = readdirSync4(specsDir, { withFileTypes: true });
402
1268
  for (const entry of entries) {
403
1269
  if (!entry.isDirectory() || entry.name.startsWith("_")) continue;
404
- const specFile = join4(specsDir, entry.name, "spec.md");
1270
+ const specFile = join8(specsDir, entry.name, "spec.md");
405
1271
  const errors = [];
406
1272
  const warnings = [];
407
- if (!existsSync4(specFile)) {
1273
+ if (!existsSync8(specFile)) {
408
1274
  errors.push("Missing spec.md");
409
1275
  } else {
410
- const content = readFileSync3(specFile, "utf-8");
1276
+ const content = readFileSync6(specFile, "utf-8");
411
1277
  for (const section of REQUIRED_SECTIONS) {
412
1278
  if (!content.includes(section)) {
413
1279
  errors.push(`Missing section: ${section}`);
@@ -430,22 +1296,22 @@ async function lint(targetPath) {
430
1296
  }
431
1297
  }
432
1298
  if (results.length === 0) {
433
- console.log(chalk4.green("All specs are valid"));
1299
+ console.log(chalk11.green("All specs are valid"));
434
1300
  process.exit(0);
435
1301
  }
436
1302
  console.log("");
437
1303
  for (const result of results) {
438
- console.log(chalk4.bold(`
1304
+ console.log(chalk11.bold(`
439
1305
  Spec: ${result.file}`));
440
1306
  for (const error of result.errors) {
441
- console.log(chalk4.red(` \u2717 ${error}`));
1307
+ console.log(chalk11.red(` \u2717 ${error}`));
442
1308
  }
443
1309
  for (const warning of result.warnings) {
444
- console.log(chalk4.yellow(` \u26A0 ${warning}`));
1310
+ console.log(chalk11.yellow(` \u26A0 ${warning}`));
445
1311
  }
446
1312
  }
447
1313
  console.log(
448
- chalk4.gray(
1314
+ chalk11.gray(
449
1315
  `
450
1316
  ${results.length} spec(s) with issues: ${totalErrors} error(s), ${totalWarnings} warning(s)`
451
1317
  )
@@ -455,15 +1321,15 @@ ${results.length} spec(s) with issues: ${totalErrors} error(s), ${totalWarnings}
455
1321
 
456
1322
  // src/commands/spec.ts
457
1323
  import {
458
- existsSync as existsSync5,
459
- mkdirSync as mkdirSync3,
460
- readFileSync as readFileSync4,
461
- readdirSync as readdirSync4,
462
- writeFileSync as writeFileSync4
1324
+ existsSync as existsSync9,
1325
+ mkdirSync as mkdirSync5,
1326
+ readFileSync as readFileSync7,
1327
+ readdirSync as readdirSync5,
1328
+ writeFileSync as writeFileSync9
463
1329
  } from "fs";
464
- import { join as join5, resolve as resolve5 } from "path";
465
- import chalk5 from "chalk";
466
- import ora2 from "ora";
1330
+ import { join as join9, resolve as resolve12 } from "path";
1331
+ import chalk12 from "chalk";
1332
+ import ora3 from "ora";
467
1333
  var builtInTemplates = {
468
1334
  "web-api": {
469
1335
  spec: `# Spec: {{name}}
@@ -567,9 +1433,9 @@ Template para features mobile nativas. Adaptado para o framework espec\xEDfico (
567
1433
  };
568
1434
  function listTemplates(root) {
569
1435
  const names = Object.keys(builtInTemplates);
570
- const customDir = join5(root, ".letra", "templates");
571
- if (existsSync5(customDir)) {
572
- for (const file of readdirSync4(customDir)) {
1436
+ const customDir = join9(root, ".letra", "templates");
1437
+ if (existsSync9(customDir)) {
1438
+ for (const file of readdirSync5(customDir)) {
573
1439
  if (file.endsWith(".md")) {
574
1440
  const name = file.replace(/\.md$/, "");
575
1441
  if (!names.includes(name)) names.push(name);
@@ -581,16 +1447,16 @@ function listTemplates(root) {
581
1447
  function findTemplate(root, type) {
582
1448
  const lower = type.toLowerCase();
583
1449
  if (builtInTemplates[lower]) return builtInTemplates[lower];
584
- const customFile = join5(root, ".letra", "templates", `${type}.md`);
585
- const customAcceptance = join5(
1450
+ const customFile = join9(root, ".letra", "templates", `${type}.md`);
1451
+ const customAcceptance = join9(
586
1452
  root,
587
1453
  ".letra",
588
1454
  "templates",
589
1455
  `${type}-acceptance.md`
590
1456
  );
591
- if (existsSync5(customFile)) {
592
- const spec = readFileSync4(customFile, "utf-8");
593
- const acceptance = existsSync5(customAcceptance) ? readFileSync4(customAcceptance, "utf-8") : `# Acceptance Criteria \u2014 ${type}
1457
+ if (existsSync9(customFile)) {
1458
+ const spec = readFileSync7(customFile, "utf-8");
1459
+ const acceptance = existsSync9(customAcceptance) ? readFileSync7(customAcceptance, "utf-8") : `# Acceptance Criteria \u2014 ${type}
594
1460
 
595
1461
  - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
596
1462
  `;
@@ -602,15 +1468,15 @@ function applyPlaceholders(content, name) {
602
1468
  return content.replace(/\{\{name\}\}/g, name);
603
1469
  }
604
1470
  async function specNew(name, options) {
605
- const root = resolve5(process.cwd());
606
- const letraDir = join5(root, ".letra");
607
- const specDir = join5(letraDir, "specs", name);
608
- if (!existsSync5(letraDir)) {
609
- console.log(chalk5.red(".letra/ not found. Run 'letra init' first."));
1471
+ const root = resolve12(process.cwd());
1472
+ const letraDir = join9(root, ".letra");
1473
+ const specDir = join9(letraDir, "specs", name);
1474
+ if (!existsSync9(letraDir)) {
1475
+ console.log(chalk12.red(".letra/ not found. Run 'letra init' first."));
610
1476
  process.exit(1);
611
1477
  }
612
- if (existsSync5(specDir)) {
613
- console.log(chalk5.yellow(`Spec "${name}" already exists`));
1478
+ if (existsSync9(specDir)) {
1479
+ console.log(chalk12.yellow(`Spec "${name}" already exists`));
614
1480
  return;
615
1481
  }
616
1482
  const templateType = options?.template || "_default";
@@ -618,20 +1484,20 @@ async function specNew(name, options) {
618
1484
  if (options?.template && !template) {
619
1485
  const available = listTemplates(root).join(", ");
620
1486
  console.log(
621
- chalk5.red(
1487
+ chalk12.red(
622
1488
  `Template "${options.template}" not found. Available: ${available}`
623
1489
  )
624
1490
  );
625
1491
  process.exit(1);
626
1492
  }
627
- const spinner = ora2(`Creating spec "${name}"...`).start();
1493
+ const spinner = ora3(`Creating spec "${name}"...`).start();
628
1494
  try {
629
- mkdirSync3(specDir, { recursive: true });
1495
+ mkdirSync5(specDir, { recursive: true });
630
1496
  if (template) {
631
1497
  const specContent = applyPlaceholders(template.spec, name);
632
1498
  const acceptanceContent = applyPlaceholders(template.acceptance, name);
633
- writeFileSync4(join5(specDir, "spec.md"), specContent);
634
- writeFileSync4(join5(specDir, "acceptance.md"), acceptanceContent);
1499
+ writeFileSync9(join9(specDir, "spec.md"), specContent);
1500
+ writeFileSync9(join9(specDir, "acceptance.md"), acceptanceContent);
635
1501
  } else {
636
1502
  const specContent = `# Spec: ${name}
637
1503
 
@@ -654,14 +1520,14 @@ Por que estamos construindo isso. Trade-offs considerados.
654
1520
 
655
1521
  - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
656
1522
  `;
657
- writeFileSync4(join5(specDir, "spec.md"), specContent);
658
- writeFileSync4(join5(specDir, "acceptance.md"), acceptanceContent);
1523
+ writeFileSync9(join9(specDir, "spec.md"), specContent);
1524
+ writeFileSync9(join9(specDir, "acceptance.md"), acceptanceContent);
659
1525
  }
660
1526
  spinner.succeed(
661
- chalk5.green(`Spec "${name}" created at .letra/specs/${name}/`)
1527
+ chalk12.green(`Spec "${name}" created at .letra/specs/${name}/`)
662
1528
  );
663
1529
  } catch (error) {
664
- spinner.fail(chalk5.red("Failed to create spec"));
1530
+ spinner.fail(chalk12.red("Failed to create spec"));
665
1531
  process.exit(1);
666
1532
  }
667
1533
  }
@@ -669,21 +1535,21 @@ Por que estamos construindo isso. Trade-offs considerados.
669
1535
  // src/commands/validate.ts
670
1536
  import { execSync } from "child_process";
671
1537
  import {
672
- existsSync as existsSync7,
1538
+ existsSync as existsSync11,
673
1539
  mkdtempSync,
674
- readFileSync as readFileSync6,
675
- readdirSync as readdirSync5,
1540
+ readFileSync as readFileSync9,
1541
+ readdirSync as readdirSync6,
676
1542
  rmSync,
677
1543
  statSync as statSync2,
678
1544
  watch
679
1545
  } from "fs";
680
1546
  import { tmpdir } from "os";
681
- import { join as join7, resolve as resolve6 } from "path";
682
- import chalk6 from "chalk";
1547
+ import { join as join11, resolve as resolve13 } from "path";
1548
+ import chalk13 from "chalk";
683
1549
 
684
1550
  // src/config.ts
685
- import { existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
686
- import { join as join6 } from "path";
1551
+ import { existsSync as existsSync10, readFileSync as readFileSync8 } from "fs";
1552
+ import { join as join10 } from "path";
687
1553
  var DEFAULT_HEURISTICS = {
688
1554
  "conteudo-minimo": { severity: "warning", minChars: 50 },
689
1555
  "consistencia-terminologia": { severity: "warning" },
@@ -698,14 +1564,14 @@ var DEFAULT_HEURISTICS = {
698
1564
  "validate-conflict": { severity: "warning" }
699
1565
  };
700
1566
  function loadConfig(root) {
701
- const configPath = join6(root, ".letra", "config.json");
1567
+ const configPath = join10(root, ".letra", "config.json");
702
1568
  const heuristics = {};
703
1569
  for (const [key, value] of Object.entries(DEFAULT_HEURISTICS)) {
704
1570
  heuristics[key] = { ...value };
705
1571
  }
706
- if (existsSync6(configPath)) {
1572
+ if (existsSync10(configPath)) {
707
1573
  try {
708
- const raw = JSON.parse(readFileSync5(configPath, "utf-8"));
1574
+ const raw = JSON.parse(readFileSync8(configPath, "utf-8"));
709
1575
  if (raw.heuristics && typeof raw.heuristics === "object") {
710
1576
  for (const [key, value] of Object.entries(raw.heuristics)) {
711
1577
  if (heuristics[key]) {
@@ -727,20 +1593,18 @@ function getHeuristicConfig(config, label) {
727
1593
  const key = heuristicKey(label);
728
1594
  return config.heuristics[key] ?? { severity: "warning" };
729
1595
  }
1596
+ function normalize(str) {
1597
+ return str.normalize("NFD").replace(/\p{M}/gu, "");
1598
+ }
730
1599
  function heuristicKey(label) {
731
- const lower = label.toLowerCase();
732
- if (lower.includes("conteudo m\xEDnimo") || lower.includes("conteudo minimo"))
733
- return "conteudo-minimo";
1600
+ const lower = normalize(label.toLowerCase());
1601
+ if (lower.includes("conteudo minimo")) return "conteudo-minimo";
734
1602
  if (lower.includes("terminologia")) return "consistencia-terminologia";
735
1603
  if (lower.includes("tom")) return "detecao-tom";
736
- if (lower.includes("drift temporal") || lower.includes("temporal"))
737
- return "drift-temporal";
738
- if (lower.includes("se\xE7\xF5es vazias") || lower.includes("secoes vazias"))
739
- return "secoes-vazias";
740
- if (lower.includes("acs sem m\xE9trica") || lower.includes("acs sem metrica"))
741
- return "acs-sem-metrica";
742
- if (lower.includes("baixa confian\xE7a") || lower.includes("baixa confianca"))
743
- return "baixa-confianca";
1604
+ if (lower.includes("drift temporal")) return "drift-temporal";
1605
+ if (lower.includes("secoes vazias")) return "secoes-vazias";
1606
+ if (lower.includes("acs sem metrica")) return "acs-sem-metrica";
1607
+ if (lower.includes("baixa confianca")) return "baixa-confianca";
744
1608
  if (lower.includes("validate conflict")) return "validate-conflict";
745
1609
  return lower.replace(/\s+/g, "-");
746
1610
  }
@@ -774,13 +1638,13 @@ var lowConfidenceMarkers = [
774
1638
  "teoricamente"
775
1639
  ];
776
1640
  function checkSpecContent(specDir, label, description, config) {
777
- const cfg = config ?? loadConfig(join7(specDir, "..", "..", ".."));
778
- const specFile = join7(specDir, "spec.md");
779
- const glossaryFile = join7(specDir, "..", "..", "glossary.md");
780
- if (!existsSync7(specFile))
1641
+ const cfg = config ?? loadConfig(join11(specDir, "..", "..", ".."));
1642
+ const specFile = join11(specDir, "spec.md");
1643
+ const glossaryFile = join11(specDir, "..", "..", "glossary.md");
1644
+ if (!existsSync11(specFile))
781
1645
  return { status: "FAIL", note: "(spec.md not found)" };
782
- const specContent = readFileSync6(specFile, "utf-8");
783
- const now = /* @__PURE__ */ new Date();
1646
+ const specContent = readFileSync9(specFile, "utf-8");
1647
+ const now6 = /* @__PURE__ */ new Date();
784
1648
  if (label.includes("Conte\xFAdo M\xEDnimo")) {
785
1649
  const outcomeMatch = specContent.match(/## Outcome\s+([\s\S]*?)(?=\n## )/);
786
1650
  if (!outcomeMatch)
@@ -800,13 +1664,13 @@ function checkSpecContent(specDir, label, description, config) {
800
1664
  };
801
1665
  }
802
1666
  if (label.includes("Consist\xEAncia de Terminologia") || label.includes("Terminologia")) {
803
- if (!existsSync7(glossaryFile)) {
1667
+ if (!existsSync11(glossaryFile)) {
804
1668
  return {
805
1669
  status: "PASS",
806
1670
  note: "(no glossary to check against)"
807
1671
  };
808
1672
  }
809
- const glossaryContent = readFileSync6(glossaryFile, "utf-8");
1673
+ const glossaryContent = readFileSync9(glossaryFile, "utf-8");
810
1674
  const terms = glossaryContent.match(/\*\*(.+?)\*\*/g) || [];
811
1675
  const extractedTerms = terms.map((t) => t.replace(/\*\*/g, "").trim()).filter((t) => t.length > 3);
812
1676
  const missingTerms = extractedTerms.filter(
@@ -846,7 +1710,7 @@ function checkSpecContent(specDir, label, description, config) {
846
1710
  if (label.includes("Drift Temporal") || label.includes("Temporal")) {
847
1711
  const stat = statSync2(specFile);
848
1712
  const daysOld = Math.floor(
849
- (now.getTime() - stat.mtimeMs) / (1e3 * 60 * 60 * 24)
1713
+ (now6.getTime() - stat.mtimeMs) / (1e3 * 60 * 60 * 24)
850
1714
  );
851
1715
  const heurConfig = getHeuristicConfig(cfg, label);
852
1716
  const maxDays = heurConfig.maxDays ?? 30;
@@ -1033,13 +1897,13 @@ function detectConflict(textA, textB) {
1033
1897
  }
1034
1898
  function checkConflicts(specsDir, config) {
1035
1899
  const results = [];
1036
- const entries = readdirSync5(specsDir, { withFileTypes: true });
1900
+ const entries = readdirSync6(specsDir, { withFileTypes: true });
1037
1901
  const specDirs = entries.filter((e) => e.isDirectory() && !e.name.startsWith("_")).map((e) => e.name);
1038
1902
  const specs = [];
1039
1903
  for (const dir of specDirs) {
1040
- const acceptanceFile = join7(specsDir, dir, "acceptance.md");
1041
- if (!existsSync7(acceptanceFile)) continue;
1042
- const content = readFileSync6(acceptanceFile, "utf-8");
1904
+ const acceptanceFile = join11(specsDir, dir, "acceptance.md");
1905
+ if (!existsSync11(acceptanceFile)) continue;
1906
+ const content = readFileSync9(acceptanceFile, "utf-8");
1043
1907
  const acLines = content.match(/- \[[ x]\] \*\*(.+?)\*\*: (.+)/g) || [];
1044
1908
  const acs = acLines.map((line) => {
1045
1909
  const m = line.match(/- \[[ x]\] \*\*(.+?)\*\*: (.+)/);
@@ -1089,12 +1953,12 @@ function out(format, level, spec, label, message, note) {
1089
1953
  if (format === "junit") {
1090
1954
  return;
1091
1955
  }
1092
- const icon = level === "pass" ? chalk6.green("\u2713") : level === "fail" ? chalk6.red("\u2717") : level === "warning" ? chalk6.yellow("\u26A0") : "";
1956
+ const icon = level === "pass" ? chalk13.green("\u2713") : level === "fail" ? chalk13.red("\u2717") : level === "warning" ? chalk13.yellow("\u26A0") : "";
1093
1957
  if (level === "info") {
1094
1958
  console.log(` ${message}`);
1095
1959
  } else {
1096
1960
  console.log(
1097
- ` [${icon}] ${chalk6.cyan(label)}: ${message} ${chalk6.gray(note)}`
1961
+ ` [${icon}] ${chalk13.cyan(label)}: ${message} ${chalk13.gray(note)}`
1098
1962
  );
1099
1963
  }
1100
1964
  }
@@ -1136,55 +2000,55 @@ function flushResults(results, format, specGroups, totalPass, totalFail, totalWa
1136
2000
  }
1137
2001
  }
1138
2002
  console.log(
1139
- chalk6.gray(
2003
+ chalk13.gray(
1140
2004
  `
1141
2005
  Results: ${totalPass} passed, ${totalFail} failed${totalWarning > 0 ? `, ${totalWarning} warnings` : ""}`
1142
2006
  )
1143
2007
  );
1144
2008
  }
1145
2009
  async function validate(targetPath, options) {
1146
- const root = resolve6(process.cwd(), targetPath || ".");
1147
- const specsDir = join7(root, ".letra", "specs");
2010
+ const root = resolve13(process.cwd(), targetPath || ".");
2011
+ const specsDir = join11(root, ".letra", "specs");
1148
2012
  const fmt = options?.format || "text";
1149
- if (!existsSync7(specsDir)) {
2013
+ if (!existsSync11(specsDir)) {
1150
2014
  const msg = "Error: .letra/specs/ not found. Run 'letra init' first.";
1151
2015
  if (fmt === "github-annotation") {
1152
2016
  console.log(`::error file=,title=Init Required::${msg}`);
1153
2017
  } else {
1154
- console.log(chalk6.red(msg));
2018
+ console.log(chalk13.red(msg));
1155
2019
  }
1156
2020
  process.exit(1);
1157
2021
  }
1158
2022
  async function runValidation() {
1159
2023
  const config = loadConfig(root);
1160
- const entries = readdirSync5(specsDir, { withFileTypes: true });
2024
+ const entries = readdirSync6(specsDir, { withFileTypes: true });
1161
2025
  let totalPass = 0;
1162
2026
  let totalFail = 0;
1163
2027
  let totalWarning = 0;
1164
2028
  const specGroups = /* @__PURE__ */ new Map();
1165
2029
  const allResults = [];
1166
- const entryPoint = join7(root, "src/index.ts");
2030
+ const entryPoint = join11(root, "src/index.ts");
1167
2031
  const opts = {
1168
2032
  stdio: "pipe",
1169
2033
  encoding: "utf-8",
1170
2034
  shell: process.platform === "win32" ? "cmd.exe" : true
1171
2035
  };
1172
- const ciFile = join7(root, ".github", "workflows", "ci.yml");
1173
- const cursorRulesFile = join7(root, ".cursorrules");
1174
- const copilotFile = join7(root, ".github", "copilot-instructions.md");
1175
- const vscodeSettingsFile = join7(root, ".vscode", "settings.json");
2036
+ const ciFile = join11(root, ".github", "workflows", "ci.yml");
2037
+ const cursorRulesFile = join11(root, ".cursorrules");
2038
+ const copilotFile = join11(root, ".github", "copilot-instructions.md");
2039
+ const vscodeSettingsFile = join11(root, ".vscode", "settings.json");
1176
2040
  if (fmt !== "junit") {
1177
2041
  out(fmt, "info", null, "", "\nLetra Validation\n", "");
1178
2042
  }
1179
2043
  for (const entry of entries) {
1180
2044
  if (!entry.isDirectory() || entry.name.startsWith("_")) continue;
1181
- const acceptanceFile = join7(specsDir, entry.name, "acceptance.md");
1182
- const specFile = join7(specsDir, entry.name, "spec.md");
2045
+ const acceptanceFile = join11(specsDir, entry.name, "acceptance.md");
2046
+ const specFile = join11(specsDir, entry.name, "spec.md");
1183
2047
  let content;
1184
- if (existsSync7(acceptanceFile)) {
1185
- content = readFileSync6(acceptanceFile, "utf-8");
1186
- } else if (existsSync7(specFile)) {
1187
- content = readFileSync6(specFile, "utf-8");
2048
+ if (existsSync11(acceptanceFile)) {
2049
+ content = readFileSync9(acceptanceFile, "utf-8");
2050
+ } else if (existsSync11(specFile)) {
2051
+ content = readFileSync9(specFile, "utf-8");
1188
2052
  } else {
1189
2053
  out(
1190
2054
  fmt,
@@ -1197,7 +2061,7 @@ async function validate(targetPath, options) {
1197
2061
  continue;
1198
2062
  }
1199
2063
  const criteriaLines = content.match(/- \[ \] \*\*(.+?)\*\*: (.+)/g) || [];
1200
- const specContent = existsSync7(specFile) ? readFileSync6(specFile, "utf-8") : null;
2064
+ const specContent = existsSync11(specFile) ? readFileSync9(specFile, "utf-8") : null;
1201
2065
  out(fmt, "info", entry.name, "", `Spec: ${entry.name}`, "");
1202
2066
  if (criteriaLines.length === 0) {
1203
2067
  out(fmt, "info", entry.name, "", "No criteria found", "");
@@ -1214,7 +2078,7 @@ async function validate(targetPath, options) {
1214
2078
  let intelligenceResult = null;
1215
2079
  try {
1216
2080
  intelligenceResult = checkSpecContent(
1217
- join7(specsDir, entry.name),
2081
+ join11(specsDir, entry.name),
1218
2082
  label,
1219
2083
  description,
1220
2084
  config
@@ -1223,20 +2087,20 @@ async function validate(targetPath, options) {
1223
2087
  status = intelligenceResult.status;
1224
2088
  note = intelligenceResult.note;
1225
2089
  } else if (label.includes("letra init")) {
1226
- const tmp = mkdtempSync(join7(tmpdir(), "letra-test-"));
2090
+ const tmp = mkdtempSync(join11(tmpdir(), "letra-test-"));
1227
2091
  execSync(`npx tsx "${entryPoint}" init "${tmp}"`, { ...opts });
1228
- if (existsSync7(join7(tmp, ".letra", "context.md")))
2092
+ if (existsSync11(join11(tmp, ".letra", "context.md")))
1229
2093
  status = "PASS";
1230
2094
  rmSync(tmp, { recursive: true });
1231
2095
  } else if (label.includes("letra spec")) {
1232
- const tmp = mkdtempSync(join7(tmpdir(), "letra-test-"));
2096
+ const tmp = mkdtempSync(join11(tmpdir(), "letra-test-"));
1233
2097
  execSync(`npx tsx "${entryPoint}" init "${tmp}"`, { ...opts });
1234
2098
  execSync(`npx tsx "${entryPoint}" spec smoke-test`, {
1235
2099
  ...opts,
1236
2100
  cwd: tmp
1237
2101
  });
1238
- if (existsSync7(
1239
- join7(tmp, ".letra", "specs", "smoke-test", "spec.md")
2102
+ if (existsSync11(
2103
+ join11(tmp, ".letra", "specs", "smoke-test", "spec.md")
1240
2104
  ))
1241
2105
  status = "PASS";
1242
2106
  rmSync(tmp, { recursive: true });
@@ -1245,23 +2109,23 @@ async function validate(targetPath, options) {
1245
2109
  status = "PASS";
1246
2110
  } else if (label.includes("letra validate")) {
1247
2111
  status = "PASS";
1248
- } else if (label.includes("Workflow Ativo") || label.includes("CI") && existsSync7(ciFile)) {
2112
+ } else if (label.includes("Workflow Ativo") || label.includes("CI") && existsSync11(ciFile)) {
1249
2113
  status = "PASS";
1250
2114
  } else if (label.includes("Lint Gate") || label.includes("Lint")) {
1251
- const ciContent = readFileSync6(ciFile, "utf-8");
2115
+ const ciContent = readFileSync9(ciFile, "utf-8");
1252
2116
  if (ciContent.includes("letra lint") || ciContent.includes("lint"))
1253
2117
  status = "PASS";
1254
2118
  } else if (label.includes("Test Gate") || label.includes("Test")) {
1255
- const ciContent = readFileSync6(ciFile, "utf-8");
2119
+ const ciContent = readFileSync9(ciFile, "utf-8");
1256
2120
  if (ciContent.includes("npm test") || ciContent.includes("vitest") || ciContent.includes("test"))
1257
2121
  status = "PASS";
1258
2122
  } else if (label.includes("Valida\xE7\xE3o de Formato") || label.includes("Formato")) {
1259
- const ciContent = readFileSync6(ciFile, "utf-8");
2123
+ const ciContent = readFileSync9(ciFile, "utf-8");
1260
2124
  if (ciContent.includes("tsc") || ciContent.includes("typecheck"))
1261
2125
  status = "PASS";
1262
2126
  } else if (label.includes("Distribui\xE7\xE3o npm") || label.includes("npm")) {
1263
2127
  const pkgJson = JSON.parse(
1264
- readFileSync6(join7(root, "package.json"), "utf-8")
2128
+ readFileSync9(join11(root, "package.json"), "utf-8")
1265
2129
  );
1266
2130
  if (pkgJson.bin && pkgJson.name) {
1267
2131
  status = "PASS";
@@ -1273,39 +2137,39 @@ async function validate(targetPath, options) {
1273
2137
  status = "PASS";
1274
2138
  note = "(npm distribution preferred)";
1275
2139
  } else if (label.includes("Gera\xE7\xE3o de Regras") || label.includes("Gera\xE7\xE3o")) {
1276
- if (existsSync7(cursorRulesFile)) {
1277
- const rulesContent = readFileSync6(cursorRulesFile, "utf-8");
2140
+ if (existsSync11(cursorRulesFile)) {
2141
+ const rulesContent = readFileSync9(cursorRulesFile, "utf-8");
1278
2142
  if (rulesContent.includes(".letra/context.md") && rulesContent.includes(".letra/constitution.md")) {
1279
2143
  status = "PASS";
1280
2144
  }
1281
2145
  }
1282
2146
  } else if (label.includes("Inje\xE7\xE3o de Contexto")) {
1283
- if (existsSync7(cursorRulesFile)) {
1284
- const rulesContent = readFileSync6(cursorRulesFile, "utf-8");
2147
+ if (existsSync11(cursorRulesFile)) {
2148
+ const rulesContent = readFileSync9(cursorRulesFile, "utf-8");
1285
2149
  if (rulesContent.includes("@.letra/")) status = "PASS";
1286
- } else if (existsSync7(copilotFile)) {
1287
- const copilotContent = readFileSync6(copilotFile, "utf-8");
2150
+ } else if (existsSync11(copilotFile)) {
2151
+ const copilotContent = readFileSync9(copilotFile, "utf-8");
1288
2152
  if (copilotContent.includes(".letra/")) status = "PASS";
1289
2153
  }
1290
2154
  } else if (label.includes("Acesso a Valida\xE7\xE3o")) {
1291
- if (existsSync7(cursorRulesFile)) {
1292
- const rulesContent = readFileSync6(cursorRulesFile, "utf-8");
2155
+ if (existsSync11(cursorRulesFile)) {
2156
+ const rulesContent = readFileSync9(cursorRulesFile, "utf-8");
1293
2157
  if (rulesContent.includes("letra validate")) status = "PASS";
1294
2158
  }
1295
2159
  } else if (label.includes("N\xE3o-intrusivo")) {
1296
- if (existsSync7(cursorRulesFile) || existsSync7(copilotFile)) {
2160
+ if (existsSync11(cursorRulesFile) || existsSync11(copilotFile)) {
1297
2161
  status = "PASS";
1298
2162
  }
1299
2163
  } else if (label.includes("Gera\xE7\xE3o de Instru\xE7\xF5es")) {
1300
- if (existsSync7(copilotFile)) {
1301
- const copilotContent = readFileSync6(copilotFile, "utf-8");
2164
+ if (existsSync11(copilotFile)) {
2165
+ const copilotContent = readFileSync9(copilotFile, "utf-8");
1302
2166
  if (copilotContent.includes(".letra/context.md") && copilotContent.includes(".letra/constitution.md")) {
1303
2167
  status = "PASS";
1304
2168
  }
1305
2169
  }
1306
2170
  } else if (label.includes("Settings do Editor")) {
1307
- if (existsSync7(vscodeSettingsFile)) {
1308
- const settingsContent = readFileSync6(
2171
+ if (existsSync11(vscodeSettingsFile)) {
2172
+ const settingsContent = readFileSync9(
1309
2173
  vscodeSettingsFile,
1310
2174
  "utf-8"
1311
2175
  );
@@ -1314,9 +2178,9 @@ async function validate(targetPath, options) {
1314
2178
  }
1315
2179
  }
1316
2180
  } else if (label.includes("Arquivo de Config")) {
1317
- const configFile = join7(root, ".letra", "config.json");
1318
- if (existsSync7(configFile)) {
1319
- const cfgContent = readFileSync6(configFile, "utf-8");
2181
+ const configFile = join11(root, ".letra", "config.json");
2182
+ if (existsSync11(configFile)) {
2183
+ const cfgContent = readFileSync9(configFile, "utf-8");
1320
2184
  try {
1321
2185
  const parsed = JSON.parse(cfgContent);
1322
2186
  if (parsed.heuristics) {
@@ -1537,14 +2401,14 @@ async function validate(targetPath, options) {
1537
2401
  const exitCode = await runValidation();
1538
2402
  if (options?.watch) {
1539
2403
  let timer = null;
1540
- console.log(chalk6.gray("\nWatching for changes... (Ctrl+C to stop)"));
2404
+ console.log(chalk13.gray("\nWatching for changes... (Ctrl+C to stop)"));
1541
2405
  const watcher = watch(specsDir, { recursive: true });
1542
2406
  watcher.on("change", () => {
1543
2407
  if (timer) clearTimeout(timer);
1544
2408
  timer = setTimeout(async () => {
1545
2409
  console.clear();
1546
2410
  const code = await runValidation();
1547
- console.log(chalk6.gray("\nWatching for changes... (Ctrl+C to stop)"));
2411
+ console.log(chalk13.gray("\nWatching for changes... (Ctrl+C to stop)"));
1548
2412
  }, 300);
1549
2413
  });
1550
2414
  process.on("SIGINT", () => {
@@ -1563,8 +2427,12 @@ async function validate(targetPath, options) {
1563
2427
  }
1564
2428
 
1565
2429
  // src/index.ts
1566
- var program = new Command3();
1567
- program.name("letra").description("SDD-agnostic memory framework for AI coding agents").version("0.0.1");
2430
+ var __dirname2 = fileURLToPath2(new URL(".", import.meta.url));
2431
+ var pkg = JSON.parse(
2432
+ readFileSync10(join12(resolve14(__dirname2, ".."), "package.json"), "utf-8")
2433
+ );
2434
+ var program = new Command4();
2435
+ program.name("letra").description("SDD-agnostic memory framework for AI coding agents").version(pkg.version);
1568
2436
  program.command("init [path]").option("--yes", "Skip prompts and use defaults").description("Initialize .letra/ directory with templates").action((path, options) => init(path, { ...options }));
1569
2437
  program.command("spec <name>").option(
1570
2438
  "--template <type>",
@@ -1573,5 +2441,6 @@ program.command("spec <name>").option(
1573
2441
  program.command("lint [path]").description("Validate spec format and completeness").action(lint);
1574
2442
  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 }));
1575
2443
  program.addCommand(decisionCommand());
2444
+ program.addCommand(flowCommand());
1576
2445
  program.addCommand(focus_default());
1577
2446
  program.parse();