@letra-ai/cli 0.6.1 → 0.7.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 (55) hide show
  1. package/dist/chunk-2GRNAFBQ.js +5305 -0
  2. package/dist/{chunk-MJ2QXNH6.js → chunk-42RST74I.js} +1 -1
  3. package/dist/chunk-HC24XMPZ.js +269 -0
  4. package/dist/chunk-LUPN3TRC.js +554 -0
  5. package/dist/{chunk-KGQLHMGZ.js → chunk-MUCIMQAU.js} +1918 -757
  6. package/dist/chunk-POGWTSEA.js +125 -0
  7. package/dist/chunk-TNF7XTFG.js +6178 -0
  8. package/dist/{chunk-BKAUN5QH.js → chunk-UMC5PDL2.js} +227 -33
  9. package/dist/{chunk-6HSUVCTR.js → chunk-YAQ2TKSK.js} +82 -30
  10. package/dist/client/assets/index-C-6kWNFi.js +232 -0
  11. package/dist/client/assets/index-QV-zN0V8.css +1 -0
  12. package/dist/client/index.html +2 -2
  13. package/dist/fallback-CXCCKHBA.js +56 -0
  14. package/dist/flow-serve-LFILD3EV.js +19 -0
  15. package/dist/{generate-N22QOXUF.js → generate-3R7POT7L.js} +4 -5
  16. package/dist/harness/default/v0.1.0/gates/all-acs-passing.yaml +1 -0
  17. package/dist/harness/default/v0.1.0/gates/has-spec-file.yaml +1 -0
  18. package/dist/harness/default/v0.1.1/gates/all-acs-passing.yaml +1 -0
  19. package/dist/harness/default/v0.1.1/gates/has-spec-file.yaml +1 -0
  20. package/dist/harness/default/v0.1.2/gates/all-acs-passing.yaml +1 -0
  21. package/dist/harness/default/v0.1.2/gates/has-spec-file.yaml +1 -0
  22. package/dist/harness/default/v0.1.3/gates/all-acs-passing.yaml +1 -0
  23. package/dist/harness/default/v0.1.3/gates/has-spec-file.yaml +1 -0
  24. package/dist/harness/default/v0.2.0/executors/registry.yaml +17 -0
  25. package/dist/harness/default/v0.2.0/flows/flow-main.yaml +84 -4
  26. package/dist/harness/default/v0.2.0/gates/code-reviewed.yaml +1 -0
  27. package/dist/harness/default/v0.2.0/gates/human-approved.yaml +4 -3
  28. package/dist/harness/default/v0.2.0/gates/security-clear.yaml +1 -0
  29. package/dist/harness/default/v0.2.0/gates/spec-approved.yaml +3 -3
  30. package/dist/{health-record-YDVXEVLR.js → health-record-JO2ZTIMR.js} +2 -2
  31. package/dist/index.js +2237 -1104
  32. package/dist/{push-5JEYSXBY.js → push-2ZCQSOHF.js} +37 -49
  33. package/dist/server-WUYVNSH7.js +677 -0
  34. package/dist/service-SVEAXQBX.js +28 -0
  35. package/dist/service-TOBY3OHO.js +22 -0
  36. package/dist/service-USTAY5E3.js +62 -0
  37. package/dist/{session-log-WTQ5JBEN.js → session-log-X2Q4XKQN.js} +6 -2
  38. package/dist/specs-CQRB7LPA.js +21 -0
  39. package/dist/sync-LIVPQXEW.js +21 -0
  40. package/package.json +1 -1
  41. package/dist/chunk-4QDEU6KP.js +0 -2765
  42. package/dist/chunk-BTPFUKHG.js +0 -275
  43. package/dist/chunk-EDD55PWL.js +0 -119
  44. package/dist/chunk-ELBTIPYN.js +0 -256
  45. package/dist/chunk-IEFSLCJL.js +0 -837
  46. package/dist/chunk-MSF44WWE.js +0 -443
  47. package/dist/chunk-QIVKP3EY.js +0 -362
  48. package/dist/client/assets/index-BuABgOyz.js +0 -232
  49. package/dist/client/assets/index-CpseCZh9.css +0 -1
  50. package/dist/fallback-UXSZ4LNR.js +0 -47
  51. package/dist/flow-serve-MTB6KZMR.js +0 -19
  52. package/dist/focus-sync-3D3XWCTI.js +0 -17
  53. package/dist/server-FUP3APZA.js +0 -415
  54. package/dist/service-OGF7BMCQ.js +0 -21
  55. package/dist/sitrep-DJXTP3JO.js +0 -16
