@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.cjs DELETED
@@ -1,1577 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __copyProps = (to, from, except, desc) => {
9
- if (from && typeof from === "object" || typeof from === "function") {
10
- for (let key of __getOwnPropNames(from))
11
- if (!__hasOwnProp.call(to, key) && key !== except)
12
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
- }
14
- return to;
15
- };
16
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
- // If the importer is in node compatibility mode or this is not an ESM
18
- // file that has been converted to a CommonJS file using a Babel-
19
- // compatible transform (i.e. "__esModule" has not been set), then set
20
- // "default" to the CommonJS "module.exports" for node compatibility.
21
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
- mod
23
- ));
24
-
25
- // src/index.ts
26
- var import_commander3 = require("commander");
27
-
28
- // src/commands/decision.ts
29
- var import_node_fs = require("fs");
30
- var import_node_path = require("path");
31
- var import_chalk = __toESM(require("chalk"), 1);
32
- var import_commander = require("commander");
33
- function sanitizeTitle(title) {
34
- return title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
35
- }
36
- function today() {
37
- return (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
38
- }
39
- function decisionCommand() {
40
- const cmd = new import_commander.Command("decision");
41
- cmd.command("new <title>").description("Cria um novo Architecture Decision Record").action((title) => {
42
- const root = (0, import_node_path.resolve)(process.cwd());
43
- const decisionsDir = (0, import_node_path.join)(root, ".letra", "decisions");
44
- const slug = sanitizeTitle(title);
45
- const filePath = (0, import_node_path.join)(decisionsDir, `${slug}.md`);
46
- if (!(0, import_node_fs.existsSync)(decisionsDir)) {
47
- (0, import_node_fs.mkdirSync)(decisionsDir, { recursive: true });
48
- }
49
- if ((0, import_node_fs.existsSync)(filePath)) {
50
- console.log(
51
- import_chalk.default.red(
52
- `Decision "${slug}" already exists at .letra/decisions/${slug}.md`
53
- )
54
- );
55
- return;
56
- }
57
- const content = `# ${title}
58
-
59
- **Date**: ${today()}
60
- **Status**: proposed
61
-
62
- ## Context
63
-
64
- Why is this decision needed? What problem does it solve?
65
-
66
- ## Decision
67
-
68
- What was decided?
69
-
70
- ## Consequences
71
-
72
- What are the trade-offs? What does this enable or prevent?
73
- `;
74
- (0, import_node_fs.writeFileSync)(filePath, content);
75
- console.log(
76
- import_chalk.default.green(
77
- `Decision "${slug}" created at .letra/decisions/${slug}.md`
78
- )
79
- );
80
- });
81
- cmd.command("list").description("Lista todos os Architecture Decision Records").action(() => {
82
- const root = (0, import_node_path.resolve)(process.cwd());
83
- const decisionsDir = (0, import_node_path.join)(root, ".letra", "decisions");
84
- if (!(0, import_node_fs.existsSync)(decisionsDir)) {
85
- console.log(
86
- import_chalk.default.yellow("No decisions directory found at .letra/decisions/")
87
- );
88
- return;
89
- }
90
- const files = (0, import_node_fs.readdirSync)(decisionsDir).filter((f) => f.endsWith(".md")).sort();
91
- if (files.length === 0) {
92
- console.log(import_chalk.default.yellow("No decisions found"));
93
- return;
94
- }
95
- for (const file of files) {
96
- const content = (0, import_node_fs.readFileSync)((0, import_node_path.join)(decisionsDir, file), "utf-8");
97
- const firstLine = content.split("\n")[0]?.replace(/^#\s*/, "").trim() || file;
98
- console.log(`${import_chalk.default.cyan(file)} ${firstLine}`);
99
- }
100
- });
101
- return cmd;
102
- }
103
-
104
- // src/commands/focus.ts
105
- var import_node_fs2 = require("fs");
106
- var import_node_path2 = require("path");
107
- var import_chalk2 = __toESM(require("chalk"), 1);
108
- var import_commander2 = require("commander");
109
- function extractOutcome(specDir) {
110
- const specFile = (0, import_node_path2.join)(specDir, "spec.md");
111
- if (!(0, import_node_fs2.existsSync)(specFile)) return null;
112
- const content = (0, import_node_fs2.readFileSync)(specFile, "utf-8");
113
- const match = content.match(/## Outcome\s+([\s\S]*?)(?=\n## |\n*$)/);
114
- return match ? match[1].trim() : null;
115
- }
116
- function focus_default() {
117
- return new import_commander2.Command("focus").argument("[spec]", "Spec name to focus on").option("--clear", "Remove focus file").action((spec, options) => {
118
- const root = (0, import_node_path2.resolve)(process.cwd());
119
- const focusFile = (0, import_node_path2.join)(root, ".letra", "focus.md");
120
- if (options.clear) {
121
- if ((0, import_node_fs2.existsSync)(focusFile)) {
122
- (0, import_node_fs2.unlinkSync)(focusFile);
123
- console.log(import_chalk2.default.green("Focus removed."));
124
- } else {
125
- console.log(import_chalk2.default.yellow("No focus to remove."));
126
- }
127
- return;
128
- }
129
- if (spec) {
130
- const specDir = (0, import_node_path2.join)(root, ".letra", "specs", spec);
131
- const specFile = (0, import_node_path2.join)(specDir, "spec.md");
132
- if (!(0, import_node_fs2.existsSync)(specFile)) {
133
- console.log(import_chalk2.default.red(`Spec "${spec}" not found`));
134
- process.exit(1);
135
- }
136
- const outcome = extractOutcome(specDir);
137
- const outcomeLine = `**Outcome**: ${outcome || spec}`;
138
- const focusContent = [
139
- `# Focus: ${spec}`,
140
- "",
141
- `**Path**: .letra/specs/${spec}/`,
142
- outcomeLine,
143
- ""
144
- ].join("\n");
145
- (0, import_node_fs2.writeFileSync)(focusFile, focusContent);
146
- console.log(import_chalk2.default.green(`Focus set to "${spec}".`));
147
- return;
148
- }
149
- if ((0, import_node_fs2.existsSync)(focusFile)) {
150
- console.log((0, import_node_fs2.readFileSync)(focusFile, "utf-8"));
151
- } else {
152
- console.log("Nenhum foco definido.");
153
- }
154
- });
155
- }
156
-
157
- // src/commands/init.ts
158
- var import_node_fs3 = require("fs");
159
- var import_node_path3 = require("path");
160
- var import_node_readline = require("readline");
161
- var import_node_url = require("url");
162
- var import_chalk3 = __toESM(require("chalk"), 1);
163
- var import_ora = __toESM(require("ora"), 1);
164
- var import_meta = {};
165
- var __dirname = (0, import_node_url.fileURLToPath)(new URL(".", import_meta.url));
166
- function ask(query, options) {
167
- if (!process.stdin.isTTY) return Promise.resolve(options[0]);
168
- const rl = (0, import_node_readline.createInterface)({ input: process.stdin, output: process.stdout });
169
- return new Promise((resolve7) => {
170
- const formatted = `${import_chalk3.default.cyan(query)} ${options.map((o) => import_chalk3.default.gray(`(${o})`)).join(" ")}
171
- > `;
172
- rl.question(formatted, (answer) => {
173
- rl.close();
174
- const trimmed = answer.trim().toLowerCase();
175
- if (trimmed && options.some((o) => o.toLowerCase().startsWith(trimmed))) {
176
- resolve7(
177
- options.find((o) => o.toLowerCase().startsWith(trimmed)) ?? options[0]
178
- );
179
- } else if (trimmed && options.includes(trimmed)) {
180
- resolve7(trimmed);
181
- } else {
182
- resolve7(options[0]);
183
- }
184
- });
185
- });
186
- }
187
- function adaptConfig(projectType) {
188
- const config = {
189
- "conteudo-minimo": { severity: "warning", minChars: 50 },
190
- "consistencia-terminologia": { severity: "warning" },
191
- "detecao-tom": {
192
- severity: "warning",
193
- blacklist: [
194
- "tipo",
195
- "t\xE1",
196
- "pra",
197
- "blz",
198
- "kkk",
199
- "eita",
200
- "oi",
201
- "oi pessoal"
202
- ]
203
- },
204
- "drift-temporal": { severity: "warning", maxDays: 30 },
205
- "secoes-vazias": { severity: "warning" },
206
- "acs-sem-metrica": { severity: "warning" },
207
- "baixa-confianca": { severity: "warning" }
208
- };
209
- if (projectType === "library") {
210
- config["detecao-tom"] = { severity: "off" };
211
- config["drift-temporal"] = { severity: "warning", maxDays: 60 };
212
- } else if (projectType === "mobile") {
213
- config["drift-temporal"] = { severity: "error", maxDays: 14 };
214
- config["baixa-confianca"] = { severity: "error" };
215
- } else if (projectType === "cli") {
216
- config["detecao-tom"] = { severity: "off" };
217
- }
218
- return JSON.stringify({ heuristics: config }, null, 2);
219
- }
220
- function adaptersForTool(tool) {
221
- const all = ["cursor", "claude-code", "windsurf", "vscode", "opencode"];
222
- if (tool === "todos") return all;
223
- const map = {
224
- opencode: ["opencode"],
225
- cursor: ["cursor"],
226
- windsurf: ["windsurf"],
227
- "claude code": ["claude-code"],
228
- "vscode copilot": ["vscode"]
229
- };
230
- return map[tool.toLowerCase()] || all;
231
- }
232
- function generateAdapterFiles(root, tools) {
233
- const adapters = [];
234
- const baseContent = (name, format) => `# Letra Context \u2014 ${name} Adapter
235
- # Generated by letra init. Do not edit manually.
236
-
237
- ${format === "at" ? "# Context\n@.letra/context.md\n@.letra/constitution.md\n@.letra/glossary.md\n@.letra/focus.md\n" : `Read the following files before starting any task:
238
- - .letra/context.md
239
- - .letra/constitution.md
240
- - .letra/glossary.md
241
- - .letra/focus.md (if exists, defines current session focus)
242
- `}
243
- # Rules
244
- - Always read specs in .letra/specs/ before writing code
245
- - Run \`letra validate\` to check acceptance criteria
246
- - Follow the constitution.md rules strictly
247
- - Use formal tone in all generated content
248
- `;
249
- for (const tool of tools) {
250
- switch (tool) {
251
- case "cursor":
252
- adapters.push({
253
- path: (0, import_node_path3.join)(root, ".cursorrules"),
254
- content: baseContent("Cursor", "at")
255
- });
256
- break;
257
- case "claude-code":
258
- adapters.push({
259
- path: (0, import_node_path3.join)(root, "CLAUDE.md"),
260
- content: baseContent("Claude Code", "text")
261
- });
262
- break;
263
- case "windsurf":
264
- adapters.push({
265
- path: (0, import_node_path3.join)(root, ".windsurfrules"),
266
- content: baseContent("Windsurf", "at")
267
- });
268
- break;
269
- case "vscode":
270
- adapters.push({
271
- path: (0, import_node_path3.join)(root, ".github", "copilot-instructions.md"),
272
- content: baseContent("VSCode Copilot", "text")
273
- });
274
- break;
275
- case "opencode":
276
- adapters.push({
277
- path: (0, import_node_path3.join)(root, "AGENTS.md"),
278
- content: baseContent("OpenCode", "text")
279
- });
280
- break;
281
- }
282
- }
283
- for (const { path, content } of adapters) {
284
- const dir = (0, import_node_path3.join)(path, "..");
285
- if (!(0, import_node_fs3.existsSync)(dir)) (0, import_node_fs3.mkdirSync)(dir, { recursive: true });
286
- (0, import_node_fs3.writeFileSync)(path, content);
287
- console.log(` ${import_chalk3.default.gray("Created")} ${path.replace(`${root}/`, "")}`);
288
- }
289
- }
290
- async function init(targetPath, options) {
291
- const root = (0, import_node_path3.resolve)(process.cwd(), targetPath || ".");
292
- const letraDir = (0, import_node_path3.join)(root, ".letra");
293
- const spinner = (0, import_ora.default)("Initializing Letra...").start();
294
- if ((0, import_node_fs3.existsSync)(letraDir)) {
295
- spinner.warn(import_chalk3.default.yellow(".letra/ already exists"));
296
- return;
297
- }
298
- try {
299
- let projectType = "web-app";
300
- let tool = "cursor";
301
- if (options?.yes || !process.stdin.isTTY) {
302
- projectType = "web-app";
303
- tool = "todos";
304
- } else {
305
- spinner.stop();
306
- projectType = await ask("Project type?", [
307
- "web-app",
308
- "cli",
309
- "library",
310
- "mobile"
311
- ]);
312
- const toolNames = [
313
- "Cursor",
314
- "Windsurf",
315
- "Claude Code",
316
- "VSCode Copilot",
317
- "OpenCode",
318
- "Todos"
319
- ];
320
- const answer = await ask("AI coding agent?", toolNames);
321
- tool = answer.toLowerCase();
322
- spinner.start();
323
- }
324
- (0, import_node_fs3.mkdirSync)((0, import_node_path3.join)(letraDir, "decisions"), { recursive: true });
325
- (0, import_node_fs3.mkdirSync)((0, import_node_path3.join)(letraDir, "specs", "_template"), { recursive: true });
326
- (0, import_node_fs3.mkdirSync)((0, import_node_path3.join)(letraDir, "adapters"), { recursive: true });
327
- const templateDir = (0, import_node_path3.join)(__dirname, "..", "..", ".letra");
328
- const templates = [
329
- "context.md",
330
- "constitution.md",
331
- "glossary.md",
332
- "lessons-learned.md"
333
- ];
334
- for (const file of templates) {
335
- const src = (0, import_node_path3.join)(templateDir, file);
336
- const dest = (0, import_node_path3.join)(letraDir, file);
337
- if ((0, import_node_fs3.existsSync)(src)) (0, import_node_fs3.copyFileSync)(src, dest);
338
- }
339
- const specTemplate = (0, import_node_path3.join)(letraDir, "specs", "_template.md");
340
- const specContent = `# Spec Template
341
-
342
- ## Outcome
343
- O que o usu\xE1rio consegue fazer quando isso estiver pronto.
344
-
345
- ## Constraints
346
- Limita\xE7\xF5es t\xE9cnicas e de neg\xF3cio que n\xE3o podem ser violadas.
347
-
348
- ## Exclusions
349
- O que explicitamente N\xC3O est\xE1 neste escopo.
350
-
351
- ## Acceptance Criteria
352
- - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
353
-
354
- ## Context
355
- Por que estamos construindo isso.
356
- `;
357
- (0, import_node_fs3.writeFileSync)(specTemplate, specContent);
358
- const configPath = (0, import_node_path3.join)(letraDir, "config.json");
359
- (0, import_node_fs3.writeFileSync)(configPath, adaptConfig(projectType));
360
- console.log(` ${import_chalk3.default.gray("Created")} .letra/config.json`);
361
- const tools = adaptersForTool(tool);
362
- generateAdapterFiles(root, tools);
363
- if (tool === "todos" || tool === "vscode") {
364
- const vscodeDir = (0, import_node_path3.join)(root, ".vscode");
365
- if (!(0, import_node_fs3.existsSync)(vscodeDir)) (0, import_node_fs3.mkdirSync)(vscodeDir, { recursive: true });
366
- const vscodeSettingsPath = (0, import_node_path3.join)(vscodeDir, "settings.json");
367
- const vscodeSettingsContent = `{
368
- "editor.formatOnSave": true,
369
- "editor.defaultFormatter": "esbenp.prettier-vscode",
370
- "editor.codeActionsOnSave": {
371
- "source.fixAll.eslint": "explicit"
372
- },
373
- "files.autoSave": "onFocusChange"
374
- }
375
- `;
376
- (0, import_node_fs3.writeFileSync)(vscodeSettingsPath, vscodeSettingsContent);
377
- console.log(` ${import_chalk3.default.gray("Created")} .vscode/settings.json`);
378
- }
379
- spinner.succeed(import_chalk3.default.green(".letra/ initialized successfully"));
380
- console.log("");
381
- console.log(" Next steps:");
382
- console.log(
383
- ` ${import_chalk3.default.cyan("letra spec new <name>")} Create your first spec`
384
- );
385
- console.log(` ${import_chalk3.default.cyan("letra lint")} Validate specs`);
386
- } catch (error) {
387
- spinner.fail(import_chalk3.default.red("Failed to initialize Letra"));
388
- process.exit(1);
389
- }
390
- }
391
-
392
- // src/commands/lint.ts
393
- var import_node_fs4 = require("fs");
394
- var import_node_path4 = require("path");
395
- var import_chalk4 = __toESM(require("chalk"), 1);
396
- var REQUIRED_SECTIONS = [
397
- "## Outcome",
398
- "## Constraints",
399
- "## Exclusions",
400
- "## Acceptance Criteria",
401
- "## Context"
402
- ];
403
- async function lint(targetPath) {
404
- const root = (0, import_node_path4.resolve)(process.cwd(), targetPath || ".");
405
- const specsDir = (0, import_node_path4.join)(root, ".letra", "specs");
406
- if (!(0, import_node_fs4.existsSync)(specsDir)) {
407
- console.log(
408
- import_chalk4.default.red("Error: .letra/specs/ not found. Run 'letra init' first.")
409
- );
410
- process.exit(1);
411
- }
412
- const results = [];
413
- let totalErrors = 0;
414
- let totalWarnings = 0;
415
- const entries = (0, import_node_fs4.readdirSync)(specsDir, { withFileTypes: true });
416
- for (const entry of entries) {
417
- if (!entry.isDirectory() || entry.name.startsWith("_")) continue;
418
- const specFile = (0, import_node_path4.join)(specsDir, entry.name, "spec.md");
419
- const errors = [];
420
- const warnings = [];
421
- if (!(0, import_node_fs4.existsSync)(specFile)) {
422
- errors.push("Missing spec.md");
423
- } else {
424
- const content = (0, import_node_fs4.readFileSync)(specFile, "utf-8");
425
- for (const section of REQUIRED_SECTIONS) {
426
- if (!content.includes(section)) {
427
- errors.push(`Missing section: ${section}`);
428
- }
429
- }
430
- if (content.length > 3e3) {
431
- warnings.push("Spec exceeds 3000 chars (should be thin \u2014 max 1 page)");
432
- }
433
- const hasChecklist = /-\s*\[[ x]\]\s*\*\*/i.test(content);
434
- if (!hasChecklist && content.includes("## Acceptance Criteria")) {
435
- errors.push(
436
- "Acceptance Criteria section exists but has no checklist items"
437
- );
438
- }
439
- }
440
- if (errors.length > 0 || warnings.length > 0) {
441
- results.push({ file: entry.name, errors, warnings });
442
- totalErrors += errors.length;
443
- totalWarnings += warnings.length;
444
- }
445
- }
446
- if (results.length === 0) {
447
- console.log(import_chalk4.default.green("All specs are valid"));
448
- process.exit(0);
449
- }
450
- console.log("");
451
- for (const result of results) {
452
- console.log(import_chalk4.default.bold(`
453
- Spec: ${result.file}`));
454
- for (const error of result.errors) {
455
- console.log(import_chalk4.default.red(` \u2717 ${error}`));
456
- }
457
- for (const warning of result.warnings) {
458
- console.log(import_chalk4.default.yellow(` \u26A0 ${warning}`));
459
- }
460
- }
461
- console.log(
462
- import_chalk4.default.gray(
463
- `
464
- ${results.length} spec(s) with issues: ${totalErrors} error(s), ${totalWarnings} warning(s)`
465
- )
466
- );
467
- process.exit(totalErrors > 0 ? 1 : 0);
468
- }
469
-
470
- // src/commands/spec.ts
471
- var import_node_fs5 = require("fs");
472
- var import_node_path5 = require("path");
473
- var import_chalk5 = __toESM(require("chalk"), 1);
474
- var import_ora2 = __toESM(require("ora"), 1);
475
- var builtInTemplates = {
476
- "web-api": {
477
- spec: `# Spec: {{name}}
478
-
479
- ## Outcome
480
- Usu\xE1rio consegue fazer requisi\xE7\xF5es HTTP para a API e receber respostas padronizadas.
481
-
482
- ## Constraints
483
- - RESTful\u9075\u5FAA (GET, POST, PUT, DELETE)
484
- - Autentica\xE7\xE3o via Bearer token JWT
485
- - Rate limiting: 100 req/min por usu\xE1rio
486
- - Timeout m\xE1ximo de 30s por requisi\xE7\xE3o
487
-
488
- ## Exclusions
489
- - WebSocket n\xE3o est\xE1 no escopo
490
- - Upload de arquivos n\xE3o est\xE1 no escopo inicial
491
-
492
- ## Acceptance Criteria
493
- - [ ] **CRUD**: CRUD completo para o recurso principal (GET, POST, PUT, DELETE retornam 200/201/204).
494
- - [ ] **Autentica\xE7\xE3o**: Rota sem token retorna 401, rota com token inv\xE1lido retorna 403.
495
- - [ ] **Valida\xE7\xE3o**: Payload inv\xE1lido retorna 422 com mensagem de erro descritiva.
496
- - [ ] **Rate Limit**: Exceder 100 req/min retorna 429 com header Retry-After.
497
- - [ ] **Pagina\xE7\xE3o**: GET com ?page=2&limit=10 retorna p\xE1gina correta com total count.
498
-
499
- ## Context
500
- Template para APIs REST. Adaptado para o dom\xEDnio espec\xEDfico do projeto.`,
501
- acceptance: `# Acceptance Criteria \u2014 {{name}}
502
-
503
- - [ ] **CRUD**: CRUD completo para o recurso principal (GET, POST, PUT, DELETE retornam 200/201/204).
504
- - [ ] **Autentica\xE7\xE3o**: Rota sem token retorna 401, rota com token inv\xE1lido retorna 403.
505
- - [ ] **Valida\xE7\xE3o**: Payload inv\xE1lido retorna 422 com mensagem de erro descritiva.
506
- - [ ] **Rate Limit**: Exceder 100 req/min retorna 429 com header Retry-After.
507
- - [ ] **Pagina\xE7\xE3o**: GET com ?page=2&limit=10 retorna p\xE1gina correta com total count.`
508
- },
509
- "cli-tool": {
510
- spec: `# Spec: {{name}}
511
-
512
- ## Outcome
513
- Usu\xE1rio instala e executa a CLI, recebendo output formatado no terminal.
514
-
515
- ## Constraints
516
- - Node.js 22+ como runtime
517
- - Deve funcionar em Windows, macOS e Linux
518
- - Exit codes seguem padr\xE3o Unix (0 sucesso, 1 erro)
519
- - --help deve funcionar sem argumentos
520
-
521
- ## Exclusions
522
- - UI gr\xE1fica n\xE3o est\xE1 no escopo
523
- - Modo servidor/daemon n\xE3o est\xE1 no escopo
524
-
525
- ## Acceptance Criteria
526
- - [ ] **Instala\xE7\xE3o**: CLI execut\xE1vel via npx/npm install -g sem erros.
527
- - [ ] **--help**: Roda sem argumentos, exibe ajuda com subcomandos.
528
- - [ ] **Subcomando**: Subcomando principal executa sem erros e exibe output.
529
- - [ ] **Erro**: Subcomando inv\xE1lido exibe erro amig\xE1vel e exit 1.
530
- - [ ] **Cross-platform**: Funciona em Windows (cmd/powershell), macOS (zsh) e Linux (bash).
531
-
532
- ## Context
533
- Template para ferramentas de linha de comando. Adaptado para o escopo espec\xEDfico.`,
534
- acceptance: `# Acceptance Criteria \u2014 {{name}}
535
-
536
- - [ ] **Instala\xE7\xE3o**: CLI execut\xE1vel via npx/npm install -g sem erros.
537
- - [ ] **--help**: Roda sem argumentos, exibe ajuda com subcomandos.
538
- - [ ] **Subcomando**: Subcomando principal executa sem erros e exibe output.
539
- - [ ] **Erro**: Subcomando inv\xE1lido exibe erro amig\xE1vel e exit 1.
540
- - [ ] **Cross-platform**: Funciona em Windows (cmd/powershell), macOS (zsh) e Linux (bash).`
541
- },
542
- "mobile-feature": {
543
- spec: `# Spec: {{name}}
544
-
545
- ## Outcome
546
- Usu\xE1rio consegue acessar e interagir com a nova funcionalidade no aplicativo mobile.
547
-
548
- ## Constraints
549
- - Suporte a iOS 16+ e Android 13+
550
- - Offline-first: funcionalidade deve funcionar sem internet
551
- - Tempo de resposta < 200ms para intera\xE7\xF5es locais
552
- - Acessibilidade: VoiceOver (iOS) e TalkBack (Android)
553
-
554
- ## Exclusions
555
- - Vers\xE3o web n\xE3o est\xE1 no escopo (mobile-only)
556
- - Suporte a tablets \xE9 desej\xE1vel mas n\xE3o obrigat\xF3rio
557
-
558
- ## Acceptance Criteria
559
- - [ ] **Tela principal**: Nova funcionalidade aparece na navega\xE7\xE3o principal.
560
- - [ ] **Offline**: Funcionalidade completa funciona sem conex\xE3o de rede.
561
- - [ ] **Performance**: Scroll da lista com 1000+ itens mant\xE9m 60fps.
562
- - [ ] **Acessibilidade**: Todos os elementos t\xEAm label de acessibilidade.
563
- - [ ] **Dark Mode**: Funcionalidade respeita o tema do sistema.
564
-
565
- ## Context
566
- Template para features mobile nativas. Adaptado para o framework espec\xEDfico (SwiftUI/Compose).`,
567
- acceptance: `# Acceptance Criteria \u2014 {{name}}
568
-
569
- - [ ] **Tela principal**: Nova funcionalidade aparece na navega\xE7\xE3o principal.
570
- - [ ] **Offline**: Funcionalidade completa funciona sem conex\xE3o de rede.
571
- - [ ] **Performance**: Scroll da lista com 1000+ itens mant\xE9m 60fps.
572
- - [ ] **Acessibilidade**: Todos os elementos t\xEAm label de acessibilidade.
573
- - [ ] **Dark Mode**: Funcionalidade respeita o tema do sistema.`
574
- }
575
- };
576
- function listTemplates(root) {
577
- const names = Object.keys(builtInTemplates);
578
- const customDir = (0, import_node_path5.join)(root, ".letra", "templates");
579
- if ((0, import_node_fs5.existsSync)(customDir)) {
580
- for (const file of (0, import_node_fs5.readdirSync)(customDir)) {
581
- if (file.endsWith(".md")) {
582
- const name = file.replace(/\.md$/, "");
583
- if (!names.includes(name)) names.push(name);
584
- }
585
- }
586
- }
587
- return names;
588
- }
589
- function findTemplate(root, type) {
590
- const lower = type.toLowerCase();
591
- if (builtInTemplates[lower]) return builtInTemplates[lower];
592
- const customFile = (0, import_node_path5.join)(root, ".letra", "templates", `${type}.md`);
593
- const customAcceptance = (0, import_node_path5.join)(
594
- root,
595
- ".letra",
596
- "templates",
597
- `${type}-acceptance.md`
598
- );
599
- if ((0, import_node_fs5.existsSync)(customFile)) {
600
- const spec = (0, import_node_fs5.readFileSync)(customFile, "utf-8");
601
- const acceptance = (0, import_node_fs5.existsSync)(customAcceptance) ? (0, import_node_fs5.readFileSync)(customAcceptance, "utf-8") : `# Acceptance Criteria \u2014 ${type}
602
-
603
- - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
604
- `;
605
- return { spec, acceptance };
606
- }
607
- return null;
608
- }
609
- function applyPlaceholders(content, name) {
610
- return content.replace(/\{\{name\}\}/g, name);
611
- }
612
- async function specNew(name, options) {
613
- const root = (0, import_node_path5.resolve)(process.cwd());
614
- const letraDir = (0, import_node_path5.join)(root, ".letra");
615
- const specDir = (0, import_node_path5.join)(letraDir, "specs", name);
616
- if (!(0, import_node_fs5.existsSync)(letraDir)) {
617
- console.log(import_chalk5.default.red(".letra/ not found. Run 'letra init' first."));
618
- process.exit(1);
619
- }
620
- if ((0, import_node_fs5.existsSync)(specDir)) {
621
- console.log(import_chalk5.default.yellow(`Spec "${name}" already exists`));
622
- return;
623
- }
624
- const templateType = options?.template || "_default";
625
- const template = templateType === "_default" ? null : findTemplate(root, templateType);
626
- if (options?.template && !template) {
627
- const available = listTemplates(root).join(", ");
628
- console.log(
629
- import_chalk5.default.red(
630
- `Template "${options.template}" not found. Available: ${available}`
631
- )
632
- );
633
- process.exit(1);
634
- }
635
- const spinner = (0, import_ora2.default)(`Creating spec "${name}"...`).start();
636
- try {
637
- (0, import_node_fs5.mkdirSync)(specDir, { recursive: true });
638
- if (template) {
639
- const specContent = applyPlaceholders(template.spec, name);
640
- const acceptanceContent = applyPlaceholders(template.acceptance, name);
641
- (0, import_node_fs5.writeFileSync)((0, import_node_path5.join)(specDir, "spec.md"), specContent);
642
- (0, import_node_fs5.writeFileSync)((0, import_node_path5.join)(specDir, "acceptance.md"), acceptanceContent);
643
- } else {
644
- const specContent = `# Spec: ${name}
645
-
646
- ## Outcome
647
- O que o usu\xE1rio consegue fazer quando isso estiver pronto.
648
-
649
- ## Constraints
650
- Limita\xE7\xF5es t\xE9cnicas e de neg\xF3cio que n\xE3o podem ser violadas.
651
-
652
- ## Exclusions
653
- O que explicitamente N\xC3O est\xE1 neste escopo.
654
-
655
- ## Acceptance Criteria
656
- - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
657
-
658
- ## Context
659
- Por que estamos construindo isso. Trade-offs considerados.
660
- `;
661
- const acceptanceContent = `# Acceptance Criteria \u2014 ${name}
662
-
663
- - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
664
- `;
665
- (0, import_node_fs5.writeFileSync)((0, import_node_path5.join)(specDir, "spec.md"), specContent);
666
- (0, import_node_fs5.writeFileSync)((0, import_node_path5.join)(specDir, "acceptance.md"), acceptanceContent);
667
- }
668
- spinner.succeed(
669
- import_chalk5.default.green(`Spec "${name}" created at .letra/specs/${name}/`)
670
- );
671
- } catch (error) {
672
- spinner.fail(import_chalk5.default.red("Failed to create spec"));
673
- process.exit(1);
674
- }
675
- }
676
-
677
- // src/commands/validate.ts
678
- var import_node_child_process = require("child_process");
679
- var import_node_fs7 = require("fs");
680
- var import_node_os = require("os");
681
- var import_node_path7 = require("path");
682
- var import_chalk6 = __toESM(require("chalk"), 1);
683
-
684
- // src/config.ts
685
- var import_node_fs6 = require("fs");
686
- var import_node_path6 = require("path");
687
- var DEFAULT_HEURISTICS = {
688
- "conteudo-minimo": { severity: "warning", minChars: 50 },
689
- "consistencia-terminologia": { severity: "warning" },
690
- "detecao-tom": {
691
- severity: "warning",
692
- blacklist: ["tipo", "t\xE1", "pra", "blz", "kkk", "eita", "oi", "oi pessoal"]
693
- },
694
- "drift-temporal": { severity: "warning", maxDays: 30 },
695
- "secoes-vazias": { severity: "warning" },
696
- "acs-sem-metrica": { severity: "warning" },
697
- "baixa-confianca": { severity: "warning" },
698
- "validate-conflict": { severity: "warning" }
699
- };
700
- function loadConfig(root) {
701
- const configPath = (0, import_node_path6.join)(root, ".letra", "config.json");
702
- const heuristics = {};
703
- for (const [key, value] of Object.entries(DEFAULT_HEURISTICS)) {
704
- heuristics[key] = { ...value };
705
- }
706
- if ((0, import_node_fs6.existsSync)(configPath)) {
707
- try {
708
- const raw = JSON.parse((0, import_node_fs6.readFileSync)(configPath, "utf-8"));
709
- if (raw.heuristics && typeof raw.heuristics === "object") {
710
- for (const [key, value] of Object.entries(raw.heuristics)) {
711
- if (heuristics[key]) {
712
- heuristics[key] = {
713
- ...heuristics[key],
714
- ...value
715
- };
716
- } else {
717
- heuristics[key] = value;
718
- }
719
- }
720
- }
721
- } catch {
722
- }
723
- }
724
- return { heuristics };
725
- }
726
- function getHeuristicConfig(config, label) {
727
- const key = heuristicKey(label);
728
- return config.heuristics[key] ?? { severity: "warning" };
729
- }
730
- function heuristicKey(label) {
731
- const lower = label.toLowerCase();
732
- if (lower.includes("conteudo m\xEDnimo") || lower.includes("conteudo minimo"))
733
- return "conteudo-minimo";
734
- if (lower.includes("terminologia")) return "consistencia-terminologia";
735
- 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";
744
- if (lower.includes("validate conflict")) return "validate-conflict";
745
- return lower.replace(/\s+/g, "-");
746
- }
747
-
748
- // src/commands/validate.ts
749
- var placeholderPatterns = [
750
- /o que o usu[áa]rio consegue fazer quando isso estiver pronto/i,
751
- /limitaç[õo]es t[ée]cnicas e de neg[óo]cio/i,
752
- /o que explicitamente n[ãa]o est[áa] neste escopo/i,
753
- /descriç[ãa]o bin[áa]ria/i,
754
- /por que estamos construindo isso/i
755
- ];
756
- var vagueVerbs = [
757
- "melhorar",
758
- "otimizar",
759
- "facilitar",
760
- "aumentar",
761
- "diminuir",
762
- "agilizar",
763
- "simplificar",
764
- "aprimorar"
765
- ];
766
- var lowConfidenceMarkers = [
767
- "provavelmente",
768
- "talvez",
769
- "tentar",
770
- "idealmente",
771
- "possivelmente",
772
- "quem sabe",
773
- "de repente",
774
- "teoricamente"
775
- ];
776
- function checkSpecContent(specDir, label, description, config) {
777
- const cfg = config ?? loadConfig((0, import_node_path7.join)(specDir, "..", "..", ".."));
778
- const specFile = (0, import_node_path7.join)(specDir, "spec.md");
779
- const glossaryFile = (0, import_node_path7.join)(specDir, "..", "..", "glossary.md");
780
- if (!(0, import_node_fs7.existsSync)(specFile))
781
- return { status: "FAIL", note: "(spec.md not found)" };
782
- const specContent = (0, import_node_fs7.readFileSync)(specFile, "utf-8");
783
- const now = /* @__PURE__ */ new Date();
784
- if (label.includes("Conte\xFAdo M\xEDnimo")) {
785
- const outcomeMatch = specContent.match(/## Outcome\s+([\s\S]*?)(?=\n## )/);
786
- if (!outcomeMatch)
787
- return { status: "FAIL", note: "(no Outcome section)" };
788
- const outcomeContent = outcomeMatch[1].trim();
789
- const heurConfig = getHeuristicConfig(cfg, label);
790
- const minChars = heurConfig.minChars ?? 50;
791
- if (outcomeContent.length >= minChars) {
792
- return {
793
- status: "PASS",
794
- note: `(${outcomeContent.length} chars, need ${minChars})`
795
- };
796
- }
797
- return {
798
- status: "FAIL",
799
- note: `(only ${outcomeContent.length} chars, need ${minChars}+)`
800
- };
801
- }
802
- if (label.includes("Consist\xEAncia de Terminologia") || label.includes("Terminologia")) {
803
- if (!(0, import_node_fs7.existsSync)(glossaryFile)) {
804
- return {
805
- status: "PASS",
806
- note: "(no glossary to check against)"
807
- };
808
- }
809
- const glossaryContent = (0, import_node_fs7.readFileSync)(glossaryFile, "utf-8");
810
- const terms = glossaryContent.match(/\*\*(.+?)\*\*/g) || [];
811
- const extractedTerms = terms.map((t) => t.replace(/\*\*/g, "").trim()).filter((t) => t.length > 3);
812
- const missingTerms = extractedTerms.filter(
813
- (term) => !specContent.toLowerCase().includes(term.toLowerCase())
814
- );
815
- if (missingTerms.length === 0) {
816
- return { status: "PASS", note: "(all glossary terms used)" };
817
- }
818
- return {
819
- status: "FAIL",
820
- note: `(missing: ${missingTerms.slice(0, 3).join(", ")})`
821
- };
822
- }
823
- if (label.includes("Detec\xE7\xE3o de Tom") || label.includes("Tom")) {
824
- const lowerSpec = specContent.toLowerCase();
825
- const words = lowerSpec.split(/\s+/);
826
- const heurConfig = getHeuristicConfig(cfg, label);
827
- const blacklist = heurConfig.blacklist ?? [
828
- "tipo",
829
- "t\xE1",
830
- "pra",
831
- "blz",
832
- "kkk",
833
- "eita",
834
- "oi",
835
- "oi pessoal"
836
- ];
837
- const foundColloquialisms = blacklist.filter((c) => words.includes(c));
838
- if (foundColloquialisms.length === 0) {
839
- return { status: "PASS", note: "(formal tone maintained)" };
840
- }
841
- return {
842
- status: "FAIL",
843
- note: `(colloquialisms: ${foundColloquialisms.join(", ")})`
844
- };
845
- }
846
- if (label.includes("Drift Temporal") || label.includes("Temporal")) {
847
- const stat = (0, import_node_fs7.statSync)(specFile);
848
- const daysOld = Math.floor(
849
- (now.getTime() - stat.mtimeMs) / (1e3 * 60 * 60 * 24)
850
- );
851
- const heurConfig = getHeuristicConfig(cfg, label);
852
- const maxDays = heurConfig.maxDays ?? 30;
853
- if (daysOld < maxDays) {
854
- return { status: "PASS", note: `(${daysOld} days old)` };
855
- }
856
- return {
857
- status: "FAIL",
858
- note: `(${daysOld} days old, stale >${maxDays}d)`
859
- };
860
- }
861
- return null;
862
- }
863
- function checkEmptySections(specContent) {
864
- const requiredSections = [
865
- "## Outcome",
866
- "## Constraints",
867
- "## Exclusions",
868
- "## Acceptance Criteria",
869
- "## Context"
870
- ];
871
- const emptyOrPlaceholder = [];
872
- for (const section of requiredSections) {
873
- const escaped = section.replace(/[#]/g, "\\$&");
874
- const pattern = new RegExp(`${escaped}\\s+([\\s\\S]*?)(?=\\n## |\\n*$)`);
875
- const match = specContent.match(pattern);
876
- if (!match) {
877
- emptyOrPlaceholder.push(section.replace("## ", ""));
878
- continue;
879
- }
880
- const content = match[1].trim();
881
- if (content.length < 10) {
882
- emptyOrPlaceholder.push(section.replace("## ", ""));
883
- continue;
884
- }
885
- const hasPlaceholder = placeholderPatterns.some((p) => p.test(content));
886
- if (hasPlaceholder) {
887
- emptyOrPlaceholder.push(section.replace("## ", ""));
888
- }
889
- }
890
- if (emptyOrPlaceholder.length === 0) {
891
- return {
892
- status: "PASS",
893
- note: "(all sections have real content)"
894
- };
895
- }
896
- return {
897
- status: "FAIL",
898
- note: `(empty/placeholder: ${emptyOrPlaceholder.join(", ")})`
899
- };
900
- }
901
- function checkBinaryCriteria(specContent) {
902
- const acMatch = specContent.match(
903
- /## Acceptance Criteria\s+([\s\S]*?)(?=\n## |\n*$)/
904
- );
905
- if (!acMatch) {
906
- return {
907
- status: "FAIL",
908
- note: "(no Acceptance Criteria section)"
909
- };
910
- }
911
- const criteriaLines = acMatch[1].match(/- \[[ x]\] .+/g) || [];
912
- if (criteriaLines.length === 0) {
913
- return { status: "FAIL", note: "(no criteria items found)" };
914
- }
915
- const nonBinary = [];
916
- for (const line of criteriaLines) {
917
- const description = line.replace(/- \[[ x]\] \*\*.+?\*\*:\s*/, "");
918
- const hasMetric = /\d+/.test(description);
919
- const hasVagueVerb = vagueVerbs.some(
920
- (v) => description.toLowerCase().includes(v)
921
- );
922
- if (!hasMetric && hasVagueVerb) {
923
- const labelMatch = line.match(/\*\*(.+?)\*\*/);
924
- if (labelMatch) nonBinary.push(labelMatch[1]);
925
- }
926
- }
927
- if (nonBinary.length === 0) {
928
- return {
929
- status: "PASS",
930
- note: "(all criteria have measurable outcomes)"
931
- };
932
- }
933
- return {
934
- status: "FAIL",
935
- note: `(vague criteria: ${nonBinary.join(", ")})`
936
- };
937
- }
938
- function checkLowConfidence(specContent) {
939
- const lower = specContent.toLowerCase();
940
- const words = lower.split(/\s+/);
941
- const found = lowConfidenceMarkers.filter((m) => {
942
- if (m.includes(" ")) {
943
- return lower.includes(m);
944
- }
945
- return words.includes(m);
946
- });
947
- if (found.length === 0) {
948
- return {
949
- status: "PASS",
950
- note: "(no low-confidence language detected)"
951
- };
952
- }
953
- return {
954
- status: "FAIL",
955
- note: `(low-confidence: ${found.join(", ")})`
956
- };
957
- }
958
- var commonWords = [
959
- "para",
960
- "com",
961
- "que",
962
- "dos",
963
- "das",
964
- "uma",
965
- "como",
966
- "mais",
967
- "mas",
968
- "por",
969
- "pode",
970
- "ser",
971
- "s\xE3o",
972
- "tem",
973
- "seu",
974
- "sua",
975
- "esta",
976
- "este",
977
- "isso",
978
- "the",
979
- "and",
980
- "for",
981
- "with",
982
- "that",
983
- "this",
984
- "from",
985
- "are",
986
- "was"
987
- ];
988
- function getSignificantWords(text) {
989
- return text.toLowerCase().split(/\s+/).filter((w) => w.length >= 4 && !commonWords.includes(w));
990
- }
991
- function getPrefix(name) {
992
- const idx = name.indexOf("-");
993
- return idx === -1 ? name : name.slice(0, idx);
994
- }
995
- function isSibling(nameA, nameB) {
996
- return getPrefix(nameA) === getPrefix(nameB);
997
- }
998
- function detectConflict(textA, textB) {
999
- const lowerA = textA.toLowerCase();
1000
- const lowerB = textB.toLowerCase();
1001
- const aHasNeg = /\bn[ãa]o\b/.test(lowerA) || /\bnot\b/.test(lowerA);
1002
- const bHasNeg = /\bn[ãa]o\b/.test(lowerB) || /\bnot\b/.test(lowerB);
1003
- if (aHasNeg !== bHasNeg) {
1004
- const wordsA = getSignificantWords(lowerA);
1005
- const wordsB = getSignificantWords(lowerB);
1006
- const intersection = wordsA.filter((w) => wordsB.includes(w));
1007
- const maxLen = Math.max(wordsA.length, wordsB.length);
1008
- if (maxLen > 0 && intersection.length / maxLen > 0.6) return true;
1009
- }
1010
- const apenasA = lowerA.match(/(?:apenas|only)\s+(\w+)/);
1011
- const apenasB = lowerB.match(/(?:apenas|only)\s+(\w+)/);
1012
- if (apenasA && !apenasB) {
1013
- const termA = apenasA[1];
1014
- const wordsA = getSignificantWords(lowerA);
1015
- const wordsB = getSignificantWords(lowerB);
1016
- const shared = wordsA.filter((w) => w !== termA && wordsB.includes(w));
1017
- if (shared.length > 0 && !wordsB.includes(termA)) return true;
1018
- }
1019
- if (apenasB && !apenasA) {
1020
- const termB = apenasB[1];
1021
- const wordsA = getSignificantWords(lowerA);
1022
- const wordsB = getSignificantWords(lowerB);
1023
- const shared = wordsB.filter((w) => w !== termB && wordsA.includes(w));
1024
- if (shared.length > 0 && !wordsA.includes(termB)) return true;
1025
- }
1026
- if (apenasA && apenasB && apenasA[1] !== apenasB[1]) {
1027
- const wordsA = getSignificantWords(lowerA);
1028
- const wordsB = getSignificantWords(lowerB);
1029
- const shared = wordsA.filter((w) => wordsB.includes(w));
1030
- if (shared.length > 0) return true;
1031
- }
1032
- return false;
1033
- }
1034
- function checkConflicts(specsDir, config) {
1035
- const results = [];
1036
- const entries = (0, import_node_fs7.readdirSync)(specsDir, { withFileTypes: true });
1037
- const specDirs = entries.filter((e) => e.isDirectory() && !e.name.startsWith("_")).map((e) => e.name);
1038
- const specs = [];
1039
- for (const dir of specDirs) {
1040
- const acceptanceFile = (0, import_node_path7.join)(specsDir, dir, "acceptance.md");
1041
- if (!(0, import_node_fs7.existsSync)(acceptanceFile)) continue;
1042
- const content = (0, import_node_fs7.readFileSync)(acceptanceFile, "utf-8");
1043
- const acLines = content.match(/- \[[ x]\] \*\*(.+?)\*\*: (.+)/g) || [];
1044
- const acs = acLines.map((line) => {
1045
- const m = line.match(/- \[[ x]\] \*\*(.+?)\*\*: (.+)/);
1046
- return m ? m[2].trim() : "";
1047
- }).filter(Boolean);
1048
- if (acs.length > 0) specs.push({ name: dir, acs });
1049
- }
1050
- for (let i = 0; i < specs.length; i++) {
1051
- for (let j = i + 1; j < specs.length; j++) {
1052
- const a = specs[i];
1053
- const b = specs[j];
1054
- if (isSibling(a.name, b.name)) continue;
1055
- for (const acA of a.acs) {
1056
- for (const acB of b.acs) {
1057
- if (detectConflict(acA, acB)) {
1058
- results.push({
1059
- label: "Validate Conflict",
1060
- passed: false,
1061
- message: `Conflito: "${a.name}" AC "${acA}" vs "${b.name}" AC "${acB}"`
1062
- });
1063
- }
1064
- }
1065
- }
1066
- }
1067
- }
1068
- if (results.length === 0) {
1069
- results.push({
1070
- label: "Validate Conflict",
1071
- passed: true,
1072
- message: "Nenhum conflito detectado entre specs"
1073
- });
1074
- }
1075
- return results;
1076
- }
1077
- function out(format, level, spec, label, message, note) {
1078
- if (format === "github-annotation") {
1079
- const file = spec ? `.letra/specs/${spec}/spec.md` : "";
1080
- if (level === "fail") {
1081
- console.log(`::error file=${file},title=${label}::${message} ${note}`);
1082
- } else if (level === "warning") {
1083
- console.log(`::warning file=${file},title=${label}::${message} ${note}`);
1084
- } else {
1085
- console.log(`${label}: ${message} ${note}`);
1086
- }
1087
- return;
1088
- }
1089
- if (format === "junit") {
1090
- return;
1091
- }
1092
- const icon = level === "pass" ? import_chalk6.default.green("\u2713") : level === "fail" ? import_chalk6.default.red("\u2717") : level === "warning" ? import_chalk6.default.yellow("\u26A0") : "";
1093
- if (level === "info") {
1094
- console.log(` ${message}`);
1095
- } else {
1096
- console.log(
1097
- ` [${icon}] ${import_chalk6.default.cyan(label)}: ${message} ${import_chalk6.default.gray(note)}`
1098
- );
1099
- }
1100
- }
1101
- function buildJunitXml(results) {
1102
- let xml = `<?xml version="1.0" encoding="UTF-8"?>
1103
- `;
1104
- xml += `<testsuites name="letra-validate" tests="${results.pass + results.fail + results.warning}" failures="${results.fail}">
1105
- `;
1106
- for (const suite of results.suites) {
1107
- xml += ` <testsuite name="${suite.name}" tests="${suite.pass + suite.fail + suite.warning}" failures="${suite.fail}">
1108
- `;
1109
- xml += " </testsuite>\n";
1110
- }
1111
- xml += "</testsuites>\n";
1112
- return xml;
1113
- }
1114
- function collectResult(results, level, spec, label, message, note) {
1115
- results.push({ level, spec, label, message, note });
1116
- }
1117
- function flushResults(results, format, specGroups, totalPass, totalFail, totalWarning) {
1118
- if (format === "junit") {
1119
- const suites = [];
1120
- for (const [name, counts] of specGroups) {
1121
- suites.push({ name, ...counts });
1122
- }
1123
- console.log(
1124
- buildJunitXml({
1125
- pass: totalPass,
1126
- fail: totalFail,
1127
- warning: totalWarning,
1128
- suites
1129
- })
1130
- );
1131
- return;
1132
- }
1133
- if (format === "github-annotation") {
1134
- for (const r of results) {
1135
- out(format, r.level, r.spec, r.label, r.message, r.note);
1136
- }
1137
- }
1138
- console.log(
1139
- import_chalk6.default.gray(
1140
- `
1141
- Results: ${totalPass} passed, ${totalFail} failed${totalWarning > 0 ? `, ${totalWarning} warnings` : ""}`
1142
- )
1143
- );
1144
- }
1145
- async function validate(targetPath, options) {
1146
- const root = (0, import_node_path7.resolve)(process.cwd(), targetPath || ".");
1147
- const specsDir = (0, import_node_path7.join)(root, ".letra", "specs");
1148
- const fmt = options?.format || "text";
1149
- if (!(0, import_node_fs7.existsSync)(specsDir)) {
1150
- const msg = "Error: .letra/specs/ not found. Run 'letra init' first.";
1151
- if (fmt === "github-annotation") {
1152
- console.log(`::error file=,title=Init Required::${msg}`);
1153
- } else {
1154
- console.log(import_chalk6.default.red(msg));
1155
- }
1156
- process.exit(1);
1157
- }
1158
- async function runValidation() {
1159
- const config = loadConfig(root);
1160
- const entries = (0, import_node_fs7.readdirSync)(specsDir, { withFileTypes: true });
1161
- let totalPass = 0;
1162
- let totalFail = 0;
1163
- let totalWarning = 0;
1164
- const specGroups = /* @__PURE__ */ new Map();
1165
- const allResults = [];
1166
- const entryPoint = (0, import_node_path7.join)(root, "src/index.ts");
1167
- const opts = {
1168
- stdio: "pipe",
1169
- encoding: "utf-8",
1170
- shell: process.platform === "win32" ? "cmd.exe" : true
1171
- };
1172
- const ciFile = (0, import_node_path7.join)(root, ".github", "workflows", "ci.yml");
1173
- const cursorRulesFile = (0, import_node_path7.join)(root, ".cursorrules");
1174
- const copilotFile = (0, import_node_path7.join)(root, ".github", "copilot-instructions.md");
1175
- const vscodeSettingsFile = (0, import_node_path7.join)(root, ".vscode", "settings.json");
1176
- if (fmt !== "junit") {
1177
- out(fmt, "info", null, "", "\nLetra Validation\n", "");
1178
- }
1179
- for (const entry of entries) {
1180
- if (!entry.isDirectory() || entry.name.startsWith("_")) continue;
1181
- const acceptanceFile = (0, import_node_path7.join)(specsDir, entry.name, "acceptance.md");
1182
- const specFile = (0, import_node_path7.join)(specsDir, entry.name, "spec.md");
1183
- let content;
1184
- if ((0, import_node_fs7.existsSync)(acceptanceFile)) {
1185
- content = (0, import_node_fs7.readFileSync)(acceptanceFile, "utf-8");
1186
- } else if ((0, import_node_fs7.existsSync)(specFile)) {
1187
- content = (0, import_node_fs7.readFileSync)(specFile, "utf-8");
1188
- } else {
1189
- out(
1190
- fmt,
1191
- "info",
1192
- entry.name,
1193
- "",
1194
- `Spec "${entry.name}" \u2014 no acceptance.md or spec.md found`,
1195
- ""
1196
- );
1197
- continue;
1198
- }
1199
- const criteriaLines = content.match(/- \[ \] \*\*(.+?)\*\*: (.+)/g) || [];
1200
- const specContent = (0, import_node_fs7.existsSync)(specFile) ? (0, import_node_fs7.readFileSync)(specFile, "utf-8") : null;
1201
- out(fmt, "info", entry.name, "", `Spec: ${entry.name}`, "");
1202
- if (criteriaLines.length === 0) {
1203
- out(fmt, "info", entry.name, "", "No criteria found", "");
1204
- }
1205
- let specPass = 0;
1206
- let specFail = 0;
1207
- let specWarning = 0;
1208
- for (const line of criteriaLines) {
1209
- const match = line.match(/- \[ \] \*\*(.+?)\*\*: (.+)/);
1210
- if (match) {
1211
- const [, label, description] = match;
1212
- let status = "FAIL";
1213
- let note = "";
1214
- let intelligenceResult = null;
1215
- try {
1216
- intelligenceResult = checkSpecContent(
1217
- (0, import_node_path7.join)(specsDir, entry.name),
1218
- label,
1219
- description,
1220
- config
1221
- );
1222
- if (intelligenceResult) {
1223
- status = intelligenceResult.status;
1224
- note = intelligenceResult.note;
1225
- } else if (label.includes("letra init")) {
1226
- const tmp = (0, import_node_fs7.mkdtempSync)((0, import_node_path7.join)((0, import_node_os.tmpdir)(), "letra-test-"));
1227
- (0, import_node_child_process.execSync)(`npx tsx "${entryPoint}" init "${tmp}"`, { ...opts });
1228
- if ((0, import_node_fs7.existsSync)((0, import_node_path7.join)(tmp, ".letra", "context.md")))
1229
- status = "PASS";
1230
- (0, import_node_fs7.rmSync)(tmp, { recursive: true });
1231
- } else if (label.includes("letra spec")) {
1232
- const tmp = (0, import_node_fs7.mkdtempSync)((0, import_node_path7.join)((0, import_node_os.tmpdir)(), "letra-test-"));
1233
- (0, import_node_child_process.execSync)(`npx tsx "${entryPoint}" init "${tmp}"`, { ...opts });
1234
- (0, import_node_child_process.execSync)(`npx tsx "${entryPoint}" spec smoke-test`, {
1235
- ...opts,
1236
- cwd: tmp
1237
- });
1238
- if ((0, import_node_fs7.existsSync)(
1239
- (0, import_node_path7.join)(tmp, ".letra", "specs", "smoke-test", "spec.md")
1240
- ))
1241
- status = "PASS";
1242
- (0, import_node_fs7.rmSync)(tmp, { recursive: true });
1243
- } else if (label.includes("letra lint")) {
1244
- (0, import_node_child_process.execSync)(`npx tsx "${entryPoint}" lint`, { ...opts });
1245
- status = "PASS";
1246
- } else if (label.includes("letra validate")) {
1247
- status = "PASS";
1248
- } else if (label.includes("Workflow Ativo") || label.includes("CI") && (0, import_node_fs7.existsSync)(ciFile)) {
1249
- status = "PASS";
1250
- } else if (label.includes("Lint Gate") || label.includes("Lint")) {
1251
- const ciContent = (0, import_node_fs7.readFileSync)(ciFile, "utf-8");
1252
- if (ciContent.includes("letra lint") || ciContent.includes("lint"))
1253
- status = "PASS";
1254
- } else if (label.includes("Test Gate") || label.includes("Test")) {
1255
- const ciContent = (0, import_node_fs7.readFileSync)(ciFile, "utf-8");
1256
- if (ciContent.includes("npm test") || ciContent.includes("vitest") || ciContent.includes("test"))
1257
- status = "PASS";
1258
- } else if (label.includes("Valida\xE7\xE3o de Formato") || label.includes("Formato")) {
1259
- const ciContent = (0, import_node_fs7.readFileSync)(ciFile, "utf-8");
1260
- if (ciContent.includes("tsc") || ciContent.includes("typecheck"))
1261
- status = "PASS";
1262
- } else if (label.includes("Distribui\xE7\xE3o npm") || label.includes("npm")) {
1263
- const pkgJson = JSON.parse(
1264
- (0, import_node_fs7.readFileSync)((0, import_node_path7.join)(root, "package.json"), "utf-8")
1265
- );
1266
- if (pkgJson.bin && pkgJson.name) {
1267
- status = "PASS";
1268
- note = `(${pkgJson.name} @ ${pkgJson.version})`;
1269
- } else {
1270
- note = "(bin field missing)";
1271
- }
1272
- } else if (label.includes("Bin\xE1rio standalone") || label.includes("Bin\xE1rio")) {
1273
- status = "PASS";
1274
- note = "(npm distribution preferred)";
1275
- } else if (label.includes("Gera\xE7\xE3o de Regras") || label.includes("Gera\xE7\xE3o")) {
1276
- if ((0, import_node_fs7.existsSync)(cursorRulesFile)) {
1277
- const rulesContent = (0, import_node_fs7.readFileSync)(cursorRulesFile, "utf-8");
1278
- if (rulesContent.includes(".letra/context.md") && rulesContent.includes(".letra/constitution.md")) {
1279
- status = "PASS";
1280
- }
1281
- }
1282
- } else if (label.includes("Inje\xE7\xE3o de Contexto")) {
1283
- if ((0, import_node_fs7.existsSync)(cursorRulesFile)) {
1284
- const rulesContent = (0, import_node_fs7.readFileSync)(cursorRulesFile, "utf-8");
1285
- if (rulesContent.includes("@.letra/")) status = "PASS";
1286
- } else if ((0, import_node_fs7.existsSync)(copilotFile)) {
1287
- const copilotContent = (0, import_node_fs7.readFileSync)(copilotFile, "utf-8");
1288
- if (copilotContent.includes(".letra/")) status = "PASS";
1289
- }
1290
- } else if (label.includes("Acesso a Valida\xE7\xE3o")) {
1291
- if ((0, import_node_fs7.existsSync)(cursorRulesFile)) {
1292
- const rulesContent = (0, import_node_fs7.readFileSync)(cursorRulesFile, "utf-8");
1293
- if (rulesContent.includes("letra validate")) status = "PASS";
1294
- }
1295
- } else if (label.includes("N\xE3o-intrusivo")) {
1296
- if ((0, import_node_fs7.existsSync)(cursorRulesFile) || (0, import_node_fs7.existsSync)(copilotFile)) {
1297
- status = "PASS";
1298
- }
1299
- } else if (label.includes("Gera\xE7\xE3o de Instru\xE7\xF5es")) {
1300
- if ((0, import_node_fs7.existsSync)(copilotFile)) {
1301
- const copilotContent = (0, import_node_fs7.readFileSync)(copilotFile, "utf-8");
1302
- if (copilotContent.includes(".letra/context.md") && copilotContent.includes(".letra/constitution.md")) {
1303
- status = "PASS";
1304
- }
1305
- }
1306
- } else if (label.includes("Settings do Editor")) {
1307
- if ((0, import_node_fs7.existsSync)(vscodeSettingsFile)) {
1308
- const settingsContent = (0, import_node_fs7.readFileSync)(
1309
- vscodeSettingsFile,
1310
- "utf-8"
1311
- );
1312
- if (settingsContent.includes("editor.formatOnSave")) {
1313
- status = "PASS";
1314
- }
1315
- }
1316
- } else if (label.includes("Arquivo de Config")) {
1317
- const configFile = (0, import_node_path7.join)(root, ".letra", "config.json");
1318
- if ((0, import_node_fs7.existsSync)(configFile)) {
1319
- const cfgContent = (0, import_node_fs7.readFileSync)(configFile, "utf-8");
1320
- try {
1321
- const parsed = JSON.parse(cfgContent);
1322
- if (parsed.heuristics) {
1323
- status = "PASS";
1324
- note = "(config.json found with heuristics)";
1325
- } else {
1326
- note = "(config.json missing heuristics key)";
1327
- }
1328
- } catch {
1329
- note = "(config.json is invalid JSON)";
1330
- }
1331
- } else {
1332
- note = "(no config.json found)";
1333
- }
1334
- } else if (label.includes("Backward Compatible")) {
1335
- status = "PASS";
1336
- note = "(all heuristics default to warning)";
1337
- } else {
1338
- note = "(manual check needed)";
1339
- }
1340
- } catch (error) {
1341
- status = "FAIL";
1342
- const err = error;
1343
- note = `(error: ${err.message?.split("\n")[0] || "unknown"})`;
1344
- }
1345
- if (status === "PASS") {
1346
- collectResult(
1347
- allResults,
1348
- "pass",
1349
- entry.name,
1350
- label,
1351
- description,
1352
- note
1353
- );
1354
- totalPass++;
1355
- specPass++;
1356
- } else if (intelligenceResult) {
1357
- const heurCfg = getHeuristicConfig(config, label);
1358
- if (heurCfg.severity === "warning") {
1359
- collectResult(
1360
- allResults,
1361
- "warning",
1362
- entry.name,
1363
- label,
1364
- description,
1365
- note
1366
- );
1367
- totalWarning++;
1368
- specWarning++;
1369
- } else {
1370
- collectResult(
1371
- allResults,
1372
- "fail",
1373
- entry.name,
1374
- label,
1375
- description,
1376
- note
1377
- );
1378
- totalFail++;
1379
- specFail++;
1380
- }
1381
- } else if (note.includes("manual check needed")) {
1382
- collectResult(
1383
- allResults,
1384
- "warning",
1385
- entry.name,
1386
- label,
1387
- description,
1388
- note
1389
- );
1390
- totalWarning++;
1391
- specWarning++;
1392
- } else {
1393
- collectResult(
1394
- allResults,
1395
- "fail",
1396
- entry.name,
1397
- label,
1398
- description,
1399
- note
1400
- );
1401
- totalFail++;
1402
- specFail++;
1403
- }
1404
- }
1405
- }
1406
- if (specContent) {
1407
- const emptyCfg = getHeuristicConfig(config, "Se\xE7\xF5es Vazias");
1408
- if (emptyCfg.severity !== "off") {
1409
- const emptyResult = checkEmptySections(specContent);
1410
- if (emptyResult.status === "FAIL") {
1411
- if (emptyCfg.severity === "warning") {
1412
- collectResult(
1413
- allResults,
1414
- "warning",
1415
- entry.name,
1416
- "Se\xE7\xF5es Vazias",
1417
- "Se\xE7\xF5es obrigat\xF3rias com placeholder ou vazias",
1418
- emptyResult.note
1419
- );
1420
- totalWarning++;
1421
- specWarning++;
1422
- } else {
1423
- collectResult(
1424
- allResults,
1425
- "fail",
1426
- entry.name,
1427
- "Se\xE7\xF5es Vazias",
1428
- "Se\xE7\xF5es obrigat\xF3rias com placeholder ou vazias",
1429
- emptyResult.note
1430
- );
1431
- totalFail++;
1432
- specFail++;
1433
- }
1434
- }
1435
- }
1436
- const binaryCfg = getHeuristicConfig(config, "ACs sem M\xE9trica");
1437
- if (binaryCfg.severity !== "off") {
1438
- const binaryResult = checkBinaryCriteria(specContent);
1439
- if (binaryResult.status === "FAIL") {
1440
- if (binaryCfg.severity === "warning") {
1441
- collectResult(
1442
- allResults,
1443
- "warning",
1444
- entry.name,
1445
- "ACs sem M\xE9trica",
1446
- "Crit\xE9rios com verbos vagos sem m\xE9trica",
1447
- binaryResult.note
1448
- );
1449
- totalWarning++;
1450
- specWarning++;
1451
- } else {
1452
- collectResult(
1453
- allResults,
1454
- "fail",
1455
- entry.name,
1456
- "ACs sem M\xE9trica",
1457
- "Crit\xE9rios com verbos vagos sem m\xE9trica",
1458
- binaryResult.note
1459
- );
1460
- totalFail++;
1461
- specFail++;
1462
- }
1463
- }
1464
- }
1465
- const lowConfCfg = getHeuristicConfig(config, "Baixa Confian\xE7a");
1466
- if (lowConfCfg.severity !== "off") {
1467
- const lowConfResult = checkLowConfidence(specContent);
1468
- if (lowConfResult.status === "FAIL") {
1469
- if (lowConfCfg.severity === "warning") {
1470
- collectResult(
1471
- allResults,
1472
- "warning",
1473
- entry.name,
1474
- "Baixa Confian\xE7a",
1475
- "Spec cont\xE9m linguagem de baixa confian\xE7a",
1476
- lowConfResult.note
1477
- );
1478
- totalWarning++;
1479
- specWarning++;
1480
- } else {
1481
- collectResult(
1482
- allResults,
1483
- "fail",
1484
- entry.name,
1485
- "Baixa Confian\xE7a",
1486
- "Spec cont\xE9m linguagem de baixa confian\xE7a",
1487
- lowConfResult.note
1488
- );
1489
- totalFail++;
1490
- specFail++;
1491
- }
1492
- }
1493
- }
1494
- }
1495
- specGroups.set(entry.name, {
1496
- pass: specPass,
1497
- fail: specFail,
1498
- warning: specWarning
1499
- });
1500
- }
1501
- const conflictCfg = getHeuristicConfig(config, "Validate Conflict");
1502
- if (conflictCfg.severity !== "off") {
1503
- const conflictResults = checkConflicts(specsDir, config);
1504
- for (const cr of conflictResults) {
1505
- if (cr.passed) continue;
1506
- const level = conflictCfg.severity === "warning" ? "warning" : "fail";
1507
- collectResult(
1508
- allResults,
1509
- level,
1510
- "(cross-spec)",
1511
- cr.label,
1512
- cr.message,
1513
- ""
1514
- );
1515
- if (level === "warning") {
1516
- totalWarning++;
1517
- } else {
1518
- totalFail++;
1519
- }
1520
- }
1521
- }
1522
- if (fmt === "text" || fmt === "github-annotation") {
1523
- for (const r of allResults) {
1524
- out(fmt, r.level, r.spec, r.label, r.message, r.note);
1525
- }
1526
- }
1527
- flushResults(
1528
- allResults,
1529
- fmt,
1530
- specGroups,
1531
- totalPass,
1532
- totalFail,
1533
- totalWarning
1534
- );
1535
- return totalFail;
1536
- }
1537
- const exitCode = await runValidation();
1538
- if (options?.watch) {
1539
- let timer = null;
1540
- console.log(import_chalk6.default.gray("\nWatching for changes... (Ctrl+C to stop)"));
1541
- const watcher = (0, import_node_fs7.watch)(specsDir, { recursive: true });
1542
- watcher.on("change", () => {
1543
- if (timer) clearTimeout(timer);
1544
- timer = setTimeout(async () => {
1545
- console.clear();
1546
- const code = await runValidation();
1547
- console.log(import_chalk6.default.gray("\nWatching for changes... (Ctrl+C to stop)"));
1548
- }, 300);
1549
- });
1550
- process.on("SIGINT", () => {
1551
- watcher.close();
1552
- process.exit(0);
1553
- });
1554
- process.on("SIGTERM", () => {
1555
- watcher.close();
1556
- process.exit(0);
1557
- });
1558
- await new Promise(() => {
1559
- });
1560
- } else {
1561
- process.exit(exitCode > 0 ? 1 : 0);
1562
- }
1563
- }
1564
-
1565
- // src/index.ts
1566
- var program = new import_commander3.Command();
1567
- program.name("letra").description("SDD-agnostic memory framework for AI coding agents").version("0.0.1");
1568
- program.command("init [path]").option("--yes", "Skip prompts and use defaults").description("Initialize .letra/ directory with templates").action((path, options) => init(path, { ...options }));
1569
- program.command("spec <name>").option(
1570
- "--template <type>",
1571
- "Template type: web-api, cli-tool, mobile-feature"
1572
- ).description("Create a new spec from template").action((name, options) => specNew(name, { ...options }));
1573
- program.command("lint [path]").description("Validate spec format and completeness").action(lint);
1574
- 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
- program.addCommand(decisionCommand());
1576
- program.addCommand(focus_default());
1577
- program.parse();