@letra-ai/cli 0.1.12 → 0.1.13

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.
package/dist/index.js CHANGED
@@ -1,31 +1,316 @@
1
1
  // src/index.ts
2
- import { Command } from "commander";
2
+ import { Command as Command3 } from "commander";
3
3
 
4
- // src/commands/init.ts
4
+ // src/commands/decision.ts
5
5
  import {
6
- copyFileSync,
7
6
  existsSync,
8
7
  mkdirSync,
8
+ readFileSync,
9
+ readdirSync,
9
10
  writeFileSync
10
11
  } from "fs";
11
12
  import { join, resolve } from "path";
12
- import { fileURLToPath } from "url";
13
13
  import chalk from "chalk";
14
+ import { Command } from "commander";
15
+ function sanitizeTitle(title) {
16
+ return title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
17
+ }
18
+ function today() {
19
+ return (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
20
+ }
21
+ function decisionCommand() {
22
+ const cmd = new Command("decision");
23
+ cmd.command("new <title>").description("Cria um novo Architecture Decision Record").action((title) => {
24
+ const root = resolve(process.cwd());
25
+ const decisionsDir = join(root, ".letra", "decisions");
26
+ const slug = sanitizeTitle(title);
27
+ const filePath = join(decisionsDir, `${slug}.md`);
28
+ if (!existsSync(decisionsDir)) {
29
+ mkdirSync(decisionsDir, { recursive: true });
30
+ }
31
+ if (existsSync(filePath)) {
32
+ console.log(
33
+ chalk.red(
34
+ `Decision "${slug}" already exists at .letra/decisions/${slug}.md`
35
+ )
36
+ );
37
+ return;
38
+ }
39
+ const content = `# ${title}
40
+
41
+ **Date**: ${today()}
42
+ **Status**: proposed
43
+
44
+ ## Context
45
+
46
+ Why is this decision needed? What problem does it solve?
47
+
48
+ ## Decision
49
+
50
+ What was decided?
51
+
52
+ ## Consequences
53
+
54
+ What are the trade-offs? What does this enable or prevent?
55
+ `;
56
+ writeFileSync(filePath, content);
57
+ console.log(
58
+ chalk.green(
59
+ `Decision "${slug}" created at .letra/decisions/${slug}.md`
60
+ )
61
+ );
62
+ });
63
+ cmd.command("list").description("Lista todos os Architecture Decision Records").action(() => {
64
+ const root = resolve(process.cwd());
65
+ const decisionsDir = join(root, ".letra", "decisions");
66
+ if (!existsSync(decisionsDir)) {
67
+ console.log(
68
+ chalk.yellow("No decisions directory found at .letra/decisions/")
69
+ );
70
+ return;
71
+ }
72
+ const files = readdirSync(decisionsDir).filter((f) => f.endsWith(".md")).sort();
73
+ if (files.length === 0) {
74
+ console.log(chalk.yellow("No decisions found"));
75
+ return;
76
+ }
77
+ for (const file of files) {
78
+ const content = readFileSync(join(decisionsDir, file), "utf-8");
79
+ const firstLine = content.split("\n")[0]?.replace(/^#\s*/, "").trim() || file;
80
+ console.log(`${chalk.cyan(file)} ${firstLine}`);
81
+ }
82
+ });
83
+ return cmd;
84
+ }
85
+
86
+ // src/commands/focus.ts
87
+ import { existsSync as existsSync2, readFileSync as readFileSync2, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
88
+ import { join as join2, resolve as resolve2 } from "path";
89
+ import chalk2 from "chalk";
90
+ import { Command as Command2 } from "commander";
91
+ function extractOutcome(specDir) {
92
+ const specFile = join2(specDir, "spec.md");
93
+ if (!existsSync2(specFile)) return null;
94
+ const content = readFileSync2(specFile, "utf-8");
95
+ const match = content.match(/## Outcome\s+([\s\S]*?)(?=\n## |\n*$)/);
96
+ return match ? match[1].trim() : null;
97
+ }
98
+ 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");
102
+ if (options.clear) {
103
+ if (existsSync2(focusFile)) {
104
+ unlinkSync(focusFile);
105
+ console.log(chalk2.green("Focus removed."));
106
+ } else {
107
+ console.log(chalk2.yellow("No focus to remove."));
108
+ }
109
+ return;
110
+ }
111
+ 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`));
116
+ process.exit(1);
117
+ }
118
+ const outcome = extractOutcome(specDir);
119
+ const outcomeLine = `**Outcome**: ${outcome || spec}`;
120
+ const focusContent = [
121
+ `# Focus: ${spec}`,
122
+ "",
123
+ `**Path**: .letra/specs/${spec}/`,
124
+ outcomeLine,
125
+ ""
126
+ ].join("\n");
127
+ writeFileSync2(focusFile, focusContent);
128
+ console.log(chalk2.green(`Focus set to "${spec}".`));
129
+ return;
130
+ }
131
+ if (existsSync2(focusFile)) {
132
+ console.log(readFileSync2(focusFile, "utf-8"));
133
+ } else {
134
+ console.log("Nenhum foco definido.");
135
+ }
136
+ });
137
+ }
138
+
139
+ // src/commands/init.ts
140
+ import {
141
+ copyFileSync,
142
+ existsSync as existsSync3,
143
+ mkdirSync as mkdirSync2,
144
+ writeFileSync as writeFileSync3
145
+ } from "fs";
146
+ import { join as join3, resolve as resolve3 } from "path";
147
+ import { createInterface } from "readline";
148
+ import { fileURLToPath } from "url";
149
+ import chalk3 from "chalk";
14
150
  import ora from "ora";
15
151
  var __dirname = fileURLToPath(new URL(".", import.meta.url));