@@ -1,837 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- logEntry
4
- } from "./chunk-BKAUN5QH.js";
5
- import {
6
- getLetraDir2 as getLetraDir
7
- } from "./chunk-6HSUVCTR.js";
8
-
9
- // src/commands/validate.ts
10
- import { existsSync as existsSync3, readFileSync as readFileSync3, readdirSync as readdirSync2, watch } from "fs";
11
- import { join as join3, resolve, dirname } from "path";
12
- import chalk from "chalk";
13
-
14
- // src/config.ts
15
- import { existsSync, readFileSync } from "fs";
16
- import { join } from "path";
17
- var DEFAULT_HEURISTICS = {
18
- "conteudo-minimo": { severity: "warning", minChars: 50 },
19
- "consistencia-terminologia": { severity: "warning" },
20
- "detecao-tom": {
21
- severity: "warning",
22
- blacklist: ["tipo", "t\xE1", "pra", "blz", "kkk", "eita", "oi", "oi pessoal"]
23
- },
24
- "drift-temporal": { severity: "warning", maxDays: 30 },
25
- "secoes-vazias": { severity: "warning" },
26
- "acs-sem-metrica": { severity: "warning" },
27
- "baixa-confianca": { severity: "warning" },
28
- "validate-conflict": { severity: "warning" }
29
- };
30
- function loadConfig(root) {
31
- const configPath = join(getLetraDir(root), "config.json");
32
- const heuristics = {};
33
- for (const [key, value] of Object.entries(DEFAULT_HEURISTICS)) {
34
- heuristics[key] = { ...value };
35
- }
36
- if (existsSync(configPath)) {
37
- try {
38
- const raw = JSON.parse(readFileSync(configPath, "utf-8"));
39
- if (raw.heuristics && typeof raw.heuristics === "object") {
40
- for (const [key, value] of Object.entries(raw.heuristics)) {
41
- if (heuristics[key]) {
42
- heuristics[key] = {
43
- ...heuristics[key],
44
- ...value
45
- };
46
- } else {
47
- heuristics[key] = value;
48
- }
49
- }
50
- }
51
- } catch {
52
- }
53
- }
54
- return { heuristics };
55
- }
56
- function getHeuristicConfig(config, label) {
57
- const key = heuristicKey(label);
58
- return config.heuristics[key] ?? { severity: "warning" };
59
- }
60
- function normalize(str) {
61
- return str.normalize("NFD").replace(/\p{M}/gu, "");
62
- }
63
- function heuristicKey(label) {
64
- const lower = normalize(label.toLowerCase());
65
- if (lower.includes("conteudo minimo")) return "conteudo-minimo";
66
- if (lower.includes("terminologia")) return "consistencia-terminologia";
67
- if (lower.includes("tom")) return "detecao-tom";
68
- if (lower.includes("drift temporal")) return "drift-temporal";
69
- if (lower.includes("secoes vazias")) return "secoes-vazias";
70
- if (lower.includes("acs sem metrica")) return "acs-sem-metrica";
71
- if (lower.includes("baixa confianca")) return "baixa-confianca";
72
- if (lower.includes("validate conflict")) return "validate-conflict";
73
- return lower.replace(/\s+/g, "-");
74
- }
75
-
76
- // src/validation/content.ts
77
- import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync2, statSync } from "fs";
78
- import { join as join2 } from "path";
79
- var placeholderPatterns = [
80
- /o que o usu[áa]rio consegue fazer quando isso estiver pronto/i,
81
- /limitaç[õo]es t[ée]cnicas e de neg[óo]cio/i,
82
- /o que explicitamente n[ãa]o est[áa] neste escopo/i,
83
- /descriç[ãa]o bin[áa]ria/i,
84
- /por que estamos construindo isso/i
85
- ];
86
- var vagueVerbs = [
87
- "melhorar",
88
- "otimizar",
89
- "facilitar",
90
- "aumentar",
91
- "diminuir",
92
- "agilizar",
93
- "simplificar",
94
- "aprimorar"
95
- ];
96
- var lowConfidenceMarkers = [
97
- "provavelmente",
98
- "talvez",
99
- "tentar",
100
- "idealmente",
101
- "possivelmente",
102
- "quem sabe",
103
- "de repente",
104
- "teoricamente"
105
- ];
106
- function checkSpecContent(specDir, label, description, config) {
107
- const cfg = config ?? loadConfig(join2(specDir, "..", "..", ".."));
108
- const specFile = join2(specDir, "spec.md");
109
- const glossaryFile = join2(specDir, "..", "..", "glossary.md");
110
- if (!existsSync2(specFile)) return { status: "FAIL", note: "(spec.md not found)" };
111
- const specContent = readFileSync2(specFile, "utf-8");
112
- const now = /* @__PURE__ */ new Date();
113
- if (label.includes("Conte\xFAdo M\xEDnimo")) {
114
- const outcomeMatch = specContent.match(/## Outcome\s+([\s\S]*?)(?=\n## )/);
115
- if (!outcomeMatch) return { status: "FAIL", note: "(no Outcome section)" };
116
- const outcomeContent = outcomeMatch[1].trim();
117
- const heurConfig = getHeuristicConfig(cfg, label);
118
- const minChars = heurConfig.minChars ?? 50;
119
- if (outcomeContent.length >= minChars) {
120
- return {
121
- status: "PASS",
122
- note: `(${outcomeContent.length} chars, need ${minChars})`
123
- };
124
- }
125
- return {
126
- status: "FAIL",
127
- note: `(only ${outcomeContent.length} chars, need ${minChars}+)`
128
- };
129
- }
130
- if (label.includes("Consist\xEAncia de Terminologia") || label.includes("Terminologia")) {
131
- if (!existsSync2(glossaryFile)) {
132
- return {
133
- status: "PASS",
134
- note: "(no glossary to check against)"
135
- };
136
- }
137
- const glossaryContent = readFileSync2(glossaryFile, "utf-8");
138
- const terms = glossaryContent.match(/\*\*(.+?)\*\*/g) || [];
139
- const extractedTerms = terms.map((t) => t.replace(/\*\*/g, "").trim()).filter((t) => t.length > 3);
140
- const missingTerms = extractedTerms.filter(
141
- (term) => !specContent.toLowerCase().includes(term.toLowerCase())
142
- );
143
- if (missingTerms.length === 0) {
144
- return { status: "PASS", note: "(all glossary terms used)" };
145
- }
146
- return {
147
- status: "FAIL",
148
- note: `(missing: ${missingTerms.slice(0, 3).join(", ")})`
149
- };
150
- }
151
- if (label.includes("Detec\xE7\xE3o de Tom") || label.includes("Tom")) {
152
- const lowerSpec = specContent.toLowerCase();
153
- const words = lowerSpec.split(/\s+/);
154
- const heurConfig = getHeuristicConfig(cfg, label);
155
- const blacklist = heurConfig.blacklist ?? [
156
- "tipo",
157
- "t\xE1",
158
- "pra",
159
- "blz",
160
- "kkk",
161
- "eita",
162
- "oi",
163
- "oi pessoal"
164
- ];
165
- const foundColloquialisms = blacklist.filter((c) => words.includes(c));
166
- if (foundColloquialisms.length === 0) {
167
- return { status: "PASS", note: "(formal tone maintained)" };
168
- }
169
- return {
170
- status: "FAIL",
171
- note: `(colloquialisms: ${foundColloquialisms.join(", ")})`
172
- };
173
- }
174
- if (label.includes("Drift Temporal") || label.includes("Temporal")) {
175
- const stat = statSync(specFile);
176
- const daysOld = Math.floor((now.getTime() - stat.mtimeMs) / (1e3 * 60 * 60 * 24));
177
- const heurConfig = getHeuristicConfig(cfg, label);
178
- const maxDays = heurConfig.maxDays ?? 30;
179
- if (daysOld < maxDays) {
180
- return { status: "PASS", note: `(${daysOld} days old)` };
181
- }
182
- return {
183
- status: "FAIL",
184
- note: `(${daysOld} days old, stale >${maxDays}d)`
185
- };
186
- }
187
- return null;
188
- }
189
- function checkEmptySections(specContent) {
190
- const requiredSections = [
191
- "## Outcome",
192
- "## Constraints",
193
- "## Exclusions",
194
- "## Acceptance Criteria",
195
- "## Context"
196
- ];
197
- const emptyOrPlaceholder = [];
198
- for (const section of requiredSections) {
199
- const escaped = section.replace(/[#]/g, "\\$&");
200
- const pattern = new RegExp(`${escaped}\\s+([\\s\\S]*?)(?=\\n## |\\n*$)`);
201
- const match = specContent.match(pattern);
202
- if (!match) {
203
- emptyOrPlaceholder.push(section.replace("## ", ""));
204
- continue;
205
- }
206
- const content = match[1].trim();
207
- if (content.length < 10) {
208
- emptyOrPlaceholder.push(section.replace("## ", ""));
209
- continue;
210
- }
211
- const hasPlaceholder = placeholderPatterns.some((p) => p.test(content));
212
- if (hasPlaceholder) {
213
- emptyOrPlaceholder.push(section.replace("## ", ""));
214
- }
215
- }
216
- if (emptyOrPlaceholder.length === 0) {
217
- return {
218
- status: "PASS",
219
- note: "(all sections have real content)"
220
- };
221
- }
222
- return {
223
- status: "FAIL",
224
- note: `(empty/placeholder: ${emptyOrPlaceholder.join(", ")})`
225
- };
226
- }
227
- function checkBinaryCriteria(specContent) {
228
- const acMatch = specContent.match(/## Acceptance Criteria\s+([\s\S]*?)(?=\n## |\n*$)/);
229
- if (!acMatch) {
230
- return {
231
- status: "FAIL",
232
- note: "(no Acceptance Criteria section)"
233
- };
234
- }
235
- const criteriaLines = acMatch[1].match(/- \[[ x]\] .+/g) || [];
236
- if (criteriaLines.length === 0) {
237
- return { status: "FAIL", note: "(no criteria items found)" };
238
- }
239
- const nonBinary = [];
240
- for (const line of criteriaLines) {
241
- const description = line.replace(/- \[[ x]\] \*\*.+?\*\*:\s*/, "");
242
- const hasMetric = /\d+/.test(description);
243
- const hasVagueVerb = vagueVerbs.some((v) => description.toLowerCase().includes(v));
244
- if (!hasMetric && hasVagueVerb) {
245
- const labelMatch = line.match(/\*\*(.+?)\*\*/);
246
- if (labelMatch) nonBinary.push(labelMatch[1]);
247
- }
248
- }
249
- if (nonBinary.length === 0) {
250
- return {
251
- status: "PASS",
252
- note: "(all criteria have measurable outcomes)"
253
- };
254
- }
255
- return {
256
- status: "FAIL",
257
- note: `(vague criteria: ${nonBinary.join(", ")})`
258
- };
259
- }
260
- function checkLowConfidence(specContent) {
261
- const lower = specContent.toLowerCase();
262
- const words = lower.split(/\s+/);
263
- const found = lowConfidenceMarkers.filter((m) => {
264
- if (m.includes(" ")) {
265
- return lower.includes(m);
266
- }
267
- return words.includes(m);
268
- });
269
- if (found.length === 0) {
270
- return {
271
- status: "PASS",
272
- note: "(no low-confidence language detected)"
273
- };
274
- }
275
- return {
276
- status: "FAIL",
277
- note: `(low-confidence: ${found.join(", ")})`
278
- };
279
- }
280
- var commonWords = [
281
- "para",
282
- "com",
283
- "que",
284
- "dos",
285
- "das",
286
- "uma",
287
- "como",
288
- "mais",
289
- "mas",
290
- "por",
291
- "pode",
292
- "ser",
293
- "s\xE3o",
294
- "tem",
295
- "seu",
296
- "sua",
297
- "esta",
298
- "este",
299
- "isso",
300
- "the",
301
- "and",
302
- "for",
303
- "with",
304
- "that",
305
- "this",
306
- "from",
307
- "are",
308
- "was"
309
- ];
310
- function getSignificantWords(text) {
311
- return text.toLowerCase().split(/\s+/).filter((w) => w.length >= 4 && !commonWords.includes(w));
312
- }
313
- function getPrefix(name) {
314
- const idx = name.indexOf("-");
315
- return idx === -1 ? name : name.slice(0, idx);
316
- }
317
- function isSibling(nameA, nameB) {
318
- return getPrefix(nameA) === getPrefix(nameB);
319
- }
320
- function detectConflict(textA, textB) {
321
- const lowerA = textA.toLowerCase();
322
- const lowerB = textB.toLowerCase();
323
- const aHasNeg = /\bn[ãa]o\b/.test(lowerA) || /\bnot\b/.test(lowerA);
324
- const bHasNeg = /\bn[ãa]o\b/.test(lowerB) || /\bnot\b/.test(lowerB);
325
- if (aHasNeg !== bHasNeg) {
326
- const wordsA = getSignificantWords(lowerA);
327
- const wordsB = getSignificantWords(lowerB);
328
- const intersection = wordsA.filter((w) => wordsB.includes(w));
329
- const maxLen = Math.max(wordsA.length, wordsB.length);
330
- if (maxLen > 0 && intersection.length / maxLen > 0.6) return true;
331
- }
332
- const apenasA = lowerA.match(/(?:apenas|only)\s+(\w+)/);
333
- const apenasB = lowerB.match(/(?:apenas|only)\s+(\w+)/);
334
- if (apenasA && !apenasB) {
335
- const termA = apenasA[1];
336
- const wordsA = getSignificantWords(lowerA);
337
- const wordsB = getSignificantWords(lowerB);
338
- const shared = wordsA.filter((w) => w !== termA && wordsB.includes(w));
339
- if (shared.length > 0 && !wordsB.includes(termA)) return true;
340
- }
341
- if (apenasB && !apenasA) {
342
- const termB = apenasB[1];
343
- const wordsA = getSignificantWords(lowerA);
344
- const wordsB = getSignificantWords(lowerB);
345
- const shared = wordsB.filter((w) => w !== termB && wordsA.includes(w));
346
- if (shared.length > 0 && !wordsA.includes(termB)) return true;
347
- }
348
- if (apenasA && apenasB && apenasA[1] !== apenasB[1]) {
349
- const wordsA = getSignificantWords(lowerA);
350
- const wordsB = getSignificantWords(lowerB);
351
- const shared = wordsA.filter((w) => wordsB.includes(w));
352
- if (shared.length > 0) return true;
353
- }
354
- return false;
355
- }
356
- function checkConflicts(specsDir, config) {
357
- const results = [];
358
- const conflictGroups = /* @__PURE__ */ new Map();
359
- const entries = readdirSync(specsDir, { withFileTypes: true });
360
- const specDirs = entries.filter((e) => e.isDirectory() && !e.name.startsWith("_")).map((e) => e.name);
361
- const specs = [];
362
- for (const dir of specDirs) {
363
- const acceptanceFile = join2(specsDir, dir, "acceptance.md");
364
- if (!existsSync2(acceptanceFile)) continue;
365
- const content = readFileSync2(acceptanceFile, "utf-8");
366
- const acLines = content.match(/- \[[ x]\] \*\*(.+?)\*\*: (.+)/g) || [];
367
- const acs = acLines.map((line) => {
368
- const m = line.match(/- \[[ x]\] \*\*(.+?)\*\*: (.+)/);
369
- return m ? m[2].trim() : "";
370
- }).filter(Boolean);
371
- if (acs.length > 0) specs.push({ name: dir, acs });
372
- }
373
- for (let i = 0; i < specs.length; i++) {
374
- for (let j = i + 1; j < specs.length; j++) {
375
- const a = specs[i];
376
- const b = specs[j];
377
- if (isSibling(a.name, b.name)) continue;
378
- for (const acA of a.acs) {
379
- for (const acB of b.acs) {
380
- if (detectConflict(acA, acB)) {
381
- const key = `${a.name}\0${b.name}`;
382
- const group = conflictGroups.get(key) ?? {
383
- specA: a.name,
384
- specB: b.name,
385
- criteriaA: /* @__PURE__ */ new Set(),
386
- criteriaB: /* @__PURE__ */ new Set(),
387
- occurrences: 0
388
- };
389
- group.criteriaA.add(acA);
390
- group.criteriaB.add(acB);
391
- group.occurrences++;
392
- conflictGroups.set(key, group);
393
- }
394
- }
395
- }
396
- }
397
- }
398
- for (const group of conflictGroups.values()) {
399
- const occurrenceLabel = group.occurrences === 1 ? "ocorr\xEAncia" : "ocorr\xEAncias";
400
- const criteriaA = [...group.criteriaA].map((criterion) => `"${criterion}"`).join("; ");
401
- const criteriaB = [...group.criteriaB].map((criterion) => `"${criterion}"`).join("; ");
402
- results.push({
403
- label: "Validate Conflict",
404
- passed: false,
405
- message: `Conflito: ${group.occurrences} ${occurrenceLabel} entre "${group.specA}" e "${group.specB}". ACs de "${group.specA}": ${criteriaA}. ACs de "${group.specB}": ${criteriaB}.`
406
- });
407
- }
408
- if (conflictGroups.size === 0) {
409
- results.push({
410
- label: "Validate Conflict",
411
- passed: true,
412
- message: "Nenhum conflito detectado entre specs"
413
- });
414
- }
415
- return results;
416
- }
417
-
418
- // src/commands/validate.ts
419
- function out(format, level, spec, label, message, note) {
420
- if (format === "silent") return;
421
- if (format === "github-annotation") {
422
- const file = spec ? `.letra/specs/${spec}/spec.md` : "";
423
- if (level === "fail") {
424
- console.log(`::error file=${file},title=${label}::${message} ${note}`);
425
- } else if (level === "warning") {
426
- console.log(`::warning file=${file},title=${label}::${message} ${note}`);
427
- } else {
428
- console.log(`${label}: ${message} ${note}`);
429
- }
430
- return;
431
- }
432
- if (format === "junit") {
433
- return;
434
- }
435
- const icon = level === "pass" ? chalk.green("\u2713") : level === "fail" ? chalk.red("\u2717") : level === "warning" ? chalk.yellow("\u26A0") : "";
436
- if (level === "info") {
437
- console.log(` ${message}`);
438
- } else {
439
- console.log(` [${icon}] ${chalk.cyan(label)}: ${message} ${chalk.gray(note)}`);
440
- }
441
- }
442
- function buildJunitXml(results) {
443
- let xml = `<?xml version="1.0" encoding="UTF-8"?>
444
- `;
445
- xml += `<testsuites name="letra-validate" tests="${results.pass + results.fail + results.warning}" failures="${results.fail}">
446
- `;
447
- for (const suite of results.suites) {
448
- xml += ` <testsuite name="${suite.name}" tests="${suite.pass + suite.fail + suite.warning}" failures="${suite.fail}">
449
- `;
450
- xml += " </testsuite>\n";
451
- }
452
- xml += "</testsuites>\n";
453
- return xml;
454
- }
455
- function collectResult(results, level, spec, label, message, note) {
456
- results.push({ level, spec, label, message, note });
457
- }
458
- function flushResults(results, format, specGroups, totalPass, totalFail, totalWarning) {
459
- if (format === "silent") return;
460
- if (format === "junit") {
461
- const suites = [];
462
- for (const [name, counts] of specGroups) {
463
- suites.push({ name, ...counts });
464
- }
465
- console.log(
466
- buildJunitXml({
467
- pass: totalPass,
468
- fail: totalFail,
469
- warning: totalWarning,
470
- suites
471
- })
472
- );
473
- return;
474
- }
475
- if (format === "github-annotation") {
476
- for (const r of results) {
477
- out(format, r.level, r.spec, r.label, r.message, r.note);
478
- }
479
- }
480
- console.log(
481
- chalk.gray(
482
- `
483
- Results: ${totalPass} passed, ${totalFail} failed${totalWarning > 0 ? `, ${totalWarning} warnings` : ""}`
484
- )
485
- );
486
- }
487
- async function validate(targetPath, options) {
488
- const root = resolve(process.cwd(), targetPath || ".");
489
- let specsDir = join3(getLetraDir(root), "specs");
490
- const fmt = options?.format || "text";
491
- if (!existsSync3(specsDir)) {
492
- let found = false;
493
- let search = root;
494
- const fsRoot = resolve("/").replace(/\\/g, "/");
495
- while (search && search !== fsRoot && search !== dirname(search)) {
496
- const candidate = join3(search, ".letra", "specs");
497
- if (existsSync3(candidate)) {
498
- specsDir = candidate;
499
- found = true;
500
- break;
501
- }
502
- search = dirname(search);
503
- }
504
- if (!found) {
505
- const msg = "Error: .letra/specs/ not found. Run 'letra init' first.";
506
- if (options?.exit === false) throw new Error(msg);
507
- if (fmt === "github-annotation") {
508
- console.log(`::error file=,title=Init Required::${msg}`);
509
- } else {
510
- console.log(chalk.red(msg));
511
- }
512
- process.exit(1);
513
- }
514
- }
515
- async function runValidation() {
516
- const config = loadConfig(root);
517
- const entries = readdirSync2(specsDir, { withFileTypes: true });
518
- let totalPass = 0;
519
- let totalFail = 0;
520
- let totalWarning = 0;
521
- const specGroups = /* @__PURE__ */ new Map();
522
- const allResults = [];
523
- const cursorRulesFile = join3(root, ".cursorrules");
524
- const copilotFile = join3(root, ".github", "copilot-instructions.md");
525
- const vscodeSettingsFile = join3(root, ".vscode", "settings.json");
526
- if (fmt !== "junit") {
527
- out(fmt, "info", null, "", "\nLetra Validation\n", "");
528
- }
529
- for (const entry of entries) {
530
- if (!entry.isDirectory() || entry.name.startsWith("_")) continue;
531
- const acceptanceFile = join3(specsDir, entry.name, "acceptance.md");
532
- const specFile = join3(specsDir, entry.name, "spec.md");
533
- let content;
534
- if (existsSync3(acceptanceFile)) {
535
- content = readFileSync3(acceptanceFile, "utf-8");
536
- } else if (existsSync3(specFile)) {
537
- content = readFileSync3(specFile, "utf-8");
538
- } else {
539
- out(
540
- fmt,
541
- "info",
542
- entry.name,
543
- "",
544
- `Spec "${entry.name}" \u2014 no acceptance.md or spec.md found`,
545
- ""
546
- );
547
- continue;
548
- }
549
- const criteriaLines = content.match(/- \[ \] \*\*(.+?)\*\*: (.+)/g) || [];
550
- const specContent = existsSync3(specFile) ? readFileSync3(specFile, "utf-8") : null;
551
- out(fmt, "info", entry.name, "", `Spec: ${entry.name}`, "");
552
- if (criteriaLines.length === 0) {
553
- out(fmt, "info", entry.name, "", "No criteria found", "");
554
- }
555
- let specPass = 0;
556
- let specFail = 0;
557
- let specWarning = 0;
558
- for (const line of criteriaLines) {
559
- const match = line.match(/- \[ \] \*\*(.+?)\*\*: (.+)/);
560
- if (match) {
561
- const [, label, description] = match;
562
- let status = "FAIL";
563
- let note = "";
564
- let intelligenceResult = null;
565
- try {
566
- intelligenceResult = checkSpecContent(
567
- join3(specsDir, entry.name),
568
- label,
569
- description,
570
- config
571
- );
572
- if (intelligenceResult) {
573
- status = intelligenceResult.status;
574
- note = intelligenceResult.note;
575
- } else if (label.includes("letra validate")) {
576
- status = "PASS";
577
- } else if (label.includes("Workflow Ativo")) {
578
- status = "PASS";
579
- } else if (label.includes("Gera\xE7\xE3o de Regras") || label.includes("Gera\xE7\xE3o")) {
580
- if (existsSync3(cursorRulesFile)) {
581
- const rulesContent = readFileSync3(cursorRulesFile, "utf-8");
582
- if (rulesContent.includes(".letra/context.md") && rulesContent.includes(".letra/constitution.md")) {
583
- status = "PASS";
584
- }
585
- }
586
- } else if (label.includes("Inje\xE7\xE3o de Contexto")) {
587
- if (existsSync3(cursorRulesFile)) {
588
- const rulesContent = readFileSync3(cursorRulesFile, "utf-8");
589
- if (rulesContent.includes("@.letra/")) status = "PASS";
590
- } else if (existsSync3(copilotFile)) {
591
- const copilotContent = readFileSync3(copilotFile, "utf-8");
592
- if (copilotContent.includes(".letra/")) status = "PASS";
593
- }
594
- } else if (label.includes("Acesso a Valida\xE7\xE3o")) {
595
- if (existsSync3(cursorRulesFile)) {
596
- const rulesContent = readFileSync3(cursorRulesFile, "utf-8");
597
- if (rulesContent.includes("letra validate")) status = "PASS";
598
- }
599
- } else if (label.includes("N\xE3o-intrusivo")) {
600
- if (existsSync3(cursorRulesFile) || existsSync3(copilotFile)) {
601
- status = "PASS";
602
- }
603
- } else if (label.includes("Gera\xE7\xE3o de Instru\xE7\xF5es")) {
604
- if (existsSync3(copilotFile)) {
605
- const copilotContent = readFileSync3(copilotFile, "utf-8");
606
- if (copilotContent.includes(".letra/context.md") && copilotContent.includes(".letra/constitution.md")) {
607
- status = "PASS";
608
- }
609
- }
610
- } else if (label.includes("Settings do Editor")) {
611
- if (existsSync3(vscodeSettingsFile)) {
612
- const settingsContent = readFileSync3(vscodeSettingsFile, "utf-8");
613
- if (settingsContent.includes("editor.formatOnSave")) {
614
- status = "PASS";
615
- }
616
- }
617
- } else if (label.includes("Arquivo de Config")) {
618
- const configFile = join3(getLetraDir(root), "config.json");
619
- if (existsSync3(configFile)) {
620
- const cfgContent = readFileSync3(configFile, "utf-8");
621
- try {
622
- const parsed = JSON.parse(cfgContent);
623
- if (parsed.heuristics) {
624
- status = "PASS";
625
- note = "(config.json found with heuristics)";
626
- } else {
627
- note = "(config.json missing heuristics key)";
628
- }
629
- } catch {
630
- note = "(config.json is invalid JSON)";
631
- }
632
- } else {
633
- note = "(no config.json found)";
634
- }
635
- } else if (label.includes("Backward Compatible")) {
636
- status = "PASS";
637
- note = "(all heuristics default to warning)";
638
- } else {
639
- note = "(manual check needed)";
640
- }
641
- } catch (error) {
642
- status = "FAIL";
643
- const err = error;
644
- note = `(error: ${err.message?.split("\n")[0] || "unknown"})`;
645
- }
646
- if (status === "PASS") {
647
- collectResult(allResults, "pass", entry.name, label, description, note);
648
- totalPass++;
649
- specPass++;
650
- } else if (intelligenceResult) {
651
- const heurCfg = getHeuristicConfig(config, label);
652
- if (heurCfg.severity === "warning") {
653
- collectResult(
654
- allResults,
655
- "warning",
656
- entry.name,
657
- label,
658
- description,
659
- note
660
- );
661
- totalWarning++;
662
- specWarning++;
663
- } else {
664
- collectResult(allResults, "fail", entry.name, label, description, note);
665
- totalFail++;
666
- specFail++;
667
- }
668
- } else if (note.includes("manual check needed")) {
669
- collectResult(allResults, "warning", entry.name, label, description, note);
670
- totalWarning++;
671
- specWarning++;
672
- } else {
673
- collectResult(allResults, "fail", entry.name, label, description, note);
674
- totalFail++;
675
- specFail++;
676
- }
677
- }
678
- }
679
- if (specContent) {
680
- const emptyCfg = getHeuristicConfig(config, "Se\xE7\xF5es Vazias");
681
- if (emptyCfg.severity !== "off") {
682
- const emptyResult = checkEmptySections(specContent);
683
- if (emptyResult.status === "FAIL") {
684
- if (emptyCfg.severity === "warning") {
685
- collectResult(
686
- allResults,
687
- "warning",
688
- entry.name,
689
- "Se\xE7\xF5es Vazias",
690
- "Se\xE7\xF5es obrigat\xF3rias com placeholder ou vazias",
691
- emptyResult.note
692
- );
693
- totalWarning++;
694
- specWarning++;
695
- } else {
696
- collectResult(
697
- allResults,
698
- "fail",
699
- entry.name,
700
- "Se\xE7\xF5es Vazias",
701
- "Se\xE7\xF5es obrigat\xF3rias com placeholder ou vazias",
702
- emptyResult.note
703
- );
704
- totalFail++;
705
- specFail++;
706
- }
707
- }
708
- }
709
- const binaryCfg = getHeuristicConfig(config, "ACs sem M\xE9trica");
710
- if (binaryCfg.severity !== "off") {
711
- const binaryResult = checkBinaryCriteria(specContent);
712
- if (binaryResult.status === "FAIL") {
713
- if (binaryCfg.severity === "warning") {
714
- collectResult(
715
- allResults,
716
- "warning",
717
- entry.name,
718
- "ACs sem M\xE9trica",
719
- "Crit\xE9rios com verbos vagos sem m\xE9trica",
720
- binaryResult.note
721
- );
722
- totalWarning++;
723
- specWarning++;
724
- } else {
725
- collectResult(
726
- allResults,
727
- "fail",
728
- entry.name,
729
- "ACs sem M\xE9trica",
730
- "Crit\xE9rios com verbos vagos sem m\xE9trica",
731
- binaryResult.note
732
- );
733
- totalFail++;
734
- specFail++;
735
- }
736
- }
737
- }
738
- const lowConfCfg = getHeuristicConfig(config, "Baixa Confian\xE7a");
739
- if (lowConfCfg.severity !== "off") {
740
- const lowConfResult = checkLowConfidence(specContent);
741
- if (lowConfResult.status === "FAIL") {
742
- if (lowConfCfg.severity === "warning") {
743
- collectResult(
744
- allResults,
745
- "warning",
746
- entry.name,
747
- "Baixa Confian\xE7a",
748
- "Spec cont\xE9m linguagem de baixa confian\xE7a",
749
- lowConfResult.note
750
- );
751
- totalWarning++;
752
- specWarning++;
753
- } else {
754
- collectResult(
755
- allResults,
756
- "fail",
757
- entry.name,
758
- "Baixa Confian\xE7a",
759
- "Spec cont\xE9m linguagem de baixa confian\xE7a",
760
- lowConfResult.note
761
- );
762
- totalFail++;
763
- specFail++;
764
- }
765
- }
766
- }
767
- }
768
- specGroups.set(entry.name, {
769
- pass: specPass,
770
- fail: specFail,
771
- warning: specWarning
772
- });
773
- }
774
- const conflictCfg = getHeuristicConfig(config, "Validate Conflict");
775
- if (conflictCfg.severity !== "off") {
776
- const conflictResults = checkConflicts(specsDir, config);
777
- for (const cr of conflictResults) {
778
- if (cr.passed) continue;
779
- const level = conflictCfg.severity === "warning" ? "warning" : "fail";
780
- collectResult(allResults, level, "(cross-spec)", cr.label, cr.message, "");
781
- if (level === "warning") {
782
- totalWarning++;
783
- } else {
784
- totalFail++;
785
- }
786
- }
787
- }
788
- if (fmt === "text" || fmt === "github-annotation") {
789
- for (const r of allResults) {
790
- out(fmt, r.level, r.spec, r.label, r.message, r.note);
791
- }
792
- }
793
- flushResults(allResults, fmt, specGroups, totalPass, totalFail, totalWarning);
794
- if (options?.log !== false) {
795
- logEntry(
796
- root,
797
- "validate",
798
- `Valida\xE7\xE3o executada \u2014 ${totalPass} passed, ${totalFail} failed, ${totalWarning} warnings`,
799
- {
800
- details: { passed: totalPass, failed: totalFail, warnings: totalWarning }
801
- }
802
- );
803
- }
804
- return { passed: totalPass, failed: totalFail, warnings: totalWarning };
805
- }
806
- const summary = await runValidation();
807
- if (options?.watch) {
808
- let timer = null;
809
- console.log(chalk.gray("\nWatching for changes... (Ctrl+C to stop)"));
810
- const watcher = watch(specsDir, { recursive: true });
811
- watcher.on("change", () => {
812
- if (timer) clearTimeout(timer);
813
- timer = setTimeout(async () => {
814
- console.clear();
815
- await runValidation();
816
- console.log(chalk.gray("\nWatching for changes... (Ctrl+C to stop)"));
817
- }, 300);
818
- });
819
- process.on("SIGINT", () => {
820
- watcher.close();
821
- process.exit(0);
822
- });
823
- process.on("SIGTERM", () => {
824
- watcher.close();
825
- process.exit(0);
826
- });
827
- await new Promise(() => {
828
- });
829
- } else {
830
- if (options?.exit !== false) process.exit(summary.failed > 0 ? 1 : 0);
831
- }
832
- return summary;
833
- }
834
-
835
- export {
836
- validate
837
- };