16
- async function init(targetPath) {
17
- const root = resolve(process.cwd(), targetPath || ".");
18
- const letraDir = join(root, ".letra");
152
+ function ask(query, options) {
153
+ 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(" ")}
157
+ > `;
158
+ rl.question(formatted, (answer) => {
159
+ rl.close();
160
+ const trimmed = answer.trim().toLowerCase();
161
+ if (trimmed && options.some((o) => o.toLowerCase().startsWith(trimmed))) {
162
+ resolve7(
163
+ options.find((o) => o.toLowerCase().startsWith(trimmed)) ?? options[0]
164
+ );
165
+ } else if (trimmed && options.includes(trimmed)) {
166
+ resolve7(trimmed);
167
+ } else {
168
+ resolve7(options[0]);
169
+ }
170
+ });
171
+ });
172
+ }
173
+ function adaptConfig(projectType) {
174
+ const config = {
175
+ "conteudo-minimo": { severity: "warning", minChars: 50 },
176
+ "consistencia-terminologia": { severity: "warning" },
177
+ "detecao-tom": {
178
+ severity: "warning",
179
+ blacklist: [
180
+ "tipo",
181
+ "t\xE1",
182
+ "pra",
183
+ "blz",
184
+ "kkk",
185
+ "eita",
186
+ "oi",
187
+ "oi pessoal"
188
+ ]
189
+ },
190
+ "drift-temporal": { severity: "warning", maxDays: 30 },
191
+ "secoes-vazias": { severity: "warning" },
192
+ "acs-sem-metrica": { severity: "warning" },
193
+ "baixa-confianca": { severity: "warning" }
194
+ };
195
+ if (projectType === "library") {
196
+ config["detecao-tom"] = { severity: "off" };
197
+ config["drift-temporal"] = { severity: "warning", maxDays: 60 };
198
+ } else if (projectType === "mobile") {
199
+ config["drift-temporal"] = { severity: "error", maxDays: 14 };
200
+ config["baixa-confianca"] = { severity: "error" };
201
+ } else if (projectType === "cli") {
202
+ config["detecao-tom"] = { severity: "off" };
203
+ }
204
+ return JSON.stringify({ heuristics: config }, null, 2);
205
+ }
206
+ function adaptersForTool(tool) {
207
+ const all = ["cursor", "claude-code", "windsurf", "vscode", "opencode"];
208
+ if (tool === "todos") return all;
209
+ const map = {
210
+ opencode: ["opencode"],
211
+ cursor: ["cursor"],
212
+ windsurf: ["windsurf"],
213
+ "claude code": ["claude-code"],
214
+ "vscode copilot": ["vscode"]
215
+ };
216
+ return map[tool.toLowerCase()] || all;
217
+ }
218
+ function generateAdapterFiles(root, tools) {
219
+ const adapters = [];
220
+ const baseContent = (name, format) => `# Letra Context \u2014 ${name} Adapter
221
+ # Generated by letra init. Do not edit manually.
222
+
223
+ ${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:
224
+ - .letra/context.md
225
+ - .letra/constitution.md
226
+ - .letra/glossary.md
227
+ - .letra/focus.md (if exists, defines current session focus)
228
+ `}
229
+ # Rules
230
+ - Always read specs in .letra/specs/ before writing code
231
+ - Run \`letra validate\` to check acceptance criteria
232
+ - Follow the constitution.md rules strictly
233
+ - Use formal tone in all generated content
234
+ `;
235
+ for (const tool of tools) {
236
+ switch (tool) {
237
+ case "cursor":
238
+ adapters.push({
239
+ path: join3(root, ".cursorrules"),
240
+ content: baseContent("Cursor", "at")
241
+ });
242
+ break;
243
+ case "claude-code":
244
+ adapters.push({
245
+ path: join3(root, "CLAUDE.md"),
246
+ content: baseContent("Claude Code", "text")
247
+ });
248
+ break;
249
+ case "windsurf":
250
+ adapters.push({
251
+ path: join3(root, ".windsurfrules"),
252
+ content: baseContent("Windsurf", "at")
253
+ });
254
+ break;
255
+ case "vscode":
256
+ adapters.push({
257
+ path: join3(root, ".github", "copilot-instructions.md"),
258
+ content: baseContent("VSCode Copilot", "text")
259
+ });
260
+ break;
261
+ case "opencode":
262
+ adapters.push({
263
+ path: join3(root, "AGENTS.md"),
264
+ content: baseContent("OpenCode", "text")
265
+ });
266
+ break;
267
+ }
268
+ }
269
+ 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}/`, "")}`);
274
+ }
275
+ }
276
+ async function init(targetPath, options) {
277
+ const root = resolve3(process.cwd(), targetPath || ".");
278
+ const letraDir = join3(root, ".letra");
19
279
  const spinner = ora("Initializing Letra...").start();
20
- if (existsSync(letraDir)) {
21
- spinner.warn(chalk.yellow(".letra/ already exists"));
280
+ if (existsSync3(letraDir)) {
281
+ spinner.warn(chalk3.yellow(".letra/ already exists"));
22
282
  return;
23
283
  }
24
284
  try {
25
- mkdirSync(join(letraDir, "decisions"), { recursive: true });
26
- mkdirSync(join(letraDir, "specs", "_template"), { recursive: true });
27
- mkdirSync(join(letraDir, "adapters"), { recursive: true });
28
- const templateDir = join(__dirname, "..", "..", ".letra");
285
+ let projectType = "web-app";
286
+ let tool = "cursor";
287
+ if (options?.yes || !process.stdin.isTTY) {
288
+ projectType = "web-app";
289
+ tool = "todos";
290
+ } else {
291
+ spinner.stop();
292
+ projectType = await ask("Project type?", [
293
+ "web-app",
294
+ "cli",
295
+ "library",
296
+ "mobile"
297
+ ]);
298
+ const toolNames = [
299
+ "Cursor",
300
+ "Windsurf",
301
+ "Claude Code",
302
+ "VSCode Copilot",
303
+ "OpenCode",
304
+ "Todos"
305
+ ];
306
+ const answer = await ask("AI coding agent?", toolNames);
307
+ tool = answer.toLowerCase();
308
+ spinner.start();
309
+ }
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");
29
314
  const templates = [
30
315
  "context.md",
31
316
  "constitution.md",
@@ -33,13 +318,11 @@ async function init(targetPath) {
33
318
  "lessons-learned.md"
34
319
  ];
35
320
  for (const file of templates) {
36
- const src = join(templateDir, file);
37
- const dest = join(letraDir, file);
38
- if (existsSync(src)) {
39
- copyFileSync(src, dest);
40
- }
321
+ const src = join3(templateDir, file);
322
+ const dest = join3(letraDir, file);
323
+ if (existsSync3(src)) copyFileSync(src, dest);
41
324
  }
42
- const specTemplate = join(letraDir, "specs", "_template.md");
325
+ const specTemplate = join3(letraDir, "specs", "_template.md");
43
326
  const specContent = `# Spec Template
44
327
 
45
328
  ## Outcome
@@ -57,82 +340,17 @@ O que explicitamente N\xC3O est\xE1 neste escopo.
57
340
  ## Context
58
341
  Por que estamos construindo isso.
59
342
  `;
60
- writeFileSync(specTemplate, specContent);
61
- const cursorRulesPath = join(root, ".cursorrules");
62
- const cursorRulesContent = `# Letra Context \u2014 Cursor Adapter
63
- # Generated by letra init. Do not edit manually.
64
-
65
- # Context
66
- @.letra/context.md
67
- @.letra/constitution.md
68
- @.letra/glossary.md
69
-
70
- # Rules
71
- - Always read specs in .letra/specs/ before writing code
72
- - Run \`letra validate\` to check acceptance criteria
73
- - Follow the constitution.md rules strictly
74
- - Use formal tone in all generated content
75
- `;
76
- writeFileSync(cursorRulesPath, cursorRulesContent);
77
- console.log(` ${chalk.gray("Created")} .cursorrules`);
78
- const claudeMdPath = join(root, "CLAUDE.md");
79
- const claudeMdContent = `# Letra Context \u2014 Claude Code Adapter
80
- # Generated by letra init. Do not edit manually.
81
-
82
- Read the following files before starting any task:
83
- - .letra/context.md
84
- - .letra/constitution.md
85
- - .letra/glossary.md
86
-
87
- # Rules
88
- - Always check specs in .letra/specs/ before writing code
89
- - Run \`letra validate\` to verify acceptance criteria
90
- - Follow constitution.md strictly
91
- - Use formal tone in all generated content
92
- `;
93
- writeFileSync(claudeMdPath, claudeMdContent);
94
- console.log(` ${chalk.gray("Created")} CLAUDE.md`);
95
- const windsurfRulesPath = join(root, ".windsurfrules");
96
- const windsurfRulesContent = `# Letra Context \u2014 Windsurf Adapter
97
- # Generated by letra init. Do not edit manually.
98
-
99
- # Context
100
- @.letra/context.md
101
- @.letra/constitution.md
102
- @.letra/glossary.md
103
-
104
- # Rules
105
- - Always read specs in .letra/specs/ before writing code
106
- - Run \`letra validate\` to check acceptance criteria
107
- - Follow the constitution.md rules strictly
108
- - Use formal tone in all generated content
109
- `;
110
- writeFileSync(windsurfRulesPath, windsurfRulesContent);
111
- console.log(` ${chalk.gray("Created")} .windsurfrules`);
112
- const githubDir = join(root, ".github");
113
- if (!existsSync(githubDir)) mkdirSync(githubDir, { recursive: true });
114
- const copilotInstructionsPath = join(githubDir, "copilot-instructions.md");
115
- const copilotInstructionsContent = `# Letra Context \u2014 VSCode Copilot Adapter
116
- # Generated by letra init. Do not edit manually.
117
-
118
- # Context
119
- Read the following files before starting any task:
120
- - .letra/context.md
121
- - .letra/constitution.md
122
- - .letra/glossary.md
123
-
124
- # Rules
125
- - Always check specs in .letra/specs/ before writing code
126
- - Run \`letra validate\` to verify acceptance criteria
127
- - Follow constitution.md strictly
128
- - Use formal tone in all generated content
129
- `;
130
- writeFileSync(copilotInstructionsPath, copilotInstructionsContent);
131
- console.log(` ${chalk.gray("Created")} .github/copilot-instructions.md`);
132
- const vscodeDir = join(root, ".vscode");
133
- if (!existsSync(vscodeDir)) mkdirSync(vscodeDir, { recursive: true });
134
- const vscodeSettingsPath = join(vscodeDir, "settings.json");
135
- const vscodeSettingsContent = `{
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`);
347
+ const tools = adaptersForTool(tool);
348
+ generateAdapterFiles(root, tools);
349
+ 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");
353
+ const vscodeSettingsContent = `{
136
354
  "editor.formatOnSave": true,
137
355
  "editor.defaultFormatter": "esbenp.prettier-vscode",
138
356
  "editor.codeActionsOnSave": {
@@ -141,25 +359,26 @@ Read the following files before starting any task:
141
359
  "files.autoSave": "onFocusChange"
142
360
  }
143
361
  `;
144
- writeFileSync(vscodeSettingsPath, vscodeSettingsContent);
145
- console.log(` ${chalk.gray("Created")} .vscode/settings.json`);
146
- spinner.succeed(chalk.green(".letra/ initialized successfully"));
362
+ writeFileSync3(vscodeSettingsPath, vscodeSettingsContent);
363
+ console.log(` ${chalk3.gray("Created")} .vscode/settings.json`);
364
+ }
365
+ spinner.succeed(chalk3.green(".letra/ initialized successfully"));
147
366
  console.log("");
148
367
  console.log(" Next steps:");
149
368
  console.log(
150
- ` ${chalk.cyan("letra spec new <name>")} Create your first spec`
369
+ ` ${chalk3.cyan("letra spec new <name>")} Create your first spec`
151
370
  );
152
- console.log(` ${chalk.cyan("letra lint")} Validate specs`);
371
+ console.log(` ${chalk3.cyan("letra lint")} Validate specs`);
153
372
  } catch (error) {
154
- spinner.fail(chalk.red("Failed to initialize Letra"));
373
+ spinner.fail(chalk3.red("Failed to initialize Letra"));
155
374
  process.exit(1);
156
375
  }
157
376
  }
158
377
 
159
378
  // src/commands/lint.ts
160
- import { existsSync as existsSync2, readFileSync, readdirSync as readdirSync2 } from "fs";
161
- import { join as join2, resolve as resolve2 } from "path";
162
- import chalk2 from "chalk";
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";
163
382
  var REQUIRED_SECTIONS = [
164
383
  "## Outcome",
165
384
  "## Constraints",
@@ -168,27 +387,27 @@ var REQUIRED_SECTIONS = [
168
387
  "## Context"
169
388
  ];
170
389
  async function lint(targetPath) {
171
- const root = resolve2(process.cwd(), targetPath || ".");
172
- const specsDir = join2(root, ".letra", "specs");
173
- if (!existsSync2(specsDir)) {
390
+ const root = resolve4(process.cwd(), targetPath || ".");
391
+ const specsDir = join4(root, ".letra", "specs");
392
+ if (!existsSync4(specsDir)) {
174
393
  console.log(
175
- chalk2.red("Error: .letra/specs/ not found. Run 'letra init' first.")
394
+ chalk4.red("Error: .letra/specs/ not found. Run 'letra init' first.")
176
395
  );
177
396
  process.exit(1);
178
397
  }
179
398
  const results = [];
180
399
  let totalErrors = 0;
181
400
  let totalWarnings = 0;
182
- const entries = readdirSync2(specsDir, { withFileTypes: true });
401
+ const entries = readdirSync3(specsDir, { withFileTypes: true });
183
402
  for (const entry of entries) {
184
403
  if (!entry.isDirectory() || entry.name.startsWith("_")) continue;
185
- const specFile = join2(specsDir, entry.name, "spec.md");
404
+ const specFile = join4(specsDir, entry.name, "spec.md");
186
405
  const errors = [];
187
406
  const warnings = [];
188
- if (!existsSync2(specFile)) {
407
+ if (!existsSync4(specFile)) {
189
408
  errors.push("Missing spec.md");
190
409
  } else {
191
- const content = readFileSync(specFile, "utf-8");
410
+ const content = readFileSync3(specFile, "utf-8");
192
411
  for (const section of REQUIRED_SECTIONS) {
193
412
  if (!content.includes(section)) {
194
413
  errors.push(`Missing section: ${section}`);
@@ -211,22 +430,22 @@ async function lint(targetPath) {
211
430
  }
212
431
  }
213
432
  if (results.length === 0) {
214
- console.log(chalk2.green("All specs are valid"));
433
+ console.log(chalk4.green("All specs are valid"));
215
434
  process.exit(0);
216
435
  }
217
436
  console.log("");
218
437
  for (const result of results) {
219
- console.log(chalk2.bold(`
438
+ console.log(chalk4.bold(`
220
439
  Spec: ${result.file}`));
221
440
  for (const error of result.errors) {
222
- console.log(chalk2.red(` \u2717 ${error}`));
441
+ console.log(chalk4.red(` \u2717 ${error}`));
223
442
  }
224
443
  for (const warning of result.warnings) {
225
- console.log(chalk2.yellow(` \u26A0 ${warning}`));
444
+ console.log(chalk4.yellow(` \u26A0 ${warning}`));
226
445
  }
227
446
  }
228
447
  console.log(
229
- chalk2.gray(
448
+ chalk4.gray(
230
449
  `
231
450
  ${results.length} spec(s) with issues: ${totalErrors} error(s), ${totalWarnings} warning(s)`
232
451
  )
@@ -235,26 +454,186 @@ ${results.length} spec(s) with issues: ${totalErrors} error(s), ${totalWarnings}
235
454
  }
236
455
 
237
456
  // src/commands/spec.ts
238
- import { existsSync as existsSync3, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
239
- import { join as join3, resolve as resolve3 } from "path";
240
- import chalk3 from "chalk";
457
+ import {
458
+ existsSync as existsSync5,
459
+ mkdirSync as mkdirSync3,
460
+ readFileSync as readFileSync4,
461
+ readdirSync as readdirSync4,
462
+ writeFileSync as writeFileSync4
463
+ } from "fs";
464
+ import { join as join5, resolve as resolve5 } from "path";
465
+ import chalk5 from "chalk";
241
466
  import ora2 from "ora";
242
- async function specNew(name) {
243
- const root = resolve3(process.cwd());
244
- const letraDir = join3(root, ".letra");
245
- const specDir = join3(letraDir, "specs", name);
246
- const spinner = ora2(`Creating spec "${name}"...`).start();
247
- if (!existsSync3(letraDir)) {
248
- spinner.fail(chalk3.red(".letra/ not found. Run 'letra init' first."));
467
+ var builtInTemplates = {
468
+ "web-api": {
469
+ spec: `# Spec: {{name}}
470
+
471
+ ## Outcome
472
+ Usu\xE1rio consegue fazer requisi\xE7\xF5es HTTP para a API e receber respostas padronizadas.
473
+
474
+ ## Constraints
475
+ - RESTful\u9075\u5FAA (GET, POST, PUT, DELETE)
476
+ - Autentica\xE7\xE3o via Bearer token JWT
477
+ - Rate limiting: 100 req/min por usu\xE1rio
478
+ - Timeout m\xE1ximo de 30s por requisi\xE7\xE3o
479
+
480
+ ## Exclusions
481
+ - WebSocket n\xE3o est\xE1 no escopo
482
+ - Upload de arquivos n\xE3o est\xE1 no escopo inicial
483
+
484
+ ## Acceptance Criteria
485
+ - [ ] **CRUD**: CRUD completo para o recurso principal (GET, POST, PUT, DELETE retornam 200/201/204).
486
+ - [ ] **Autentica\xE7\xE3o**: Rota sem token retorna 401, rota com token inv\xE1lido retorna 403.
487
+ - [ ] **Valida\xE7\xE3o**: Payload inv\xE1lido retorna 422 com mensagem de erro descritiva.
488
+ - [ ] **Rate Limit**: Exceder 100 req/min retorna 429 com header Retry-After.
489
+ - [ ] **Pagina\xE7\xE3o**: GET com ?page=2&limit=10 retorna p\xE1gina correta com total count.
490
+
491
+ ## Context
492
+ Template para APIs REST. Adaptado para o dom\xEDnio espec\xEDfico do projeto.`,
493
+ acceptance: `# Acceptance Criteria \u2014 {{name}}
494
+
495
+ - [ ] **CRUD**: CRUD completo para o recurso principal (GET, POST, PUT, DELETE retornam 200/201/204).
496
+ - [ ] **Autentica\xE7\xE3o**: Rota sem token retorna 401, rota com token inv\xE1lido retorna 403.
497
+ - [ ] **Valida\xE7\xE3o**: Payload inv\xE1lido retorna 422 com mensagem de erro descritiva.
498
+ - [ ] **Rate Limit**: Exceder 100 req/min retorna 429 com header Retry-After.
499
+ - [ ] **Pagina\xE7\xE3o**: GET com ?page=2&limit=10 retorna p\xE1gina correta com total count.`
500
+ },
501
+ "cli-tool": {
502
+ spec: `# Spec: {{name}}
503
+
504
+ ## Outcome
505
+ Usu\xE1rio instala e executa a CLI, recebendo output formatado no terminal.
506
+
507
+ ## Constraints
508
+ - Node.js 22+ como runtime
509
+ - Deve funcionar em Windows, macOS e Linux
510
+ - Exit codes seguem padr\xE3o Unix (0 sucesso, 1 erro)
511
+ - --help deve funcionar sem argumentos
512
+
513
+ ## Exclusions
514
+ - UI gr\xE1fica n\xE3o est\xE1 no escopo
515
+ - Modo servidor/daemon n\xE3o est\xE1 no escopo
516
+
517
+ ## Acceptance Criteria
518
+ - [ ] **Instala\xE7\xE3o**: CLI execut\xE1vel via npx/npm install -g sem erros.
519
+ - [ ] **--help**: Roda sem argumentos, exibe ajuda com subcomandos.
520
+ - [ ] **Subcomando**: Subcomando principal executa sem erros e exibe output.
521
+ - [ ] **Erro**: Subcomando inv\xE1lido exibe erro amig\xE1vel e exit 1.
522
+ - [ ] **Cross-platform**: Funciona em Windows (cmd/powershell), macOS (zsh) e Linux (bash).
523
+
524
+ ## Context
525
+ Template para ferramentas de linha de comando. Adaptado para o escopo espec\xEDfico.`,
526
+ acceptance: `# Acceptance Criteria \u2014 {{name}}
527
+
528
+ - [ ] **Instala\xE7\xE3o**: CLI execut\xE1vel via npx/npm install -g sem erros.
529
+ - [ ] **--help**: Roda sem argumentos, exibe ajuda com subcomandos.
530
+ - [ ] **Subcomando**: Subcomando principal executa sem erros e exibe output.
531
+ - [ ] **Erro**: Subcomando inv\xE1lido exibe erro amig\xE1vel e exit 1.
532
+ - [ ] **Cross-platform**: Funciona em Windows (cmd/powershell), macOS (zsh) e Linux (bash).`
533
+ },
534
+ "mobile-feature": {
535
+ spec: `# Spec: {{name}}
536
+
537
+ ## Outcome
538
+ Usu\xE1rio consegue acessar e interagir com a nova funcionalidade no aplicativo mobile.
539
+
540
+ ## Constraints
541
+ - Suporte a iOS 16+ e Android 13+
542
+ - Offline-first: funcionalidade deve funcionar sem internet
543
+ - Tempo de resposta < 200ms para intera\xE7\xF5es locais
544
+ - Acessibilidade: VoiceOver (iOS) e TalkBack (Android)
545
+
546
+ ## Exclusions
547
+ - Vers\xE3o web n\xE3o est\xE1 no escopo (mobile-only)
548
+ - Suporte a tablets \xE9 desej\xE1vel mas n\xE3o obrigat\xF3rio
549
+
550
+ ## Acceptance Criteria
551
+ - [ ] **Tela principal**: Nova funcionalidade aparece na navega\xE7\xE3o principal.
552
+ - [ ] **Offline**: Funcionalidade completa funciona sem conex\xE3o de rede.
553
+ - [ ] **Performance**: Scroll da lista com 1000+ itens mant\xE9m 60fps.
554
+ - [ ] **Acessibilidade**: Todos os elementos t\xEAm label de acessibilidade.
555
+ - [ ] **Dark Mode**: Funcionalidade respeita o tema do sistema.
556
+
557
+ ## Context
558
+ Template para features mobile nativas. Adaptado para o framework espec\xEDfico (SwiftUI/Compose).`,
559
+ acceptance: `# Acceptance Criteria \u2014 {{name}}
560
+
561
+ - [ ] **Tela principal**: Nova funcionalidade aparece na navega\xE7\xE3o principal.
562
+ - [ ] **Offline**: Funcionalidade completa funciona sem conex\xE3o de rede.
563
+ - [ ] **Performance**: Scroll da lista com 1000+ itens mant\xE9m 60fps.
564
+ - [ ] **Acessibilidade**: Todos os elementos t\xEAm label de acessibilidade.
565
+ - [ ] **Dark Mode**: Funcionalidade respeita o tema do sistema.`
566
+ }
567
+ };
568
+ function listTemplates(root) {
569
+ const names = Object.keys(builtInTemplates);
570
+ const customDir = join5(root, ".letra", "templates");
571
+ if (existsSync5(customDir)) {
572
+ for (const file of readdirSync4(customDir)) {
573
+ if (file.endsWith(".md")) {
574
+ const name = file.replace(/\.md$/, "");
575
+ if (!names.includes(name)) names.push(name);
576
+ }
577
+ }
578
+ }
579
+ return names;
580
+ }
581
+ function findTemplate(root, type) {
582
+ const lower = type.toLowerCase();
583
+ if (builtInTemplates[lower]) return builtInTemplates[lower];
584
+ const customFile = join5(root, ".letra", "templates", `${type}.md`);
585
+ const customAcceptance = join5(
586
+ root,
587
+ ".letra",
588
+ "templates",
589
+ `${type}-acceptance.md`
590
+ );
591
+ if (existsSync5(customFile)) {
592
+ const spec = readFileSync4(customFile, "utf-8");
593
+ const acceptance = existsSync5(customAcceptance) ? readFileSync4(customAcceptance, "utf-8") : `# Acceptance Criteria \u2014 ${type}
594
+
595
+ - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
596
+ `;
597
+ return { spec, acceptance };
598
+ }
599
+ return null;
600
+ }
601
+ function applyPlaceholders(content, name) {
602
+ return content.replace(/\{\{name\}\}/g, name);
603
+ }
604
+ 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."));
249
610
  process.exit(1);
250
611
  }
251
- if (existsSync3(specDir)) {
252
- spinner.warn(chalk3.yellow(`Spec "${name}" already exists`));
612
+ if (existsSync5(specDir)) {
613
+ console.log(chalk5.yellow(`Spec "${name}" already exists`));
253
614
  return;
254
615
  }
616
+ const templateType = options?.template || "_default";
617
+ const template = templateType === "_default" ? null : findTemplate(root, templateType);
618
+ if (options?.template && !template) {
619
+ const available = listTemplates(root).join(", ");
620
+ console.log(
621
+ chalk5.red(
622
+ `Template "${options.template}" not found. Available: ${available}`
623
+ )
624
+ );
625
+ process.exit(1);
626
+ }
627
+ const spinner = ora2(`Creating spec "${name}"...`).start();
255
628
  try {
256
- mkdirSync2(specDir, { recursive: true });
257
- const specContent = `# Spec: ${name}
629
+ mkdirSync3(specDir, { recursive: true });
630
+ if (template) {
631
+ const specContent = applyPlaceholders(template.spec, name);
632
+ const acceptanceContent = applyPlaceholders(template.acceptance, name);
633
+ writeFileSync4(join5(specDir, "spec.md"), specContent);
634
+ writeFileSync4(join5(specDir, "acceptance.md"), acceptanceContent);
635
+ } else {
636
+ const specContent = `# Spec: ${name}
258
637
 
259
638
  ## Outcome
260
639
  O que o usu\xE1rio consegue fazer quando isso estiver pronto.
@@ -271,28 +650,18 @@ O que explicitamente N\xC3O est\xE1 neste escopo.
271
650
  ## Context
272
651
  Por que estamos construindo isso. Trade-offs considerados.
273
652
  `;
274
- const acceptanceContent = `# Acceptance Criteria \u2014 ${name}
653
+ const acceptanceContent = `# Acceptance Criteria \u2014 ${name}
275
654
 
276
655
  - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
277
656
  `;
278
- const statusContent = `# Status \u2014 ${name}
279
-
280
- **Spec:** \`.letra/specs/${name}/spec.md\`
281
- **Status:** pending
282
- **Last sync:** ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}
283
-
284
- ## Progresso
285
-
286
- - [ ] Implementado
287
- `;
288
- writeFileSync2(join3(specDir, "spec.md"), specContent);
289
- writeFileSync2(join3(specDir, "acceptance.md"), acceptanceContent);
290
- writeFileSync2(join3(specDir, "status.md"), statusContent);
657
+ writeFileSync4(join5(specDir, "spec.md"), specContent);
658
+ writeFileSync4(join5(specDir, "acceptance.md"), acceptanceContent);
659
+ }
291
660
  spinner.succeed(
292
- chalk3.green(`Spec "${name}" created at .letra/specs/${name}/`)
661
+ chalk5.green(`Spec "${name}" created at .letra/specs/${name}/`)
293
662
  );
294
663
  } catch (error) {
295
- spinner.fail(chalk3.red("Failed to create spec"));
664
+ spinner.fail(chalk5.red("Failed to create spec"));
296
665
  process.exit(1);
297
666
  }
298
667
  }
@@ -300,57 +669,144 @@ Por que estamos construindo isso. Trade-offs considerados.
300
669
  // src/commands/validate.ts
301
670
  import { execSync } from "child_process";
302
671
  import {
303
- existsSync as existsSync4,
672
+ existsSync as existsSync7,
304
673
  mkdtempSync,
305
- readFileSync as readFileSync2,
306
- readdirSync as readdirSync3,
674
+ readFileSync as readFileSync6,
675
+ readdirSync as readdirSync5,
307
676
  rmSync,
308
- statSync as statSync2
677
+ statSync as statSync2,
678
+ watch
309
679
  } from "fs";
310
680
  import { tmpdir } from "os";
311
- import { join as join4, resolve as resolve4 } from "path";
312
- import chalk4 from "chalk";
313
- var colloquialisms = [
314
- "tipo",
315
- "t\xE1",
316
- "pra",
317
- "blz",
318
- "kkk",
319
- "eita",
320
- "oi",
321
- "oi pessoal"
681
+ import { join as join7, resolve as resolve6 } from "path";
682
+ import chalk6 from "chalk";
683
+
684
+ // src/config.ts
685
+ import { existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
686
+ import { join as join6 } from "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 = join6(root, ".letra", "config.json");
702
+ const heuristics = {};
703
+ for (const [key, value] of Object.entries(DEFAULT_HEURISTICS)) {
704
+ heuristics[key] = { ...value };
705
+ }
706
+ if (existsSync6(configPath)) {
707
+ try {
708
+ const raw = JSON.parse(readFileSync5(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"
322
775
  ];
323
- function checkSpecContent(specDir, label, description) {
324
- const specFile = join4(specDir, "spec.md");
325
- const glossaryFile = join4(specDir, "..", "..", "glossary.md");
326
- if (!existsSync4(specFile))
776
+ 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))
327
781
  return { status: "FAIL", note: "(spec.md not found)" };
328
- const specContent = readFileSync2(specFile, "utf-8");
782
+ const specContent = readFileSync6(specFile, "utf-8");
329
783
  const now = /* @__PURE__ */ new Date();
330
784
  if (label.includes("Conte\xFAdo M\xEDnimo")) {
331
785
  const outcomeMatch = specContent.match(/## Outcome\s+([\s\S]*?)(?=\n## )/);
332
786
  if (!outcomeMatch)
333
787
  return { status: "FAIL", note: "(no Outcome section)" };
334
788
  const outcomeContent = outcomeMatch[1].trim();
335
- if (outcomeContent.length >= 50) {
789
+ const heurConfig = getHeuristicConfig(cfg, label);
790
+ const minChars = heurConfig.minChars ?? 50;
791
+ if (outcomeContent.length >= minChars) {
336
792
  return {
337
793
  status: "PASS",
338
- note: `(${outcomeContent.length} chars)`
794
+ note: `(${outcomeContent.length} chars, need ${minChars})`
339
795
  };
340
796
  }
341
797
  return {
342
798
  status: "FAIL",
343
- note: `(only ${outcomeContent.length} chars, need 50+)`
799
+ note: `(only ${outcomeContent.length} chars, need ${minChars}+)`
344
800
  };
345
801
  }
346
802
  if (label.includes("Consist\xEAncia de Terminologia") || label.includes("Terminologia")) {
347
- if (!existsSync4(glossaryFile)) {
803
+ if (!existsSync7(glossaryFile)) {
348
804
  return {
349
805
  status: "PASS",
350
806
  note: "(no glossary to check against)"
351
807
  };
352
808
  }
353
- const glossaryContent = readFileSync2(glossaryFile, "utf-8");
809
+ const glossaryContent = readFileSync6(glossaryFile, "utf-8");
354
810
  const terms = glossaryContent.match(/\*\*(.+?)\*\*/g) || [];
355
811
  const extractedTerms = terms.map((t) => t.replace(/\*\*/g, "").trim()).filter((t) => t.length > 3);
356
812
  const missingTerms = extractedTerms.filter(
@@ -367,7 +823,18 @@ function checkSpecContent(specDir, label, description) {
367
823
  if (label.includes("Detec\xE7\xE3o de Tom") || label.includes("Tom")) {
368
824
  const lowerSpec = specContent.toLowerCase();
369
825
  const words = lowerSpec.split(/\s+/);
370
- const foundColloquialisms = colloquialisms.filter((c) => words.includes(c));
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));
371
838
  if (foundColloquialisms.length === 0) {
372
839
  return { status: "PASS", note: "(formal tone maintained)" };
373
840
  }
@@ -381,197 +848,730 @@ function checkSpecContent(specDir, label, description) {
381
848
  const daysOld = Math.floor(
382
849
  (now.getTime() - stat.mtimeMs) / (1e3 * 60 * 60 * 24)
383
850
  );
384
- if (daysOld < 30) {
851
+ const heurConfig = getHeuristicConfig(cfg, label);
852
+ const maxDays = heurConfig.maxDays ?? 30;
853
+ if (daysOld < maxDays) {
385
854
  return { status: "PASS", note: `(${daysOld} days old)` };
386
855
  }
387
856
  return {
388
857
  status: "FAIL",
389
- note: `(${daysOld} days old, stale >30d)`
858
+ note: `(${daysOld} days old, stale >${maxDays}d)`
390
859
  };
391
860
  }
392
861
  return null;
393
862
  }
394
- async function validate(targetPath) {
395
- const root = resolve4(process.cwd(), targetPath || ".");
396
- const specsDir = join4(root, ".letra", "specs");
397
- if (!existsSync4(specsDir)) {
398
- console.log(
399
- chalk4.red("Error: .letra/specs/ not found. Run 'letra init' first.")
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)
400
921
  );
401
- process.exit(1);
922
+ if (!hasMetric && hasVagueVerb) {
923
+ const labelMatch = line.match(/\*\*(.+?)\*\*/);
924
+ if (labelMatch) nonBinary.push(labelMatch[1]);
925
+ }
402
926
  }
403
- console.log(chalk4.bold("\nLetra Validation\n"));
404
- const entries = readdirSync3(specsDir, { withFileTypes: true });
405
- let totalPass = 0;
406
- let totalFail = 0;
407
- const entryPoint = join4(root, "src/index.ts");
408
- const opts = {
409
- stdio: "pipe",
410
- encoding: "utf-8",
411
- shell: process.platform === "win32" ? "cmd.exe" : true
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(", ")})`
412
936
  };
413
- const ciFile = join4(root, ".github", "workflows", "ci.yml");
414
- const cursorRulesFile = join4(root, ".cursorrules");
415
- const copilotFile = join4(root, ".github", "copilot-instructions.md");
416
- const vscodeSettingsFile = join4(root, ".vscode", "settings.json");
417
- for (const entry of entries) {
418
- if (!entry.isDirectory() || entry.name.startsWith("_")) continue;
419
- const acceptanceFile = join4(specsDir, entry.name, "acceptance.md");
420
- const specFile = join4(specsDir, entry.name, "spec.md");
421
- let content;
422
- if (existsSync4(acceptanceFile)) {
423
- content = readFileSync2(acceptanceFile, "utf-8");
424
- } else if (existsSync4(specFile)) {
425
- content = readFileSync2(specFile, "utf-8");
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 = readdirSync5(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 = join7(specsDir, dir, "acceptance.md");
1041
+ if (!existsSync7(acceptanceFile)) continue;
1042
+ const content = readFileSync6(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}`);
426
1084
  } else {
427
- console.log(
428
- chalk4.gray(
429
- ` Spec "${entry.name}" \u2014 no acceptance.md or spec.md found`
430
- )
431
- );
432
- continue;
1085
+ console.log(`${label}: ${message} ${note}`);
433
1086
  }
434
- const criteriaLines = content.match(/- \[ \] \*\*(.+?)\*\*: (.+)/g) || [];
435
- console.log(chalk4.bold(` Spec: ${entry.name}`));
436
- if (criteriaLines.length === 0) {
437
- console.log(chalk4.gray(" No criteria found"));
438
- continue;
1087
+ return;
1088
+ }
1089
+ if (format === "junit") {
1090
+ return;
1091
+ }
1092
+ const icon = level === "pass" ? chalk6.green("\u2713") : level === "fail" ? chalk6.red("\u2717") : level === "warning" ? chalk6.yellow("\u26A0") : "";
1093
+ if (level === "info") {
1094
+ console.log(` ${message}`);
1095
+ } else {
1096
+ console.log(
1097
+ ` [${icon}] ${chalk6.cyan(label)}: ${message} ${chalk6.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 });
439
1122
  }
440
- for (const line of criteriaLines) {
441
- const match = line.match(/- \[ \] \*\*(.+?)\*\*: (.+)/);
442
- if (match) {
443
- const [, label, description] = match;
444
- let status = "FAIL";
445
- let note = "";
446
- try {
447
- const intelligenceResult = checkSpecContent(
448
- join4(specsDir, entry.name),
449
- label,
450
- description
451
- );
452
- if (intelligenceResult) {
453
- status = intelligenceResult.status;
454
- note = intelligenceResult.note;
455
- } else if (label.includes("letra init")) {
456
- const tmp = mkdtempSync(join4(tmpdir(), "letra-test-"));
457
- execSync(`npx tsx "${entryPoint}" init "${tmp}"`, { ...opts });
458
- if (existsSync4(join4(tmp, ".letra", "context.md"))) status = "PASS";
459
- rmSync(tmp, { recursive: true });
460
- } else if (label.includes("letra spec")) {
461
- const tmp = mkdtempSync(join4(tmpdir(), "letra-test-"));
462
- execSync(`npx tsx "${entryPoint}" init "${tmp}"`, { ...opts });
463
- execSync(`npx tsx "${entryPoint}" spec smoke-test`, {
464
- ...opts,
465
- cwd: tmp
466
- });
467
- if (existsSync4(join4(tmp, ".letra", "specs", "smoke-test", "spec.md")))
468
- status = "PASS";
469
- rmSync(tmp, { recursive: true });
470
- } else if (label.includes("letra lint")) {
471
- execSync(`npx tsx "${entryPoint}" lint`, { ...opts });
472
- status = "PASS";
473
- } else if (label.includes("letra validate")) {
474
- status = "PASS";
475
- } else if (label.includes("Workflow Ativo") || label.includes("CI") && existsSync4(ciFile)) {
476
- status = "PASS";
477
- } else if (label.includes("Lint Gate") || label.includes("Lint")) {
478
- const ciContent = readFileSync2(ciFile, "utf-8");
479
- if (ciContent.includes("letra lint") || ciContent.includes("lint"))
480
- status = "PASS";
481
- } else if (label.includes("Test Gate") || label.includes("Test")) {
482
- const ciContent = readFileSync2(ciFile, "utf-8");
483
- if (ciContent.includes("npm test") || ciContent.includes("vitest") || ciContent.includes("test"))
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
+ chalk6.gray(
1140
+ `
1141
+ Results: ${totalPass} passed, ${totalFail} failed${totalWarning > 0 ? `, ${totalWarning} warnings` : ""}`
1142
+ )
1143
+ );
1144
+ }
1145
+ async function validate(targetPath, options) {
1146
+ const root = resolve6(process.cwd(), targetPath || ".");
1147
+ const specsDir = join7(root, ".letra", "specs");
1148
+ const fmt = options?.format || "text";
1149
+ if (!existsSync7(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(chalk6.red(msg));
1155
+ }
1156
+ process.exit(1);
1157
+ }
1158
+ async function runValidation() {
1159
+ const config = loadConfig(root);
1160
+ const entries = readdirSync5(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 = join7(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 = 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");
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 = join7(specsDir, entry.name, "acceptance.md");
1182
+ const specFile = join7(specsDir, entry.name, "spec.md");
1183
+ let content;
1184
+ if (existsSync7(acceptanceFile)) {
1185
+ content = readFileSync6(acceptanceFile, "utf-8");
1186
+ } else if (existsSync7(specFile)) {
1187
+ content = readFileSync6(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 = existsSync7(specFile) ? readFileSync6(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
+ join7(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 = mkdtempSync(join7(tmpdir(), "letra-test-"));
1227
+ execSync(`npx tsx "${entryPoint}" init "${tmp}"`, { ...opts });
1228
+ if (existsSync7(join7(tmp, ".letra", "context.md")))
1229
+ status = "PASS";
1230
+ rmSync(tmp, { recursive: true });
1231
+ } else if (label.includes("letra spec")) {
1232
+ const tmp = mkdtempSync(join7(tmpdir(), "letra-test-"));
1233
+ execSync(`npx tsx "${entryPoint}" init "${tmp}"`, { ...opts });
1234
+ execSync(`npx tsx "${entryPoint}" spec smoke-test`, {
1235
+ ...opts,
1236
+ cwd: tmp
1237
+ });
1238
+ if (existsSync7(
1239
+ join7(tmp, ".letra", "specs", "smoke-test", "spec.md")
1240
+ ))
1241
+ status = "PASS";
1242
+ rmSync(tmp, { recursive: true });
1243
+ } else if (label.includes("letra lint")) {
1244
+ execSync(`npx tsx "${entryPoint}" lint`, { ...opts });
484
1245
  status = "PASS";
485
- } else if (label.includes("Valida\xE7\xE3o de Formato") || label.includes("Formato")) {
486
- const ciContent = readFileSync2(ciFile, "utf-8");
487
- if (ciContent.includes("tsc") || ciContent.includes("typecheck"))
1246
+ } else if (label.includes("letra validate")) {
488
1247
  status = "PASS";
489
- } else if (label.includes("Distribui\xE7\xE3o npm") || label.includes("npm")) {
490
- const pkgJson = JSON.parse(
491
- readFileSync2(join4(root, "package.json"), "utf-8")
492
- );
493
- if (pkgJson.bin && pkgJson.name) {
1248
+ } else if (label.includes("Workflow Ativo") || label.includes("CI") && existsSync7(ciFile)) {
494
1249
  status = "PASS";
495
- note = `(${pkgJson.name} @ ${pkgJson.version})`;
496
- } else {
497
- note = "(bin field missing)";
498
- }
499
- } else if (label.includes("Bin\xE1rio standalone") || label.includes("Bin\xE1rio")) {
500
- status = "PASS";
501
- note = "(npm distribution preferred)";
502
- } else if (label.includes("Gera\xE7\xE3o de Regras") || label.includes("Gera\xE7\xE3o")) {
503
- if (existsSync4(cursorRulesFile)) {
504
- const rulesContent = readFileSync2(cursorRulesFile, "utf-8");
505
- if (rulesContent.includes(".letra/context.md") && rulesContent.includes(".letra/constitution.md")) {
1250
+ } else if (label.includes("Lint Gate") || label.includes("Lint")) {
1251
+ const ciContent = readFileSync6(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 = readFileSync6(ciFile, "utf-8");
1256
+ if (ciContent.includes("npm test") || ciContent.includes("vitest") || ciContent.includes("test"))
506
1257
  status = "PASS";
1258
+ } else if (label.includes("Valida\xE7\xE3o de Formato") || label.includes("Formato")) {
1259
+ const ciContent = readFileSync6(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
+ readFileSync6(join7(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)";
507
1271
  }
508
- }
509
- } else if (label.includes("Inje\xE7\xE3o de Contexto")) {
510
- if (existsSync4(cursorRulesFile)) {
511
- const rulesContent = readFileSync2(cursorRulesFile, "utf-8");
512
- if (rulesContent.includes("@.letra/")) status = "PASS";
513
- } else if (existsSync4(copilotFile)) {
514
- const copilotContent = readFileSync2(copilotFile, "utf-8");
515
- if (copilotContent.includes(".letra/")) status = "PASS";
516
- }
517
- } else if (label.includes("Acesso a Valida\xE7\xE3o")) {
518
- if (existsSync4(cursorRulesFile)) {
519
- const rulesContent = readFileSync2(cursorRulesFile, "utf-8");
520
- if (rulesContent.includes("letra validate")) status = "PASS";
521
- }
522
- } else if (label.includes("N\xE3o-intrusivo")) {
523
- if (existsSync4(cursorRulesFile) || existsSync4(copilotFile)) {
1272
+ } else if (label.includes("Bin\xE1rio standalone") || label.includes("Bin\xE1rio")) {
524
1273
  status = "PASS";
525
- }
526
- } else if (label.includes("Gera\xE7\xE3o de Instru\xE7\xF5es")) {
527
- if (existsSync4(copilotFile)) {
528
- const copilotContent = readFileSync2(copilotFile, "utf-8");
529
- if (copilotContent.includes(".letra/context.md") && copilotContent.includes(".letra/constitution.md")) {
530
- status = "PASS";
1274
+ note = "(npm distribution preferred)";
1275
+ } 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");
1278
+ if (rulesContent.includes(".letra/context.md") && rulesContent.includes(".letra/constitution.md")) {
1279
+ status = "PASS";
1280
+ }
531
1281
  }
532
- }
533
- } else if (label.includes("Settings do Editor")) {
534
- if (existsSync4(vscodeSettingsFile)) {
535
- const settingsContent = readFileSync2(vscodeSettingsFile, "utf-8");
536
- if (settingsContent.includes("editor.formatOnSave")) {
1282
+ } else if (label.includes("Inje\xE7\xE3o de Contexto")) {
1283
+ if (existsSync7(cursorRulesFile)) {
1284
+ const rulesContent = readFileSync6(cursorRulesFile, "utf-8");
1285
+ if (rulesContent.includes("@.letra/")) status = "PASS";
1286
+ } else if (existsSync7(copilotFile)) {
1287
+ const copilotContent = readFileSync6(copilotFile, "utf-8");
1288
+ if (copilotContent.includes(".letra/")) status = "PASS";
1289
+ }
1290
+ } else if (label.includes("Acesso a Valida\xE7\xE3o")) {
1291
+ if (existsSync7(cursorRulesFile)) {
1292
+ const rulesContent = readFileSync6(cursorRulesFile, "utf-8");
1293
+ if (rulesContent.includes("letra validate")) status = "PASS";
1294
+ }
1295
+ } else if (label.includes("N\xE3o-intrusivo")) {
1296
+ if (existsSync7(cursorRulesFile) || existsSync7(copilotFile)) {
537
1297
  status = "PASS";
538
1298
  }
1299
+ } else if (label.includes("Gera\xE7\xE3o de Instru\xE7\xF5es")) {
1300
+ if (existsSync7(copilotFile)) {
1301
+ const copilotContent = readFileSync6(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 (existsSync7(vscodeSettingsFile)) {
1308
+ const settingsContent = readFileSync6(
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 = join7(root, ".letra", "config.json");
1318
+ if (existsSync7(configFile)) {
1319
+ const cfgContent = readFileSync6(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)";
539
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++;
540
1392
  } else {
541
- note = "(manual check needed)";
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
+ }
542
1492
  }
543
- } catch (error) {
544
- status = "FAIL";
545
- const err = error;
546
- note = `(error: ${err.message?.split("\n")[0] || "unknown"})`;
547
1493
  }
548
- if (status === "PASS") {
549
- console.log(
550
- ` [${chalk4.green("\u2713")}] ${chalk4.cyan(label)}: ${description} ${chalk4.gray(note)}`
551
- );
552
- totalPass++;
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++;
553
1517
  } else {
554
- console.log(
555
- ` [${chalk4.red("\u2717")}] ${chalk4.cyan(label)}: ${description} ${chalk4.gray(note)}`
556
- );
557
1518
  totalFail++;
558
1519
  }
559
1520
  }
560
1521
  }
561
- console.log("");
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(chalk6.gray("\nWatching for changes... (Ctrl+C to stop)"));
1541
+ const watcher = 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(chalk6.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);
562
1562
  }
563
- console.log(
564
- chalk4.gray(`
565
- Results: ${totalPass} passed, ${totalFail} failed`)
566
- );
567
- process.exit(totalFail > 0 ? 1 : 0);
568
1563
  }
569
1564
 
570
1565
  // src/index.ts
571
- var program = new Command();
1566
+ var program = new Command3();
572
1567
  program.name("letra").description("SDD-agnostic memory framework for AI coding agents").version("0.0.1");
573
- program.command("init [path]").description("Initialize .letra/ directory with templates").action(init);
574
- program.command("spec <name>").description("Create a new spec from template").action(specNew);
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 }));
575
1573
  program.command("lint [path]").description("Validate spec format and completeness").action(lint);
576
- program.command("validate [path]").description("Check if artifacts meet acceptance criteria").action(validate);
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());
577
1577
  program.parse();