@letra-ai/cli 0.4.0 → 0.5.3

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,10 +1,35 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ DiagnosticEngine,
4
+ detectProjectName,
5
+ flowInitAction,
6
+ loadWorkflow,
7
+ logEntry,
8
+ queryLog,
9
+ sitrep,
10
+ sitrep_default,
11
+ writeWorkflow
12
+ } from "./chunk-56GTTLC4.js";
13
+ import {
14
+ ackEntry,
15
+ clearFocusFile,
16
+ dismissEntry,
17
+ generateAdapters,
18
+ getActiveEntries,
19
+ getSummary,
20
+ loadHealthRecord,
21
+ mergeScanResults,
22
+ readFocusFile,
23
+ saveHealthRecord,
24
+ syncFocus,
25
+ writeFocusFile
26
+ } from "./chunk-QWT5M4XU.js";
2
27
 
3
28
  // src/index.ts
4
- import { readFileSync as readFileSync11 } from "fs";
5
- import { join as join13, resolve as resolve16 } from "path";
29
+ import { readFileSync as readFileSync17 } from "fs";
30
+ import { join as join19, resolve as resolve23 } from "path";
6
31
  import { fileURLToPath as fileURLToPath3 } from "url";
7
- import { Command as Command4 } from "commander";
32
+ import { Command as Command9 } from "commander";
8
33
 
9
34
  // src/commands/decision.ts
10
35
  import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "fs";
@@ -51,6 +76,9 @@ What was decided?
51
76
  What are the trade-offs? What does this enable or prevent?
52
77
  `;
53
78
  writeFileSync(filePath, content);
79
+ logEntry(root, "decision", `Decis\xE3o registrada: ${title}`, {
80
+ details: { decisionFile: `.letra/decisions/${slug}.md` }
81
+ });
54
82
  console.log(chalk.green(`Decision "${slug}" created at .letra/decisions/${slug}.md`));
55
83
  });
56
84
  cmd.command("list").description("Lista todos os Architecture Decision Records").action(() => {
@@ -75,177 +103,16 @@ What are the trade-offs? What does this enable or prevent?
75
103
  }
76
104
 
77
105
  // src/commands/flow.ts
78
- import { Command as Command2 } from "commander";
106
+ import chalk12 from "chalk";
107
+ import { Command as Command3 } from "commander";
79
108
 
80
109
  // src/commands/flow-backlog.ts
81
- import { resolve as resolve3 } from "path";
82
- import chalk3 from "chalk";
83
-
84
- // src/commands/flow-init.ts
85
- import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
86
- import { join as join2, resolve as resolve2 } from "path";
87
- import { createInterface } from "readline";
110
+ import { existsSync as existsSync2 } from "fs";
111
+ import { resolve as resolve2, join as join2 } from "path";
88
112
  import chalk2 from "chalk";
89
- import ora from "ora";
90
- function askText(query, defaultValue) {
91
- if (!process.stdin.isTTY) return Promise.resolve(defaultValue);
92
- const rl = createInterface({ input: process.stdin, output: process.stdout });
93
- return new Promise((resolve17) => {
94
- const formatted = `${chalk2.cyan(query)} ${chalk2.gray(`(default: ${defaultValue})`)}
95
- > `;
96
- rl.question(formatted, (answer) => {
97
- rl.close();
98
- resolve17(answer.trim() || defaultValue);
99
- });
100
- });
101
- }
102
- function detectExistingTools(root) {
103
- const tools = [];
104
- if (existsSync2(join2(root, ".cursorrules"))) tools.push("cursor");
105
- if (existsSync2(join2(root, "CLAUDE.md"))) tools.push("claude-code");
106
- if (existsSync2(join2(root, ".windsurfrules"))) tools.push("windsurf");
107
- if (existsSync2(join2(root, "AGENTS.md"))) tools.push("opencode");
108
- if (existsSync2(join2(root, ".github", "copilot-instructions.md"))) tools.push("vscode");
109
- return tools;
110
- }
111
- function detectProjectName(root) {
112
- const pkgPath = join2(root, "package.json");
113
- if (existsSync2(pkgPath)) {
114
- try {
115
- const pkg2 = JSON.parse(readFileSync2(pkgPath, "utf-8"));
116
- if (pkg2.name) return pkg2.name.replace(/^@[^/]+\//, "");
117
- } catch {
118
- }
119
- }
120
- return resolve2(root).split(/[\\/]/).pop() || "meu-projeto";
121
- }
122
- function stagesFromInput(input) {
123
- return input.split(",").map((s, i) => {
124
- const trimmed = s.trim();
125
- if (!trimmed) return null;
126
- return {
127
- id: trimmed.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, ""),
128
- name: trimmed.charAt(0).toUpperCase() + trimmed.slice(1),
129
- order: i
130
- };
131
- }).filter((s) => s !== null);
132
- }
133
113
  function now() {
134
114
  return (/* @__PURE__ */ new Date()).toISOString();
135
115
  }
136
- function workflowFilePath(root) {
137
- return join2(root, ".letra", "workflow.json");
138
- }
139
- function loadWorkflow(root) {
140
- const filePath = workflowFilePath(root);
141
- if (!existsSync2(filePath)) return null;
142
- try {
143
- return JSON.parse(readFileSync2(filePath, "utf-8"));
144
- } catch {
145
- return null;
146
- }
147
- }
148
- function saveWorkflow(root, workflow) {
149
- const dir = join2(root, ".letra");
150
- if (!existsSync2(dir)) mkdirSync2(dir, { recursive: true });
151
- const filePath = workflowFilePath(root);
152
- if (existsSync2(filePath)) {
153
- const backupDir = join2(root, ".letra", "backups");
154
- if (!existsSync2(backupDir)) mkdirSync2(backupDir, { recursive: true });
155
- const ts = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
156
- const backupPath = join2(backupDir, `workflow-${ts}.json`);
157
- try {
158
- const existing = readFileSync2(filePath, "utf-8");
159
- writeFileSync2(backupPath, existing, "utf-8");
160
- } catch {
161
- }
162
- }
163
- writeFileSync2(filePath, JSON.stringify(workflow, null, 2));
164
- }
165
- async function flowInit(root, options) {
166
- if (!process.stdin.isTTY && !options?.quick) {
167
- console.log(chalk2.yellow("Non-TTY: usando defaults. Passe --quick para confirmar."));
168
- return flowInitQuick(root);
169
- }
170
- if (options?.quick) {
171
- return flowInitQuick(root);
172
- }
173
- const name = await askText("Workflow name?", detectProjectName(root));
174
- const stagesInput = await askText(
175
- "Stages (comma-separated)?",
176
- "backlog, design, code, review, done"
177
- );
178
- const stages = stagesFromInput(stagesInput);
179
- const detected = detectExistingTools(root);
180
- const defaultTools = detected.length > 0 ? detected.join(", ") : "cursor, opencode";
181
- const toolsInput = await askText("Tools (comma-separated)?", defaultTools);
182
- const tools = toolsInput.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
183
- const workflow = {
184
- version: "1.0",
185
- name,
186
- createdAt: now(),
187
- updatedAt: now(),
188
- stages,
189
- items: [],
190
- tools
191
- };
192
- return workflow;
193
- }
194
- async function flowInitQuick(root) {
195
- const defaultName = detectProjectName(root);
196
- const defaultStagesList = "backlog, design, code, review, done";
197
- const detected = detectExistingTools(root);
198
- const defaultTools = detected.length > 0 ? detected.join(", ") : "cursor, opencode";
199
- const name = await askText("Workflow name?", defaultName);
200
- const stagesInput = await askText("Stages (comma-separated)?", defaultStagesList);
201
- const stages = stagesFromInput(stagesInput);
202
- const toolsInput = await askText("Tools (comma-separated)?", defaultTools);
203
- const tools = toolsInput.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
204
- const workflow = {
205
- version: "1.0",
206
- name,
207
- createdAt: now(),
208
- updatedAt: now(),
209
- stages,
210
- items: [],
211
- tools
212
- };
213
- return workflow;
214
- }
215
- async function flowInitAction(targetPath, options) {
216
- const root = resolve2(process.cwd(), targetPath || ".");
217
- const filePath = workflowFilePath(root);
218
- if (existsSync2(filePath)) {
219
- console.log(chalk2.yellow("Workflow already exists at .letra/workflow.json"));
220
- return;
221
- }
222
- const spinner = ora("Setting up workflow...").start();
223
- try {
224
- spinner.stop();
225
- const workflow = await flowInit(root, options);
226
- spinner.start();
227
- saveWorkflow(root, workflow);
228
- spinner.succeed(chalk2.green("Workflow created at .letra/workflow.json"));
229
- console.log("");
230
- console.log(` Name: ${chalk2.cyan(workflow.name)}`);
231
- console.log(` Stages: ${chalk2.cyan(workflow.stages.map((s) => s.name).join(" \u2192 "))}`);
232
- console.log(` Tools: ${chalk2.cyan(workflow.tools.join(", "))}`);
233
- console.log("");
234
- console.log(" Next steps:");
235
- console.log(
236
- ` ${chalk2.cyan("letra flow backlog add <desc>")} Add items to your backlog`
237
- );
238
- console.log(` ${chalk2.cyan("letra flow board")} View your board`);
239
- } catch (error) {
240
- spinner.fail(chalk2.red("Failed to create workflow"));
241
- process.exit(1);
242
- }
243
- }
244
-
245
- // src/commands/flow-backlog.ts
246
- function now2() {
247
- return (/* @__PURE__ */ new Date()).toISOString();
248
- }
249
116
  function nextItemId(workflow) {
250
117
  let max = 0;
251
118
  for (const item of workflow.items) {
@@ -260,18 +127,25 @@ function nextItemId(workflow) {
260
127
  function workflowExists(root) {
261
128
  return loadWorkflow(root);
262
129
  }
263
- function backlogAdd(root, description) {
130
+ function backlogAdd(root, description, spec) {
264
131
  if (!description) {
265
- console.log(chalk3.red("Description is required"));
132
+ console.log(chalk2.red("Description is required"));
266
133
  process.exit(1);
267
134
  }
135
+ if (spec) {
136
+ const specsDir = join2(root, ".letra", "specs", spec);
137
+ if (!existsSync2(specsDir)) {
138
+ console.log(chalk2.red(`Spec "${spec}" not found at .letra/specs/${spec}/`));
139
+ return;
140
+ }
141
+ }
268
142
  const workflow = workflowExists(root);
269
143
  if (!workflow) {
270
- console.log(chalk3.red("No workflow found. Run 'letra flow init --quick' first"));
144
+ console.log(chalk2.red("No workflow found. Run 'letra flow init --quick' first"));
271
145
  process.exit(1);
272
146
  }
273
147
  if (workflow.stages.length === 0) {
274
- console.log(chalk3.red("Workflow has no stages defined"));
148
+ console.log(chalk2.red("Workflow has no stages defined"));
275
149
  process.exit(1);
276
150
  }
277
151
  const firstStage = workflow.stages[0].id;
@@ -279,55 +153,64 @@ function backlogAdd(root, description) {
279
153
  id: nextItemId(workflow),
280
154
  description,
281
155
  stage: firstStage,
282
- createdAt: now2()
156
+ createdAt: now(),
157
+ spec: spec || void 0
283
158
  };
159
+ if (spec) {
160
+ if (!workflow.specLinks) workflow.specLinks = {};
161
+ if (!workflow.specLinks[spec]) {
162
+ workflow.specLinks[spec] = { path: `.letra/specs/${spec}/spec.md` };
163
+ }
164
+ }
284
165
  workflow.items.push(item);
285
- workflow.updatedAt = now2();
286
- saveWorkflow(root, workflow);
166
+ workflow.updatedAt = now();
167
+ writeWorkflow(root, { workflow, source: "flow-backlog", primaryItemId: item.id, skipSitrep: true });
287
168
  console.log(
288
- ` ${chalk3.green("\u2713")} Item ${chalk3.cyan(item.id)} added to ${chalk3.cyan(workflow.stages[0].name)}`
169
+ ` ${chalk2.green("\u2713")} Item ${chalk2.cyan(item.id)} added to ${chalk2.cyan(workflow.stages[0].name)}`
289
170
  );
290
171
  }
291
172
  function backlogList(root) {
292
173
  const workflow = workflowExists(root);
293
174
  if (!workflow) {
294
- console.log(chalk3.yellow("No workflow found. Run 'letra flow init --quick' first"));
175
+ console.log(chalk2.yellow("No workflow found. Run 'letra flow init --quick' first"));
295
176
  return;
296
177
  }
297
178
  if (workflow.items.length === 0) {
298
- console.log(chalk3.yellow("No items in backlog"));
179
+ console.log(chalk2.yellow("No items in backlog"));
299
180
  return;
300
181
  }
301
182
  const stageNames = new Map(workflow.stages.map((s) => [s.id, s.name]));
302
183
  console.log("");
303
184
  console.log(
304
- ` ${chalk3.bold("ID")} ${chalk3.bold("Description".padEnd(30))} ${chalk3.bold("Stage".padEnd(15))} ${chalk3.bold("Age")}`
185
+ ` ${chalk2.bold("ID")} ${chalk2.bold("Description".padEnd(30))} ${chalk2.bold("Stage".padEnd(15))} ${chalk2.bold("Age")}`
305
186
  );
306
- console.log(` ${"\u2500".repeat(70)}`);
187
+ console.log(` ${"\u2500".repeat(75)}`);
307
188
  for (const item of workflow.items) {
308
189
  const stageName2 = stageNames.get(item.stage) || item.stage;
309
190
  const created = new Date(item.createdAt);
310
191
  const age = Math.floor((Date.now() - created.getTime()) / (1e3 * 60 * 60 * 24));
311
192
  const ageStr = age === 0 ? "today" : `${age}d`;
312
193
  const desc = item.description.length > 28 ? `${item.description.slice(0, 27)}\u2026` : item.description.padEnd(30);
194
+ const claimIcon = item.claimedBy ? "\u{1F916}" : " ";
313
195
  console.log(
314
- ` ${chalk3.cyan(item.id.padEnd(7))} ${desc} ${chalk3.yellow(stageName2.padEnd(15))} ${chalk3.gray(ageStr)}`
196
+ ` ${chalk2.cyan(item.id.padEnd(7))} ${desc} ${claimIcon} ${chalk2.yellow(stageName2.padEnd(15))} ${chalk2.gray(ageStr)}`
315
197
  );
316
198
  }
317
199
  console.log("");
318
200
  }
319
- function backlogActionAdd(targetPath, description) {
320
- const root = resolve3(process.cwd(), targetPath || ".");
321
- backlogAdd(root, description);
201
+ function backlogActionAdd(targetPath, description, spec) {
202
+ const root = resolve2(process.cwd(), targetPath || ".");
203
+ backlogAdd(root, description, spec);
322
204
  }
323
205
  function backlogActionList(targetPath) {
324
- const root = resolve3(process.cwd(), targetPath || ".");
206
+ const root = resolve2(process.cwd(), targetPath || ".");
325
207
  backlogList(root);
326
208
  }
327
209
 
328
210
  // src/commands/flow-board.ts
329
- import { resolve as resolve4 } from "path";
330
- import chalk4 from "chalk";
211
+ import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
212
+ import { join as join3, resolve as resolve3 } from "path";
213
+ import chalk3 from "chalk";
331
214
  function ageLabel(createdAt) {
332
215
  const created = new Date(createdAt);
333
216
  const age = Math.floor((Date.now() - created.getTime()) / (1e3 * 60 * 60 * 24));
@@ -336,12 +219,34 @@ function ageLabel(createdAt) {
336
219
  function flowBoard(root) {
337
220
  const workflow = loadWorkflow(root);
338
221
  if (!workflow) {
339
- console.log(chalk4.yellow("No workflow found. Run 'letra flow init --quick' first"));
222
+ console.log(chalk3.yellow("No workflow found. Run 'letra flow init --quick' first"));
340
223
  return;
341
224
  }
342
225
  console.log(`
343
- ${chalk4.bold("Board")} \u2014 ${chalk4.cyan(workflow.name)}
226
+ ${chalk3.bold("Board")} \u2014 ${chalk3.cyan(workflow.name)}
227
+ `);
228
+ if (workflow.items.length === 0) {
229
+ console.log(` ${chalk3.gray("Nenhum item no board. Adicione via:")}`);
230
+ console.log(` ${chalk3.cyan("letra flow backlog add <desc>")}
344
231
  `);
232
+ }
233
+ const healthPath = join3(root, ".letra", "health-record.json");
234
+ let itemAlerts = /* @__PURE__ */ new Map();
235
+ try {
236
+ if (existsSync3(healthPath)) {
237
+ const health = JSON.parse(readFileSync2(healthPath, "utf-8"));
238
+ const entries = health.entries || [];
239
+ for (const entry of entries) {
240
+ if (entry.status !== "novo") continue;
241
+ const match = entry.id.match(/_([A-Z]+-\d+)_/);
242
+ if (match) {
243
+ const itemId = match[1];
244
+ itemAlerts.set(itemId, (itemAlerts.get(itemId) || 0) + 1);
245
+ }
246
+ }
247
+ }
248
+ } catch {
249
+ }
345
250
  const stageMap = new Map(workflow.stages.map((s) => [s.id, s]));
346
251
  const itemsByStage = /* @__PURE__ */ new Map();
347
252
  for (const stage of workflow.stages) {
@@ -354,27 +259,45 @@ function flowBoard(root) {
354
259
  for (const stage of workflow.stages) {
355
260
  const items = itemsByStage.get(stage.id) || [];
356
261
  const count = items.length;
357
- const countLabel = count === 0 ? chalk4.gray("(empty)") : count === 1 ? chalk4.white(`${count} item`) : chalk4.white(`${count} items`);
358
- console.log(` ${chalk4.bold(stage.name)} ${countLabel}`);
262
+ const countLabel = count === 0 ? chalk3.gray("(empty)") : count === 1 ? chalk3.white(`${count} item`) : chalk3.white(`${count} items`);
263
+ console.log(` ${chalk3.bold(stage.name)} ${countLabel}`);
264
+ const backlogStageIds = new Set(
265
+ workflow.stages.filter((s) => s.zone === "todo" || s.id === "backlog").map((s) => s.id)
266
+ );
359
267
  for (const item of items) {
360
268
  const desc = item.description.length > 50 ? `${item.description.slice(0, 49)}\u2026` : item.description;
269
+ const claimIcon = item.claimedBy ? chalk3.cyan("\u{1F916}") : "";
270
+ let specInfo = "";
271
+ if (item.spec) {
272
+ const specLink2 = workflow.specLinks?.[item.spec];
273
+ if (specLink2) {
274
+ const specPath = join3(root, specLink2.path);
275
+ specInfo = existsSync3(specPath) ? chalk3.cyan(`\u{1F4CE}${item.spec}`) : chalk3.red(`\u26A0spec?`);
276
+ } else {
277
+ specInfo = chalk3.red(`\u26A0reg?`);
278
+ }
279
+ } else if (!backlogStageIds.has(item.stage)) {
280
+ specInfo = chalk3.yellow("\u26A0sem");
281
+ }
282
+ const alertCount = itemAlerts.get(item.id) || 0;
283
+ const alertBadge = alertCount > 0 ? chalk3.red(` \u26A0${alertCount}`) : "";
361
284
  console.log(
362
- ` ${chalk4.cyan(item.id.padEnd(7))} ${desc} ${chalk4.gray(ageLabel(item.createdAt))}`
285
+ ` ${chalk3.cyan(item.id.padEnd(7))} ${desc} ${claimIcon}${specInfo}${alertBadge} ${chalk3.gray(ageLabel(item.createdAt))}`
363
286
  );
364
287
  }
365
288
  if (items.length > 0) console.log("");
366
289
  }
367
290
  }
368
291
  function flowBoardAction(targetPath) {
369
- const root = resolve4(process.cwd(), targetPath || ".");
292
+ const root = resolve3(process.cwd(), targetPath || ".");
370
293
  flowBoard(root);
371
294
  }
372
295
 
373
296
  // src/commands/flow-edit-diff.ts
374
- import { existsSync as existsSync3, readFileSync as readFileSync3, readdirSync as readdirSync2, writeFileSync as writeFileSync3 } from "fs";
375
- import { join as join3, resolve as resolve5 } from "path";
376
- import chalk5 from "chalk";
377
- function now3() {
297
+ import { existsSync as existsSync4, readFileSync as readFileSync3, readdirSync as readdirSync2, writeFileSync as writeFileSync2 } from "fs";
298
+ import { join as join4, resolve as resolve4 } from "path";
299
+ import chalk4 from "chalk";
300
+ function now2() {
378
301
  return (/* @__PURE__ */ new Date()).toISOString();
379
302
  }
380
303
  function normalizeVersion(v) {
@@ -389,8 +312,8 @@ function incrementVersion(v) {
389
312
  return parts.join(".");
390
313
  }
391
314
  function loadBackup(root, version) {
392
- const path = join3(root, ".letra", `workflow.v${version}.json`);
393
- if (!existsSync3(path)) return null;
315
+ const path = join4(root, ".letra", `workflow.v${version}.json`);
316
+ if (!existsSync4(path)) return null;
394
317
  try {
395
318
  return JSON.parse(readFileSync3(path, "utf-8"));
396
319
  } catch {
@@ -405,8 +328,8 @@ function loadVersion(root, version) {
405
328
  return null;
406
329
  }
407
330
  function getLatestBackupVersion(root) {
408
- const dir = join3(root, ".letra");
409
- if (!existsSync3(dir)) return null;
331
+ const dir = join4(root, ".letra");
332
+ if (!existsSync4(dir)) return null;
410
333
  const files = readdirSync2(dir).filter((f) => f.startsWith("workflow.v") && f.endsWith(".json"));
411
334
  if (files.length === 0) return null;
412
335
  const versions = files.map((f) => f.replace("workflow.v", "").replace(".json", ""));
@@ -421,18 +344,18 @@ function getLatestBackupVersion(root) {
421
344
  return versions[versions.length - 1];
422
345
  }
423
346
  function backupFilePath(root, version) {
424
- return join3(root, ".letra", `workflow.v${version}.json`);
347
+ return join4(root, ".letra", `workflow.v${version}.json`);
425
348
  }
426
349
  function flowEdit(root, options) {
427
350
  const workflow = loadWorkflow(root);
428
351
  if (!workflow) {
429
- console.log(chalk5.yellow("No workflow found. Run 'letra flow init --quick' first"));
352
+ console.log(chalk4.yellow("No workflow found. Run 'letra flow init --quick' first"));
430
353
  return;
431
354
  }
432
355
  const currentVersion = normalizeVersion(workflow.version);
433
356
  const backupPath = backupFilePath(root, currentVersion);
434
- if (!existsSync3(backupPath)) {
435
- writeFileSync3(backupPath, JSON.stringify(workflow, null, 2));
357
+ if (!existsSync4(backupPath)) {
358
+ writeFileSync2(backupPath, JSON.stringify(workflow, null, 2));
436
359
  }
437
360
  if (options.name !== void 0) {
438
361
  workflow.name = options.name;
@@ -441,14 +364,14 @@ function flowEdit(root, options) {
441
364
  workflow.description = options.desc;
442
365
  }
443
366
  workflow.version = incrementVersion(workflow.version);
444
- workflow.updatedAt = now3();
445
- saveWorkflow(root, workflow);
446
- console.log(` ${chalk5.green("\u2713")} Workflow updated to v${workflow.version}`);
367
+ workflow.updatedAt = now2();
368
+ writeWorkflow(root, { workflow, source: "flow-edit", skipSitrep: true });
369
+ console.log(` ${chalk4.green("\u2713")} Workflow updated to v${workflow.version}`);
447
370
  if (options.name !== void 0) {
448
- console.log(` Name: ${chalk5.cyan(options.name)}`);
371
+ console.log(` Name: ${chalk4.cyan(options.name)}`);
449
372
  }
450
373
  if (options.desc !== void 0) {
451
- console.log(` Description: ${chalk5.cyan(options.desc)}`);
374
+ console.log(` Description: ${chalk4.cyan(options.desc)}`);
452
375
  }
453
376
  }
454
377
  function stageName(workflow, stageId) {
@@ -526,22 +449,22 @@ function stripVPrefix(v) {
526
449
  function flowDiff(root, v1, v2) {
527
450
  const current = loadWorkflow(root);
528
451
  if (!current) {
529
- console.log(chalk5.yellow("No workflow found"));
452
+ console.log(chalk4.yellow("No workflow found"));
530
453
  return;
531
454
  }
532
455
  if (v1 && v2) {
533
456
  const wf1 = loadVersion(root, stripVPrefix(v1));
534
457
  const wf2 = loadVersion(root, stripVPrefix(v2));
535
458
  if (!wf1 && !wf2) {
536
- console.log(chalk5.yellow(`No backups found for versions ${v1} and ${v2}`));
459
+ console.log(chalk4.yellow(`No backups found for versions ${v1} and ${v2}`));
537
460
  return;
538
461
  }
539
462
  if (!wf1) {
540
- console.log(chalk5.yellow(`No backup found for version ${v1}`));
463
+ console.log(chalk4.yellow(`No backup found for version ${v1}`));
541
464
  return;
542
465
  }
543
466
  if (!wf2) {
544
- console.log(chalk5.yellow(`No backup found for version ${v2}`));
467
+ console.log(chalk4.yellow(`No backup found for version ${v2}`));
545
468
  return;
546
469
  }
547
470
  const diff = computeDiff(wf1, wf2);
@@ -550,12 +473,12 @@ function flowDiff(root, v1, v2) {
550
473
  } else {
551
474
  const latestVersion = getLatestBackupVersion(root);
552
475
  if (!latestVersion) {
553
- console.log(chalk5.yellow("No backup versions found to compare"));
476
+ console.log(chalk4.yellow("No backup versions found to compare"));
554
477
  return;
555
478
  }
556
479
  const backup = loadBackup(root, latestVersion);
557
480
  if (!backup) {
558
- console.log(chalk5.yellow(`Failed to load backup version ${latestVersion}`));
481
+ console.log(chalk4.yellow(`Failed to load backup version ${latestVersion}`));
559
482
  return;
560
483
  }
561
484
  const diff = computeDiff(backup, current);
@@ -564,37 +487,37 @@ function flowDiff(root, v1, v2) {
564
487
  }
565
488
  }
566
489
  function flowEditAction(targetPath, options) {
567
- const root = resolve5(process.cwd(), targetPath || ".");
490
+ const root = resolve4(process.cwd(), targetPath || ".");
568
491
  flowEdit(root, options);
569
492
  }
570
493
  function flowDiffAction(targetPath, v1, v2) {
571
- const root = resolve5(process.cwd(), targetPath || ".");
494
+ const root = resolve4(process.cwd(), targetPath || ".");
572
495
  flowDiff(root, v1, v2);
573
496
  }
574
497
 
575
498
  // src/commands/flow-export-import.ts
576
- import { existsSync as existsSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync4 } from "fs";
577
- import { join as join4, resolve as resolve6 } from "path";
578
- import chalk6 from "chalk";
499
+ import { existsSync as existsSync5, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "fs";
500
+ import { join as join5, resolve as resolve5 } from "path";
501
+ import chalk5 from "chalk";
579
502
  function flowExport(root, options) {
580
503
  const workflow = loadWorkflow(root);
581
504
  if (!workflow) {
582
- console.log(chalk6.yellow("No workflow found"));
505
+ console.log(chalk5.yellow("No workflow found"));
583
506
  return;
584
507
  }
585
508
  const json = JSON.stringify(workflow, null, options?.minified ? 0 : 2);
586
509
  console.log(json);
587
510
  }
588
511
  function flowExportAction(targetPath, options) {
589
- const root = resolve6(process.cwd(), targetPath || ".");
512
+ const root = resolve5(process.cwd(), targetPath || ".");
590
513
  flowExport(root, options);
591
514
  }
592
- function now4() {
515
+ function now3() {
593
516
  return (/* @__PURE__ */ new Date()).toISOString();
594
517
  }
595
518
  function flowImport(root, filePath) {
596
- if (!existsSync4(filePath)) {
597
- console.log(chalk6.red(`File not found: ${filePath}`));
519
+ if (!existsSync5(filePath)) {
520
+ console.log(chalk5.red(`File not found: ${filePath}`));
598
521
  process.exit(1);
599
522
  }
600
523
  let parsed;
@@ -602,43 +525,43 @@ function flowImport(root, filePath) {
602
525
  const content = readFileSync4(filePath, "utf-8");
603
526
  parsed = JSON.parse(content);
604
527
  } catch {
605
- console.log(chalk6.red("Invalid JSON file"));
528
+ console.log(chalk5.red("Invalid JSON file"));
606
529
  process.exit(1);
607
530
  }
608
531
  const obj = parsed;
609
532
  if (!obj.name || typeof obj.name !== "string" || !obj.name.trim()) {
610
- console.log(chalk6.red("Missing required field: name (non-empty string)"));
533
+ console.log(chalk5.red("Missing required field: name (non-empty string)"));
611
534
  process.exit(1);
612
535
  }
613
536
  if (!obj.stages || !Array.isArray(obj.stages) || obj.stages.length === 0) {
614
- console.log(chalk6.red("Missing required field: stages (non-empty array)"));
537
+ console.log(chalk5.red("Missing required field: stages (non-empty array)"));
615
538
  process.exit(1);
616
539
  }
617
540
  const imported = parsed;
618
541
  const existingWorkflow = loadWorkflow(root);
619
542
  if (existingWorkflow) {
620
- const backup = join4(root, ".letra", `workflow.v${existingWorkflow.version}.json`);
621
- if (!existsSync4(backup)) {
622
- writeFileSync4(backup, JSON.stringify(existingWorkflow, null, 2));
543
+ const backup = join5(root, ".letra", `workflow.v${existingWorkflow.version}.json`);
544
+ if (!existsSync5(backup)) {
545
+ writeFileSync3(backup, JSON.stringify(existingWorkflow, null, 2));
623
546
  console.log(
624
- chalk6.gray(`Backup saved: .letra/workflow.v${existingWorkflow.version}.json`)
547
+ chalk5.gray(`Backup saved: .letra/workflow.v${existingWorkflow.version}.json`)
625
548
  );
626
549
  }
627
550
  }
628
- imported.createdAt = now4();
629
- imported.updatedAt = now4();
630
- saveWorkflow(root, imported);
631
- console.log(chalk6.green(`Workflow imported: ${imported.name} (${imported.version})`));
551
+ imported.createdAt = now3();
552
+ imported.updatedAt = now3();
553
+ writeWorkflow(root, { workflow: imported, source: "flow-import", skipSitrep: true });
554
+ console.log(chalk5.green(`Workflow imported: ${imported.name} (${imported.version})`));
632
555
  }
633
556
  function flowImportAction(targetPath, filePath) {
634
- const root = resolve6(process.cwd(), targetPath || ".");
557
+ const root = resolve5(process.cwd(), targetPath || ".");
635
558
  flowImport(root, filePath);
636
559
  }
637
560
 
638
561
  // src/commands/flow-import-issues.ts
639
- import { resolve as resolve7 } from "path";
640
- import chalk7 from "chalk";
641
- function now5() {
562
+ import { resolve as resolve6 } from "path";
563
+ import chalk6 from "chalk";
564
+ function now4() {
642
565
  return (/* @__PURE__ */ new Date()).toISOString();
643
566
  }
644
567
  function nextItemId2(workflow) {
@@ -655,11 +578,11 @@ function nextItemId2(workflow) {
655
578
  function ensureWorkflow(root) {
656
579
  const workflow = loadWorkflow(root);
657
580
  if (!workflow) {
658
- console.log(chalk7.red("No workflow found. Run 'letra flow init --quick' first"));
581
+ console.log(chalk6.red("No workflow found. Run 'letra flow init --quick' first"));
659
582
  process.exit(1);
660
583
  }
661
584
  if (workflow.stages.length === 0) {
662
- console.log(chalk7.red("Workflow has no stages defined"));
585
+ console.log(chalk6.red("Workflow has no stages defined"));
663
586
  process.exit(1);
664
587
  }
665
588
  return workflow;
@@ -686,17 +609,17 @@ async function backlogImportGitHub(root, repo, options) {
686
609
  response = await fetch(url.toString(), { headers });
687
610
  } catch (err) {
688
611
  const msg = err instanceof Error ? err.message : String(err);
689
- console.log(chalk7.red(`Failed to fetch issues: ${msg}`));
612
+ console.log(chalk6.red(`Failed to fetch issues: ${msg}`));
690
613
  process.exit(1);
691
614
  }
692
615
  if (!response.ok) {
693
616
  const text = await response.text().catch(() => "unknown error");
694
617
  if (response.status === 404) {
695
- console.log(chalk7.red(`Repository "${repo}" not found or is private`));
618
+ console.log(chalk6.red(`Repository "${repo}" not found or is private`));
696
619
  } else if (response.status === 401 || response.status === 403) {
697
- console.log(chalk7.red(`GitHub API error (${response.status}). Check GITHUB_TOKEN`));
620
+ console.log(chalk6.red(`GitHub API error (${response.status}). Check GITHUB_TOKEN`));
698
621
  } else {
699
- console.log(chalk7.red(`GitHub API error (${response.status}): ${text}`));
622
+ console.log(chalk6.red(`GitHub API error (${response.status}): ${text}`));
700
623
  }
701
624
  process.exit(1);
702
625
  }
@@ -704,12 +627,12 @@ async function backlogImportGitHub(root, repo, options) {
704
627
  try {
705
628
  issues = await response.json();
706
629
  } catch {
707
- console.log(chalk7.red("Failed to parse GitHub response"));
630
+ console.log(chalk6.red("Failed to parse GitHub response"));
708
631
  process.exit(1);
709
632
  }
710
633
  issues = issues.filter((i) => !("pull_request" in i));
711
634
  if (issues.length === 0) {
712
- console.log(chalk7.yellow("No open issues found"));
635
+ console.log(chalk6.yellow("No open issues found"));
713
636
  return { imported: 0, total: 0 };
714
637
  }
715
638
  const firstStage = workflow.stages[0].id;
@@ -721,24 +644,24 @@ async function backlogImportGitHub(root, repo, options) {
721
644
  id: nextItemId2(workflow),
722
645
  description,
723
646
  stage: firstStage,
724
- createdAt: now5(),
647
+ createdAt: now4(),
725
648
  source: "github",
726
649
  sourceUrl: issue.html_url
727
650
  };
728
651
  workflow.items.push(item);
729
652
  imported++;
730
653
  }
731
- workflow.updatedAt = now5();
732
- saveWorkflow(root, workflow);
654
+ workflow.updatedAt = now4();
655
+ writeWorkflow(root, { workflow, source: "flow-import", skipSitrep: true, quiet: true });
733
656
  console.log(
734
- ` ${chalk7.green("\u2713")} Imported ${chalk7.cyan(String(imported))} issue${imported !== 1 ? "s" : ""} from ${chalk7.cyan(repo)}`
657
+ ` ${chalk6.green("\u2713")} Imported ${chalk6.cyan(String(imported))} issue${imported !== 1 ? "s" : ""} from ${chalk6.cyan(repo)}`
735
658
  );
736
659
  return { imported, total: issues.length };
737
660
  }
738
661
  async function backlogImportLinear(root, team, options) {
739
662
  const apiKey = process.env.LINEAR_API_KEY;
740
663
  if (!apiKey) {
741
- console.log(chalk7.red("LINEAR_API_KEY environment variable is required for Linear import"));
664
+ console.log(chalk6.red("LINEAR_API_KEY environment variable is required for Linear import"));
742
665
  process.exit(1);
743
666
  }
744
667
  const workflow = ensureWorkflow(root);
@@ -768,15 +691,15 @@ async function backlogImportLinear(root, team, options) {
768
691
  });
769
692
  } catch (err) {
770
693
  const msg = err instanceof Error ? err.message : String(err);
771
- console.log(chalk7.red(`Failed to fetch Linear issues: ${msg}`));
694
+ console.log(chalk6.red(`Failed to fetch Linear issues: ${msg}`));
772
695
  process.exit(1);
773
696
  }
774
697
  if (!response.ok) {
775
698
  const text = await response.text().catch(() => "unknown error");
776
699
  if (response.status === 401) {
777
- console.log(chalk7.red("Invalid Linear API key. Check LINEAR_API_KEY"));
700
+ console.log(chalk6.red("Invalid Linear API key. Check LINEAR_API_KEY"));
778
701
  } else {
779
- console.log(chalk7.red(`Linear API error (${response.status}): ${text}`));
702
+ console.log(chalk6.red(`Linear API error (${response.status}): ${text}`));
780
703
  }
781
704
  process.exit(1);
782
705
  }
@@ -784,17 +707,17 @@ async function backlogImportLinear(root, team, options) {
784
707
  try {
785
708
  data = await response.json();
786
709
  } catch {
787
- console.log(chalk7.red("Failed to parse Linear response"));
710
+ console.log(chalk6.red("Failed to parse Linear response"));
788
711
  process.exit(1);
789
712
  }
790
713
  if (data.data?.team?.issues?.nodes == null) {
791
714
  const errMsg = data?.data?.team == null ? `Team "${team}" not found` : "Failed to fetch Linear issues";
792
- console.log(chalk7.red(errMsg));
715
+ console.log(chalk6.red(errMsg));
793
716
  process.exit(1);
794
717
  }
795
718
  const issues = data.data.team.issues.nodes;
796
719
  if (issues.length === 0) {
797
- console.log(chalk7.yellow(`No open issues found for team "${team}"`));
720
+ console.log(chalk6.yellow(`No open issues found for team "${team}"`));
798
721
  return { imported: 0, total: 0 };
799
722
  }
800
723
  const firstStage = workflow.stages[0].id;
@@ -805,39 +728,39 @@ async function backlogImportLinear(root, team, options) {
805
728
  id: nextItemId2(workflow),
806
729
  description,
807
730
  stage: firstStage,
808
- createdAt: now5(),
731
+ createdAt: now4(),
809
732
  source: "linear",
810
733
  sourceUrl: issue.url
811
734
  };
812
735
  workflow.items.push(item);
813
736
  imported++;
814
737
  }
815
- workflow.updatedAt = now5();
816
- saveWorkflow(root, workflow);
738
+ workflow.updatedAt = now4();
739
+ writeWorkflow(root, { workflow, source: "flow-import", skipSitrep: true, quiet: true });
817
740
  console.log(
818
- ` ${chalk7.green("\u2713")} Imported ${chalk7.cyan(String(imported))} issue${imported !== 1 ? "s" : ""} from Linear team ${chalk7.cyan(team)}`
741
+ ` ${chalk6.green("\u2713")} Imported ${chalk6.cyan(String(imported))} issue${imported !== 1 ? "s" : ""} from Linear team ${chalk6.cyan(team)}`
819
742
  );
820
743
  return { imported, total: issues.length };
821
744
  }
822
745
  async function backlogImportGitHubAction(targetPath, repo, options) {
823
- const root = resolve7(process.cwd(), targetPath || ".");
746
+ const root = resolve6(process.cwd(), targetPath || ".");
824
747
  await backlogImportGitHub(root, repo, {
825
748
  label: options.label,
826
749
  limit: options.limit ? Number(options.limit) : void 0
827
750
  });
828
751
  }
829
752
  async function backlogImportLinearAction(targetPath, team, options) {
830
- const root = resolve7(process.cwd(), targetPath || ".");
753
+ const root = resolve6(process.cwd(), targetPath || ".");
831
754
  await backlogImportLinear(root, team, {
832
755
  limit: options.limit ? Number(options.limit) : void 0
833
756
  });
834
757
  }
835
758
 
836
759
  // src/commands/flow-move.ts
837
- import { existsSync as existsSync5, mkdirSync as mkdirSync3, writeFileSync as writeFileSync5 } from "fs";
838
- import { join as join5, resolve as resolve8 } from "path";
839
- import chalk8 from "chalk";
840
- function now6() {
760
+ import { existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
761
+ import { join as join6, resolve as resolve7 } from "path";
762
+ import chalk7 from "chalk";
763
+ function now5() {
841
764
  return (/* @__PURE__ */ new Date()).toISOString();
842
765
  }
843
766
  function resolveStage(workflow, input) {
@@ -848,180 +771,577 @@ function resolveStage(workflow, input) {
848
771
  }
849
772
  return null;
850
773
  }
851
- function adapterContent(workflowName, currentStageName, items, stageNames) {
852
- const stageItems = items.filter(
853
- (item) => item.stage === currentStageName.toLowerCase().replace(/[^a-z0-9]+/g, "-") || stageNames.get(item.stage) === currentStageName
854
- );
855
- const itemsBlock = stageItems.length > 0 ? stageItems.map((item) => `- ${item.id}: ${item.description}`).join("\n") : "(nenhum item ativo neste estagio)";
856
- return `# Letra Context \u2014 ${workflowName}
857
-
858
- ## Workflow
859
-
860
- **Estagio atual:** ${currentStageName}
861
-
862
- ### Itens neste estagio
863
-
864
- ${itemsBlock}
865
-
866
- ### Regras
867
-
868
- - Leia as specs em .letra/specs/ antes de codificar
869
- - Execute \`letra validate\` para verificar acceptance criteria
870
- - Siga a constitution.md rigorosamente
871
- - Ao concluir, mova o item com \`letra flow move <id> --to <proximo_estagio>\`
872
- `;
873
- }
874
- function generateAdapters(root, tools, content) {
875
- const adapters = [];
876
- const header = `# Gerado por letra flow move. Nao edite manualmente.
877
- `;
878
- for (const tool of tools) {
879
- switch (tool) {
880
- case "cursor":
881
- adapters.push({
882
- path: join5(root, ".cursorrules"),
883
- content: header + content
884
- });
885
- break;
886
- case "claude-code":
887
- adapters.push({
888
- path: join5(root, "CLAUDE.md"),
889
- content: header + content
890
- });
891
- break;
892
- case "windsurf":
893
- adapters.push({
894
- path: join5(root, ".windsurfrules"),
895
- content: header + content
896
- });
897
- break;
898
- case "vscode": {
899
- const dir = join5(root, ".github");
900
- if (!existsSync5(dir)) mkdirSync3(dir, { recursive: true });
901
- adapters.push({
902
- path: join5(dir, "copilot-instructions.md"),
903
- content: header + content
904
- });
905
- break;
906
- }
907
- case "opencode":
908
- adapters.push({
909
- path: join5(root, "AGENTS.md"),
910
- content: header + content
911
- });
912
- break;
913
- }
914
- }
915
- for (const { path, content: fileContent } of adapters) {
916
- const dir = join5(path, "..");
917
- if (!existsSync5(dir)) mkdirSync3(dir, { recursive: true });
918
- writeFileSync5(path, fileContent);
919
- console.log(` ${chalk8.gray("Updated")} ${path.replace(`${root}/`, "")}`);
920
- }
921
- }
922
- function flowMove(root, itemId, targetStageInput) {
774
+ async function flowMove(root, itemId, targetStageInput, options) {
923
775
  const workflow = loadWorkflow(root);
924
776
  if (!workflow) {
925
- console.log(chalk8.red("No workflow found. Run 'letra flow init --quick' first"));
777
+ console.log(chalk7.red("No workflow found. Run 'letra flow init --quick' first"));
926
778
  process.exit(1);
927
779
  }
928
780
  const item = workflow.items.find((i) => i.id === itemId) || workflow.items.find((i) => i.description === itemId);
929
781
  if (!item) {
930
- console.log(chalk8.red(`Item "${itemId}" not found`));
782
+ console.log(chalk7.red(`Item "${itemId}" not found`));
931
783
  process.exit(1);
932
784
  }
785
+ if (options?.auto) {
786
+ const currentStage = workflow.stages.find((s) => s.id === item.stage);
787
+ if (!currentStage) {
788
+ console.log(chalk7.red(`Stage "${item.stage}" not found in workflow`));
789
+ process.exit(1);
790
+ return;
791
+ }
792
+ const nextStage = workflow.stages.filter((s) => s.order > currentStage.order).sort((a, b) => a.order - b.order)[0];
793
+ if (!nextStage) {
794
+ console.log(chalk7.yellow(`Item ${itemId} is already at the last stage (${currentStage.name})`));
795
+ return;
796
+ }
797
+ targetStageInput = nextStage.id;
798
+ if (!options?.force && item.spec) {
799
+ const specFile = join6(root, ".letra", "specs", item.spec, "spec.md");
800
+ if (existsSync6(specFile)) {
801
+ const content = readFileSync5(specFile, "utf-8");
802
+ const pendingACs = content.match(/^- \[ \]/gm) || [];
803
+ if (pendingACs.length > 0) {
804
+ console.log(chalk7.yellow(`\u26A0 Item ${itemId} has ${pendingACs.length} pending AC(s) in "${item.spec}"`));
805
+ console.log(chalk7.yellow(` Use --force to move anyway, or complete ACs first.`));
806
+ return;
807
+ }
808
+ const doneACs = content.match(/^- \[[xX]\]/gm) || [];
809
+ if (doneACs.length > 0) {
810
+ const acLogEntries = queryLog(root, { itemId, action: "ac_done", limit: 999 });
811
+ if (acLogEntries.length < doneACs.length) {
812
+ console.log(chalk7.yellow(`\u26A0 ${doneACs.length - acLogEntries.length} AC(s) marked [x] without "ac done" log entry.`));
813
+ console.log(chalk7.yellow(` Run \`letra ac done <ID>\` for each completed AC.`));
814
+ }
815
+ }
816
+ }
817
+ }
818
+ }
933
819
  const targetStageId = resolveStage(workflow, targetStageInput);
934
820
  if (!targetStageId) {
935
821
  const valid = workflow.stages.map((s) => `${s.id} (${s.name})`).join(", ");
936
- console.log(chalk8.red(`Stage "${targetStageInput}" not found. Valid stages: ${valid}`));
822
+ console.log(chalk7.red(`Stage "${targetStageInput}" not found. Valid stages: ${valid}`));
937
823
  process.exit(1);
938
824
  }
939
825
  if (item.stage === targetStageId) {
940
- console.log(chalk8.yellow(`Item ${itemId} is already in stage "${targetStageId}"`));
826
+ console.log(chalk7.yellow(`Item ${itemId} is already in stage "${targetStageId}"`));
941
827
  return;
942
828
  }
943
829
  const fromStage = workflow.stages.find((s) => s.id === item.stage)?.name || item.stage;
944
830
  const toStage = workflow.stages.find((s) => s.id === targetStageId)?.name || targetStageId;
945
831
  item.stage = targetStageId;
946
- workflow.updatedAt = now6();
947
- saveWorkflow(root, workflow);
948
- const stageNames = new Map(workflow.stages.map((s) => [s.id, s.name]));
949
- const currentStageName = stageNames.get(targetStageId) || targetStageId;
950
- const content = adapterContent(workflow.name, currentStageName, workflow.items, stageNames);
951
- generateAdapters(root, workflow.tools, content);
832
+ workflow.updatedAt = now5();
833
+ const targetStageIsDone = workflow.stages.find((s) => s.id === targetStageId)?.zone === "done";
834
+ if (targetStageIsDone && item.claimedBy) {
835
+ if (item.claimedBy === "opencode") {
836
+ console.log(` ${chalk7.gray("Release autom\xE1tico:")} ${itemId} n\xE3o est\xE1 mais sob responsabilidade do agente`);
837
+ }
838
+ delete item.claimedBy;
839
+ delete item.claimedAt;
840
+ }
841
+ const result = await writeWorkflow(root, {
842
+ workflow,
843
+ source: "flow-move",
844
+ primaryItemId: itemId,
845
+ skipSitrep: true
846
+ });
847
+ if (item.spec) {
848
+ writeFocusFile(root, item.spec, item.id);
849
+ }
850
+ logEntry(root, "item_move", `Item ${itemId} movido: ${fromStage} \u2192 ${toStage}`, {
851
+ itemId,
852
+ details: { from: item.stage, to: targetStageId }
853
+ });
952
854
  console.log(
953
- ` ${chalk8.green("\u2713")} Item ${chalk8.cyan(itemId)} moved: ${chalk8.yellow(fromStage)} \u2192 ${chalk8.green(toStage)}`
855
+ ` ${chalk7.green("\u2713")} Item ${chalk7.cyan(itemId)} moved: ${chalk7.yellow(fromStage)} \u2192 ${chalk7.green(toStage)}`
954
856
  );
955
- console.log(` ${chalk8.gray("Adapters regenerated for:")} ${workflow.tools.join(", ")}`);
857
+ if (result.ok && result.filesUpdated.length > 0) {
858
+ console.log(` ${chalk7.gray("Updated:")} ${result.filesUpdated.join(", ")}`);
859
+ }
860
+ }
861
+ function normalizeItemId(input) {
862
+ if (/^ITEM-\d+$/i.test(input)) return input.toUpperCase();
863
+ if (/^\d+$/.test(input)) return `ITEM-${input}`;
864
+ console.log(chalk7.red(`Invalid item ID: "${input}". Use a number (e.g. 34) or ITEM-N format.`));
865
+ process.exit(1);
956
866
  }
957
867
  function flowMoveAction(targetPath, itemId, options) {
958
- const root = resolve8(process.cwd(), targetPath || ".");
959
- flowMove(root, itemId, options.to);
868
+ const root = resolve7(process.cwd(), targetPath || ".");
869
+ const normalized = normalizeItemId(itemId);
870
+ if (options.auto) {
871
+ flowMove(root, normalized, options.to || "", { auto: true, force: options.force });
872
+ } else {
873
+ flowMove(root, normalized, options.to || "");
874
+ }
960
875
  }
961
876
 
962
- // src/commands/flow-serve.ts
963
- import { existsSync as existsSync6, mkdirSync as mkdirSync4, readFileSync as readFileSync5, readdirSync as readdirSync3, watch, writeFileSync as writeFileSync6 } from "fs";
964
- import { createServer } from "http";
965
- import { dirname, extname, join as join6, resolve as resolve9 } from "path";
966
- import { fileURLToPath } from "url";
967
- var DEFAULT_PORT = 3e3;
968
- function loadSpecs(root, workflow) {
969
- const result = [];
970
- if (workflow?.specLinks) {
971
- for (const [id, link] of Object.entries(workflow.specLinks)) {
972
- const filePath = join6(root, link.path);
973
- if (existsSync6(filePath)) {
974
- result.push({ id, content: readFileSync5(filePath, "utf-8") });
975
- }
877
+ // src/commands/flow-claim.ts
878
+ import { createInterface } from "readline";
879
+ import { resolve as resolve8 } from "path";
880
+ import chalk8 from "chalk";
881
+ function askYesNo(query) {
882
+ if (!process.stdin.isTTY) return Promise.resolve(true);
883
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
884
+ return new Promise((resolve24) => {
885
+ rl.question(`${chalk8.yellow(query)} (y/N) `, (answer) => {
886
+ rl.close();
887
+ resolve24(answer.trim().toLowerCase() === "y");
888
+ });
889
+ });
890
+ }
891
+ async function claimItem(root, itemId) {
892
+ const workflow = loadWorkflow(root);
893
+ if (!workflow) {
894
+ console.log(chalk8.red("No workflow found"));
895
+ process.exit(1);
896
+ }
897
+ const item = workflow.items.find((i) => i.id === itemId);
898
+ if (!item) {
899
+ console.log(chalk8.red(`Item ${itemId} not found`));
900
+ process.exit(1);
901
+ }
902
+ if (item.stage === "done" || workflow.stages.find((s) => s.id === item.stage)?.zone === "done") {
903
+ console.log(chalk8.red(`Cannot claim ${itemId}: item is already completed`));
904
+ process.exit(1);
905
+ }
906
+ if (item.claimedBy) {
907
+ if (item.claimedBy === "opencode") {
908
+ console.log(chalk8.yellow(`${itemId} is already under your responsibility`));
909
+ return;
910
+ }
911
+ const ok = await askYesNo(`${itemId} is claimed by "${item.claimedBy}". Overwrite?`);
912
+ if (!ok) {
913
+ console.log(chalk8.dim("Claim cancelled"));
914
+ return;
976
915
  }
977
916
  }
978
- const specsDir = join6(root, ".letra", "specs");
979
- const registered = new Set(result.map((s) => s.id));
980
- if (existsSync6(specsDir)) {
981
- for (const entry of readdirSync3(specsDir, { withFileTypes: true })) {
982
- if (entry.isDirectory() && !registered.has(entry.name)) {
983
- const specPath = join6(specsDir, entry.name, "spec.md");
984
- if (existsSync6(specPath)) {
985
- result.push({ id: entry.name, content: readFileSync5(specPath, "utf-8") });
986
- }
917
+ item.claimedBy = "opencode";
918
+ item.claimedAt = (/* @__PURE__ */ new Date()).toISOString();
919
+ workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
920
+ writeWorkflow(root, { workflow, source: "flow-claim", primaryItemId: item.id, skipSitrep: true });
921
+ logEntry(root, "item_claim", "claimed by opencode", { itemId: item.id });
922
+ console.log(` ${chalk8.green("\u2713")} ${itemId} claimed`);
923
+ }
924
+ async function releaseItem(root, options) {
925
+ const workflow = loadWorkflow(root);
926
+ if (!workflow) {
927
+ console.log(chalk8.red("No workflow found"));
928
+ process.exit(1);
929
+ }
930
+ if (options?.item) {
931
+ const item = workflow.items.find((i) => i.id === options.item);
932
+ if (!item) {
933
+ console.log(chalk8.red(`Item ${options.item} not found`));
934
+ process.exit(1);
935
+ }
936
+ if (!item.claimedBy) {
937
+ console.log(chalk8.yellow(`${options.item} is not claimed`));
938
+ return;
939
+ }
940
+ if (item.claimedBy !== "opencode") {
941
+ const ok = await askYesNo(`${options.item} is claimed by "${item.claimedBy}". Release anyway?`);
942
+ if (!ok) {
943
+ console.log(chalk8.dim("Release cancelled"));
944
+ return;
987
945
  }
988
946
  }
947
+ delete item.claimedBy;
948
+ delete item.claimedAt;
949
+ workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
950
+ writeWorkflow(root, { workflow, source: "flow-release", primaryItemId: item.id, skipSitrep: true });
951
+ logEntry(root, "item_release", "released by opencode", { itemId: item.id });
952
+ console.log(` ${chalk8.green("\u2713")} ${options.item} released`);
953
+ return;
989
954
  }
990
- return result;
991
- }
992
- var TEMPLATES = {
993
- padrao: {
994
- name: "Padr\xE3o",
995
- stages: [
996
- { id: "backlog", name: "Backlog", zone: "todo" },
997
- { id: "design", name: "Design", zone: "doing" },
998
- { id: "code", name: "Code", zone: "doing" },
999
- { id: "review", name: "Review", zone: "doing" },
1000
- { id: "done", name: "Done", zone: "done" }
1001
- ]
1002
- },
1003
- kanban: {
1004
- name: "Kanban",
1005
- stages: [
1006
- { id: "todo", name: "A Fazer", zone: "todo" },
1007
- { id: "doing", name: "Fazendo", zone: "doing" },
1008
- { id: "done", name: "Feito", zone: "done" }
1009
- ]
1010
- },
1011
- agil: {
1012
- name: "\xC1gil",
1013
- stages: [
1014
- { id: "product-backlog", name: "Product Backlog", zone: "todo" },
1015
- { id: "sprint-backlog", name: "Sprint Backlog", zone: "todo" },
1016
- { id: "in-progress", name: "In Progress", zone: "doing" },
1017
- { id: "review", name: "Review", zone: "doing" },
1018
- { id: "done", name: "Done", zone: "done" }
1019
- ]
955
+ const claimed = workflow.items.filter((i) => i.claimedBy === "opencode");
956
+ if (claimed.length === 0) {
957
+ console.log(chalk8.yellow("No items currently claimed by opencode"));
958
+ return;
1020
959
  }
1021
- };
1022
- function createWorkflowFromTemplate(root, templateId, options) {
1023
- const t = TEMPLATES[templateId];
1024
- if (!t) {
960
+ for (const item of claimed) {
961
+ delete item.claimedBy;
962
+ delete item.claimedAt;
963
+ logEntry(root, "item_release", "released by opencode (batch)", { itemId: item.id });
964
+ }
965
+ workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
966
+ writeWorkflow(root, { workflow, source: "flow-release", skipSitrep: true });
967
+ console.log(` ${chalk8.green("\u2713")} Released ${claimed.length} item(s)`);
968
+ }
969
+ async function claimAction(targetPath, itemId) {
970
+ const root = resolve8(process.cwd(), targetPath || ".");
971
+ await claimItem(root, itemId);
972
+ }
973
+ async function releaseAction(targetPath, options) {
974
+ const root = resolve8(process.cwd(), targetPath || ".");
975
+ await releaseItem(root, options);
976
+ }
977
+
978
+ // src/commands/flow-ac.ts
979
+ import { existsSync as existsSync7, readFileSync as readFileSync6, writeFileSync as writeFileSync5 } from "fs";
980
+ import { join as join7, resolve as resolve9 } from "path";
981
+ import chalk9 from "chalk";
982
+ function findACLine(lines, n) {
983
+ let count = 0;
984
+ for (let i = 0; i < lines.length; i++) {
985
+ const trimmed = lines[i].trim();
986
+ if (/^- \[ \]/.test(trimmed)) {
987
+ count++;
988
+ if (count === n) return i;
989
+ }
990
+ }
991
+ return null;
992
+ }
993
+ function markAC(root, itemId, acNum) {
994
+ const workflow = loadWorkflow(root);
995
+ if (!workflow) {
996
+ console.log(chalk9.red("No workflow found"));
997
+ process.exit(1);
998
+ }
999
+ const item = workflow.items.find((i) => i.id === itemId);
1000
+ if (!item) {
1001
+ console.log(chalk9.red(`Item ${itemId} not found`));
1002
+ process.exit(1);
1003
+ }
1004
+ if (!item.spec) {
1005
+ console.log(chalk9.red(`Item ${itemId} has no linked spec`));
1006
+ process.exit(1);
1007
+ }
1008
+ const specDir = join7(root, ".letra", "specs", item.spec);
1009
+ const specFile = join7(specDir, "spec.md");
1010
+ if (!existsSync7(specFile)) {
1011
+ console.log(chalk9.red(`Spec file not found: ${specFile}`));
1012
+ process.exit(1);
1013
+ }
1014
+ const content = readFileSync6(specFile, "utf-8");
1015
+ const lines = content.split("\n");
1016
+ const lineIdx = findACLine(lines, acNum);
1017
+ if (lineIdx === null) {
1018
+ console.log(chalk9.red(`AC #${acNum} not found in spec "${item.spec}" (unchecked ACs: ${lines.filter((l) => /^- \[ \]/.test(l.trim())).length})`));
1019
+ process.exit(1);
1020
+ }
1021
+ const orig = lines[lineIdx];
1022
+ lines[lineIdx] = orig.replace(/^- \[ \]/, "- [x]");
1023
+ writeFileSync5(specFile, lines.join("\n"), "utf-8");
1024
+ if (workflow.specLinks?.[item.spec]) {
1025
+ writeWorkflow(root, { workflow, source: "flow-ac", primaryItemId: item.id, skipSitrep: true, quiet: true });
1026
+ }
1027
+ logEntry(root, "ac_done", `AC ${acNum} marcado como conclu\xEDdo em ${item.spec}`, {
1028
+ itemId: item.id,
1029
+ acId: `${acNum}`,
1030
+ details: { spec: item.spec }
1031
+ });
1032
+ console.log(` ${chalk9.green("\u2713")} AC #${acNum} marcado como conclu\xEDdo em ${chalk9.cyan(item.spec)}`);
1033
+ }
1034
+ function flowAcAction(targetPath, itemId, acNumber) {
1035
+ const root = resolve9(process.cwd(), targetPath || ".");
1036
+ const n = Number(acNumber);
1037
+ if (!Number.isInteger(n) || n < 1) {
1038
+ console.log(chalk9.red("AC number must be a positive integer"));
1039
+ process.exit(1);
1040
+ }
1041
+ markAC(root, itemId, n);
1042
+ }
1043
+
1044
+ // src/commands/flow-serve.ts
1045
+ import { existsSync as existsSync10, mkdirSync as mkdirSync3, readFileSync as readFileSync9, readdirSync as readdirSync3, watch, writeFileSync as writeFileSync6 } from "fs";
1046
+ import { createServer } from "http";
1047
+ import { dirname, extname, join as join9, resolve as resolve11 } from "path";
1048
+ import { fileURLToPath } from "url";
1049
+
1050
+ // src/validation/structure.ts
1051
+ import { existsSync as existsSync8, readFileSync as readFileSync7 } from "fs";
1052
+ var REQUIRED_SECTIONS = [
1053
+ "## Outcome",
1054
+ "## Constraints",
1055
+ "## Exclusions",
1056
+ "## Acceptance Criteria",
1057
+ "## Context"
1058
+ ];
1059
+ function checkRequiredSections(content) {
1060
+ return REQUIRED_SECTIONS.filter((section) => !content.includes(section));
1061
+ }
1062
+ function checkSpecLength(content, maxChars = 3e3) {
1063
+ return content.length > maxChars ? `Spec exceeds ${maxChars} chars (should be thin \u2014 max 1 page)` : null;
1064
+ }
1065
+ function checkChecklist(content) {
1066
+ const hasChecklist = /-\s*\[[ x]\]\s*\*\*/i.test(content);
1067
+ if (!hasChecklist && content.includes("## Acceptance Criteria")) {
1068
+ return "Acceptance Criteria section exists but has no checklist items";
1069
+ }
1070
+ return null;
1071
+ }
1072
+ function validateSpecStructure(specFile) {
1073
+ const errors = [];
1074
+ const warnings = [];
1075
+ if (!existsSync8(specFile)) {
1076
+ errors.push("Missing spec.md");
1077
+ return { errors, warnings };
1078
+ }
1079
+ const content = readFileSync7(specFile, "utf-8");
1080
+ const missingSections = checkRequiredSections(content);
1081
+ errors.push(...missingSections.map((s) => `Missing section: ${s}`));
1082
+ const lengthWarning = checkSpecLength(content);
1083
+ if (lengthWarning) warnings.push(lengthWarning);
1084
+ const checklistError = checkChecklist(content);
1085
+ if (checklistError) errors.push(checklistError);
1086
+ return { errors, warnings };
1087
+ }
1088
+
1089
+ // src/commands/pulse.ts
1090
+ import { existsSync as existsSync9, readFileSync as readFileSync8 } from "fs";
1091
+ import { resolve as resolve10, join as join8 } from "path";
1092
+ import chalk10 from "chalk";
1093
+ import { Command as Command2 } from "commander";
1094
+ function daysSince(date) {
1095
+ return Math.floor((Date.now() - date.getTime()) / (1e3 * 60 * 60 * 24));
1096
+ }
1097
+ function daysInStage(item) {
1098
+ return daysSince(new Date(item.createdAt));
1099
+ }
1100
+ function findCurrentItem(workflow) {
1101
+ const activeStages = workflow.stages.filter((s) => s.zone === "doing" || !s.zone && (s.id === "code" || s.id === "review" || s.order > 0 && s.order < workflow.stages.length - 1)).map((s) => s.id);
1102
+ const stageSet = new Set(activeStages);
1103
+ if (stageSet.size === 0) {
1104
+ const middle = Math.floor(workflow.stages.length / 2);
1105
+ const stage = workflow.stages[middle];
1106
+ if (stage) stageSet.add(stage.id);
1107
+ }
1108
+ const items = workflow.items.filter((i) => stageSet.has(i.stage));
1109
+ if (items.length === 0) return null;
1110
+ return items.reduce((a, b) => new Date(a.createdAt) > new Date(b.createdAt) ? a : b);
1111
+ }
1112
+ function findNextBacklog(workflow) {
1113
+ const firstStage = workflow.stages[0];
1114
+ if (!firstStage) return null;
1115
+ const items = workflow.items.filter((i) => i.stage === firstStage.id);
1116
+ if (items.length === 0) return null;
1117
+ return items.reduce((a, b) => new Date(a.createdAt) < new Date(b.createdAt) ? a : b);
1118
+ }
1119
+ function getStageName(workflow, stageId) {
1120
+ return workflow.stages.find((s) => s.id === stageId)?.name ?? stageId;
1121
+ }
1122
+ function countSpecACs(root, specName) {
1123
+ const specDir = join8(root, ".letra", "specs", specName);
1124
+ const specFile = join8(specDir, "spec.md");
1125
+ if (!existsSync9(specFile)) return { pending: 0, done: 0, total: 0 };
1126
+ try {
1127
+ const content = readFileSync8(specFile, "utf-8");
1128
+ const boldPending = content.match(/-\s*\[ \]\s*\*\*(.+?)\*\*/g) || [];
1129
+ const boldDone = content.match(/-\s*\[[xX]\]\s*\*\*(.+?)\*\*/g) || [];
1130
+ if (boldPending.length > 0 || boldDone.length > 0) {
1131
+ return { pending: boldPending.length, done: boldDone.length, total: boldPending.length + boldDone.length };
1132
+ }
1133
+ const genericPending = content.match(/^- \[ \]/gm) || [];
1134
+ const genericDone = content.match(/^- \[[xX]\]/gm) || [];
1135
+ return { pending: genericPending.length, done: genericDone.length, total: genericPending.length + genericDone.length };
1136
+ } catch {
1137
+ return { pending: 0, done: 0, total: 0 };
1138
+ }
1139
+ }
1140
+ function getTaskCounts(item) {
1141
+ if (!item.tasks || item.tasks.length === 0) return { open: 0, done: 0, total: 0 };
1142
+ const done = item.tasks.filter((t) => t.done).length;
1143
+ return { open: item.tasks.length - done, done, total: item.tasks.length };
1144
+ }
1145
+ async function pulse(rootPath, options) {
1146
+ const workflow = loadWorkflow(rootPath);
1147
+ const name = workflow?.name ?? "meu-projeto";
1148
+ if (!workflow) {
1149
+ const empty = {
1150
+ workspace: name,
1151
+ pulseAt: (/* @__PURE__ */ new Date()).toISOString(),
1152
+ currentItem: null,
1153
+ alerts: { novo: 0, acknowledged: 0, resolved: 0, dismissed: 0, highSeverity: 0 },
1154
+ lastUpdated: null,
1155
+ daysIdle: null,
1156
+ nextItem: null
1157
+ };
1158
+ if (options?.json) {
1159
+ console.log(JSON.stringify(empty, null, 2));
1160
+ } else {
1161
+ renderPulseText(empty);
1162
+ }
1163
+ return empty;
1164
+ }
1165
+ const healthRecord = loadHealthRecord(rootPath);
1166
+ const summary = getSummary(healthRecord);
1167
+ const currentItem = findCurrentItem(workflow);
1168
+ let acCounts = { pending: 0, done: 0, total: 0 };
1169
+ if (currentItem?.spec) {
1170
+ acCounts = countSpecACs(rootPath, currentItem.spec);
1171
+ }
1172
+ const pulseData = {
1173
+ workspace: name,
1174
+ pulseAt: (/* @__PURE__ */ new Date()).toISOString(),
1175
+ currentItem: currentItem ? {
1176
+ id: currentItem.id,
1177
+ description: currentItem.description,
1178
+ stage: currentItem.stage,
1179
+ stageName: getStageName(workflow, currentItem.stage),
1180
+ daysInStage: daysInStage(currentItem),
1181
+ spec: currentItem.spec ?? null,
1182
+ acs: acCounts,
1183
+ tasks: getTaskCounts(currentItem),
1184
+ claimedBy: currentItem.claimedBy,
1185
+ claimedAt: currentItem.claimedAt
1186
+ } : null,
1187
+ alerts: {
1188
+ novo: summary.novo,
1189
+ acknowledged: summary.ciente,
1190
+ resolved: summary.resolvido,
1191
+ dismissed: summary.descartado,
1192
+ highSeverity: summary.alta
1193
+ },
1194
+ lastUpdated: workflow.updatedAt ?? null,
1195
+ daysIdle: workflow.updatedAt ? daysSince(new Date(workflow.updatedAt)) : null,
1196
+ nextItem: findNextBacklog(workflow) ? {
1197
+ id: findNextBacklog(workflow).id,
1198
+ description: findNextBacklog(workflow).description,
1199
+ stage: findNextBacklog(workflow).stage
1200
+ } : null
1201
+ };
1202
+ const focusResult = syncFocus(rootPath, workflow);
1203
+ if (focusResult.cleared) {
1204
+ console.log(chalk10.yellow(" focus.md limpo \u2014 item referenciado n\xE3o encontrado no workflow"));
1205
+ }
1206
+ const focusData = readFocusFile(rootPath);
1207
+ let focusDiverged = false;
1208
+ if (focusData && currentItem?.spec && focusData.specName !== currentItem.spec) {
1209
+ focusDiverged = true;
1210
+ }
1211
+ if (options?.json) {
1212
+ const pulseJson = { ...pulseData, focusDiverged };
1213
+ console.log(JSON.stringify(pulseJson, null, 2));
1214
+ } else {
1215
+ renderPulseText(pulseData, focusDiverged);
1216
+ }
1217
+ return pulseData;
1218
+ }
1219
+ function renderPulseText(data, focusDiverged) {
1220
+ const dateStr = new Date(data.pulseAt).toLocaleDateString("pt-BR", {
1221
+ day: "2-digit",
1222
+ month: "2-digit",
1223
+ year: "numeric",
1224
+ hour: "2-digit",
1225
+ minute: "2-digit"
1226
+ });
1227
+ console.log(`
1228
+ ${chalk10.bold("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557")}`);
1229
+ console.log(`${chalk10.bold("\u2551 Pulso do Workspace")} `);
1230
+ console.log(`${chalk10.bold("\u2551")} ${chalk10.gray(`${data.workspace} \xB7 ${dateStr}`)}`);
1231
+ console.log(`${chalk10.bold("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D")}
1232
+ `);
1233
+ if (data.currentItem) {
1234
+ const ci = data.currentItem;
1235
+ console.log(` ${chalk10.bold("Item em andamento:")}`);
1236
+ console.log(` ${chalk10.cyan(ci.id)} \xB7 ${ci.description}`);
1237
+ const agentInfo = ci.claimedBy ? ` \u{1F916} Agent: ${ci.claimedBy}` : "";
1238
+ console.log(` ${chalk10.gray(`Est\xE1gio: ${ci.stageName} \xB7 ${ci.daysInStage} dia(s) no est\xE1gio${agentInfo}`)}`);
1239
+ console.log(` ${chalk10.gray(`ACs: ${ci.acs.pending}/${ci.acs.total} pendentes (${ci.acs.done} feito(s))`)}`);
1240
+ if (ci.tasks.total > 0) {
1241
+ console.log(` ${chalk10.gray(`Tasks: ${ci.tasks.open}/${ci.tasks.total} abertas (${ci.tasks.done} feita(s))`)}`);
1242
+ }
1243
+ if (ci.spec) {
1244
+ console.log(` ${chalk10.gray(`Spec: .letra/specs/${ci.spec}/spec.md`)}`);
1245
+ } else {
1246
+ console.log(` ${chalk10.yellow("\u26A0 sem spec associada")}`);
1247
+ }
1248
+ } else {
1249
+ console.log(` ${chalk10.yellow("Nenhum item em andamento.")}`);
1250
+ }
1251
+ console.log();
1252
+ const alerts = data.alerts;
1253
+ if (alerts.novo > 0 || alerts.acknowledged > 0 || alerts.resolved > 0) {
1254
+ console.log(` ${chalk10.bold("Alertas:")}`);
1255
+ console.log(` ${chalk10.red(`${alerts.novo} novo(s)`)} \xB7 ${chalk10.yellow(`${alerts.acknowledged} em acompanhamento`)} \xB7 ${chalk10.gray(`${alerts.resolved} resolvido(s)`)}`);
1256
+ if (alerts.highSeverity > 0) {
1257
+ console.log(` ${chalk10.red.bold(`\u26A0 ${alerts.highSeverity} alerta(s) de severidade alta`)}`);
1258
+ }
1259
+ console.log(` ${chalk10.gray("\u2192 Corra `letra health` para detalhes")}`);
1260
+ } else {
1261
+ console.log(` ${chalk10.gray("Nenhum alerta ativo.")}`);
1262
+ }
1263
+ console.log();
1264
+ if (data.lastUpdated) {
1265
+ const idle = data.daysIdle !== null ? `(${data.daysIdle} dia(s) parado)` : "";
1266
+ console.log(` ${chalk10.gray(`\xDAltima atualiza\xE7\xE3o: ${new Date(data.lastUpdated).toLocaleDateString("pt-BR")} ${idle}`)}`);
1267
+ }
1268
+ if (data.nextItem) {
1269
+ console.log(` ${chalk10.gray(`Pr\xF3ximo item na fila: ${data.nextItem.id} \xB7 ${data.nextItem.description} (${data.nextItem.stage})`)}`);
1270
+ }
1271
+ if (focusDiverged) {
1272
+ console.log(` ${chalk10.red.bold("\u26A0 Foco dessincronizado!")} focus.md aponta para spec diferente do item ativo`);
1273
+ console.log(` ${chalk10.gray("\u2192 Corra `letra focus <spec>` para corrigir")}`);
1274
+ }
1275
+ console.log();
1276
+ }
1277
+ function pulse_default() {
1278
+ const cmd = new Command2("pulse").description("Pulse do workspace \u2014 overview de uma olhada s\xF3");
1279
+ cmd.option("--json", "Output in JSON format").action(async (options) => {
1280
+ const root = resolve10(process.cwd());
1281
+ await pulse(root, options);
1282
+ });
1283
+ return cmd;
1284
+ }
1285
+
1286
+ // src/commands/flow-serve.ts
1287
+ var DEFAULT_PORT = 3e3;
1288
+ function loadSpecs(root, workflow) {
1289
+ const result = [];
1290
+ if (workflow?.specLinks) {
1291
+ for (const [id, link] of Object.entries(workflow.specLinks)) {
1292
+ const filePath = join9(root, link.path);
1293
+ if (existsSync10(filePath)) {
1294
+ result.push({ id, content: readFileSync9(filePath, "utf-8") });
1295
+ }
1296
+ }
1297
+ }
1298
+ const specsDir = join9(root, ".letra", "specs");
1299
+ const registered = new Set(result.map((s) => s.id));
1300
+ if (existsSync10(specsDir)) {
1301
+ for (const entry of readdirSync3(specsDir, { withFileTypes: true })) {
1302
+ if (entry.isDirectory() && !registered.has(entry.name)) {
1303
+ const specPath = join9(specsDir, entry.name, "spec.md");
1304
+ if (existsSync10(specPath)) {
1305
+ result.push({ id: entry.name, content: readFileSync9(specPath, "utf-8") });
1306
+ }
1307
+ }
1308
+ }
1309
+ }
1310
+ return result;
1311
+ }
1312
+ var TEMPLATES = {
1313
+ padrao: {
1314
+ name: "Padr\xE3o",
1315
+ stages: [
1316
+ { id: "backlog", name: "Backlog", zone: "todo" },
1317
+ { id: "design", name: "Design", zone: "doing" },
1318
+ { id: "code", name: "Code", zone: "doing" },
1319
+ { id: "review", name: "Review", zone: "doing" },
1320
+ { id: "done", name: "Done", zone: "done" }
1321
+ ]
1322
+ },
1323
+ kanban: {
1324
+ name: "Kanban",
1325
+ stages: [
1326
+ { id: "todo", name: "A Fazer", zone: "todo" },
1327
+ { id: "doing", name: "Fazendo", zone: "doing" },
1328
+ { id: "done", name: "Feito", zone: "done" }
1329
+ ]
1330
+ },
1331
+ agil: {
1332
+ name: "\xC1gil",
1333
+ stages: [
1334
+ { id: "product-backlog", name: "Product Backlog", zone: "todo" },
1335
+ { id: "sprint-backlog", name: "Sprint Backlog", zone: "todo" },
1336
+ { id: "in-progress", name: "In Progress", zone: "doing" },
1337
+ { id: "review", name: "Review", zone: "doing" },
1338
+ { id: "done", name: "Done", zone: "done" }
1339
+ ]
1340
+ }
1341
+ };
1342
+ function createWorkflowFromTemplate(root, templateId, options) {
1343
+ const t = TEMPLATES[templateId];
1344
+ if (!t) {
1025
1345
  throw new Error(
1026
1346
  `Template "${templateId}" not found. Available: ${Object.keys(TEMPLATES).join(", ")}`
1027
1347
  );
@@ -1036,6 +1356,7 @@ function createWorkflowFromTemplate(root, templateId, options) {
1036
1356
  return {
1037
1357
  version: "1.0",
1038
1358
  name: options?.name ?? detectProjectName(root) ?? t.name,
1359
+ language: existing?.language,
1039
1360
  createdAt: existing?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
1040
1361
  updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1041
1362
  stages,
@@ -1047,16 +1368,20 @@ function createWorkflowFromTemplate(root, templateId, options) {
1047
1368
  var FlowServer = class {
1048
1369
  server;
1049
1370
  watcher;
1371
+ specsWatcher;
1372
+ diagnosticsTimer;
1050
1373
  clients = /* @__PURE__ */ new Set();
1051
1374
  root;
1052
1375
  port;
1053
1376
  loadWorkflow;
1377
+ engine;
1054
1378
  constructor(root, port = DEFAULT_PORT) {
1055
1379
  this.root = root;
1056
1380
  this.port = port;
1057
1381
  this.loadWorkflow = () => loadWorkflow(root);
1382
+ this.engine = new DiagnosticEngine(root);
1058
1383
  }
1059
- handleRequest = (req, res) => {
1384
+ handleRequest = async (req, res) => {
1060
1385
  const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
1061
1386
  const path = url.pathname;
1062
1387
  if (path === "/events") {
@@ -1098,6 +1423,7 @@ var FlowServer = class {
1098
1423
  wf = {
1099
1424
  version: "1.0",
1100
1425
  name: data.name ?? detectProjectName(this.root) ?? "Personalizado",
1426
+ language: existing?.language,
1101
1427
  createdAt: existing?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
1102
1428
  updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1103
1429
  stages,
@@ -1106,12 +1432,17 @@ var FlowServer = class {
1106
1432
  tools: data.tools ?? existing?.tools ?? []
1107
1433
  };
1108
1434
  } else {
1435
+ const existing = loadWorkflow(this.root);
1109
1436
  wf = createWorkflowFromTemplate(this.root, data.template, {
1110
1437
  name: data.name,
1111
1438
  tools: data.tools
1112
1439
  });
1440
+ if (existing?.language && wf) {
1441
+ wf.language = existing.language;
1442
+ }
1113
1443
  }
1114
- saveWorkflow(this.root, wf);
1444
+ writeWorkflow(this.root, { workflow: wf, source: "web-ui", skipSitrep: true, quiet: true });
1445
+ this.broadcast();
1115
1446
  res.writeHead(200, { "Content-Type": "application/json" });
1116
1447
  res.end(JSON.stringify(wf));
1117
1448
  } catch (e) {
@@ -1146,15 +1477,15 @@ var FlowServer = class {
1146
1477
  res.end(JSON.stringify({ error: "id and content required" }));
1147
1478
  return;
1148
1479
  }
1149
- const specDir = join6(this.root, ".letra", "specs", id);
1150
- if (!existsSync6(specDir)) mkdirSync4(specDir, { recursive: true });
1151
- writeFileSync6(join6(specDir, "spec.md"), content, "utf-8");
1480
+ const specDir = join9(this.root, ".letra", "specs", id);
1481
+ if (!existsSync10(specDir)) mkdirSync3(specDir, { recursive: true });
1482
+ writeFileSync6(join9(specDir, "spec.md"), content, "utf-8");
1152
1483
  const wf = this.loadWorkflow();
1153
1484
  if (wf) {
1154
1485
  if (!wf.specLinks) wf.specLinks = {};
1155
1486
  wf.specLinks[id] = { path: `.letra/specs/${id}/spec.md` };
1156
1487
  wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1157
- saveWorkflow(this.root, wf);
1488
+ writeWorkflow(this.root, { workflow: wf, source: "web-ui", skipSitrep: true, quiet: true });
1158
1489
  this.broadcast();
1159
1490
  }
1160
1491
  res.writeHead(200, { "Content-Type": "application/json" });
@@ -1173,15 +1504,15 @@ var FlowServer = class {
1173
1504
  res.end(JSON.stringify({ error: "spec id required" }));
1174
1505
  return;
1175
1506
  }
1176
- const specDir = join6(this.root, ".letra", "specs", specId);
1177
- if (existsSync6(specDir)) {
1178
- writeFileSync6(join6(specDir, "spec.md"), "", "utf-8");
1507
+ const specDir = join9(this.root, ".letra", "specs", specId);
1508
+ if (existsSync10(specDir)) {
1509
+ writeFileSync6(join9(specDir, "spec.md"), "", "utf-8");
1179
1510
  }
1180
1511
  const wf = this.loadWorkflow();
1181
1512
  if (wf?.specLinks) {
1182
1513
  delete wf.specLinks[specId];
1183
1514
  wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1184
- saveWorkflow(this.root, wf);
1515
+ writeWorkflow(this.root, { workflow: wf, source: "web-ui", skipSitrep: true, quiet: true });
1185
1516
  this.broadcast();
1186
1517
  }
1187
1518
  res.writeHead(200, { "Content-Type": "application/json" });
@@ -1207,13 +1538,13 @@ var FlowServer = class {
1207
1538
  res.end(JSON.stringify({ error: "content required" }));
1208
1539
  return;
1209
1540
  }
1210
- const specDir = join6(this.root, ".letra", "specs", specId);
1211
- if (!existsSync6(specDir)) mkdirSync4(specDir, { recursive: true });
1212
- writeFileSync6(join6(specDir, "spec.md"), content, "utf-8");
1541
+ const specDir = join9(this.root, ".letra", "specs", specId);
1542
+ if (!existsSync10(specDir)) mkdirSync3(specDir, { recursive: true });
1543
+ writeFileSync6(join9(specDir, "spec.md"), content, "utf-8");
1213
1544
  const wf = this.loadWorkflow();
1214
1545
  if (wf) {
1215
1546
  wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1216
- saveWorkflow(this.root, wf);
1547
+ writeWorkflow(this.root, { workflow: wf, source: "web-ui", skipSitrep: true, quiet: true });
1217
1548
  this.broadcast();
1218
1549
  }
1219
1550
  res.writeHead(200, { "Content-Type": "application/json" });
@@ -1227,10 +1558,10 @@ var FlowServer = class {
1227
1558
  }
1228
1559
  if (path.match(/^\/api\/specs\/[^/]+\/validate$/) && req.method === "POST") {
1229
1560
  const specId = path.replace("/api/specs/", "").split("/")[0];
1230
- const specDir = join6(this.root, ".letra", "specs", specId);
1231
- const specFile = join6(specDir, "spec.md");
1561
+ const specDir = join9(this.root, ".letra", "specs", specId);
1562
+ const specFile = join9(specDir, "spec.md");
1232
1563
  const issues = [];
1233
- if (!existsSync6(specFile)) {
1564
+ if (!existsSync10(specFile)) {
1234
1565
  res.writeHead(200, { "Content-Type": "application/json" });
1235
1566
  res.end(
1236
1567
  JSON.stringify({
@@ -1241,34 +1572,10 @@ var FlowServer = class {
1241
1572
  );
1242
1573
  return;
1243
1574
  }
1244
- const content = readFileSync5(specFile, "utf-8");
1245
- const requiredSections = [
1246
- "Outcome",
1247
- "Constraints",
1248
- "Exclusions",
1249
- "Acceptance Criteria",
1250
- "Context"
1251
- ];
1252
- for (const section of requiredSections) {
1253
- const re = new RegExp(`## ${section}`);
1254
- if (!re.test(content)) {
1255
- issues.push({ type: "error", msg: `Missing section: ## ${section}` });
1256
- }
1257
- }
1258
- const acMatch = content.match(/## Acceptance Criteria\s+([\s\S]*?)(?=\n## |$)/);
1259
- if (acMatch) {
1260
- const acSection = acMatch[1];
1261
- const items = [...acSection.matchAll(/-\s+\[(\s|x)\]\s+/g)];
1262
- if (items.length === 0) {
1263
- issues.push({
1264
- type: "warning",
1265
- msg: "Acceptance Criteria section has no checklist items"
1266
- });
1267
- }
1268
- }
1269
- if (content.length > 3e3) {
1270
- issues.push({ type: "warning", msg: "Spec exceeds 3000 chars (should be thin)" });
1271
- }
1575
+ const content = readFileSync9(specFile, "utf-8");
1576
+ const { errors: structErrors, warnings: structWarnings } = validateSpecStructure(specFile);
1577
+ for (const e of structErrors) issues.push({ type: "error", msg: e });
1578
+ for (const w of structWarnings) issues.push({ type: "warning", msg: w });
1272
1579
  res.writeHead(200, { "Content-Type": "application/json" });
1273
1580
  res.end(
1274
1581
  JSON.stringify({
@@ -1307,7 +1614,7 @@ var FlowServer = class {
1307
1614
  };
1308
1615
  wf.items.push(item);
1309
1616
  wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1310
- saveWorkflow(this.root, wf);
1617
+ writeWorkflow(this.root, { workflow: wf, source: "web-ui", primaryItemId: item.id, skipSitrep: true, quiet: true });
1311
1618
  this.broadcast();
1312
1619
  res.writeHead(200, { "Content-Type": "application/json" });
1313
1620
  res.end(JSON.stringify(item));
@@ -1318,6 +1625,24 @@ var FlowServer = class {
1318
1625
  });
1319
1626
  return;
1320
1627
  }
1628
+ if (path.match(/^\/api\/items\/[^/]+$/) && req.method === "GET") {
1629
+ const itemId = path.replace("/api/items/", "");
1630
+ const wf = this.loadWorkflow();
1631
+ if (!wf) {
1632
+ res.writeHead(404, { "Content-Type": "application/json" });
1633
+ res.end(JSON.stringify({ error: "No workflow" }));
1634
+ return;
1635
+ }
1636
+ const item = wf.items.find((i) => i.id === itemId);
1637
+ if (!item) {
1638
+ res.writeHead(404, { "Content-Type": "application/json" });
1639
+ res.end(JSON.stringify({ error: "Item not found" }));
1640
+ return;
1641
+ }
1642
+ res.writeHead(200, { "Content-Type": "application/json" });
1643
+ res.end(JSON.stringify(item));
1644
+ return;
1645
+ }
1321
1646
  if (path.match(/^\/api\/items\/[^/]+$/) && req.method === "PATCH") {
1322
1647
  const itemId = path.replace("/api/items/", "");
1323
1648
  let body = "";
@@ -1344,9 +1669,14 @@ var FlowServer = class {
1344
1669
  if (data.description !== void 0) item.description = data.description;
1345
1670
  if (data.tasks !== void 0) item.tasks = data.tasks;
1346
1671
  wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1347
- saveWorkflow(this.root, wf);
1672
+ writeWorkflow(this.root, { workflow: wf, source: "web-ui", primaryItemId: itemId, skipSitrep: true, quiet: true });
1348
1673
  this.broadcast();
1349
1674
  if (data.stage !== void 0 && data.stage !== oldStage) {
1675
+ if (item.spec) {
1676
+ writeFocusFile(this.root, item.spec, item.id);
1677
+ logEntry(this.root, "focus_sync", `Focus synced to ${item.spec} via item move (${item.id})`, { itemId: item.id, spec: item.spec });
1678
+ console.log(` [focus] Synced to ${item.spec} via drag`);
1679
+ }
1350
1680
  this.fireWebhooks("item.moved", {
1351
1681
  itemId: item.id,
1352
1682
  itemDescription: item.description,
@@ -1379,12 +1709,86 @@ var FlowServer = class {
1379
1709
  }
1380
1710
  wf.items.splice(idx, 1);
1381
1711
  wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1382
- saveWorkflow(this.root, wf);
1712
+ writeWorkflow(this.root, { workflow: wf, source: "web-ui", skipSitrep: true, quiet: true });
1383
1713
  this.broadcast();
1384
1714
  res.writeHead(200, { "Content-Type": "application/json" });
1385
1715
  res.end(JSON.stringify({ deleted: itemId }));
1386
1716
  return;
1387
1717
  }
1718
+ if (path.match(/^\/api\/items\/[^/]+\/claim$/) && req.method === "POST") {
1719
+ const itemId = path.replace("/api/items/", "").replace("/claim", "");
1720
+ const wf = this.loadWorkflow();
1721
+ if (!wf) {
1722
+ res.writeHead(404, { "Content-Type": "application/json" });
1723
+ res.end(JSON.stringify({ error: "No workflow" }));
1724
+ return;
1725
+ }
1726
+ const item = wf.items.find((i) => i.id === itemId);
1727
+ if (!item) {
1728
+ res.writeHead(404, { "Content-Type": "application/json" });
1729
+ res.end(JSON.stringify({ error: "Item not found" }));
1730
+ return;
1731
+ }
1732
+ const doneZones = new Set(wf.stages.filter((s) => s.zone === "done").map((s) => s.id));
1733
+ if (doneZones.has(item.stage)) {
1734
+ res.writeHead(400, { "Content-Type": "application/json" });
1735
+ res.end(JSON.stringify({ error: "Cannot claim a completed item" }));
1736
+ return;
1737
+ }
1738
+ item.claimedBy = "web-ui";
1739
+ item.claimedAt = (/* @__PURE__ */ new Date()).toISOString();
1740
+ wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1741
+ writeWorkflow(this.root, { workflow: wf, source: "web-ui", primaryItemId: item.id, skipSitrep: true, quiet: true });
1742
+ this.broadcast();
1743
+ res.writeHead(200, { "Content-Type": "application/json" });
1744
+ res.end(JSON.stringify(item));
1745
+ return;
1746
+ }
1747
+ if (path.match(/^\/api\/items\/[^/]+\/release$/) && req.method === "POST") {
1748
+ const itemId = path.replace("/api/items/", "").replace("/release", "");
1749
+ const wf = this.loadWorkflow();
1750
+ if (!wf) {
1751
+ res.writeHead(404, { "Content-Type": "application/json" });
1752
+ res.end(JSON.stringify({ error: "No workflow" }));
1753
+ return;
1754
+ }
1755
+ const item = wf.items.find((i) => i.id === itemId);
1756
+ if (!item) {
1757
+ res.writeHead(404, { "Content-Type": "application/json" });
1758
+ res.end(JSON.stringify({ error: "Item not found" }));
1759
+ return;
1760
+ }
1761
+ delete item.claimedBy;
1762
+ delete item.claimedAt;
1763
+ wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1764
+ writeWorkflow(this.root, { workflow: wf, source: "web-ui", skipSitrep: true, quiet: true });
1765
+ this.broadcast();
1766
+ res.writeHead(200, { "Content-Type": "application/json" });
1767
+ res.end(JSON.stringify(item));
1768
+ return;
1769
+ }
1770
+ if (path.match(/^\/api\/items\/[^/]+\/focus$/) && req.method === "POST") {
1771
+ const itemId = path.replace("/api/items/", "").replace("/focus", "");
1772
+ const wf = this.loadWorkflow();
1773
+ if (!wf) {
1774
+ res.writeHead(404, { "Content-Type": "application/json" });
1775
+ res.end(JSON.stringify({ error: "No workflow" }));
1776
+ return;
1777
+ }
1778
+ const item = wf.items.find((i) => i.id === itemId);
1779
+ if (!item) {
1780
+ res.writeHead(404, { "Content-Type": "application/json" });
1781
+ res.end(JSON.stringify({ error: "Item not found" }));
1782
+ return;
1783
+ }
1784
+ const specName = item.spec || itemId;
1785
+ writeFocusFile(this.root, specName, item.id);
1786
+ logEntry(this.root, "focus_set", `Focus set via UI: ${specName}`, { itemId });
1787
+ this.broadcast();
1788
+ res.writeHead(200, { "Content-Type": "application/json" });
1789
+ res.end(JSON.stringify({ itemId, spec: specName }));
1790
+ return;
1791
+ }
1388
1792
  if (path === "/api/workflow" && req.method === "PATCH") {
1389
1793
  let body = "";
1390
1794
  req.on("data", (chunk) => {
@@ -1403,7 +1807,7 @@ var FlowServer = class {
1403
1807
  if (data.name !== void 0) wf.name = data.name;
1404
1808
  if (data.description !== void 0) wf.description = data.description;
1405
1809
  wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1406
- saveWorkflow(this.root, wf);
1810
+ writeWorkflow(this.root, { workflow: wf, source: "web-ui", skipSitrep: true, quiet: true });
1407
1811
  this.broadcast();
1408
1812
  res.writeHead(200, { "Content-Type": "application/json" });
1409
1813
  res.end(JSON.stringify(wf));
@@ -1424,7 +1828,7 @@ var FlowServer = class {
1424
1828
  if (item) {
1425
1829
  item.stage = stage;
1426
1830
  wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1427
- saveWorkflow(this.root, wf);
1831
+ writeWorkflow(this.root, { workflow: wf, source: "web-ui", primaryItemId: itemId, skipSitrep: true, quiet: true });
1428
1832
  this.broadcast();
1429
1833
  }
1430
1834
  }
@@ -1434,15 +1838,47 @@ var FlowServer = class {
1434
1838
  return;
1435
1839
  }
1436
1840
  if (path === "/api/focus") {
1437
- const focusFile = join6(this.root, ".letra", "focus.md");
1438
- if (existsSync6(focusFile)) {
1439
- const content = readFileSync5(focusFile, "utf-8");
1841
+ if (req.method === "DELETE") {
1842
+ clearFocusFile(this.root);
1843
+ logEntry(this.root, "focus_clear", "Focus cleared via UI");
1844
+ this.broadcast();
1845
+ res.writeHead(200, { "Content-Type": "application/json" });
1846
+ res.end(JSON.stringify({ active: false }));
1847
+ return;
1848
+ }
1849
+ if (req.method === "POST") {
1850
+ let body = "";
1851
+ req.on("data", (chunk) => {
1852
+ body += chunk;
1853
+ });
1854
+ req.on("end", () => {
1855
+ try {
1856
+ const data = JSON.parse(body);
1857
+ const specName = data.spec || "unknown";
1858
+ const itemId = data.itemId || "";
1859
+ writeFocusFile(this.root, specName, itemId);
1860
+ logEntry(this.root, "focus_set", `Focus set via UI: ${specName}`, { itemId });
1861
+ this.broadcast();
1862
+ res.writeHead(200, { "Content-Type": "application/json" });
1863
+ res.end(JSON.stringify({ active: true, spec: specName, itemId }));
1864
+ } catch (e) {
1865
+ res.writeHead(400, { "Content-Type": "application/json" });
1866
+ res.end(JSON.stringify({ error: e.message }));
1867
+ }
1868
+ });
1869
+ return;
1870
+ }
1871
+ const focusFile = join9(this.root, ".letra", "focus.md");
1872
+ if (existsSync10(focusFile)) {
1873
+ const content = readFileSync9(focusFile, "utf-8");
1440
1874
  res.writeHead(200, { "Content-Type": "application/json" });
1441
1875
  const lines = content.split("\n").filter((l) => l.trim());
1876
+ const itemMatch = content.match(/\*\*Item\*\*:\s*(.+)/);
1442
1877
  res.end(
1443
1878
  JSON.stringify({
1444
1879
  active: true,
1445
1880
  spec: lines[0]?.replace(/^#\s*/, "") || "",
1881
+ itemId: itemMatch ? itemMatch[1].trim() : null,
1446
1882
  content
1447
1883
  })
1448
1884
  );
@@ -1454,15 +1890,15 @@ var FlowServer = class {
1454
1890
  }
1455
1891
  if (path === "/api/context") {
1456
1892
  const file = url.searchParams.get("file") || "context.md";
1457
- const letraDir = join6(this.root, ".letra");
1893
+ const letraDir = join9(this.root, ".letra");
1458
1894
  const allowedFiles = ["context.md", "constitution.md", "glossary.md"];
1459
1895
  if (file === "decisions") {
1460
- const decisionsDir = join6(letraDir, "decisions");
1896
+ const decisionsDir = join9(letraDir, "decisions");
1461
1897
  const files = [];
1462
- if (existsSync6(decisionsDir)) {
1898
+ if (existsSync10(decisionsDir)) {
1463
1899
  const names = readdirSync3(decisionsDir).filter((f) => f.endsWith(".md"));
1464
1900
  for (const name of names.sort().reverse()) {
1465
- const content2 = readFileSync5(join6(decisionsDir, name), "utf-8");
1901
+ const content2 = readFileSync9(join9(decisionsDir, name), "utf-8");
1466
1902
  files.push({ name, content: content2 });
1467
1903
  }
1468
1904
  }
@@ -1475,41 +1911,241 @@ var FlowServer = class {
1475
1911
  res.end(JSON.stringify({ error: `Invalid file: ${file}` }));
1476
1912
  return;
1477
1913
  }
1478
- const filePath = join6(letraDir, file);
1479
- if (!existsSync6(filePath)) {
1914
+ const filePath = join9(letraDir, file);
1915
+ if (!existsSync10(filePath)) {
1480
1916
  res.writeHead(404, { "Content-Type": "application/json" });
1481
1917
  res.end(JSON.stringify({ error: `File not found: ${file}` }));
1482
1918
  return;
1483
1919
  }
1484
- const content = readFileSync5(filePath, "utf-8");
1920
+ const content = readFileSync9(filePath, "utf-8");
1485
1921
  res.writeHead(200, { "Content-Type": "text/plain" });
1486
1922
  res.end(content);
1487
1923
  return;
1488
1924
  }
1489
- this.serveClient(path, req, res);
1490
- };
1491
- clientDir = null;
1492
- serveClient(path, req, res) {
1493
- if (!this.clientDir) {
1494
- const cliDir = dirname(fileURLToPath(import.meta.url));
1495
- const builtIn = join6(cliDir, "client");
1496
- const monorepoDev = join6(this.root, "packages", "client", "dist");
1497
- const candidates = [builtIn, monorepoDev];
1498
- for (const dir of candidates) {
1499
- const idx = join6(dir, "index.html");
1500
- if (existsSync6(idx)) {
1501
- this.clientDir = dir;
1502
- break;
1503
- }
1925
+ if (path === "/api/diagnostics" && req.method === "GET") {
1926
+ const output = this.engine.getLastOutput();
1927
+ res.writeHead(200, { "Content-Type": "application/json" });
1928
+ res.end(JSON.stringify(output));
1929
+ return;
1930
+ }
1931
+ if (path === "/api/diagnostics/snapshots" && req.method === "GET") {
1932
+ let snapshots = this.engine.listSnapshots();
1933
+ const total = snapshots.length;
1934
+ const limitParam = url.searchParams.get("limit");
1935
+ const offsetParam = url.searchParams.get("offset");
1936
+ if (limitParam !== null || offsetParam !== null) {
1937
+ const limit = limitParam ? parseInt(limitParam, 10) : total;
1938
+ const offset = offsetParam ? parseInt(offsetParam, 10) : 0;
1939
+ snapshots = snapshots.slice(offset, offset + limit);
1940
+ res.writeHead(200, { "Content-Type": "application/json" });
1941
+ res.end(JSON.stringify({ snapshots, total, limit, offset }));
1942
+ } else {
1943
+ res.writeHead(200, { "Content-Type": "application/json" });
1944
+ res.end(JSON.stringify({ snapshots }));
1504
1945
  }
1946
+ return;
1505
1947
  }
1506
- if (!this.clientDir) {
1507
- this.proxyToVite(req, res);
1948
+ if (path === "/api/diagnostics/scan" && req.method === "POST") {
1949
+ this.engine.runAll().then((output) => {
1950
+ this.broadcastDiagnostics(output);
1951
+ res.writeHead(200, { "Content-Type": "application/json" });
1952
+ res.end(JSON.stringify(output));
1953
+ }).catch((e) => {
1954
+ res.writeHead(500, { "Content-Type": "application/json" });
1955
+ res.end(JSON.stringify({ error: e.message }));
1956
+ });
1508
1957
  return;
1509
1958
  }
1510
- let filePath = join6(this.clientDir, path === "/" ? "index.html" : path);
1511
- if (!existsSync6(filePath)) {
1512
- filePath = join6(this.clientDir, "index.html");
1959
+ if (path.match(/^\/api\/diagnostics\/undo\/[^/]+$/) && req.method === "POST") {
1960
+ const snapshotId = path.replace("/api/diagnostics/undo/", "");
1961
+ this.engine.undo(snapshotId).then((result) => {
1962
+ if (!result.ok) {
1963
+ res.writeHead(404, { "Content-Type": "application/json" });
1964
+ res.end(JSON.stringify({ error: "Snapshot not found" }));
1965
+ return;
1966
+ }
1967
+ this.broadcast();
1968
+ res.writeHead(200, { "Content-Type": "application/json" });
1969
+ res.end(JSON.stringify(result));
1970
+ }).catch((e) => {
1971
+ res.writeHead(500, { "Content-Type": "application/json" });
1972
+ res.end(JSON.stringify({ error: e.message }));
1973
+ });
1974
+ return;
1975
+ }
1976
+ if (path.match(/^\/api\/diagnostics\/redo\/[^/]+$/) && req.method === "POST") {
1977
+ const snapshotId = path.replace("/api/diagnostics/redo/", "");
1978
+ this.engine.redo(snapshotId).then((result) => {
1979
+ if (!result.ok) {
1980
+ res.writeHead(404, { "Content-Type": "application/json" });
1981
+ res.end(JSON.stringify({ error: "Snapshot not found" }));
1982
+ return;
1983
+ }
1984
+ this.broadcast();
1985
+ res.writeHead(200, { "Content-Type": "application/json" });
1986
+ res.end(JSON.stringify(result));
1987
+ }).catch((e) => {
1988
+ res.writeHead(500, { "Content-Type": "application/json" });
1989
+ res.end(JSON.stringify({ error: e.message }));
1990
+ });
1991
+ return;
1992
+ }
1993
+ if (path === "/api/health" && req.method === "GET") {
1994
+ const record = loadHealthRecord(this.root);
1995
+ const summary = getSummary(record);
1996
+ const active = getActiveEntries(record);
1997
+ res.writeHead(200, { "Content-Type": "application/json" });
1998
+ res.end(JSON.stringify({ summary, entries: record.entries, active }));
1999
+ return;
2000
+ }
2001
+ if (path === "/api/health/alerts" && req.method === "GET") {
2002
+ const record = loadHealthRecord(this.root);
2003
+ const alerts = record.entries.filter((e) => e.status === "novo");
2004
+ res.writeHead(200, { "Content-Type": "application/json" });
2005
+ res.end(JSON.stringify(alerts));
2006
+ return;
2007
+ }
2008
+ if (path === "/api/health/scan" && req.method === "POST") {
2009
+ this.engine.runAll().then((output) => {
2010
+ const suggestions = output.suggestions.map((s) => ({
2011
+ id: s.id,
2012
+ type: s.type,
2013
+ title: s.title,
2014
+ description: s.description,
2015
+ certainty: 0.8,
2016
+ detector: s.detector
2017
+ }));
2018
+ const record = loadHealthRecord(this.root);
2019
+ mergeScanResults(record, suggestions);
2020
+ saveHealthRecord(this.root, record);
2021
+ this.broadcastDiagnostics(output);
2022
+ res.writeHead(200, { "Content-Type": "application/json" });
2023
+ res.end(JSON.stringify({ fixes: output.fixes.length, suggestions: output.suggestions.length }));
2024
+ }).catch((e) => {
2025
+ res.writeHead(500, { "Content-Type": "application/json" });
2026
+ res.end(JSON.stringify({ error: e.message }));
2027
+ });
2028
+ return;
2029
+ }
2030
+ if (path === "/api/health/ack" && req.method === "POST") {
2031
+ let body = "";
2032
+ req.on("data", (chunk) => {
2033
+ body += chunk;
2034
+ });
2035
+ req.on("end", () => {
2036
+ try {
2037
+ const { id } = JSON.parse(body);
2038
+ const record = loadHealthRecord(this.root);
2039
+ if (ackEntry(record, id)) {
2040
+ saveHealthRecord(this.root, record);
2041
+ this.broadcast();
2042
+ res.writeHead(200, { "Content-Type": "application/json" });
2043
+ res.end(JSON.stringify({ acked: id }));
2044
+ } else {
2045
+ res.writeHead(404, { "Content-Type": "application/json" });
2046
+ res.end(JSON.stringify({ error: "Entry not found" }));
2047
+ }
2048
+ } catch (e) {
2049
+ res.writeHead(400, { "Content-Type": "application/json" });
2050
+ res.end(JSON.stringify({ error: e.message }));
2051
+ }
2052
+ });
2053
+ return;
2054
+ }
2055
+ if (path === "/api/health/dismiss" && req.method === "POST") {
2056
+ let body = "";
2057
+ req.on("data", (chunk) => {
2058
+ body += chunk;
2059
+ });
2060
+ req.on("end", () => {
2061
+ try {
2062
+ const { id, reason } = JSON.parse(body);
2063
+ const record = loadHealthRecord(this.root);
2064
+ if (dismissEntry(record, id, reason)) {
2065
+ saveHealthRecord(this.root, record);
2066
+ this.broadcast();
2067
+ res.writeHead(200, { "Content-Type": "application/json" });
2068
+ res.end(JSON.stringify({ dismissed: id }));
2069
+ } else {
2070
+ res.writeHead(404, { "Content-Type": "application/json" });
2071
+ res.end(JSON.stringify({ error: "Entry not found" }));
2072
+ }
2073
+ } catch (e) {
2074
+ res.writeHead(400, { "Content-Type": "application/json" });
2075
+ res.end(JSON.stringify({ error: e.message }));
2076
+ }
2077
+ });
2078
+ return;
2079
+ }
2080
+ if (path === "/api/items/alerts" && req.method === "GET") {
2081
+ const record = loadHealthRecord(this.root);
2082
+ const itemAlerts = {};
2083
+ for (const entry of record.entries) {
2084
+ if (entry.status !== "novo") continue;
2085
+ const match = entry.id.match(/_([A-Z]+-\d+)_/);
2086
+ if (match) {
2087
+ const itemId = match[1];
2088
+ itemAlerts[itemId] = (itemAlerts[itemId] || 0) + 1;
2089
+ }
2090
+ }
2091
+ res.writeHead(200, { "Content-Type": "application/json" });
2092
+ res.end(JSON.stringify({ itemAlerts }));
2093
+ return;
2094
+ }
2095
+ if (path === "/api/log" && req.method === "GET") {
2096
+ const itemId = url.searchParams.get("item") ?? void 0;
2097
+ const action = url.searchParams.get("action") ?? void 0;
2098
+ const since = url.searchParams.get("since") ?? void 0;
2099
+ const all = url.searchParams.get("all") === "true";
2100
+ const limitParam = url.searchParams.get("limit");
2101
+ const entries = queryLog(this.root, {
2102
+ all,
2103
+ itemId,
2104
+ action,
2105
+ since,
2106
+ limit: limitParam ? parseInt(limitParam, 10) : 50
2107
+ });
2108
+ res.writeHead(200, { "Content-Type": "application/json" });
2109
+ res.end(JSON.stringify({ entries }));
2110
+ return;
2111
+ }
2112
+ if (path === "/api/sitrep" && req.method === "POST") {
2113
+ const dryRun = url.searchParams.get("dryRun") === "true";
2114
+ await sitrep(this.root, { dryRun });
2115
+ res.writeHead(200, { "Content-Type": "application/json" });
2116
+ res.end(JSON.stringify({ ok: true }));
2117
+ return;
2118
+ }
2119
+ if (path === "/api/pulse" && req.method === "GET") {
2120
+ const data = await pulse(this.root, { json: false });
2121
+ res.writeHead(200, { "Content-Type": "application/json" });
2122
+ res.end(JSON.stringify(data));
2123
+ return;
2124
+ }
2125
+ this.serveClient(path, req, res);
2126
+ };
2127
+ clientDir = null;
2128
+ serveClient(path, req, res) {
2129
+ if (!this.clientDir) {
2130
+ const cliDir = dirname(fileURLToPath(import.meta.url));
2131
+ const builtIn = join9(cliDir, "client");
2132
+ const monorepoDev = join9(this.root, "packages", "client", "dist");
2133
+ const candidates = [builtIn, monorepoDev];
2134
+ for (const dir of candidates) {
2135
+ const idx = join9(dir, "index.html");
2136
+ if (existsSync10(idx)) {
2137
+ this.clientDir = dir;
2138
+ break;
2139
+ }
2140
+ }
2141
+ }
2142
+ if (!this.clientDir) {
2143
+ this.proxyToVite(req, res);
2144
+ return;
2145
+ }
2146
+ let filePath = join9(this.clientDir, path === "/" ? "index.html" : path);
2147
+ if (!existsSync10(filePath)) {
2148
+ filePath = join9(this.clientDir, "index.html");
1513
2149
  }
1514
2150
  const ext = extname(filePath);
1515
2151
  const mime = {
@@ -1523,7 +2159,7 @@ var FlowServer = class {
1523
2159
  };
1524
2160
  const contentType = mime[ext] ?? "application/octet-stream";
1525
2161
  res.writeHead(200, { "Content-Type": contentType });
1526
- res.end(readFileSync5(filePath));
2162
+ res.end(readFileSync9(filePath));
1527
2163
  }
1528
2164
  proxyToVite(req, res) {
1529
2165
  const proxyUrl = `http://localhost:5173${req.url}`;
@@ -1555,6 +2191,20 @@ var FlowServer = class {
1555
2191
  }
1556
2192
  }
1557
2193
  }
2194
+ broadcastDiagnostics(output) {
2195
+ if (this.clients.size === 0) return;
2196
+ const data = `event: diagnostics-updated
2197
+ data: ${JSON.stringify({ fixes: output.fixes.length, suggestions: output.suggestions.length, errors: output.errors.length })}
2198
+
2199
+ `;
2200
+ for (const client of this.clients) {
2201
+ try {
2202
+ client.write(data);
2203
+ } catch {
2204
+ this.clients.delete(client);
2205
+ }
2206
+ }
2207
+ }
1558
2208
  async fireWebhooks(event, payload) {
1559
2209
  const wf = this.loadWorkflow();
1560
2210
  if (!wf?.webhooks || wf.webhooks.length === 0) return;
@@ -1579,26 +2229,68 @@ var FlowServer = class {
1579
2229
  }
1580
2230
  wh.lastSentAt = (/* @__PURE__ */ new Date()).toISOString();
1581
2231
  }
1582
- saveWorkflow(this.root, wf);
2232
+ writeWorkflow(this.root, { workflow: wf, source: "web-ui", skipAdapters: true, skipSitrep: true, skipLog: true, quiet: true });
1583
2233
  }
1584
2234
  start() {
1585
- return new Promise((resolve17, reject) => {
2235
+ return new Promise((resolve24, reject) => {
1586
2236
  this.server = createServer(this.handleRequest);
1587
2237
  this.server.listen(this.port, () => {
1588
- const wfPath = join6(this.root, ".letra", "workflow.json");
1589
- if (existsSync6(wfPath)) {
2238
+ const wfPath = join9(this.root, ".letra", "workflow.json");
2239
+ if (existsSync10(wfPath)) {
1590
2240
  try {
1591
2241
  this.watcher = watch(wfPath, () => this.broadcast());
1592
2242
  } catch {
1593
2243
  }
1594
2244
  }
1595
- resolve17();
2245
+ const specsDir = join9(this.root, ".letra", "specs");
2246
+ if (existsSync10(specsDir)) {
2247
+ try {
2248
+ this.specsWatcher = watch(specsDir, { recursive: true }, () => this.broadcast());
2249
+ } catch {
2250
+ }
2251
+ }
2252
+ this.engine.ensureDirs();
2253
+ this.engine.runAll().then((output) => {
2254
+ this.broadcastDiagnostics(output);
2255
+ const suggestions = output.suggestions.map((s) => ({
2256
+ id: s.id,
2257
+ type: s.type,
2258
+ title: s.title,
2259
+ description: s.description,
2260
+ certainty: 0.8,
2261
+ detector: s.detector
2262
+ }));
2263
+ const record = loadHealthRecord(this.root);
2264
+ mergeScanResults(record, suggestions);
2265
+ saveHealthRecord(this.root, record);
2266
+ }).catch(() => {
2267
+ });
2268
+ this.diagnosticsTimer = setInterval(() => {
2269
+ this.engine.runAll().then((output) => {
2270
+ this.broadcastDiagnostics(output);
2271
+ const suggestions = output.suggestions.map((s) => ({
2272
+ id: s.id,
2273
+ type: s.type,
2274
+ title: s.title,
2275
+ description: s.description,
2276
+ certainty: 0.8,
2277
+ detector: s.detector
2278
+ }));
2279
+ const record = loadHealthRecord(this.root);
2280
+ mergeScanResults(record, suggestions);
2281
+ saveHealthRecord(this.root, record);
2282
+ }).catch(() => {
2283
+ });
2284
+ }, 3e4);
2285
+ resolve24();
1596
2286
  });
1597
2287
  this.server.on("error", reject);
1598
2288
  });
1599
2289
  }
1600
2290
  stop() {
1601
2291
  if (this.watcher) this.watcher.close();
2292
+ if (this.specsWatcher) this.specsWatcher.close();
2293
+ if (this.diagnosticsTimer) clearInterval(this.diagnosticsTimer);
1602
2294
  if (this.server) this.server.close();
1603
2295
  for (const client of this.clients) {
1604
2296
  client.destroy();
@@ -1610,7 +2302,7 @@ var FlowServer = class {
1610
2302
  }
1611
2303
  };
1612
2304
  async function flowServeAction(targetPath, options) {
1613
- const root = resolve9(process.cwd(), targetPath ?? ".");
2305
+ const root = resolve11(process.cwd(), targetPath ?? ".");
1614
2306
  const port = options?.port ?? DEFAULT_PORT;
1615
2307
  const wf = loadWorkflow(root);
1616
2308
  if (!wf) {
@@ -1625,17 +2317,17 @@ async function flowServeAction(targetPath, options) {
1625
2317
  `);
1626
2318
  console.log(" Press Ctrl+C to stop\n");
1627
2319
  if (options?.open) {
1628
- const { execSync: execSync2 } = await import("child_process");
2320
+ const { execSync } = await import("child_process");
1629
2321
  const cmd = process.platform === "win32" ? "start" : process.platform === "darwin" ? "open" : "xdg-open";
1630
2322
  try {
1631
- execSync2(`${cmd} http://localhost:${port}`, { stdio: "ignore" });
2323
+ execSync(`${cmd} http://localhost:${port}`, { stdio: "ignore" });
1632
2324
  } catch {
1633
2325
  }
1634
2326
  }
1635
- await new Promise((resolve17) => {
2327
+ await new Promise((resolve24) => {
1636
2328
  process.on("SIGINT", () => {
1637
2329
  server.stop();
1638
- resolve17();
2330
+ resolve24();
1639
2331
  });
1640
2332
  });
1641
2333
  } catch (err) {
@@ -1646,8 +2338,8 @@ async function flowServeAction(targetPath, options) {
1646
2338
 
1647
2339
  // src/commands/flow-visualize.ts
1648
2340
  import { writeFileSync as writeFileSync7 } from "fs";
1649
- import { resolve as resolve10 } from "path";
1650
- import chalk9 from "chalk";
2341
+ import { resolve as resolve12 } from "path";
2342
+ import chalk11 from "chalk";
1651
2343
  var MERMAID_LIVE = "https://mermaid.live/edit#";
1652
2344
  function generateMermaid(workflow) {
1653
2345
  const sorted = [...workflow.stages].sort((a, b) => a.order - b.order);
@@ -1697,12 +2389,12 @@ ${mermaid}
1697
2389
  function flowVisualize(root, options) {
1698
2390
  const workflow = loadWorkflow(root);
1699
2391
  if (!workflow) {
1700
- console.log(chalk9.yellow("No workflow found. Run 'letra flow init --quick' first"));
2392
+ console.log(chalk11.yellow("No workflow found. Run 'letra flow init --quick' first"));
1701
2393
  return;
1702
2394
  }
1703
2395
  const mermaid = generateMermaid(workflow);
1704
2396
  if (options?.output) {
1705
- const outputPath = resolve10(root, options.output);
2397
+ const outputPath = resolve12(root, options.output);
1706
2398
  const ext = options.output.toLowerCase().split(".").pop();
1707
2399
  let content;
1708
2400
  let label;
@@ -1724,24 +2416,24 @@ ${mermaid}
1724
2416
  console.log(`${label} saved to ${options.output}`);
1725
2417
  } else {
1726
2418
  console.log(mermaid);
1727
- console.log(chalk9.dim(`
2419
+ console.log(chalk11.dim(`
1728
2420
  Copy to ${MERMAID_LIVE} to render`));
1729
2421
  }
1730
2422
  }
1731
2423
  function flowVisualizeAction(targetPath, options) {
1732
- const root = resolve10(process.cwd(), targetPath || ".");
2424
+ const root = resolve12(process.cwd(), targetPath || ".");
1733
2425
  flowVisualize(root, options);
1734
2426
  }
1735
2427
 
1736
2428
  // src/commands/flow.ts
1737
2429
  function flowCommand() {
1738
- const cmd = new Command2("flow");
2430
+ const cmd = new Command3("flow");
1739
2431
  cmd.command("init [path]").option("--quick", "Quick setup with 3 questions only").description("Initialize workflow in .letra/workflow.json").action((path, options) => {
1740
2432
  flowInitAction(path, { quick: options.quick });
1741
2433
  });
1742
2434
  const backlog = cmd.command("backlog").description("Manage backlog items");
1743
- backlog.command("add <description>").description("Add item to the first stage").action((description) => {
1744
- backlogActionAdd(void 0, description);
2435
+ backlog.command("add <description>").option("--spec <name>", "Spec name to link").description("Add item to the first stage").action((description, options) => {
2436
+ backlogActionAdd(void 0, description, options.spec);
1745
2437
  });
1746
2438
  backlog.command("list").description("List all items with stage and age").action(() => {
1747
2439
  backlogActionList(void 0);
@@ -1753,7 +2445,11 @@ function flowCommand() {
1753
2445
  importCmd.command("linear <team>").option("--limit <number>", "Max issues to import", "50").description("Import issues from a Linear team").action((team, options) => {
1754
2446
  backlogImportLinearAction(void 0, team, options);
1755
2447
  });
1756
- cmd.command("move <item-id>").requiredOption("--to <stage>", "Target stage id or name").description("Move item to another stage and regenerate adapters").action((itemId, options) => {
2448
+ cmd.command("move <item-id>").option("--to <stage>", "Target stage id or name").option("--auto", "Automatically discover next stage by order").option("--force", "Skip pre-move validation (pending ACs, etc)").description("Move item to another stage and regenerate adapters").action((itemId, options) => {
2449
+ if (!options.to && !options.auto) {
2450
+ console.log(chalk12.red("Either --to or --auto is required"));
2451
+ process.exit(1);
2452
+ }
1757
2453
  flowMoveAction(void 0, itemId, options);
1758
2454
  });
1759
2455
  cmd.command("board").description("Show board with all stages and items").action(() => {
@@ -1774,6 +2470,15 @@ function flowCommand() {
1774
2470
  cmd.command("visualize").option("--output <file>", "Save diagram to file").description("Generate Mermaid diagram of workflow").action((options) => {
1775
2471
  flowVisualizeAction(void 0, options);
1776
2472
  });
2473
+ cmd.command("claim <item-id>").description("Claim an item (mark as being worked on)").action(async (itemId) => {
2474
+ await claimAction(void 0, itemId);
2475
+ });
2476
+ cmd.command("release").option("--item <id>", "Specific item to release (releases all by default)").description("Release claimed item(s)").action(async (options) => {
2477
+ await releaseAction(void 0, options);
2478
+ });
2479
+ cmd.command("ac <item-id> <ac-number>").description("Mark an acceptance criterion as completed in the spec file").action((itemId, acNumber) => {
2480
+ flowAcAction(void 0, itemId, acNumber);
2481
+ });
1777
2482
  cmd.command("edit").option("--name <name>", "New workflow name").option("--desc <desc>", "New workflow description").description("Edit workflow metadata").action((options) => {
1778
2483
  flowEditAction(void 0, options);
1779
2484
  });
@@ -1785,879 +2490,620 @@ function flowCommand() {
1785
2490
  }
1786
2491
 
1787
2492
  // src/commands/focus.ts
1788
- import { existsSync as existsSync7, readFileSync as readFileSync6, unlinkSync, writeFileSync as writeFileSync8 } from "fs";
1789
- import { join as join7, resolve as resolve11 } from "path";
1790
- import chalk10 from "chalk";
1791
- import { Command as Command3 } from "commander";
1792
- function extractOutcome(specDir) {
1793
- const specFile = join7(specDir, "spec.md");
1794
- if (!existsSync7(specFile)) return null;
1795
- const content = readFileSync6(specFile, "utf-8");
1796
- const match = content.match(/## Outcome\s+([\s\S]*?)(?=\n## |\n*$)/);
1797
- return match ? match[1].trim() : null;
1798
- }
2493
+ import { existsSync as existsSync11, readFileSync as readFileSync10 } from "fs";
2494
+ import { join as join10, resolve as resolve13 } from "path";
2495
+ import chalk13 from "chalk";
2496
+ import { Command as Command4 } from "commander";
1799
2497
  function focus_default() {
1800
- return new Command3("focus").argument("[spec]", "Spec name to focus on").option("--clear", "Remove focus file").action((spec, options) => {
1801
- const root = resolve11(process.cwd());
1802
- const focusFile = join7(root, ".letra", "focus.md");
2498
+ return new Command4("focus").argument("[spec]", "Spec name to focus on").option("--claim", "Also claim the item (set claimedBy)").option("--clear", "Remove focus file").action(async (spec, options) => {
2499
+ const root = resolve13(process.cwd());
2500
+ const focusFile = join10(root, ".letra", "focus.md");
1803
2501
  if (options.clear) {
1804
- if (existsSync7(focusFile)) {
1805
- unlinkSync(focusFile);
1806
- console.log(chalk10.green("Focus removed."));
2502
+ if (existsSync11(focusFile)) {
2503
+ clearFocusFile(root);
2504
+ logEntry(root, "focus_set", "Foco removido");
2505
+ console.log(chalk13.green("Focus removed."));
1807
2506
  } else {
1808
- console.log(chalk10.yellow("No focus to remove."));
2507
+ console.log(chalk13.yellow("No focus to remove."));
2508
+ }
2509
+ const workflow = loadWorkflow(root);
2510
+ if (workflow) {
2511
+ let releasedCount = 0;
2512
+ for (const item of workflow.items) {
2513
+ if (item.claimedBy) {
2514
+ logEntry(root, "item_release", `Auto-release on focus clear: ${item.id}`, { itemId: item.id });
2515
+ delete item.claimedBy;
2516
+ delete item.claimedAt;
2517
+ releasedCount++;
2518
+ }
2519
+ }
2520
+ if (releasedCount > 0) {
2521
+ console.log(chalk13.gray(` Released ${releasedCount} item(s).`));
2522
+ }
2523
+ await writeWorkflow(root, {
2524
+ workflow,
2525
+ source: "focus",
2526
+ skipSitrep: true,
2527
+ quiet: true
2528
+ });
1809
2529
  }
1810
2530
  return;
1811
2531
  }
1812
2532
  if (spec) {
1813
- const specDir = join7(root, ".letra", "specs", spec);
1814
- const specFile = join7(specDir, "spec.md");
1815
- if (!existsSync7(specFile)) {
1816
- console.log(chalk10.red(`Spec "${spec}" not found`));
2533
+ const specDir = join10(root, ".letra", "specs", spec);
2534
+ const specFile = join10(specDir, "spec.md");
2535
+ if (!existsSync11(specFile)) {
2536
+ console.log(chalk13.red(`Spec "${spec}" not found`));
1817
2537
  process.exit(1);
1818
2538
  }
1819
- const outcome = extractOutcome(specDir);
1820
- const outcomeLine = `**Outcome**: ${outcome || spec}`;
1821
- const focusContent = [
1822
- `# Focus: ${spec}`,
1823
- "",
1824
- `**Path**: .letra/specs/${spec}/`,
1825
- outcomeLine,
1826
- ""
1827
- ].join("\n");
1828
- writeFileSync8(focusFile, focusContent);
1829
- console.log(chalk10.green(`Focus set to "${spec}".`));
2539
+ const workflow = loadWorkflow(root);
2540
+ let itemId = "";
2541
+ let activeStageId = "code";
2542
+ if (workflow) {
2543
+ const itemWithSpec = workflow.items.find((item) => item.spec === spec);
2544
+ if (itemWithSpec) {
2545
+ itemId = itemWithSpec.id;
2546
+ activeStageId = itemWithSpec.stage;
2547
+ } else {
2548
+ const codeStage = workflow.stages.find(
2549
+ (s) => s.id === "code" || s.name.toLowerCase() === "code"
2550
+ );
2551
+ activeStageId = codeStage ? codeStage.id : workflow.stages[0]?.id;
2552
+ }
2553
+ }
2554
+ if (options.claim && workflow && itemId) {
2555
+ const itemWithSpec = workflow.items.find((item) => item.spec === spec);
2556
+ if (itemWithSpec && itemWithSpec.id === itemId) {
2557
+ for (const other of workflow.items) {
2558
+ if (other.claimedBy === "opencode" && other.id !== itemId) {
2559
+ logEntry(root, "item_release", `Auto-release on refocus: ${other.id}`, { itemId: other.id });
2560
+ delete other.claimedBy;
2561
+ delete other.claimedAt;
2562
+ }
2563
+ }
2564
+ itemWithSpec.claimedBy = "opencode";
2565
+ itemWithSpec.claimedAt = (/* @__PURE__ */ new Date()).toISOString();
2566
+ console.log(chalk13.gray(` Claimed ${itemId}.`));
2567
+ logEntry(root, "item_claim", `Auto-claim: ${itemId}`, { itemId, by: "opencode" });
2568
+ }
2569
+ }
2570
+ writeFocusFile(root, spec, itemId);
2571
+ logEntry(root, "focus_set", `Foco definido: ${spec}`, { itemId });
2572
+ console.log(chalk13.green(`Focus set to "${spec}".`));
2573
+ if (workflow) {
2574
+ await writeWorkflow(root, {
2575
+ workflow,
2576
+ source: "focus",
2577
+ primaryItemId: itemId || void 0,
2578
+ skipSitrep: true,
2579
+ quiet: true
2580
+ });
2581
+ }
1830
2582
  return;
1831
2583
  }
1832
- if (existsSync7(focusFile)) {
1833
- console.log(readFileSync6(focusFile, "utf-8"));
2584
+ if (existsSync11(focusFile)) {
2585
+ console.log(readFileSync10(focusFile, "utf-8"));
1834
2586
  } else {
1835
2587
  console.log("Nenhum foco definido.");
1836
2588
  }
1837
2589
  });
1838
2590
  }
1839
2591
 
1840
- // src/commands/init.ts
1841
- import { existsSync as existsSync8, mkdirSync as mkdirSync5, writeFileSync as writeFileSync9 } from "fs";
1842
- import { join as join8, resolve as resolve12 } from "path";
1843
- import { createInterface as createInterface2 } from "readline";
1844
- import { fileURLToPath as fileURLToPath2 } from "url";
1845
- import chalk11 from "chalk";
1846
- import ora2 from "ora";
1847
- var __dirname = fileURLToPath2(new URL(".", import.meta.url));
1848
- function ask(query, options) {
1849
- if (!process.stdin.isTTY) return Promise.resolve(options[0]);
1850
- const rl = createInterface2({ input: process.stdin, output: process.stdout });
1851
- return new Promise((resolve17) => {
1852
- const formatted = `${chalk11.cyan(query)} ${options.map((o) => chalk11.gray(`(${o})`)).join(" ")}
1853
- > `;
1854
- rl.question(formatted, (answer) => {
1855
- rl.close();
1856
- const trimmed = answer.trim().toLowerCase();
1857
- if (trimmed && options.some((o) => o.toLowerCase().startsWith(trimmed))) {
1858
- resolve17(options.find((o) => o.toLowerCase().startsWith(trimmed)) ?? options[0]);
1859
- } else if (trimmed && options.includes(trimmed)) {
1860
- resolve17(trimmed);
1861
- } else {
1862
- resolve17(options[0]);
2592
+ // src/commands/health.ts
2593
+ import { resolve as resolve14 } from "path";
2594
+ import chalk14 from "chalk";
2595
+ import { Command as Command5 } from "commander";
2596
+ function health_default() {
2597
+ const cmd = new Command5("health").description("Manage health record \u2014 persistent diagnostic state");
2598
+ cmd.option("--json", "Output in JSON format").option("--all", "Show all entries including resolved and dismissed").action((options) => {
2599
+ const root = resolve14(process.cwd());
2600
+ const record = loadHealthRecord(root);
2601
+ const summary = getSummary(record);
2602
+ if (options.json) {
2603
+ console.log(JSON.stringify({ summary, entries: record.entries }, null, 2));
2604
+ return;
2605
+ }
2606
+ console.log(`
2607
+ ${chalk14.bold("\u{1F4CB} Prontu\xE1rio de Sa\xFAde")}
2608
+ `);
2609
+ console.log(` ${chalk14.red(`${summary.novo} novo(s)${summary.alta > 0 ? ` (${summary.alta} cr\xEDtico(s))` : ""}`)}`);
2610
+ console.log(` ${chalk14.yellow(`${summary.ciente} em acompanhamento`)}`);
2611
+ console.log(` ${chalk14.gray(`${summary.resolvido} resolvido(s)`)}`);
2612
+ console.log(` ${chalk14.gray(`${summary.descartado} descartado(s)`)}`);
2613
+ console.log();
2614
+ if (summary.novo === 0 && summary.ciente === 0) {
2615
+ console.log(" Nenhum alerta ativo. Tudo ok.");
2616
+ }
2617
+ const entries = options.all ? record.entries : getActiveEntries(record);
2618
+ if (entries.length > 0) {
2619
+ for (const entry of entries) {
2620
+ const color = entry.severity === "alta" ? chalk14.red : entry.severity === "media" ? chalk14.yellow : chalk14.blue;
2621
+ console.log(` ${color(entry.id)} \u2014 ${entry.title}`);
2622
+ console.log(` ${chalk14.gray(`${entry.status} | ${entry.severity} | ${entry.source} | ${new Date(entry.detectedAt).toLocaleString()}`)}`);
1863
2623
  }
2624
+ console.log();
2625
+ }
2626
+ });
2627
+ cmd.command("scan").description("Run diagnostics and merge into health record").action(async () => {
2628
+ const root = resolve14(process.cwd());
2629
+ const engine = new DiagnosticEngine(root);
2630
+ engine.ensureDirs();
2631
+ const output = await engine.runAll();
2632
+ const suggestions = output.suggestions.map((s) => ({
2633
+ id: s.id,
2634
+ type: s.type,
2635
+ title: s.title,
2636
+ description: s.description,
2637
+ certainty: 0.8,
2638
+ detector: s.detector
2639
+ }));
2640
+ const record = loadHealthRecord(root);
2641
+ mergeScanResults(record, suggestions);
2642
+ saveHealthRecord(root, record);
2643
+ logEntry(root, "health_scan", `Scan de sa\xFAde executado \u2014 ${output.fixes.length} auto-corre\xE7\xE3o(\xF5es), ${output.suggestions.length} sugest\xE3o(\xF5es)`, {
2644
+ details: { fixes: output.fixes.length, suggestions: output.suggestions.length }
1864
2645
  });
2646
+ const wf = loadWorkflow(root);
2647
+ if (wf) {
2648
+ const activeStageId = wf.stages.find((s) => wf.items.some((i) => i.stage === s.id))?.id ?? wf.stages[0]?.id;
2649
+ if (activeStageId) {
2650
+ generateAdapters(root, wf.tools, {
2651
+ source: "flow-move",
2652
+ workflow: wf,
2653
+ activeStageId,
2654
+ quiet: true,
2655
+ verb: "Updated"
2656
+ });
2657
+ }
2658
+ }
2659
+ console.log(chalk14.green(`
2660
+ \u2705 Scan conclu\xEDdo. ${output.fixes.length} auto-corre\xE7\xE3o(\xF5es), ${output.suggestions.length} sugest\xE3o(\xF5es) registradas.
2661
+ `));
2662
+ });
2663
+ cmd.command("ack <id>").description("Acknowledge a health entry").action((id) => {
2664
+ const root = resolve14(process.cwd());
2665
+ const record = loadHealthRecord(root);
2666
+ if (ackEntry(record, id)) {
2667
+ saveHealthRecord(root, record);
2668
+ const wf = loadWorkflow(root);
2669
+ if (wf) {
2670
+ const activeStageId = wf.stages.find((s) => wf.items.some((i) => i.stage === s.id))?.id ?? wf.stages[0]?.id;
2671
+ if (activeStageId) {
2672
+ generateAdapters(root, wf.tools, {
2673
+ source: "flow-move",
2674
+ workflow: wf,
2675
+ activeStageId,
2676
+ quiet: true,
2677
+ verb: "Updated"
2678
+ });
2679
+ }
2680
+ }
2681
+ logEntry(root, "health_ack", `Alerta ${id} reconhecido`);
2682
+ console.log(chalk14.green(`Entrada ${id} reconhecida.`));
2683
+ } else {
2684
+ console.log(chalk14.red(`Entrada ${id} n\xE3o encontrada.`));
2685
+ process.exit(1);
2686
+ }
2687
+ });
2688
+ cmd.command("dismiss <id>").description("Dismiss a health entry").option("--reason <reason>", "Dismiss reason").action((id, options) => {
2689
+ const root = resolve14(process.cwd());
2690
+ const record = loadHealthRecord(root);
2691
+ if (dismissEntry(record, id, options.reason)) {
2692
+ saveHealthRecord(root, record);
2693
+ const wf = loadWorkflow(root);
2694
+ if (wf) {
2695
+ const activeStageId = wf.stages.find((s) => wf.items.some((i) => i.stage === s.id))?.id ?? wf.stages[0]?.id;
2696
+ if (activeStageId) {
2697
+ generateAdapters(root, wf.tools, {
2698
+ source: "flow-move",
2699
+ workflow: wf,
2700
+ activeStageId,
2701
+ quiet: true,
2702
+ verb: "Updated"
2703
+ });
2704
+ }
2705
+ }
2706
+ logEntry(root, "health_dismiss", `Alerta ${id} descartado${options.reason ? `: ${options.reason}` : ""}`, {
2707
+ details: { reason: options.reason }
2708
+ });
2709
+ console.log(chalk14.green(`Entrada ${id} descartada.`));
2710
+ } else {
2711
+ console.log(chalk14.red(`Entrada ${id} n\xE3o encontrada.`));
2712
+ process.exit(1);
2713
+ }
1865
2714
  });
2715
+ return cmd;
1866
2716
  }
1867
- function adaptConfig(projectType) {
1868
- const config = {
1869
- "conteudo-minimo": { severity: "warning", minChars: 50 },
1870
- "consistencia-terminologia": { severity: "warning" },
1871
- "detecao-tom": {
1872
- severity: "warning",
1873
- blacklist: ["tipo", "t\xE1", "pra", "blz", "kkk", "eita", "oi", "oi pessoal"]
1874
- },
1875
- "drift-temporal": { severity: "warning", maxDays: 30 },
1876
- "secoes-vazias": { severity: "warning" },
1877
- "acs-sem-metrica": { severity: "warning" },
1878
- "baixa-confianca": { severity: "warning" }
1879
- };
1880
- if (projectType === "library") {
1881
- config["detecao-tom"] = { severity: "off" };
1882
- config["drift-temporal"] = { severity: "warning", maxDays: 60 };
1883
- } else if (projectType === "mobile") {
1884
- config["drift-temporal"] = { severity: "error", maxDays: 14 };
1885
- config["baixa-confianca"] = { severity: "error" };
1886
- } else if (projectType === "cli") {
1887
- config["detecao-tom"] = { severity: "off" };
1888
- }
1889
- return JSON.stringify({ heuristics: config }, null, 2);
2717
+
2718
+ // src/commands/log.ts
2719
+ import { resolve as resolve15 } from "path";
2720
+ import chalk15 from "chalk";
2721
+ import { Command as Command6 } from "commander";
2722
+ function log_default() {
2723
+ const cmd = new Command6("log").description("Session log \u2014 continuity between agent sessions");
2724
+ cmd.option("--all", "Show all entries").option("--json", "Output in JSON format").option("--item <id>", "Filter by item ID").option("--action <action>", "Filter by action type").option("--since <date>", "Filter by date (ISO or YYYY-MM-DD)").action((options) => {
2725
+ const root = resolve15(process.cwd());
2726
+ const entries = queryLog(root, {
2727
+ all: options.all,
2728
+ itemId: options.item,
2729
+ action: options.action,
2730
+ since: options.since
2731
+ });
2732
+ if (options.json) {
2733
+ console.log(JSON.stringify({ entries }, null, 2));
2734
+ return;
2735
+ }
2736
+ if (entries.length === 0) {
2737
+ console.log("Nenhum registro encontrado.");
2738
+ return;
2739
+ }
2740
+ console.log(`
2741
+ ${chalk15.bold("\u{1F4D3} Di\xE1rio de Bordo")}${options.all ? " (todos)" : " (\xFAltimos 10)"}
2742
+ `);
2743
+ for (const entry of entries) {
2744
+ const actionColor = actionColors[entry.action] ?? chalk15.white;
2745
+ console.log(` ${chalk15.gray(entry.id)} ${actionColor(entry.action)} ${chalk15.gray(new Date(entry.timestamp).toLocaleString())}`);
2746
+ console.log(` ${entry.description}`);
2747
+ if (entry.itemId) console.log(` ${chalk15.cyan(`item: ${entry.itemId}${entry.acId ? ` | ac: ${entry.acId}` : ""}`)}`);
2748
+ console.log();
2749
+ }
2750
+ });
2751
+ cmd.command("add <description>").option("--item <id>", "Associated item ID").option("--ac <id>", "Associated AC ID").description("Add a manual log entry").action((description, options) => {
2752
+ const root = resolve15(process.cwd());
2753
+ logEntry(root, "manual", description, {
2754
+ itemId: options.item,
2755
+ acId: options.ac
2756
+ });
2757
+ console.log(chalk15.green("Registro adicionado ao di\xE1rio de bordo."));
2758
+ });
2759
+ cmd.command("ac <acId>").option("--item <id>", "Associated item ID").description("Register an AC as completed").action((acId, options) => {
2760
+ const root = resolve15(process.cwd());
2761
+ logEntry(root, "ac_done", `AC ${acId} conclu\xEDdo${options.item ? ` (${options.item})` : ""}`, {
2762
+ itemId: options.item,
2763
+ acId
2764
+ });
2765
+ console.log(chalk15.green(`AC ${acId} registrado como conclu\xEDdo.`));
2766
+ });
2767
+ cmd.command("session-end").description("Mark end of session").option("--item <id>", "Current item at end of session").action((options) => {
2768
+ const root = resolve15(process.cwd());
2769
+ logEntry(root, "session_end", "Sess\xE3o encerrada", { itemId: options.item });
2770
+ console.log(chalk15.green("Fim de sess\xE3o registrado."));
2771
+ });
2772
+ return cmd;
1890
2773
  }
1891
- function adaptersForTool(tool) {
1892
- const all = ["cursor", "claude-code", "windsurf", "vscode", "opencode"];
1893
- if (tool === "todos") return all;
1894
- const map = {
1895
- opencode: ["opencode"],
1896
- cursor: ["cursor"],
1897
- windsurf: ["windsurf"],
1898
- "claude code": ["claude-code"],
1899
- "vscode copilot": ["vscode"]
1900
- };
1901
- return map[tool.toLowerCase()] || all;
1902
- }
1903
- function generateAdapterFiles(root, tools) {
1904
- const adapters = [];
1905
- const baseContent = (name, format) => `# Letra Context \u2014 ${name} Adapter
1906
- # Generated by letra init. Do not edit manually.
1907
-
1908
- ${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:
1909
- - .letra/context.md
1910
- - .letra/constitution.md
1911
- - .letra/glossary.md
1912
- - .letra/focus.md (if exists, defines current session focus)
1913
- `}
1914
- # Rules
1915
- - Always read specs in .letra/specs/ before writing code
1916
- - Run \`letra validate\` to check acceptance criteria
1917
- - Follow the constitution.md rules strictly
1918
- - Use formal tone in all generated content
1919
- `;
1920
- for (const tool of tools) {
1921
- switch (tool) {
1922
- case "cursor":
1923
- adapters.push({
1924
- path: join8(root, ".cursorrules"),
1925
- content: baseContent("Cursor", "at")
1926
- });
1927
- break;
1928
- case "claude-code":
1929
- adapters.push({
1930
- path: join8(root, "CLAUDE.md"),
1931
- content: baseContent("Claude Code", "text")
1932
- });
1933
- break;
1934
- case "windsurf":
1935
- adapters.push({
1936
- path: join8(root, ".windsurfrules"),
1937
- content: baseContent("Windsurf", "at")
1938
- });
1939
- break;
1940
- case "vscode":
1941
- adapters.push({
1942
- path: join8(root, ".github", "copilot-instructions.md"),
1943
- content: baseContent("VSCode Copilot", "text")
1944
- });
1945
- break;
1946
- case "opencode":
1947
- adapters.push({
1948
- path: join8(root, "AGENTS.md"),
1949
- content: baseContent("OpenCode", "text")
1950
- });
1951
- break;
2774
+ var actionColors = {
2775
+ validate: (s) => chalk15.blue(s),
2776
+ diagnose: (s) => chalk15.blue(s),
2777
+ health_scan: (s) => chalk15.magenta(s),
2778
+ health_ack: (s) => chalk15.magenta(s),
2779
+ health_dismiss: (s) => chalk15.magenta(s),
2780
+ ac_complete: (s) => chalk15.green(s),
2781
+ ac_done: (s) => chalk15.green(s),
2782
+ item_move: (s) => chalk15.cyan(s),
2783
+ decision: (s) => chalk15.yellow(s),
2784
+ sitrep: (s) => chalk15.blue(s),
2785
+ focus_set: (s) => chalk15.cyan(s),
2786
+ manual: (s) => chalk15.white(s),
2787
+ session_end: (s) => chalk15.red(s)
2788
+ };
2789
+
2790
+ // src/commands/sync.ts
2791
+ import { existsSync as existsSync12 } from "fs";
2792
+ import { resolve as resolve16, join as join11 } from "path";
2793
+ import { Command as Command7 } from "commander";
2794
+ import chalk16 from "chalk";
2795
+ async function validateFocus(focusSpec, items, stages) {
2796
+ const warnings = [];
2797
+ const doneIds = new Set(stages.filter((s) => s.id === "done").map((s) => s.id));
2798
+ const matchingItems = items.filter((i) => i.spec === focusSpec);
2799
+ if (matchingItems.length === 0) {
2800
+ warnings.push(`Focus spec "${focusSpec}" does not match any item's spec in workflow`);
2801
+ } else {
2802
+ for (const item of matchingItems) {
2803
+ if (doneIds.has(item.stage)) {
2804
+ warnings.push(`Focus spec "${focusSpec}" matches ${item.id} which is in "done" stage`);
2805
+ }
1952
2806
  }
1953
2807
  }
1954
- for (const { path, content } of adapters) {
1955
- const dir = join8(path, "..");
1956
- if (!existsSync8(dir)) mkdirSync5(dir, { recursive: true });
1957
- writeFileSync9(path, content);
1958
- console.log(` ${chalk11.gray("Created")} ${path.replace(`${root}/`, "")}`);
2808
+ return warnings;
2809
+ }
2810
+ async function syncNow(rootPath, options) {
2811
+ const workflowFile = join11(rootPath, ".letra", "workflow.json");
2812
+ if (!existsSync12(workflowFile)) {
2813
+ return { ok: false, filesUpdated: [], warnings: [], error: "No workflow found at .letra/workflow.json" };
2814
+ }
2815
+ const workflow = loadWorkflow(rootPath);
2816
+ if (!workflow) {
2817
+ return { ok: false, filesUpdated: [], warnings: [], error: "Failed to load workflow" };
2818
+ }
2819
+ const warnings = [];
2820
+ const focus = readFocusFile(rootPath);
2821
+ if (focus?.specName) {
2822
+ const focusWarnings = await validateFocus(focus.specName, workflow.items, workflow.stages);
2823
+ warnings.push(...focusWarnings);
2824
+ }
2825
+ if (options?.dryRun) {
2826
+ const filesUpdated = [".letra/workflow.json", ...(workflow.tools || []).map((t) => t), ".letra/context.md"];
2827
+ return { ok: true, filesUpdated, warnings, error: void 0 };
1959
2828
  }
2829
+ const result = await writeWorkflow(rootPath, { workflow, source: "flow-edit", skipSitrep: options?.skipSitrep ?? false });
2830
+ return { ...result, warnings };
1960
2831
  }
1961
- async function init(targetPath, options) {
1962
- const root = resolve12(process.cwd(), targetPath || ".");
1963
- const letraDir = join8(root, ".letra");
1964
- if (existsSync8(letraDir)) {
1965
- if (options?.serve) {
1966
- console.log(chalk11.cyan(".letra/ already exists \u2014 starting UI..."));
1967
- await flowServeAction(targetPath, { open: true });
2832
+ function sync_default() {
2833
+ const cmd = new Command7("sync").description("Sync workflow state to all adapters");
2834
+ cmd.option("--dry-run", "Show what would be done without writing").option("--fix", "Apply reconciliation (default behavior)").action(async (opts) => {
2835
+ const root = resolve16(process.cwd());
2836
+ const isDryRun = !!opts.dryRun;
2837
+ const result = await syncNow(root, { dryRun: isDryRun });
2838
+ if (!result.ok) {
2839
+ console.log(chalk16.red("\u2717 Sync failed: " + (result.error ?? "unknown error")));
2840
+ process.exit(1);
2841
+ }
2842
+ if (result.warnings.length > 0) {
2843
+ for (const w of result.warnings) {
2844
+ console.log(chalk16.yellow(` \u26A0 ${w}`));
2845
+ }
2846
+ }
2847
+ if (isDryRun) {
2848
+ console.log(chalk16.bold("\n\u{1F4CB} Simula\xE7\xE3o \u2014 dry-run\n"));
2849
+ console.log(chalk16.gray(` Seriam regenerados:`));
2850
+ for (const f of result.filesUpdated) {
2851
+ console.log(` ${chalk16.gray("\u2192")} ${f}`);
2852
+ }
1968
2853
  return;
1969
2854
  }
1970
- console.log(chalk11.yellow(".letra/ already exists"));
1971
- return;
1972
- }
1973
- const spinner = ora2("Initializing Letra...").start();
1974
- try {
1975
- let projectType = "web-app";
1976
- let tool = "cursor";
1977
- if (options?.yes || !process.stdin.isTTY) {
1978
- projectType = "web-app";
1979
- tool = "todos";
1980
- } else {
1981
- spinner.stop();
1982
- projectType = await ask("Project type?", ["web-app", "cli", "library", "mobile"]);
1983
- const toolNames = [
1984
- "Cursor",
1985
- "Windsurf",
1986
- "Claude Code",
1987
- "VSCode Copilot",
1988
- "OpenCode",
1989
- "Todos"
1990
- ];
1991
- const answer = await ask("AI coding agent?", toolNames);
1992
- tool = answer.toLowerCase();
1993
- spinner.start();
2855
+ console.log(chalk16.green("\u2713 Workflow synced"));
2856
+ for (const f of result.filesUpdated) {
2857
+ console.log(` ${chalk16.gray("\u2192")} ${f}`);
1994
2858
  }
1995
- mkdirSync5(join8(letraDir, "decisions"), { recursive: true });
1996
- mkdirSync5(join8(letraDir, "specs", "_template"), { recursive: true });
1997
- mkdirSync5(join8(letraDir, "adapters"), { recursive: true });
1998
- const templateFiles = {
1999
- "context.md": `# Context
2000
-
2001
- > Updated: 2026-05-01
2002
- > Owner: letra-dev
2003
-
2004
- ## Intent
2005
-
2006
- Letra \xE9 um framework de Specification-Driven Development (SDD) agn\xF3stico a ferramentas.
2007
- Captura dire\xE7\xE3o, inten\xE7\xE3o e contexto, enriquecendo prompts de agentes de c\xF3digo.
2008
-
2009
- ## Dom\xEDnio
2010
-
2011
- - **Produto**: CLI + adapters + formato de mem\xF3ria .letra/
2012
- - **P\xFAblico**: 1. N\xE3o-devs
2013
-
2014
- ## Restri\xE7\xF5es Reais
2015
-
2016
- - Specs devem ser thin (m\xE1x 1 p\xE1gina por feature)
2017
- - Sem lock-in de IDE
2018
- - Drift detection deve funcionar para qualquer dom\xEDnio (n\xE3o s\xF3 c\xF3digo)
2019
-
2020
- ## Porqu\xEAs
2021
-
2022
- - Escolhemos TypeScript porque 82% dos novos pacotes npm s\xE3o TS em 2026
2023
- - Escolhemos Markdown checklist porque n\xE3o-devs precisam ler e escrever specs
2024
- `,
2025
- "constitution.md": `# Constitution
2026
-
2027
- ## Arquitetura
2028
- - Adapter layer desde o dia 1 \u2014 nunca travar em uma IDE
2029
- - Formato .letra/ \xE9 a fonte da verdade, n\xE3o o c\xF3digo
2030
- - CLI deve ser extens\xEDvel via plugins
2031
-
2032
- ## C\xF3digo
2033
- - TypeScript estrito (strict: true)
2034
- - Zero dependencies desnecess\xE1rias
2035
-
2036
- ## Specs
2037
- - Thin specs: m\xE1ximo 1 p\xE1gina por feature
2038
- - Markdown checklist para acceptance criteria
2039
- - Toda spec deve ter: Outcome, Constraints, Exclusions, Acceptance Criteria, Context
2040
-
2041
- ## Seguran\xE7a
2042
- - Nunca incluir secrets, tokens ou chaves no reposit\xF3rio
2043
- `,
2044
- "glossary.md": `# Glossary
2045
-
2046
- | Termo | Defini\xE7\xE3o |
2047
- |-------|-----------|
2048
- | **Spec** | Especifica\xE7\xE3o thin que define o que deve ser constru\xEDdo. |
2049
- | **Drift** | Diverg\xEAncia entre o que a spec diz e o que o artefato realmente entrega. |
2050
- | **Adapter** | Tradutor que converte .letra/ para o formato que uma IDE/agent entende. |
2051
- | **Context** | Documento que captura intent, dom\xEDnio, restri\xE7\xF5es reais e "porqu\xEAs" do projeto. |
2052
- | **Constitution** | Regras n\xE3o-negoci\xE1veis de arquitetura, c\xF3digo e workflow. |
2053
- | **Thin Spec** | Spec de no m\xE1ximo 1 p\xE1gina, focada em outcome. |
2054
- `,
2055
- "lessons-learned.md": `# Lessons Learned
2056
-
2057
- ## O que funcionou
2058
- - Pesquisar dores reais do SDD antes de definir arquitetura
2059
- - Decidir por evid\xEAncias (m\xE9tricas, dados) e n\xE3o por intui\xE7\xE3o
2060
-
2061
- ## O que aprendemos
2062
- - Drift detection n\xE3o pode ser code-centric \u2014 p\xFAblico prim\xE1rio s\xE3o n\xE3o-devs
2063
- - Obsidian nunca deve ser requisito \u2014 barreira de ado\xE7\xE3o
2064
- - TypeScript domina CLIs em 2026 (82% dos novos pacotes npm)
2065
-
2066
- ## Padr\xF5es a evitar
2067
- - Specs gigantes (Markdown Madness)
2068
- - Lock-in de IDE
2069
- - Spec que vira pseudo-c\xF3digo
2070
- `
2071
- };
2072
- for (const [file, content] of Object.entries(templateFiles)) {
2073
- writeFileSync9(join8(letraDir, file), content, "utf-8");
2074
- }
2075
- const specTemplate = join8(letraDir, "specs", "_template.md");
2076
- const specContent = `# Spec Template
2077
-
2078
- > Updated: YYYY-MM-DD
2079
-
2080
- ## Outcome
2081
- O que o usu\xE1rio consegue fazer quando isso estiver pronto.
2082
-
2083
- ## Constraints
2084
- Limita\xE7\xF5es t\xE9cnicas e de neg\xF3cio que n\xE3o podem ser violadas.
2859
+ });
2860
+ return cmd;
2861
+ }
2085
2862
 
2086
- ## Exclusions
2087
- O que explicitamente N\xC3O est\xE1 neste escopo.
2863
+ // src/commands/ac.ts
2864
+ import { existsSync as existsSync16, readFileSync as readFileSync15, writeFileSync as writeFileSync8 } from "fs";
2865
+ import { join as join15, resolve as resolve18 } from "path";
2866
+ import chalk18 from "chalk";
2867
+ import { Command as Command8 } from "commander";
2088
2868
 
2089
- ## Acceptance Criteria
2090
- - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
2869
+ // src/commands/validate.ts
2870
+ import { existsSync as existsSync15, readFileSync as readFileSync14, readdirSync as readdirSync5, watch as watch2 } from "fs";
2871
+ import { join as join14, resolve as resolve17 } from "path";
2872
+ import chalk17 from "chalk";
2091
2873
 
2092
- ## Context
2093
- Por que estamos construindo isso.
2094
- `;
2095
- writeFileSync9(specTemplate, specContent);
2096
- const configPath = join8(letraDir, "config.json");
2097
- writeFileSync9(configPath, adaptConfig(projectType));
2098
- console.log(` ${chalk11.gray("Created")} .letra/config.json`);
2099
- const tools = adaptersForTool(tool);
2100
- generateAdapterFiles(root, tools);
2101
- if (tool === "todos" || tool === "vscode") {
2102
- const vscodeDir = join8(root, ".vscode");
2103
- if (!existsSync8(vscodeDir)) mkdirSync5(vscodeDir, { recursive: true });
2104
- const vscodeSettingsPath = join8(vscodeDir, "settings.json");
2105
- const vscodeSettingsContent = `{
2106
- "editor.formatOnSave": true,
2107
- "editor.defaultFormatter": "esbenp.prettier-vscode",
2108
- "editor.codeActionsOnSave": {
2109
- "source.fixAll.eslint": "explicit"
2874
+ // src/config.ts
2875
+ import { existsSync as existsSync13, readFileSync as readFileSync12 } from "fs";
2876
+ import { join as join12 } from "path";
2877
+ var DEFAULT_HEURISTICS = {
2878
+ "conteudo-minimo": { severity: "warning", minChars: 50 },
2879
+ "consistencia-terminologia": { severity: "warning" },
2880
+ "detecao-tom": {
2881
+ severity: "warning",
2882
+ blacklist: ["tipo", "t\xE1", "pra", "blz", "kkk", "eita", "oi", "oi pessoal"]
2110
2883
  },
2111
- "files.autoSave": "onFocusChange"
2112
- }
2113
- `;
2114
- writeFileSync9(vscodeSettingsPath, vscodeSettingsContent);
2115
- console.log(` ${chalk11.gray("Created")} .vscode/settings.json`);
2116
- }
2117
- spinner.succeed(chalk11.green(".letra/ initialized successfully"));
2118
- console.log("");
2119
- console.log(" Next steps:");
2120
- console.log(` ${chalk11.cyan("letra spec new <name>")} Create your first spec`);
2121
- console.log(` ${chalk11.cyan("letra lint")} Validate specs`);
2122
- console.log(` ${chalk11.cyan("letra init --serve")} Open web UI to configure workflow`);
2123
- if (options?.serve) {
2124
- console.log(`
2125
- ${chalk11.cyan("Opening web UI...")}
2126
- `);
2127
- await flowServeAction(targetPath, { open: true });
2128
- return;
2884
+ "drift-temporal": { severity: "warning", maxDays: 30 },
2885
+ "secoes-vazias": { severity: "warning" },
2886
+ "acs-sem-metrica": { severity: "warning" },
2887
+ "baixa-confianca": { severity: "warning" },
2888
+ "validate-conflict": { severity: "warning" }
2889
+ };
2890
+ function loadConfig(root) {
2891
+ const configPath = join12(root, ".letra", "config.json");
2892
+ const heuristics = {};
2893
+ for (const [key, value] of Object.entries(DEFAULT_HEURISTICS)) {
2894
+ heuristics[key] = { ...value };
2895
+ }
2896
+ if (existsSync13(configPath)) {
2897
+ try {
2898
+ const raw = JSON.parse(readFileSync12(configPath, "utf-8"));
2899
+ if (raw.heuristics && typeof raw.heuristics === "object") {
2900
+ for (const [key, value] of Object.entries(raw.heuristics)) {
2901
+ if (heuristics[key]) {
2902
+ heuristics[key] = {
2903
+ ...heuristics[key],
2904
+ ...value
2905
+ };
2906
+ } else {
2907
+ heuristics[key] = value;
2908
+ }
2909
+ }
2910
+ }
2911
+ } catch {
2129
2912
  }
2130
- } catch (error) {
2131
- spinner.fail(chalk11.red("Failed to initialize Letra"));
2132
- process.exit(1);
2133
2913
  }
2914
+ return { heuristics };
2915
+ }
2916
+ function getHeuristicConfig(config, label) {
2917
+ const key = heuristicKey(label);
2918
+ return config.heuristics[key] ?? { severity: "warning" };
2919
+ }
2920
+ function normalize(str) {
2921
+ return str.normalize("NFD").replace(/\p{M}/gu, "");
2922
+ }
2923
+ function heuristicKey(label) {
2924
+ const lower = normalize(label.toLowerCase());
2925
+ if (lower.includes("conteudo minimo")) return "conteudo-minimo";
2926
+ if (lower.includes("terminologia")) return "consistencia-terminologia";
2927
+ if (lower.includes("tom")) return "detecao-tom";
2928
+ if (lower.includes("drift temporal")) return "drift-temporal";
2929
+ if (lower.includes("secoes vazias")) return "secoes-vazias";
2930
+ if (lower.includes("acs sem metrica")) return "acs-sem-metrica";
2931
+ if (lower.includes("baixa confianca")) return "baixa-confianca";
2932
+ if (lower.includes("validate conflict")) return "validate-conflict";
2933
+ return lower.replace(/\s+/g, "-");
2134
2934
  }
2135
2935
 
2136
- // src/commands/lint.ts
2137
- import { existsSync as existsSync9, readFileSync as readFileSync7, readdirSync as readdirSync5 } from "fs";
2138
- import { join as join9, resolve as resolve13 } from "path";
2139
- import chalk12 from "chalk";
2140
- var REQUIRED_SECTIONS = [
2141
- "## Outcome",
2142
- "## Constraints",
2143
- "## Exclusions",
2144
- "## Acceptance Criteria",
2145
- "## Context"
2936
+ // src/validation/content.ts
2937
+ import { existsSync as existsSync14, readdirSync as readdirSync4, readFileSync as readFileSync13, statSync } from "fs";
2938
+ import { join as join13 } from "path";
2939
+ var placeholderPatterns = [
2940
+ /o que o usu[áa]rio consegue fazer quando isso estiver pronto/i,
2941
+ /limitaç[õo]es t[ée]cnicas e de neg[óo]cio/i,
2942
+ /o que explicitamente n[ãa]o est[áa] neste escopo/i,
2943
+ /descriç[ãa]o bin[áa]ria/i,
2944
+ /por que estamos construindo isso/i
2146
2945
  ];
2147
- async function lint(targetPath) {
2148
- const root = resolve13(process.cwd(), targetPath || ".");
2149
- const specsDir = join9(root, ".letra", "specs");
2150
- if (!existsSync9(specsDir)) {
2151
- console.log(chalk12.red("Error: .letra/specs/ not found. Run 'letra init' first."));
2152
- process.exit(1);
2153
- }
2154
- const results = [];
2155
- let totalErrors = 0;
2156
- let totalWarnings = 0;
2157
- const entries = readdirSync5(specsDir, { withFileTypes: true });
2158
- for (const entry of entries) {
2159
- if (!entry.isDirectory() || entry.name.startsWith("_")) continue;
2160
- const specFile = join9(specsDir, entry.name, "spec.md");
2161
- const errors = [];
2162
- const warnings = [];
2163
- if (!existsSync9(specFile)) {
2164
- errors.push("Missing spec.md");
2165
- } else {
2166
- const content = readFileSync7(specFile, "utf-8");
2167
- for (const section of REQUIRED_SECTIONS) {
2168
- if (!content.includes(section)) {
2169
- errors.push(`Missing section: ${section}`);
2170
- }
2171
- }
2172
- if (content.length > 3e3) {
2173
- warnings.push("Spec exceeds 3000 chars (should be thin \u2014 max 1 page)");
2174
- }
2175
- const hasChecklist = /-\s*\[[ x]\]\s*\*\*/i.test(content);
2176
- if (!hasChecklist && content.includes("## Acceptance Criteria")) {
2177
- errors.push("Acceptance Criteria section exists but has no checklist items");
2178
- }
2179
- }
2180
- if (errors.length > 0 || warnings.length > 0) {
2181
- results.push({ file: entry.name, errors, warnings });
2182
- totalErrors += errors.length;
2183
- totalWarnings += warnings.length;
2946
+ var vagueVerbs = [
2947
+ "melhorar",
2948
+ "otimizar",
2949
+ "facilitar",
2950
+ "aumentar",
2951
+ "diminuir",
2952
+ "agilizar",
2953
+ "simplificar",
2954
+ "aprimorar"
2955
+ ];
2956
+ var lowConfidenceMarkers = [
2957
+ "provavelmente",
2958
+ "talvez",
2959
+ "tentar",
2960
+ "idealmente",
2961
+ "possivelmente",
2962
+ "quem sabe",
2963
+ "de repente",
2964
+ "teoricamente"
2965
+ ];
2966
+ function checkSpecContent(specDir, label, description, config) {
2967
+ const cfg = config ?? loadConfig(join13(specDir, "..", "..", ".."));
2968
+ const specFile = join13(specDir, "spec.md");
2969
+ const glossaryFile = join13(specDir, "..", "..", "glossary.md");
2970
+ if (!existsSync14(specFile)) return { status: "FAIL", note: "(spec.md not found)" };
2971
+ const specContent = readFileSync13(specFile, "utf-8");
2972
+ const now6 = /* @__PURE__ */ new Date();
2973
+ if (label.includes("Conte\xFAdo M\xEDnimo")) {
2974
+ const outcomeMatch = specContent.match(/## Outcome\s+([\s\S]*?)(?=\n## )/);
2975
+ if (!outcomeMatch) return { status: "FAIL", note: "(no Outcome section)" };
2976
+ const outcomeContent = outcomeMatch[1].trim();
2977
+ const heurConfig = getHeuristicConfig(cfg, label);
2978
+ const minChars = heurConfig.minChars ?? 50;
2979
+ if (outcomeContent.length >= minChars) {
2980
+ return {
2981
+ status: "PASS",
2982
+ note: `(${outcomeContent.length} chars, need ${minChars})`
2983
+ };
2184
2984
  }
2985
+ return {
2986
+ status: "FAIL",
2987
+ note: `(only ${outcomeContent.length} chars, need ${minChars}+)`
2988
+ };
2185
2989
  }
2186
- if (results.length === 0) {
2187
- console.log(chalk12.green("All specs are valid"));
2188
- process.exit(0);
2189
- }
2190
- console.log("");
2191
- for (const result of results) {
2192
- console.log(chalk12.bold(`
2193
- Spec: ${result.file}`));
2194
- for (const error of result.errors) {
2195
- console.log(chalk12.red(` \u2717 ${error}`));
2990
+ if (label.includes("Consist\xEAncia de Terminologia") || label.includes("Terminologia")) {
2991
+ if (!existsSync14(glossaryFile)) {
2992
+ return {
2993
+ status: "PASS",
2994
+ note: "(no glossary to check against)"
2995
+ };
2196
2996
  }
2197
- for (const warning of result.warnings) {
2198
- console.log(chalk12.yellow(` \u26A0 ${warning}`));
2997
+ const glossaryContent = readFileSync13(glossaryFile, "utf-8");
2998
+ const terms = glossaryContent.match(/\*\*(.+?)\*\*/g) || [];
2999
+ const extractedTerms = terms.map((t) => t.replace(/\*\*/g, "").trim()).filter((t) => t.length > 3);
3000
+ const missingTerms = extractedTerms.filter(
3001
+ (term) => !specContent.toLowerCase().includes(term.toLowerCase())
3002
+ );
3003
+ if (missingTerms.length === 0) {
3004
+ return { status: "PASS", note: "(all glossary terms used)" };
2199
3005
  }
3006
+ return {
3007
+ status: "FAIL",
3008
+ note: `(missing: ${missingTerms.slice(0, 3).join(", ")})`
3009
+ };
2200
3010
  }
2201
- console.log(
2202
- chalk12.gray(
2203
- `
2204
- ${results.length} spec(s) with issues: ${totalErrors} error(s), ${totalWarnings} warning(s)`
2205
- )
2206
- );
2207
- process.exit(totalErrors > 0 ? 1 : 0);
2208
- }
2209
-
2210
- // src/commands/spec.ts
2211
- import { existsSync as existsSync10, mkdirSync as mkdirSync6, readFileSync as readFileSync8, readdirSync as readdirSync6, writeFileSync as writeFileSync10 } from "fs";
2212
- import { join as join10, resolve as resolve14 } from "path";
2213
- import chalk13 from "chalk";
2214
- import ora3 from "ora";
2215
- var builtInTemplates = {
2216
- "web-api": {
2217
- spec: `# Spec: {{name}}
2218
-
2219
- > Updated: {{date}}
2220
-
2221
- ## Outcome
2222
- Usu\xE1rio consegue fazer requisi\xE7\xF5es HTTP para a API e receber respostas padronizadas.
2223
-
2224
- ## Constraints
2225
- - RESTful\u9075\u5FAA (GET, POST, PUT, DELETE)
2226
- - Autentica\xE7\xE3o via Bearer token JWT
2227
- - Rate limiting: 100 req/min por usu\xE1rio
2228
- - Timeout m\xE1ximo de 30s por requisi\xE7\xE3o
2229
-
2230
- ## Exclusions
2231
- - WebSocket n\xE3o est\xE1 no escopo
2232
- - Upload de arquivos n\xE3o est\xE1 no escopo inicial
2233
-
2234
- ## Acceptance Criteria
2235
- - [ ] **CRUD**: CRUD completo para o recurso principal (GET, POST, PUT, DELETE retornam 200/201/204).
2236
- - [ ] **Autentica\xE7\xE3o**: Rota sem token retorna 401, rota com token inv\xE1lido retorna 403.
2237
- - [ ] **Valida\xE7\xE3o**: Payload inv\xE1lido retorna 422 com mensagem de erro descritiva.
2238
- - [ ] **Rate Limit**: Exceder 100 req/min retorna 429 com header Retry-After.
2239
- - [ ] **Pagina\xE7\xE3o**: GET com ?page=2&limit=10 retorna p\xE1gina correta com total count.
2240
-
2241
- ## Context
2242
- Template para APIs REST. Adaptado para o dom\xEDnio espec\xEDfico do projeto.`,
2243
- acceptance: `# Acceptance Criteria \u2014 {{name}}
2244
-
2245
- - [ ] **CRUD**: CRUD completo para o recurso principal (GET, POST, PUT, DELETE retornam 200/201/204).
2246
- - [ ] **Autentica\xE7\xE3o**: Rota sem token retorna 401, rota com token inv\xE1lido retorna 403.
2247
- - [ ] **Valida\xE7\xE3o**: Payload inv\xE1lido retorna 422 com mensagem de erro descritiva.
2248
- - [ ] **Rate Limit**: Exceder 100 req/min retorna 429 com header Retry-After.
2249
- - [ ] **Pagina\xE7\xE3o**: GET com ?page=2&limit=10 retorna p\xE1gina correta com total count.`
2250
- },
2251
- "cli-tool": {
2252
- spec: `# Spec: {{name}}
2253
-
2254
- > Updated: {{date}}
2255
-
2256
- ## Outcome
2257
- Usu\xE1rio instala e executa a CLI, recebendo output formatado no terminal.
2258
-
2259
- ## Constraints
2260
- - Node.js 22+ como runtime
2261
- - Deve funcionar em Windows, macOS e Linux
2262
- - Exit codes seguem padr\xE3o Unix (0 sucesso, 1 erro)
2263
- - --help deve funcionar sem argumentos
2264
-
2265
- ## Exclusions
2266
- - UI gr\xE1fica n\xE3o est\xE1 no escopo
2267
- - Modo servidor/daemon n\xE3o est\xE1 no escopo
2268
-
2269
- ## Acceptance Criteria
2270
- - [ ] **Instala\xE7\xE3o**: CLI execut\xE1vel via npx/npm install -g sem erros.
2271
- - [ ] **--help**: Roda sem argumentos, exibe ajuda com subcomandos.
2272
- - [ ] **Subcomando**: Subcomando principal executa sem erros e exibe output.
2273
- - [ ] **Erro**: Subcomando inv\xE1lido exibe erro amig\xE1vel e exit 1.
2274
- - [ ] **Cross-platform**: Funciona em Windows (cmd/powershell), macOS (zsh) e Linux (bash).
2275
-
2276
- ## Context
2277
- Template para ferramentas de linha de comando. Adaptado para o escopo espec\xEDfico.`,
2278
- acceptance: `# Acceptance Criteria \u2014 {{name}}
2279
-
2280
- - [ ] **Instala\xE7\xE3o**: CLI execut\xE1vel via npx/npm install -g sem erros.
2281
- - [ ] **--help**: Roda sem argumentos, exibe ajuda com subcomandos.
2282
- - [ ] **Subcomando**: Subcomando principal executa sem erros e exibe output.
2283
- - [ ] **Erro**: Subcomando inv\xE1lido exibe erro amig\xE1vel e exit 1.
2284
- - [ ] **Cross-platform**: Funciona em Windows (cmd/powershell), macOS (zsh) e Linux (bash).`
2285
- },
2286
- "mobile-feature": {
2287
- spec: `# Spec: {{name}}
2288
-
2289
- > Updated: {{date}}
2290
-
2291
- ## Outcome
2292
- Usu\xE1rio consegue acessar e interagir com a nova funcionalidade no aplicativo mobile.
2293
-
2294
- ## Constraints
2295
- - Suporte a iOS 16+ e Android 13+
2296
- - Offline-first: funcionalidade deve funcionar sem internet
2297
- - Tempo de resposta < 200ms para intera\xE7\xF5es locais
2298
- - Acessibilidade: VoiceOver (iOS) e TalkBack (Android)
2299
-
2300
- ## Exclusions
2301
- - Vers\xE3o web n\xE3o est\xE1 no escopo (mobile-only)
2302
- - Suporte a tablets \xE9 desej\xE1vel mas n\xE3o obrigat\xF3rio
2303
-
2304
- ## Acceptance Criteria
2305
- - [ ] **Tela principal**: Nova funcionalidade aparece na navega\xE7\xE3o principal.
2306
- - [ ] **Offline**: Funcionalidade completa funciona sem conex\xE3o de rede.
2307
- - [ ] **Performance**: Scroll da lista com 1000+ itens mant\xE9m 60fps.
2308
- - [ ] **Acessibilidade**: Todos os elementos t\xEAm label de acessibilidade.
2309
- - [ ] **Dark Mode**: Funcionalidade respeita o tema do sistema.
2310
-
2311
- ## Context
2312
- Template para features mobile nativas. Adaptado para o framework espec\xEDfico (SwiftUI/Compose).`,
2313
- acceptance: `# Acceptance Criteria \u2014 {{name}}
2314
-
2315
- - [ ] **Tela principal**: Nova funcionalidade aparece na navega\xE7\xE3o principal.
2316
- - [ ] **Offline**: Funcionalidade completa funciona sem conex\xE3o de rede.
2317
- - [ ] **Performance**: Scroll da lista com 1000+ itens mant\xE9m 60fps.
2318
- - [ ] **Acessibilidade**: Todos os elementos t\xEAm label de acessibilidade.
2319
- - [ ] **Dark Mode**: Funcionalidade respeita o tema do sistema.`
2320
- }
2321
- };
2322
- function listTemplates(root) {
2323
- const names = Object.keys(builtInTemplates);
2324
- const customDir = join10(root, ".letra", "templates");
2325
- if (existsSync10(customDir)) {
2326
- for (const file of readdirSync6(customDir)) {
2327
- if (file.endsWith(".md")) {
2328
- const name = file.replace(/\.md$/, "");
2329
- if (!names.includes(name)) names.push(name);
2330
- }
3011
+ if (label.includes("Detec\xE7\xE3o de Tom") || label.includes("Tom")) {
3012
+ const lowerSpec = specContent.toLowerCase();
3013
+ const words = lowerSpec.split(/\s+/);
3014
+ const heurConfig = getHeuristicConfig(cfg, label);
3015
+ const blacklist = heurConfig.blacklist ?? [
3016
+ "tipo",
3017
+ "t\xE1",
3018
+ "pra",
3019
+ "blz",
3020
+ "kkk",
3021
+ "eita",
3022
+ "oi",
3023
+ "oi pessoal"
3024
+ ];
3025
+ const foundColloquialisms = blacklist.filter((c) => words.includes(c));
3026
+ if (foundColloquialisms.length === 0) {
3027
+ return { status: "PASS", note: "(formal tone maintained)" };
2331
3028
  }
3029
+ return {
3030
+ status: "FAIL",
3031
+ note: `(colloquialisms: ${foundColloquialisms.join(", ")})`
3032
+ };
2332
3033
  }
2333
- return names;
2334
- }
2335
- function findTemplate(root, type) {
2336
- const lower = type.toLowerCase();
2337
- if (builtInTemplates[lower]) return builtInTemplates[lower];
2338
- const customFile = join10(root, ".letra", "templates", `${type}.md`);
2339
- const customAcceptance = join10(root, ".letra", "templates", `${type}-acceptance.md`);
2340
- if (existsSync10(customFile)) {
2341
- const spec = readFileSync8(customFile, "utf-8");
2342
- const acceptance = existsSync10(customAcceptance) ? readFileSync8(customAcceptance, "utf-8") : `# Acceptance Criteria \u2014 ${type}
2343
-
2344
- - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
2345
- `;
2346
- return { spec, acceptance };
3034
+ if (label.includes("Drift Temporal") || label.includes("Temporal")) {
3035
+ const stat = statSync(specFile);
3036
+ const daysOld = Math.floor((now6.getTime() - stat.mtimeMs) / (1e3 * 60 * 60 * 24));
3037
+ const heurConfig = getHeuristicConfig(cfg, label);
3038
+ const maxDays = heurConfig.maxDays ?? 30;
3039
+ if (daysOld < maxDays) {
3040
+ return { status: "PASS", note: `(${daysOld} days old)` };
3041
+ }
3042
+ return {
3043
+ status: "FAIL",
3044
+ note: `(${daysOld} days old, stale >${maxDays}d)`
3045
+ };
2347
3046
  }
2348
3047
  return null;
2349
3048
  }
2350
- function applyPlaceholders(content, name, date) {
2351
- return content.replace(/\{\{name\}\}/g, name).replace(/\{\{date\}\}/g, date);
2352
- }
2353
- async function specNew(name, options) {
2354
- const root = resolve14(process.cwd());
2355
- const letraDir = join10(root, ".letra");
2356
- const specDir = join10(letraDir, "specs", name);
2357
- if (!existsSync10(letraDir)) {
2358
- console.log(chalk13.red(".letra/ not found. Run 'letra init' first."));
2359
- process.exit(1);
3049
+ function checkEmptySections(specContent) {
3050
+ const requiredSections = [
3051
+ "## Outcome",
3052
+ "## Constraints",
3053
+ "## Exclusions",
3054
+ "## Acceptance Criteria",
3055
+ "## Context"
3056
+ ];
3057
+ const emptyOrPlaceholder = [];
3058
+ for (const section of requiredSections) {
3059
+ const escaped = section.replace(/[#]/g, "\\$&");
3060
+ const pattern = new RegExp(`${escaped}\\s+([\\s\\S]*?)(?=\\n## |\\n*$)`);
3061
+ const match = specContent.match(pattern);
3062
+ if (!match) {
3063
+ emptyOrPlaceholder.push(section.replace("## ", ""));
3064
+ continue;
3065
+ }
3066
+ const content = match[1].trim();
3067
+ if (content.length < 10) {
3068
+ emptyOrPlaceholder.push(section.replace("## ", ""));
3069
+ continue;
3070
+ }
3071
+ const hasPlaceholder = placeholderPatterns.some((p) => p.test(content));
3072
+ if (hasPlaceholder) {
3073
+ emptyOrPlaceholder.push(section.replace("## ", ""));
3074
+ }
2360
3075
  }
2361
- if (existsSync10(specDir)) {
2362
- console.log(chalk13.yellow(`Spec "${name}" already exists`));
2363
- return;
3076
+ if (emptyOrPlaceholder.length === 0) {
3077
+ return {
3078
+ status: "PASS",
3079
+ note: "(all sections have real content)"
3080
+ };
2364
3081
  }
2365
- const templateType = options?.template || "_default";
2366
- const template = templateType === "_default" ? null : findTemplate(root, templateType);
2367
- if (options?.template && !template) {
2368
- const available = listTemplates(root).join(", ");
2369
- console.log(chalk13.red(`Template "${options.template}" not found. Available: ${available}`));
2370
- process.exit(1);
3082
+ return {
3083
+ status: "FAIL",
3084
+ note: `(empty/placeholder: ${emptyOrPlaceholder.join(", ")})`
3085
+ };
3086
+ }
3087
+ function checkBinaryCriteria(specContent) {
3088
+ const acMatch = specContent.match(/## Acceptance Criteria\s+([\s\S]*?)(?=\n## |\n*$)/);
3089
+ if (!acMatch) {
3090
+ return {
3091
+ status: "FAIL",
3092
+ note: "(no Acceptance Criteria section)"
3093
+ };
2371
3094
  }
2372
- const spinner = ora3(`Creating spec "${name}"...`).start();
2373
- try {
2374
- const today2 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
2375
- mkdirSync6(specDir, { recursive: true });
2376
- if (template) {
2377
- const specContent = applyPlaceholders(template.spec, name, today2);
2378
- const acceptanceContent = applyPlaceholders(template.acceptance, name, today2);
2379
- writeFileSync10(join10(specDir, "spec.md"), specContent);
2380
- writeFileSync10(join10(specDir, "acceptance.md"), acceptanceContent);
2381
- } else {
2382
- const specContent = `# Spec: ${name}
2383
-
2384
- > Updated: ${today2}
2385
-
2386
- ## Outcome
2387
- O que o usu\xE1rio consegue fazer quando isso estiver pronto.
2388
-
2389
- ## Constraints
2390
- Limita\xE7\xF5es t\xE9cnicas e de neg\xF3cio que n\xE3o podem ser violadas.
2391
-
2392
- ## Exclusions
2393
- O que explicitamente N\xC3O est\xE1 neste escopo.
2394
-
2395
- ## Acceptance Criteria
2396
- - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
2397
-
2398
- ## Context
2399
- Por que estamos construindo isso. Trade-offs considerados.
2400
- `;
2401
- const acceptanceContent = `# Acceptance Criteria \u2014 ${name}
2402
-
2403
- - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
2404
- `;
2405
- writeFileSync10(join10(specDir, "spec.md"), specContent);
2406
- writeFileSync10(join10(specDir, "acceptance.md"), acceptanceContent);
2407
- }
2408
- spinner.succeed(chalk13.green(`Spec "${name}" created at .letra/specs/${name}/`));
2409
- } catch (error) {
2410
- spinner.fail(chalk13.red("Failed to create spec"));
2411
- process.exit(1);
2412
- }
2413
- }
2414
-
2415
- // src/commands/validate.ts
2416
- import { execSync } from "child_process";
2417
- import {
2418
- existsSync as existsSync12,
2419
- mkdtempSync,
2420
- readFileSync as readFileSync10,
2421
- readdirSync as readdirSync7,
2422
- rmSync,
2423
- statSync as statSync2,
2424
- watch as watch2
2425
- } from "fs";
2426
- import { tmpdir } from "os";
2427
- import { join as join12, resolve as resolve15 } from "path";
2428
- import chalk14 from "chalk";
2429
-
2430
- // src/config.ts
2431
- import { existsSync as existsSync11, readFileSync as readFileSync9 } from "fs";
2432
- import { join as join11 } from "path";
2433
- var DEFAULT_HEURISTICS = {
2434
- "conteudo-minimo": { severity: "warning", minChars: 50 },
2435
- "consistencia-terminologia": { severity: "warning" },
2436
- "detecao-tom": {
2437
- severity: "warning",
2438
- blacklist: ["tipo", "t\xE1", "pra", "blz", "kkk", "eita", "oi", "oi pessoal"]
2439
- },
2440
- "drift-temporal": { severity: "warning", maxDays: 30 },
2441
- "secoes-vazias": { severity: "warning" },
2442
- "acs-sem-metrica": { severity: "warning" },
2443
- "baixa-confianca": { severity: "warning" },
2444
- "validate-conflict": { severity: "warning" }
2445
- };
2446
- function loadConfig(root) {
2447
- const configPath = join11(root, ".letra", "config.json");
2448
- const heuristics = {};
2449
- for (const [key, value] of Object.entries(DEFAULT_HEURISTICS)) {
2450
- heuristics[key] = { ...value };
2451
- }
2452
- if (existsSync11(configPath)) {
2453
- try {
2454
- const raw = JSON.parse(readFileSync9(configPath, "utf-8"));
2455
- if (raw.heuristics && typeof raw.heuristics === "object") {
2456
- for (const [key, value] of Object.entries(raw.heuristics)) {
2457
- if (heuristics[key]) {
2458
- heuristics[key] = {
2459
- ...heuristics[key],
2460
- ...value
2461
- };
2462
- } else {
2463
- heuristics[key] = value;
2464
- }
2465
- }
2466
- }
2467
- } catch {
2468
- }
2469
- }
2470
- return { heuristics };
2471
- }
2472
- function getHeuristicConfig(config, label) {
2473
- const key = heuristicKey(label);
2474
- return config.heuristics[key] ?? { severity: "warning" };
2475
- }
2476
- function normalize(str) {
2477
- return str.normalize("NFD").replace(/\p{M}/gu, "");
2478
- }
2479
- function heuristicKey(label) {
2480
- const lower = normalize(label.toLowerCase());
2481
- if (lower.includes("conteudo minimo")) return "conteudo-minimo";
2482
- if (lower.includes("terminologia")) return "consistencia-terminologia";
2483
- if (lower.includes("tom")) return "detecao-tom";
2484
- if (lower.includes("drift temporal")) return "drift-temporal";
2485
- if (lower.includes("secoes vazias")) return "secoes-vazias";
2486
- if (lower.includes("acs sem metrica")) return "acs-sem-metrica";
2487
- if (lower.includes("baixa confianca")) return "baixa-confianca";
2488
- if (lower.includes("validate conflict")) return "validate-conflict";
2489
- return lower.replace(/\s+/g, "-");
2490
- }
2491
-
2492
- // src/commands/validate.ts
2493
- var placeholderPatterns = [
2494
- /o que o usu[áa]rio consegue fazer quando isso estiver pronto/i,
2495
- /limitaç[õo]es t[ée]cnicas e de neg[óo]cio/i,
2496
- /o que explicitamente n[ãa]o est[áa] neste escopo/i,
2497
- /descriç[ãa]o bin[áa]ria/i,
2498
- /por que estamos construindo isso/i
2499
- ];
2500
- var vagueVerbs = [
2501
- "melhorar",
2502
- "otimizar",
2503
- "facilitar",
2504
- "aumentar",
2505
- "diminuir",
2506
- "agilizar",
2507
- "simplificar",
2508
- "aprimorar"
2509
- ];
2510
- var lowConfidenceMarkers = [
2511
- "provavelmente",
2512
- "talvez",
2513
- "tentar",
2514
- "idealmente",
2515
- "possivelmente",
2516
- "quem sabe",
2517
- "de repente",
2518
- "teoricamente"
2519
- ];
2520
- function checkSpecContent(specDir, label, description, config) {
2521
- const cfg = config ?? loadConfig(join12(specDir, "..", "..", ".."));
2522
- const specFile = join12(specDir, "spec.md");
2523
- const glossaryFile = join12(specDir, "..", "..", "glossary.md");
2524
- if (!existsSync12(specFile)) return { status: "FAIL", note: "(spec.md not found)" };
2525
- const specContent = readFileSync10(specFile, "utf-8");
2526
- const now7 = /* @__PURE__ */ new Date();
2527
- if (label.includes("Conte\xFAdo M\xEDnimo")) {
2528
- const outcomeMatch = specContent.match(/## Outcome\s+([\s\S]*?)(?=\n## )/);
2529
- if (!outcomeMatch) return { status: "FAIL", note: "(no Outcome section)" };
2530
- const outcomeContent = outcomeMatch[1].trim();
2531
- const heurConfig = getHeuristicConfig(cfg, label);
2532
- const minChars = heurConfig.minChars ?? 50;
2533
- if (outcomeContent.length >= minChars) {
2534
- return {
2535
- status: "PASS",
2536
- note: `(${outcomeContent.length} chars, need ${minChars})`
2537
- };
2538
- }
2539
- return {
2540
- status: "FAIL",
2541
- note: `(only ${outcomeContent.length} chars, need ${minChars}+)`
2542
- };
2543
- }
2544
- if (label.includes("Consist\xEAncia de Terminologia") || label.includes("Terminologia")) {
2545
- if (!existsSync12(glossaryFile)) {
2546
- return {
2547
- status: "PASS",
2548
- note: "(no glossary to check against)"
2549
- };
2550
- }
2551
- const glossaryContent = readFileSync10(glossaryFile, "utf-8");
2552
- const terms = glossaryContent.match(/\*\*(.+?)\*\*/g) || [];
2553
- const extractedTerms = terms.map((t) => t.replace(/\*\*/g, "").trim()).filter((t) => t.length > 3);
2554
- const missingTerms = extractedTerms.filter(
2555
- (term) => !specContent.toLowerCase().includes(term.toLowerCase())
2556
- );
2557
- if (missingTerms.length === 0) {
2558
- return { status: "PASS", note: "(all glossary terms used)" };
2559
- }
2560
- return {
2561
- status: "FAIL",
2562
- note: `(missing: ${missingTerms.slice(0, 3).join(", ")})`
2563
- };
2564
- }
2565
- if (label.includes("Detec\xE7\xE3o de Tom") || label.includes("Tom")) {
2566
- const lowerSpec = specContent.toLowerCase();
2567
- const words = lowerSpec.split(/\s+/);
2568
- const heurConfig = getHeuristicConfig(cfg, label);
2569
- const blacklist = heurConfig.blacklist ?? [
2570
- "tipo",
2571
- "t\xE1",
2572
- "pra",
2573
- "blz",
2574
- "kkk",
2575
- "eita",
2576
- "oi",
2577
- "oi pessoal"
2578
- ];
2579
- const foundColloquialisms = blacklist.filter((c) => words.includes(c));
2580
- if (foundColloquialisms.length === 0) {
2581
- return { status: "PASS", note: "(formal tone maintained)" };
2582
- }
2583
- return {
2584
- status: "FAIL",
2585
- note: `(colloquialisms: ${foundColloquialisms.join(", ")})`
2586
- };
2587
- }
2588
- if (label.includes("Drift Temporal") || label.includes("Temporal")) {
2589
- const stat = statSync2(specFile);
2590
- const daysOld = Math.floor((now7.getTime() - stat.mtimeMs) / (1e3 * 60 * 60 * 24));
2591
- const heurConfig = getHeuristicConfig(cfg, label);
2592
- const maxDays = heurConfig.maxDays ?? 30;
2593
- if (daysOld < maxDays) {
2594
- return { status: "PASS", note: `(${daysOld} days old)` };
2595
- }
2596
- return {
2597
- status: "FAIL",
2598
- note: `(${daysOld} days old, stale >${maxDays}d)`
2599
- };
2600
- }
2601
- return null;
2602
- }
2603
- function checkEmptySections(specContent) {
2604
- const requiredSections = [
2605
- "## Outcome",
2606
- "## Constraints",
2607
- "## Exclusions",
2608
- "## Acceptance Criteria",
2609
- "## Context"
2610
- ];
2611
- const emptyOrPlaceholder = [];
2612
- for (const section of requiredSections) {
2613
- const escaped = section.replace(/[#]/g, "\\$&");
2614
- const pattern = new RegExp(`${escaped}\\s+([\\s\\S]*?)(?=\\n## |\\n*$)`);
2615
- const match = specContent.match(pattern);
2616
- if (!match) {
2617
- emptyOrPlaceholder.push(section.replace("## ", ""));
2618
- continue;
2619
- }
2620
- const content = match[1].trim();
2621
- if (content.length < 10) {
2622
- emptyOrPlaceholder.push(section.replace("## ", ""));
2623
- continue;
2624
- }
2625
- const hasPlaceholder = placeholderPatterns.some((p) => p.test(content));
2626
- if (hasPlaceholder) {
2627
- emptyOrPlaceholder.push(section.replace("## ", ""));
2628
- }
2629
- }
2630
- if (emptyOrPlaceholder.length === 0) {
2631
- return {
2632
- status: "PASS",
2633
- note: "(all sections have real content)"
2634
- };
2635
- }
2636
- return {
2637
- status: "FAIL",
2638
- note: `(empty/placeholder: ${emptyOrPlaceholder.join(", ")})`
2639
- };
2640
- }
2641
- function checkBinaryCriteria(specContent) {
2642
- const acMatch = specContent.match(/## Acceptance Criteria\s+([\s\S]*?)(?=\n## |\n*$)/);
2643
- if (!acMatch) {
2644
- return {
2645
- status: "FAIL",
2646
- note: "(no Acceptance Criteria section)"
2647
- };
2648
- }
2649
- const criteriaLines = acMatch[1].match(/- \[[ x]\] .+/g) || [];
2650
- if (criteriaLines.length === 0) {
2651
- return { status: "FAIL", note: "(no criteria items found)" };
2652
- }
2653
- const nonBinary = [];
2654
- for (const line of criteriaLines) {
2655
- const description = line.replace(/- \[[ x]\] \*\*.+?\*\*:\s*/, "");
2656
- const hasMetric = /\d+/.test(description);
2657
- const hasVagueVerb = vagueVerbs.some((v) => description.toLowerCase().includes(v));
2658
- if (!hasMetric && hasVagueVerb) {
2659
- const labelMatch = line.match(/\*\*(.+?)\*\*/);
2660
- if (labelMatch) nonBinary.push(labelMatch[1]);
3095
+ const criteriaLines = acMatch[1].match(/- \[[ x]\] .+/g) || [];
3096
+ if (criteriaLines.length === 0) {
3097
+ return { status: "FAIL", note: "(no criteria items found)" };
3098
+ }
3099
+ const nonBinary = [];
3100
+ for (const line of criteriaLines) {
3101
+ const description = line.replace(/- \[[ x]\] \*\*.+?\*\*:\s*/, "");
3102
+ const hasMetric = /\d+/.test(description);
3103
+ const hasVagueVerb = vagueVerbs.some((v) => description.toLowerCase().includes(v));
3104
+ if (!hasMetric && hasVagueVerb) {
3105
+ const labelMatch = line.match(/\*\*(.+?)\*\*/);
3106
+ if (labelMatch) nonBinary.push(labelMatch[1]);
2661
3107
  }
2662
3108
  }
2663
3109
  if (nonBinary.length === 0) {
@@ -2769,13 +3215,13 @@ function detectConflict(textA, textB) {
2769
3215
  }
2770
3216
  function checkConflicts(specsDir, config) {
2771
3217
  const results = [];
2772
- const entries = readdirSync7(specsDir, { withFileTypes: true });
3218
+ const entries = readdirSync4(specsDir, { withFileTypes: true });
2773
3219
  const specDirs = entries.filter((e) => e.isDirectory() && !e.name.startsWith("_")).map((e) => e.name);
2774
3220
  const specs = [];
2775
3221
  for (const dir of specDirs) {
2776
- const acceptanceFile = join12(specsDir, dir, "acceptance.md");
2777
- if (!existsSync12(acceptanceFile)) continue;
2778
- const content = readFileSync10(acceptanceFile, "utf-8");
3222
+ const acceptanceFile = join13(specsDir, dir, "acceptance.md");
3223
+ if (!existsSync14(acceptanceFile)) continue;
3224
+ const content = readFileSync13(acceptanceFile, "utf-8");
2779
3225
  const acLines = content.match(/- \[[ x]\] \*\*(.+?)\*\*: (.+)/g) || [];
2780
3226
  const acs = acLines.map((line) => {
2781
3227
  const m = line.match(/- \[[ x]\] \*\*(.+?)\*\*: (.+)/);
@@ -2810,6 +3256,8 @@ function checkConflicts(specsDir, config) {
2810
3256
  }
2811
3257
  return results;
2812
3258
  }
3259
+
3260
+ // src/commands/validate.ts
2813
3261
  function out(format, level, spec, label, message, note) {
2814
3262
  if (format === "github-annotation") {
2815
3263
  const file = spec ? `.letra/specs/${spec}/spec.md` : "";
@@ -2825,11 +3273,11 @@ function out(format, level, spec, label, message, note) {
2825
3273
  if (format === "junit") {
2826
3274
  return;
2827
3275
  }
2828
- const icon = level === "pass" ? chalk14.green("\u2713") : level === "fail" ? chalk14.red("\u2717") : level === "warning" ? chalk14.yellow("\u26A0") : "";
3276
+ const icon = level === "pass" ? chalk17.green("\u2713") : level === "fail" ? chalk17.red("\u2717") : level === "warning" ? chalk17.yellow("\u26A0") : "";
2829
3277
  if (level === "info") {
2830
3278
  console.log(` ${message}`);
2831
3279
  } else {
2832
- console.log(` [${icon}] ${chalk14.cyan(label)}: ${message} ${chalk14.gray(note)}`);
3280
+ console.log(` [${icon}] ${chalk17.cyan(label)}: ${message} ${chalk17.gray(note)}`);
2833
3281
  }
2834
3282
  }
2835
3283
  function buildJunitXml(results) {
@@ -2870,55 +3318,48 @@ function flushResults(results, format, specGroups, totalPass, totalFail, totalWa
2870
3318
  }
2871
3319
  }
2872
3320
  console.log(
2873
- chalk14.gray(
3321
+ chalk17.gray(
2874
3322
  `
2875
3323
  Results: ${totalPass} passed, ${totalFail} failed${totalWarning > 0 ? `, ${totalWarning} warnings` : ""}`
2876
3324
  )
2877
3325
  );
2878
3326
  }
2879
3327
  async function validate(targetPath, options) {
2880
- const root = resolve15(process.cwd(), targetPath || ".");
2881
- const specsDir = join12(root, ".letra", "specs");
3328
+ const root = resolve17(process.cwd(), targetPath || ".");
3329
+ const specsDir = join14(root, ".letra", "specs");
2882
3330
  const fmt = options?.format || "text";
2883
- if (!existsSync12(specsDir)) {
3331
+ if (!existsSync15(specsDir)) {
2884
3332
  const msg = "Error: .letra/specs/ not found. Run 'letra init' first.";
2885
3333
  if (fmt === "github-annotation") {
2886
3334
  console.log(`::error file=,title=Init Required::${msg}`);
2887
3335
  } else {
2888
- console.log(chalk14.red(msg));
3336
+ console.log(chalk17.red(msg));
2889
3337
  }
2890
3338
  process.exit(1);
2891
3339
  }
2892
3340
  async function runValidation() {
2893
3341
  const config = loadConfig(root);
2894
- const entries = readdirSync7(specsDir, { withFileTypes: true });
3342
+ const entries = readdirSync5(specsDir, { withFileTypes: true });
2895
3343
  let totalPass = 0;
2896
3344
  let totalFail = 0;
2897
3345
  let totalWarning = 0;
2898
3346
  const specGroups = /* @__PURE__ */ new Map();
2899
3347
  const allResults = [];
2900
- const entryPoint = join12(root, "src/index.ts");
2901
- const opts = {
2902
- stdio: "pipe",
2903
- encoding: "utf-8",
2904
- shell: process.platform === "win32" ? "cmd.exe" : true
2905
- };
2906
- const ciFile = join12(root, ".github", "workflows", "ci.yml");
2907
- const cursorRulesFile = join12(root, ".cursorrules");
2908
- const copilotFile = join12(root, ".github", "copilot-instructions.md");
2909
- const vscodeSettingsFile = join12(root, ".vscode", "settings.json");
3348
+ const cursorRulesFile = join14(root, ".cursorrules");
3349
+ const copilotFile = join14(root, ".github", "copilot-instructions.md");
3350
+ const vscodeSettingsFile = join14(root, ".vscode", "settings.json");
2910
3351
  if (fmt !== "junit") {
2911
3352
  out(fmt, "info", null, "", "\nLetra Validation\n", "");
2912
3353
  }
2913
3354
  for (const entry of entries) {
2914
3355
  if (!entry.isDirectory() || entry.name.startsWith("_")) continue;
2915
- const acceptanceFile = join12(specsDir, entry.name, "acceptance.md");
2916
- const specFile = join12(specsDir, entry.name, "spec.md");
3356
+ const acceptanceFile = join14(specsDir, entry.name, "acceptance.md");
3357
+ const specFile = join14(specsDir, entry.name, "spec.md");
2917
3358
  let content;
2918
- if (existsSync12(acceptanceFile)) {
2919
- content = readFileSync10(acceptanceFile, "utf-8");
2920
- } else if (existsSync12(specFile)) {
2921
- content = readFileSync10(specFile, "utf-8");
3359
+ if (existsSync15(acceptanceFile)) {
3360
+ content = readFileSync14(acceptanceFile, "utf-8");
3361
+ } else if (existsSync15(specFile)) {
3362
+ content = readFileSync14(specFile, "utf-8");
2922
3363
  } else {
2923
3364
  out(
2924
3365
  fmt,
@@ -2931,7 +3372,7 @@ async function validate(targetPath, options) {
2931
3372
  continue;
2932
3373
  }
2933
3374
  const criteriaLines = content.match(/- \[ \] \*\*(.+?)\*\*: (.+)/g) || [];
2934
- const specContent = existsSync12(specFile) ? readFileSync10(specFile, "utf-8") : null;
3375
+ const specContent = existsSync15(specFile) ? readFileSync14(specFile, "utf-8") : null;
2935
3376
  out(fmt, "info", entry.name, "", `Spec: ${entry.name}`, "");
2936
3377
  if (criteriaLines.length === 0) {
2937
3378
  out(fmt, "info", entry.name, "", "No criteria found", "");
@@ -2948,7 +3389,7 @@ async function validate(targetPath, options) {
2948
3389
  let intelligenceResult = null;
2949
3390
  try {
2950
3391
  intelligenceResult = checkSpecContent(
2951
- join12(specsDir, entry.name),
3392
+ join14(specsDir, entry.name),
2952
3393
  label,
2953
3394
  description,
2954
3395
  config
@@ -2956,95 +3397,52 @@ async function validate(targetPath, options) {
2956
3397
  if (intelligenceResult) {
2957
3398
  status = intelligenceResult.status;
2958
3399
  note = intelligenceResult.note;
2959
- } else if (label.includes("letra init")) {
2960
- const tmp = mkdtempSync(join12(tmpdir(), "letra-test-"));
2961
- execSync(`npx tsx "${entryPoint}" init "${tmp}"`, { ...opts });
2962
- if (existsSync12(join12(tmp, ".letra", "context.md"))) status = "PASS";
2963
- rmSync(tmp, { recursive: true });
2964
- } else if (label.includes("letra spec")) {
2965
- const tmp = mkdtempSync(join12(tmpdir(), "letra-test-"));
2966
- execSync(`npx tsx "${entryPoint}" init "${tmp}"`, { ...opts });
2967
- execSync(`npx tsx "${entryPoint}" spec smoke-test`, {
2968
- ...opts,
2969
- cwd: tmp
2970
- });
2971
- if (existsSync12(join12(tmp, ".letra", "specs", "smoke-test", "spec.md")))
2972
- status = "PASS";
2973
- rmSync(tmp, { recursive: true });
2974
- } else if (label.includes("letra lint")) {
2975
- execSync(`npx tsx "${entryPoint}" lint`, { ...opts });
2976
- status = "PASS";
2977
3400
  } else if (label.includes("letra validate")) {
2978
3401
  status = "PASS";
2979
- } else if (label.includes("Workflow Ativo") || label.includes("CI") && existsSync12(ciFile)) {
2980
- status = "PASS";
2981
- } else if (label.includes("Lint Gate") || label.includes("Lint")) {
2982
- const ciContent = readFileSync10(ciFile, "utf-8");
2983
- if (ciContent.includes("letra lint") || ciContent.includes("lint"))
2984
- status = "PASS";
2985
- } else if (label.includes("Test Gate") || label.includes("Test")) {
2986
- const ciContent = readFileSync10(ciFile, "utf-8");
2987
- if (ciContent.includes("npm test") || ciContent.includes("vitest") || ciContent.includes("test"))
2988
- status = "PASS";
2989
- } else if (label.includes("Valida\xE7\xE3o de Formato") || label.includes("Formato")) {
2990
- const ciContent = readFileSync10(ciFile, "utf-8");
2991
- if (ciContent.includes("tsc") || ciContent.includes("typecheck"))
2992
- status = "PASS";
2993
- } else if (label.includes("Distribui\xE7\xE3o npm") || label.includes("npm")) {
2994
- const pkgJson = JSON.parse(
2995
- readFileSync10(join12(root, "package.json"), "utf-8")
2996
- );
2997
- if (pkgJson.bin && pkgJson.name) {
2998
- status = "PASS";
2999
- note = `(${pkgJson.name} @ ${pkgJson.version})`;
3000
- } else {
3001
- note = "(bin field missing)";
3002
- }
3003
- } else if (label.includes("Bin\xE1rio standalone") || label.includes("Bin\xE1rio")) {
3402
+ } else if (label.includes("Workflow Ativo")) {
3004
3403
  status = "PASS";
3005
- note = "(npm distribution preferred)";
3006
3404
  } else if (label.includes("Gera\xE7\xE3o de Regras") || label.includes("Gera\xE7\xE3o")) {
3007
- if (existsSync12(cursorRulesFile)) {
3008
- const rulesContent = readFileSync10(cursorRulesFile, "utf-8");
3405
+ if (existsSync15(cursorRulesFile)) {
3406
+ const rulesContent = readFileSync14(cursorRulesFile, "utf-8");
3009
3407
  if (rulesContent.includes(".letra/context.md") && rulesContent.includes(".letra/constitution.md")) {
3010
3408
  status = "PASS";
3011
3409
  }
3012
3410
  }
3013
3411
  } else if (label.includes("Inje\xE7\xE3o de Contexto")) {
3014
- if (existsSync12(cursorRulesFile)) {
3015
- const rulesContent = readFileSync10(cursorRulesFile, "utf-8");
3412
+ if (existsSync15(cursorRulesFile)) {
3413
+ const rulesContent = readFileSync14(cursorRulesFile, "utf-8");
3016
3414
  if (rulesContent.includes("@.letra/")) status = "PASS";
3017
- } else if (existsSync12(copilotFile)) {
3018
- const copilotContent = readFileSync10(copilotFile, "utf-8");
3415
+ } else if (existsSync15(copilotFile)) {
3416
+ const copilotContent = readFileSync14(copilotFile, "utf-8");
3019
3417
  if (copilotContent.includes(".letra/")) status = "PASS";
3020
3418
  }
3021
3419
  } else if (label.includes("Acesso a Valida\xE7\xE3o")) {
3022
- if (existsSync12(cursorRulesFile)) {
3023
- const rulesContent = readFileSync10(cursorRulesFile, "utf-8");
3420
+ if (existsSync15(cursorRulesFile)) {
3421
+ const rulesContent = readFileSync14(cursorRulesFile, "utf-8");
3024
3422
  if (rulesContent.includes("letra validate")) status = "PASS";
3025
3423
  }
3026
3424
  } else if (label.includes("N\xE3o-intrusivo")) {
3027
- if (existsSync12(cursorRulesFile) || existsSync12(copilotFile)) {
3425
+ if (existsSync15(cursorRulesFile) || existsSync15(copilotFile)) {
3028
3426
  status = "PASS";
3029
3427
  }
3030
3428
  } else if (label.includes("Gera\xE7\xE3o de Instru\xE7\xF5es")) {
3031
- if (existsSync12(copilotFile)) {
3032
- const copilotContent = readFileSync10(copilotFile, "utf-8");
3429
+ if (existsSync15(copilotFile)) {
3430
+ const copilotContent = readFileSync14(copilotFile, "utf-8");
3033
3431
  if (copilotContent.includes(".letra/context.md") && copilotContent.includes(".letra/constitution.md")) {
3034
3432
  status = "PASS";
3035
3433
  }
3036
3434
  }
3037
3435
  } else if (label.includes("Settings do Editor")) {
3038
- if (existsSync12(vscodeSettingsFile)) {
3039
- const settingsContent = readFileSync10(vscodeSettingsFile, "utf-8");
3436
+ if (existsSync15(vscodeSettingsFile)) {
3437
+ const settingsContent = readFileSync14(vscodeSettingsFile, "utf-8");
3040
3438
  if (settingsContent.includes("editor.formatOnSave")) {
3041
3439
  status = "PASS";
3042
3440
  }
3043
3441
  }
3044
3442
  } else if (label.includes("Arquivo de Config")) {
3045
- const configFile = join12(root, ".letra", "config.json");
3046
- if (existsSync12(configFile)) {
3047
- const cfgContent = readFileSync10(configFile, "utf-8");
3443
+ const configFile = join14(root, ".letra", "config.json");
3444
+ if (existsSync15(configFile)) {
3445
+ const cfgContent = readFileSync14(configFile, "utf-8");
3048
3446
  try {
3049
3447
  const parsed = JSON.parse(cfgContent);
3050
3448
  if (parsed.heuristics) {
@@ -3218,19 +3616,22 @@ async function validate(targetPath, options) {
3218
3616
  }
3219
3617
  }
3220
3618
  flushResults(allResults, fmt, specGroups, totalPass, totalFail, totalWarning);
3619
+ logEntry(targetPath || process.cwd(), "validate", `Valida\xE7\xE3o executada \u2014 ${totalPass} passed, ${totalFail} failed, ${totalWarning} warnings`, {
3620
+ details: { passed: totalPass, failed: totalFail, warnings: totalWarning }
3621
+ });
3221
3622
  return totalFail;
3222
3623
  }
3223
3624
  const exitCode = await runValidation();
3224
3625
  if (options?.watch) {
3225
3626
  let timer = null;
3226
- console.log(chalk14.gray("\nWatching for changes... (Ctrl+C to stop)"));
3627
+ console.log(chalk17.gray("\nWatching for changes... (Ctrl+C to stop)"));
3227
3628
  const watcher = watch2(specsDir, { recursive: true });
3228
3629
  watcher.on("change", () => {
3229
3630
  if (timer) clearTimeout(timer);
3230
3631
  timer = setTimeout(async () => {
3231
3632
  console.clear();
3232
3633
  const code = await runValidation();
3233
- console.log(chalk14.gray("\nWatching for changes... (Ctrl+C to stop)"));
3634
+ console.log(chalk17.gray("\nWatching for changes... (Ctrl+C to stop)"));
3234
3635
  }, 300);
3235
3636
  });
3236
3637
  process.on("SIGINT", () => {
@@ -3248,17 +3649,768 @@ async function validate(targetPath, options) {
3248
3649
  }
3249
3650
  }
3250
3651
 
3652
+ // src/commands/ac.ts
3653
+ function findAcByPattern(lines, acId) {
3654
+ const pattern = new RegExp(`^- \\[ \\] \\*\\*${escapeRegex(acId)}\\*\\*`);
3655
+ for (let i = 0; i < lines.length; i++) {
3656
+ if (pattern.test(lines[i].trim())) return i;
3657
+ }
3658
+ return null;
3659
+ }
3660
+ function escapeRegex(s) {
3661
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3662
+ }
3663
+ function listPendingACs(lines) {
3664
+ const result = [];
3665
+ const pattern = /^- \[ \] \*\*(AC[\d.]+)\*\*: (.+)$/;
3666
+ for (let i = 0; i < lines.length; i++) {
3667
+ const match = lines[i].trim().match(pattern);
3668
+ if (match) result.push({ lineIdx: i, id: match[1], text: match[2] });
3669
+ }
3670
+ return result;
3671
+ }
3672
+ function markAcById(root, acId, specName) {
3673
+ const workflow = loadWorkflow(root);
3674
+ let spec = specName;
3675
+ if (!spec && workflow) {
3676
+ const primaryItem = workflow.items.find((i) => i.id === workflow.primaryItemId);
3677
+ spec = primaryItem?.spec;
3678
+ }
3679
+ if (!spec) {
3680
+ throw new Error("Spec name required. Use --spec <name> or ensure an active item has a linked spec.");
3681
+ }
3682
+ const specFile = join15(root, ".letra", "specs", spec, "spec.md");
3683
+ if (!existsSync16(specFile)) {
3684
+ throw new Error(`Spec file not found: ${specFile}`);
3685
+ }
3686
+ const content = readFileSync15(specFile, "utf-8");
3687
+ const lines = content.split("\n");
3688
+ const lineIdx = findAcByPattern(lines, acId);
3689
+ if (lineIdx === null) {
3690
+ const pendings = listPendingACs(lines);
3691
+ const msg = `AC "${acId}" n\xE3o encontrado ou j\xE1 marcado como conclu\xEDdo.`;
3692
+ if (pendings.length > 0) {
3693
+ const pendingStr = pendings.map((ac) => `${ac.id}: ${ac.text}`).join(", ");
3694
+ throw new Error(`${msg} Pendentes: ${pendingStr}`);
3695
+ }
3696
+ throw new Error(msg);
3697
+ }
3698
+ lines[lineIdx] = lines[lineIdx].replace(/^- \[ \]/, "- [x]");
3699
+ writeFileSync8(specFile, lines.join("\n"), "utf-8");
3700
+ const itemId = workflow?.items.find((i) => i.spec === spec)?.id;
3701
+ logEntry(root, "ac_done", `AC ${acId} marcado como conclu\xEDdo em ${spec}`, {
3702
+ itemId,
3703
+ acId,
3704
+ details: { spec }
3705
+ });
3706
+ console.log(` ${chalk18.green("\u2713")} AC ${chalk18.cyan(acId)} marcado como conclu\xEDdo em ${chalk18.cyan(spec)}`);
3707
+ try {
3708
+ validate(root, { format: "text" });
3709
+ } catch {
3710
+ }
3711
+ if (workflow?.tools && workflow.tools.length > 0) {
3712
+ generateAdapters(root, workflow.tools, { source: "flow-ac", quiet: true });
3713
+ }
3714
+ }
3715
+ function listPendingAction(root, specName) {
3716
+ const workflow = loadWorkflow(root);
3717
+ let spec = specName;
3718
+ if (!spec && workflow) {
3719
+ const primaryItem = workflow.items.find((i) => i.id === workflow.primaryItemId);
3720
+ spec = primaryItem?.spec;
3721
+ }
3722
+ if (!spec) {
3723
+ console.log(chalk18.yellow("Nenhum spec ativo. Use --spec <name> ou tenha um item ativo com spec vinculada."));
3724
+ return;
3725
+ }
3726
+ const specFile = join15(root, ".letra", "specs", spec, "spec.md");
3727
+ if (!existsSync16(specFile)) {
3728
+ console.log(chalk18.red(`Spec file not found: ${specFile}`));
3729
+ return;
3730
+ }
3731
+ const content = readFileSync15(specFile, "utf-8");
3732
+ const lines = content.split("\n");
3733
+ const pendings = listPendingACs(lines);
3734
+ if (pendings.length === 0) {
3735
+ console.log(chalk18.green(`\u2705 Todos os ACs em "${spec}" est\xE3o conclu\xEDdos!`));
3736
+ } else {
3737
+ console.log(chalk18.yellow(`
3738
+ ACs pendentes em "${chalk18.cyan(spec)}":`));
3739
+ for (const ac of pendings) {
3740
+ console.log(` ${chalk18.red("\u2717")} ${chalk18.cyan(ac.id)}: ${ac.text}`);
3741
+ }
3742
+ console.log(chalk18.dim(`
3743
+ Para marcar um AC: letra ac done <AC-ID>`));
3744
+ }
3745
+ }
3746
+ function acCommand() {
3747
+ const cmd = new Command8("ac").description("Gerenciar Acceptance Criteria \u2014 marcar como conclu\xEDdo e listar pendentes");
3748
+ cmd.command("done <ac-id>").option("--spec <name>", "Nome do spec (padr\xE3o: spec do item ativo)").description("Marcar um AC como conclu\xEDdo no spec.md").action((acId, options) => {
3749
+ const root = resolve18(process.cwd());
3750
+ markAcById(root, acId, options.spec);
3751
+ });
3752
+ cmd.command("list").option("--spec <name>", "Nome do spec (padr\xE3o: spec do item ativo)").description("Listar ACs pendentes de um spec").action((options) => {
3753
+ const root = resolve18(process.cwd());
3754
+ listPendingAction(root, options.spec);
3755
+ });
3756
+ cmd.action(() => {
3757
+ const root = resolve18(process.cwd());
3758
+ listPendingAction(root);
3759
+ });
3760
+ return cmd;
3761
+ }
3762
+
3763
+ // src/commands/init.ts
3764
+ import { existsSync as existsSync18, mkdirSync as mkdirSync4, writeFileSync as writeFileSync9 } from "fs";
3765
+ import { join as join16, resolve as resolve19 } from "path";
3766
+ import { createInterface as createInterface2 } from "readline";
3767
+ import { fileURLToPath as fileURLToPath2 } from "url";
3768
+ import chalk19 from "chalk";
3769
+ import ora from "ora";
3770
+
3771
+ // src/adapters/language-registry.ts
3772
+ import { readdirSync as readdirSync6 } from "fs";
3773
+ var LANGUAGE_REGISTRY = [
3774
+ { name: "Node.js", detect: ["package.json"] },
3775
+ { name: "Python", detect: ["pyproject.toml", "setup.py", "requirements.txt"] },
3776
+ { name: "C# (.NET)", detect: ["*.csproj", "*.sln"] },
3777
+ { name: "Java", detect: ["pom.xml", "build.gradle"] },
3778
+ { name: "Go", detect: ["go.mod"] },
3779
+ { name: "Rust", detect: ["Cargo.toml"] },
3780
+ { name: "PHP", detect: ["composer.json"] },
3781
+ { name: "Ruby", detect: ["Gemfile"] },
3782
+ { name: "C/C++", detect: ["CMakeLists.txt", "Makefile"] },
3783
+ { name: "Swift", detect: ["Package.swift"] }
3784
+ ];
3785
+ function detectLanguage(root) {
3786
+ const entries = [];
3787
+ try {
3788
+ const files = readdirSync6(root);
3789
+ entries.push(...files);
3790
+ } catch {
3791
+ return null;
3792
+ }
3793
+ for (const lang of LANGUAGE_REGISTRY) {
3794
+ for (const pattern of lang.detect) {
3795
+ if (pattern.startsWith("*.")) {
3796
+ const ext = pattern.slice(1);
3797
+ if (entries.some((e) => e.endsWith(ext))) return lang.name;
3798
+ }
3799
+ if (entries.includes(pattern)) return lang.name;
3800
+ }
3801
+ }
3802
+ return null;
3803
+ }
3804
+
3805
+ // src/commands/init.ts
3806
+ var __dirname = fileURLToPath2(new URL(".", import.meta.url));
3807
+ function ask(query, options) {
3808
+ if (!process.stdin.isTTY) return Promise.resolve(options[0]);
3809
+ const rl = createInterface2({ input: process.stdin, output: process.stdout });
3810
+ return new Promise((resolve24) => {
3811
+ const formatted = `${chalk19.cyan(query)} ${options.map((o) => chalk19.gray(`(${o})`)).join(" ")}
3812
+ > `;
3813
+ rl.question(formatted, (answer) => {
3814
+ rl.close();
3815
+ const trimmed = answer.trim().toLowerCase();
3816
+ if (trimmed && options.some((o) => o.toLowerCase().startsWith(trimmed))) {
3817
+ resolve24(options.find((o) => o.toLowerCase().startsWith(trimmed)) ?? options[0]);
3818
+ } else if (trimmed && options.includes(trimmed)) {
3819
+ resolve24(trimmed);
3820
+ } else {
3821
+ resolve24(options[0]);
3822
+ }
3823
+ });
3824
+ });
3825
+ }
3826
+ function adaptConfig(projectType) {
3827
+ const config = {
3828
+ "conteudo-minimo": { severity: "warning", minChars: 50 },
3829
+ "consistencia-terminologia": { severity: "warning" },
3830
+ "detecao-tom": {
3831
+ severity: "warning",
3832
+ blacklist: ["tipo", "t\xE1", "pra", "blz", "kkk", "eita", "oi", "oi pessoal"]
3833
+ },
3834
+ "drift-temporal": { severity: "warning", maxDays: 30 },
3835
+ "secoes-vazias": { severity: "warning" },
3836
+ "acs-sem-metrica": { severity: "warning" },
3837
+ "baixa-confianca": { severity: "warning" }
3838
+ };
3839
+ if (projectType === "library") {
3840
+ config["detecao-tom"] = { severity: "off" };
3841
+ config["drift-temporal"] = { severity: "warning", maxDays: 60 };
3842
+ } else if (projectType === "mobile") {
3843
+ config["drift-temporal"] = { severity: "error", maxDays: 14 };
3844
+ config["baixa-confianca"] = { severity: "error" };
3845
+ } else if (projectType === "cli") {
3846
+ config["detecao-tom"] = { severity: "off" };
3847
+ }
3848
+ return JSON.stringify({ heuristics: config }, null, 2);
3849
+ }
3850
+ var TOOL_MAP = {
3851
+ opencode: ["opencode"],
3852
+ cursor: ["cursor"],
3853
+ windsurf: ["windsurf"],
3854
+ "claude code": ["claude-code"],
3855
+ "vscode copilot": ["vscode"],
3856
+ todos: ["cursor", "claude-code", "windsurf", "vscode", "opencode", "hermes"]
3857
+ };
3858
+ async function init(targetPath, options) {
3859
+ const root = resolve19(process.cwd(), targetPath || ".");
3860
+ const letraDir = join16(root, ".letra");
3861
+ if (existsSync18(letraDir)) {
3862
+ if (options?.serve) {
3863
+ console.log(chalk19.cyan(".letra/ already exists \u2014 starting UI..."));
3864
+ await flowServeAction(targetPath, { open: true });
3865
+ return;
3866
+ }
3867
+ console.log(chalk19.yellow(".letra/ already exists"));
3868
+ return;
3869
+ }
3870
+ const spinner = ora("Initializing Letra...").start();
3871
+ try {
3872
+ let projectType = "web-app";
3873
+ let tool = "cursor";
3874
+ if (options?.yes || !process.stdin.isTTY) {
3875
+ projectType = "web-app";
3876
+ tool = "todos";
3877
+ } else {
3878
+ spinner.stop();
3879
+ projectType = await ask("Project type?", ["web-app", "cli", "library", "mobile"]);
3880
+ const toolNames = [
3881
+ "Cursor",
3882
+ "Windsurf",
3883
+ "Claude Code",
3884
+ "VSCode Copilot",
3885
+ "OpenCode",
3886
+ "Todos"
3887
+ ];
3888
+ const answer = await ask("AI coding agent?", toolNames);
3889
+ tool = answer.toLowerCase();
3890
+ spinner.start();
3891
+ }
3892
+ mkdirSync4(join16(letraDir, "decisions"), { recursive: true });
3893
+ mkdirSync4(join16(letraDir, "specs", "_template"), { recursive: true });
3894
+ mkdirSync4(join16(letraDir, "adapters"), { recursive: true });
3895
+ const lang = detectLanguage(root);
3896
+ const langDisplay = lang ?? "general";
3897
+ const stackLine = lang ? `- **Stack**: ${lang}` : "- Sem stack espec\xEDfica (projeto general)";
3898
+ const codeRules = lang === "Node.js" ? "- TypeScript estrito (strict: true)\n- Zero dependencies desnecess\xE1rias" : "- C\xF3digo limpo e documentado\n- Seguir conven\xE7\xF5es do ecossistema";
3899
+ const templateFiles = {
3900
+ "context.md": `# Context
3901
+
3902
+ > Updated: 2026-06-16
3903
+ > Owner: time
3904
+
3905
+ ## Intent
3906
+
3907
+ Este projeto segue Specification-Driven Development (SDD).
3908
+ Capturamos dire\xE7\xE3o, inten\xE7\xE3o e contexto para enriquecer prompts de agentes de IA.
3909
+
3910
+ ## Dom\xEDnio
3911
+
3912
+ - ${stackLine}
3913
+ - Ferramenta: .letra/ memory format
3914
+ - P\xFAblico: equipe de desenvolvimento
3915
+
3916
+ ## Restri\xE7\xF5es Reais
3917
+
3918
+ - Specs devem ser thin (m\xE1x 1 p\xE1gina por feature)
3919
+ - Sem lock-in de IDE
3920
+ - Drift detection deve funcionar para qualquer dom\xEDnio (n\xE3o s\xF3 c\xF3digo)
3921
+ `,
3922
+ "constitution.md": `# Constitution
3923
+
3924
+ ## Arquitetura
3925
+ - Adapter layer desde o dia 1 \u2014 nunca travar em uma IDE
3926
+ - Formato .letra/ \xE9 a fonte da verdade, n\xE3o o c\xF3digo
3927
+ - CLI deve ser extens\xEDvel via plugins
3928
+
3929
+ ## C\xF3digo
3930
+ ${codeRules}
3931
+
3932
+ ## Specs
3933
+ - Thin specs: m\xE1ximo 1 p\xE1gina por feature
3934
+ - Markdown checklist para acceptance criteria
3935
+ - Toda spec deve ter: Outcome, Constraints, Exclusions, Acceptance Criteria, Context
3936
+
3937
+ ## Seguran\xE7a
3938
+ - Nunca incluir secrets, tokens ou chaves no reposit\xF3rio
3939
+ `,
3940
+ "glossary.md": `# Glossary
3941
+
3942
+ | Termo | Defini\xE7\xE3o |
3943
+ |-------|-----------|
3944
+ | **Spec** | Especifica\xE7\xE3o thin que define o que deve ser constru\xEDdo. |
3945
+ | **Drift** | Diverg\xEAncia entre o que a spec diz e o que o artefato realmente entrega. |
3946
+ | **Adapter** | Tradutor que converte .letra/ para o formato que uma IDE/agent entende. |
3947
+ | **Context** | Documento que captura intent, dom\xEDnio, restri\xE7\xF5es reais e "porqu\xEAs" do projeto. |
3948
+ | **Constitution** | Regras n\xE3o-negoci\xE1veis de arquitetura, c\xF3digo e workflow. |
3949
+ | **Thin Spec** | Spec de no m\xE1ximo 1 p\xE1gina, focada em outcome. |
3950
+ `,
3951
+ "lessons-learned.md": `# Lessons Learned
3952
+
3953
+ ## O que funcionou
3954
+ - Pesquisar dores reais do SDD antes de definir arquitetura
3955
+ - Decidir por evid\xEAncias (m\xE9tricas, dados) e n\xE3o por intui\xE7\xE3o
3956
+
3957
+ ## O que aprendemos
3958
+ - Drift detection n\xE3o pode ser code-centric \u2014 p\xFAblico prim\xE1rio s\xE3o n\xE3o-devs
3959
+ - Obsidian nunca deve ser requisito \u2014 barreira de ado\xE7\xE3o
3960
+ - Specs thin focadas em outcome reduzem atrito
3961
+
3962
+ ## Padr\xF5es a evitar
3963
+ - Specs gigantes (Markdown Madness)
3964
+ - Lock-in de IDE
3965
+ - Spec que vira pseudo-c\xF3digo
3966
+ `
3967
+ };
3968
+ for (const [file, content] of Object.entries(templateFiles)) {
3969
+ writeFileSync9(join16(letraDir, file), content, "utf-8");
3970
+ }
3971
+ const specTemplate = join16(letraDir, "specs", "_template.md");
3972
+ const specContent = `# Spec Template
3973
+
3974
+ > Updated: YYYY-MM-DD
3975
+
3976
+ ## Outcome
3977
+ O que o usu\xE1rio consegue fazer quando isso estiver pronto.
3978
+
3979
+ ## Constraints
3980
+ Limita\xE7\xF5es t\xE9cnicas e de neg\xF3cio que n\xE3o podem ser violadas.
3981
+
3982
+ ## Exclusions
3983
+ O que explicitamente N\xC3O est\xE1 neste escopo.
3984
+
3985
+ ## Acceptance Criteria
3986
+ - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
3987
+
3988
+ ## Context
3989
+ Por que estamos construindo isso.
3990
+ `;
3991
+ writeFileSync9(specTemplate, specContent);
3992
+ const configPath = join16(letraDir, "config.json");
3993
+ writeFileSync9(configPath, adaptConfig(projectType));
3994
+ console.log(` ${chalk19.gray("Created")} .letra/config.json`);
3995
+ const tools = TOOL_MAP[tool] || TOOL_MAP.todos;
3996
+ generateAdapters(root, tools, { source: "init" });
3997
+ if ((tool === "todos" || tool === "vscode") && lang === "Node.js") {
3998
+ const vscodeDir = join16(root, ".vscode");
3999
+ if (!existsSync18(vscodeDir)) mkdirSync4(vscodeDir, { recursive: true });
4000
+ const vscodeSettingsPath = join16(vscodeDir, "settings.json");
4001
+ const vscodeSettingsContent = `{
4002
+ "editor.formatOnSave": true,
4003
+ "editor.defaultFormatter": "esbenp.prettier-vscode",
4004
+ "editor.codeActionsOnSave": {
4005
+ "source.fixAll.eslint": "explicit"
4006
+ },
4007
+ "files.autoSave": "onFocusChange"
4008
+ }
4009
+ `;
4010
+ writeFileSync9(vscodeSettingsPath, vscodeSettingsContent);
4011
+ console.log(` ${chalk19.gray("Created")} .vscode/settings.json`);
4012
+ }
4013
+ spinner.succeed(chalk19.green(".letra/ initialized successfully"));
4014
+ console.log("");
4015
+ console.log(" Next steps:");
4016
+ console.log(` ${chalk19.cyan("letra spec new <name>")} Create your first spec`);
4017
+ console.log(` ${chalk19.cyan("letra lint")} Validate specs`);
4018
+ console.log(` ${chalk19.cyan("letra init --serve")} Open web UI to configure workflow`);
4019
+ if (lang) {
4020
+ const workflow = {
4021
+ version: "1.0",
4022
+ name: resolve19(root).split(/[\\/]/).pop() || "meu-projeto",
4023
+ language: lang,
4024
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
4025
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
4026
+ stages: [
4027
+ { id: "backlog", name: "Backlog", order: 0, zone: "todo" },
4028
+ { id: "design", name: "Design", order: 1, zone: "doing" },
4029
+ { id: "code", name: "Code", order: 2, zone: "doing" },
4030
+ { id: "review", name: "Review", order: 3, zone: "doing" },
4031
+ { id: "done", name: "Done", order: 4, zone: "done" }
4032
+ ],
4033
+ items: [],
4034
+ tools: ["cursor", "opencode"]
4035
+ };
4036
+ writeWorkflow(root, { workflow, source: "init", skipSitrep: true, quiet: true });
4037
+ }
4038
+ if (options?.serve) {
4039
+ console.log(`
4040
+ ${chalk19.cyan("Opening web UI...")}
4041
+ `);
4042
+ await flowServeAction(targetPath, { open: true });
4043
+ return;
4044
+ }
4045
+ } catch (error) {
4046
+ spinner.fail(chalk19.red("Failed to initialize Letra"));
4047
+ process.exit(1);
4048
+ }
4049
+ }
4050
+
4051
+ // src/commands/lint.ts
4052
+ import { existsSync as existsSync19, readdirSync as readdirSync8 } from "fs";
4053
+ import { join as join17, resolve as resolve20 } from "path";
4054
+ import chalk20 from "chalk";
4055
+ async function lint(targetPath) {
4056
+ const root = resolve20(process.cwd(), targetPath || ".");
4057
+ const specsDir = join17(root, ".letra", "specs");
4058
+ if (!existsSync19(specsDir)) {
4059
+ console.log(chalk20.red("Error: .letra/specs/ not found. Run 'letra init' first."));
4060
+ process.exit(1);
4061
+ }
4062
+ let totalErrors = 0;
4063
+ let totalWarnings = 0;
4064
+ const results = [];
4065
+ const entries = readdirSync8(specsDir, { withFileTypes: true });
4066
+ for (const entry of entries) {
4067
+ if (!entry.isDirectory() || entry.name.startsWith("_")) continue;
4068
+ const specFile = join17(specsDir, entry.name, "spec.md");
4069
+ const { errors, warnings } = validateSpecStructure(specFile);
4070
+ if (errors.length > 0 || warnings.length > 0) {
4071
+ results.push({ file: entry.name, errors, warnings });
4072
+ totalErrors += errors.length;
4073
+ totalWarnings += warnings.length;
4074
+ }
4075
+ }
4076
+ if (results.length === 0) {
4077
+ console.log(chalk20.green("All specs are valid"));
4078
+ process.exit(0);
4079
+ }
4080
+ console.log("");
4081
+ for (const result of results) {
4082
+ console.log(chalk20.bold(`
4083
+ Spec: ${result.file}`));
4084
+ for (const error of result.errors) {
4085
+ console.log(chalk20.red(` \u2717 ${error}`));
4086
+ }
4087
+ for (const warning of result.warnings) {
4088
+ console.log(chalk20.yellow(` \u26A0 ${warning}`));
4089
+ }
4090
+ }
4091
+ console.log(
4092
+ chalk20.gray(
4093
+ `
4094
+ ${results.length} spec(s) with issues: ${totalErrors} error(s), ${totalWarnings} warning(s)`
4095
+ )
4096
+ );
4097
+ process.exit(totalErrors > 0 ? 1 : 0);
4098
+ }
4099
+
4100
+ // src/commands/spec.ts
4101
+ import { existsSync as existsSync20, mkdirSync as mkdirSync5, readFileSync as readFileSync16, readdirSync as readdirSync9, writeFileSync as writeFileSync10 } from "fs";
4102
+ import { join as join18, resolve as resolve21 } from "path";
4103
+ import chalk21 from "chalk";
4104
+ import ora2 from "ora";
4105
+ var builtInTemplates = {
4106
+ "web-api": {
4107
+ spec: `# Spec: {{name}}
4108
+
4109
+ > Updated: {{date}}
4110
+
4111
+ ## Outcome
4112
+ Usu\xE1rio consegue fazer requisi\xE7\xF5es HTTP para a API e receber respostas padronizadas.
4113
+
4114
+ ## Constraints
4115
+ - RESTful\u9075\u5FAA (GET, POST, PUT, DELETE)
4116
+ - Autentica\xE7\xE3o via Bearer token JWT
4117
+ - Rate limiting: 100 req/min por usu\xE1rio
4118
+ - Timeout m\xE1ximo de 30s por requisi\xE7\xE3o
4119
+
4120
+ ## Exclusions
4121
+ - WebSocket n\xE3o est\xE1 no escopo
4122
+ - Upload de arquivos n\xE3o est\xE1 no escopo inicial
4123
+
4124
+ ## Acceptance Criteria
4125
+ - [ ] **CRUD**: CRUD completo para o recurso principal (GET, POST, PUT, DELETE retornam 200/201/204).
4126
+ - [ ] **Autentica\xE7\xE3o**: Rota sem token retorna 401, rota com token inv\xE1lido retorna 403.
4127
+ - [ ] **Valida\xE7\xE3o**: Payload inv\xE1lido retorna 422 com mensagem de erro descritiva.
4128
+ - [ ] **Rate Limit**: Exceder 100 req/min retorna 429 com header Retry-After.
4129
+ - [ ] **Pagina\xE7\xE3o**: GET com ?page=2&limit=10 retorna p\xE1gina correta com total count.
4130
+
4131
+ ## Context
4132
+ Template para APIs REST. Adaptado para o dom\xEDnio espec\xEDfico do projeto.`,
4133
+ acceptance: `# Acceptance Criteria \u2014 {{name}}
4134
+
4135
+ - [ ] **CRUD**: CRUD completo para o recurso principal (GET, POST, PUT, DELETE retornam 200/201/204).
4136
+ - [ ] **Autentica\xE7\xE3o**: Rota sem token retorna 401, rota com token inv\xE1lido retorna 403.
4137
+ - [ ] **Valida\xE7\xE3o**: Payload inv\xE1lido retorna 422 com mensagem de erro descritiva.
4138
+ - [ ] **Rate Limit**: Exceder 100 req/min retorna 429 com header Retry-After.
4139
+ - [ ] **Pagina\xE7\xE3o**: GET com ?page=2&limit=10 retorna p\xE1gina correta com total count.`
4140
+ },
4141
+ "cli-tool": {
4142
+ spec: `# Spec: {{name}}
4143
+
4144
+ > Updated: {{date}}
4145
+
4146
+ ## Outcome
4147
+ Usu\xE1rio instala e executa a CLI, recebendo output formatado no terminal.
4148
+
4149
+ ## Constraints
4150
+ - Node.js 22+ como runtime
4151
+ - Deve funcionar em Windows, macOS e Linux
4152
+ - Exit codes seguem padr\xE3o Unix (0 sucesso, 1 erro)
4153
+ - --help deve funcionar sem argumentos
4154
+
4155
+ ## Exclusions
4156
+ - UI gr\xE1fica n\xE3o est\xE1 no escopo
4157
+ - Modo servidor/daemon n\xE3o est\xE1 no escopo
4158
+
4159
+ ## Acceptance Criteria
4160
+ - [ ] **Instala\xE7\xE3o**: CLI execut\xE1vel via npx/npm install -g sem erros.
4161
+ - [ ] **--help**: Roda sem argumentos, exibe ajuda com subcomandos.
4162
+ - [ ] **Subcomando**: Subcomando principal executa sem erros e exibe output.
4163
+ - [ ] **Erro**: Subcomando inv\xE1lido exibe erro amig\xE1vel e exit 1.
4164
+ - [ ] **Cross-platform**: Funciona em Windows (cmd/powershell), macOS (zsh) e Linux (bash).
4165
+
4166
+ ## Context
4167
+ Template para ferramentas de linha de comando. Adaptado para o escopo espec\xEDfico.`,
4168
+ acceptance: `# Acceptance Criteria \u2014 {{name}}
4169
+
4170
+ - [ ] **Instala\xE7\xE3o**: CLI execut\xE1vel via npx/npm install -g sem erros.
4171
+ - [ ] **--help**: Roda sem argumentos, exibe ajuda com subcomandos.
4172
+ - [ ] **Subcomando**: Subcomando principal executa sem erros e exibe output.
4173
+ - [ ] **Erro**: Subcomando inv\xE1lido exibe erro amig\xE1vel e exit 1.
4174
+ - [ ] **Cross-platform**: Funciona em Windows (cmd/powershell), macOS (zsh) e Linux (bash).`
4175
+ },
4176
+ "mobile-feature": {
4177
+ spec: `# Spec: {{name}}
4178
+
4179
+ > Updated: {{date}}
4180
+
4181
+ ## Outcome
4182
+ Usu\xE1rio consegue acessar e interagir com a nova funcionalidade no aplicativo mobile.
4183
+
4184
+ ## Constraints
4185
+ - Suporte a iOS 16+ e Android 13+
4186
+ - Offline-first: funcionalidade deve funcionar sem internet
4187
+ - Tempo de resposta < 200ms para intera\xE7\xF5es locais
4188
+ - Acessibilidade: VoiceOver (iOS) e TalkBack (Android)
4189
+
4190
+ ## Exclusions
4191
+ - Vers\xE3o web n\xE3o est\xE1 no escopo (mobile-only)
4192
+ - Suporte a tablets \xE9 desej\xE1vel mas n\xE3o obrigat\xF3rio
4193
+
4194
+ ## Acceptance Criteria
4195
+ - [ ] **Tela principal**: Nova funcionalidade aparece na navega\xE7\xE3o principal.
4196
+ - [ ] **Offline**: Funcionalidade completa funciona sem conex\xE3o de rede.
4197
+ - [ ] **Performance**: Scroll da lista com 1000+ itens mant\xE9m 60fps.
4198
+ - [ ] **Acessibilidade**: Todos os elementos t\xEAm label de acessibilidade.
4199
+ - [ ] **Dark Mode**: Funcionalidade respeita o tema do sistema.
4200
+
4201
+ ## Context
4202
+ Template para features mobile nativas. Adaptado para o framework espec\xEDfico (SwiftUI/Compose).`,
4203
+ acceptance: `# Acceptance Criteria \u2014 {{name}}
4204
+
4205
+ - [ ] **Tela principal**: Nova funcionalidade aparece na navega\xE7\xE3o principal.
4206
+ - [ ] **Offline**: Funcionalidade completa funciona sem conex\xE3o de rede.
4207
+ - [ ] **Performance**: Scroll da lista com 1000+ itens mant\xE9m 60fps.
4208
+ - [ ] **Acessibilidade**: Todos os elementos t\xEAm label de acessibilidade.
4209
+ - [ ] **Dark Mode**: Funcionalidade respeita o tema do sistema.`
4210
+ }
4211
+ };
4212
+ function listTemplates(root) {
4213
+ const names = Object.keys(builtInTemplates);
4214
+ const customDir = join18(root, ".letra", "templates");
4215
+ if (existsSync20(customDir)) {
4216
+ for (const file of readdirSync9(customDir)) {
4217
+ if (file.endsWith(".md")) {
4218
+ const name = file.replace(/\.md$/, "");
4219
+ if (!names.includes(name)) names.push(name);
4220
+ }
4221
+ }
4222
+ }
4223
+ return names;
4224
+ }
4225
+ function findTemplate(root, type) {
4226
+ const lower = type.toLowerCase();
4227
+ if (builtInTemplates[lower]) return builtInTemplates[lower];
4228
+ const customFile = join18(root, ".letra", "templates", `${type}.md`);
4229
+ const customAcceptance = join18(root, ".letra", "templates", `${type}-acceptance.md`);
4230
+ if (existsSync20(customFile)) {
4231
+ const spec = readFileSync16(customFile, "utf-8");
4232
+ const acceptance = existsSync20(customAcceptance) ? readFileSync16(customAcceptance, "utf-8") : `# Acceptance Criteria \u2014 ${type}
4233
+
4234
+ - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
4235
+ `;
4236
+ return { spec, acceptance };
4237
+ }
4238
+ return null;
4239
+ }
4240
+ function applyPlaceholders(content, name, date) {
4241
+ return content.replace(/\{\{name\}\}/g, name).replace(/\{\{date\}\}/g, date);
4242
+ }
4243
+ function specLink(itemId, specName) {
4244
+ const root = resolve21(process.cwd());
4245
+ const workflow = loadWorkflow(root);
4246
+ if (!workflow) {
4247
+ console.log(chalk21.red("No workflow found"));
4248
+ process.exit(1);
4249
+ }
4250
+ const item = workflow.items.find((i) => i.id === itemId);
4251
+ if (!item) {
4252
+ console.log(chalk21.red(`Item ${itemId} not found`));
4253
+ process.exit(1);
4254
+ }
4255
+ const specDir = join18(root, ".letra", "specs", specName);
4256
+ if (!existsSync20(specDir)) {
4257
+ console.log(chalk21.red(`Spec "${specName}" not found at .letra/specs/${specName}/`));
4258
+ return;
4259
+ }
4260
+ item.spec = specName;
4261
+ if (!workflow.specLinks) workflow.specLinks = {};
4262
+ workflow.specLinks[specName] = { path: `.letra/specs/${specName}/spec.md` };
4263
+ workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
4264
+ writeWorkflow(root, { workflow, source: "flow-edit", skipSitrep: true });
4265
+ logEntry(root, "manual", `spec linked: ${itemId} \u2192 ${specName}`, { itemId });
4266
+ console.log(` ${chalk21.green("\u2713")} ${itemId} \u2192 ${chalk21.cyan(specName)}`);
4267
+ }
4268
+ async function specNew(name, options) {
4269
+ const root = resolve21(process.cwd());
4270
+ const letraDir = join18(root, ".letra");
4271
+ const specDir = join18(letraDir, "specs", name);
4272
+ if (!existsSync20(letraDir)) {
4273
+ console.log(chalk21.red(".letra/ not found. Run 'letra init' first."));
4274
+ process.exit(1);
4275
+ }
4276
+ if (existsSync20(specDir)) {
4277
+ console.log(chalk21.yellow(`Spec "${name}" already exists`));
4278
+ return;
4279
+ }
4280
+ const templateType = options?.template || "_default";
4281
+ const template = templateType === "_default" ? null : findTemplate(root, templateType);
4282
+ if (options?.template && !template) {
4283
+ const available = listTemplates(root).join(", ");
4284
+ console.log(chalk21.red(`Template "${options.template}" not found. Available: ${available}`));
4285
+ process.exit(1);
4286
+ }
4287
+ const spinner = ora2(`Creating spec "${name}"...`).start();
4288
+ try {
4289
+ const today2 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
4290
+ mkdirSync5(specDir, { recursive: true });
4291
+ if (template) {
4292
+ const specContent = applyPlaceholders(template.spec, name, today2);
4293
+ const acceptanceContent = applyPlaceholders(template.acceptance, name, today2);
4294
+ writeFileSync10(join18(specDir, "spec.md"), specContent);
4295
+ writeFileSync10(join18(specDir, "acceptance.md"), acceptanceContent);
4296
+ } else {
4297
+ const specContent = `# Spec: ${name}
4298
+
4299
+ > Updated: ${today2}
4300
+
4301
+ ## Outcome
4302
+ O que o usu\xE1rio consegue fazer quando isso estiver pronto.
4303
+
4304
+ ## Constraints
4305
+ Limita\xE7\xF5es t\xE9cnicas e de neg\xF3cio que n\xE3o podem ser violadas.
4306
+
4307
+ ## Exclusions
4308
+ O que explicitamente N\xC3O est\xE1 neste escopo.
4309
+
4310
+ ## Acceptance Criteria
4311
+ - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
4312
+
4313
+ ## Context
4314
+ Por que estamos construindo isso. Trade-offs considerados.
4315
+ `;
4316
+ const acceptanceContent = `# Acceptance Criteria \u2014 ${name}
4317
+
4318
+ - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
4319
+ `;
4320
+ writeFileSync10(join18(specDir, "spec.md"), specContent);
4321
+ writeFileSync10(join18(specDir, "acceptance.md"), acceptanceContent);
4322
+ }
4323
+ spinner.succeed(chalk21.green(`Spec "${name}" created at .letra/specs/${name}/`));
4324
+ } catch (error) {
4325
+ spinner.fail(chalk21.red("Failed to create spec"));
4326
+ process.exit(1);
4327
+ }
4328
+ }
4329
+
4330
+ // src/commands/diagnose.ts
4331
+ import { resolve as resolve22 } from "path";
4332
+ async function diagnose(targetPath) {
4333
+ const root = resolve22(process.cwd(), targetPath ?? ".");
4334
+ const engine = new DiagnosticEngine(root);
4335
+ engine.ensureDirs();
4336
+ console.log("\n\u{1F50D} Auto-diagn\xF3stico do Letra\n");
4337
+ const output = await engine.runAll();
4338
+ if (output.fixes.length > 0) {
4339
+ console.log(`\u2705 ${output.fixes.length} auto-corre\xE7\xE3o(\xF5es) aplicada(s):
4340
+ `);
4341
+ for (const fix of output.fixes) {
4342
+ console.log(` \u2022 ${fix.title}`);
4343
+ }
4344
+ console.log();
4345
+ }
4346
+ if (output.suggestions.length > 0) {
4347
+ console.log(`\u{1F4A1} ${output.suggestions.length} sugest\xE3o(\xF5es):
4348
+ `);
4349
+ for (const s of output.suggestions) {
4350
+ console.log(` \u2022 [${s.type}] ${s.title}`);
4351
+ console.log(` ${s.description}`);
4352
+ }
4353
+ console.log();
4354
+ }
4355
+ if (output.errors.length > 0) {
4356
+ console.log(`\u274C ${output.errors.length} erro(s) nos detectores:
4357
+ `);
4358
+ for (const err of output.errors) {
4359
+ console.log(` \u2022 ${err}`);
4360
+ }
4361
+ console.log();
4362
+ }
4363
+ if (output.fixes.length === 0 && output.suggestions.length === 0 && output.errors.length === 0) {
4364
+ console.log(" Nenhum problema detectado. Tudo ok.\n");
4365
+ }
4366
+ const suggestions = output.suggestions.map((s) => ({
4367
+ id: s.id,
4368
+ type: s.type,
4369
+ title: s.title,
4370
+ description: s.description,
4371
+ certainty: 0.8,
4372
+ detector: s.detector
4373
+ }));
4374
+ const record = loadHealthRecord(root);
4375
+ mergeScanResults(record, suggestions);
4376
+ saveHealthRecord(root, record);
4377
+ const snapshots = engine.listSnapshots();
4378
+ if (snapshots.length > 0) {
4379
+ console.log(`\u{1F4E6} ${snapshots.length} snapshots dispon\xEDveis para undo:`);
4380
+ for (const snap of snapshots.slice(0, 5)) {
4381
+ console.log(
4382
+ ` \u2022 ${snap.id} \u2014 ${snap.diagnosticTitle} (${new Date(snap.timestamp).toLocaleString()})`
4383
+ );
4384
+ }
4385
+ if (snapshots.length > 5) {
4386
+ console.log(` ... e mais ${snapshots.length - 5}`);
4387
+ }
4388
+ console.log();
4389
+ }
4390
+ logEntry(root, "diagnose", `Diagn\xF3stico executado \u2014 ${output.fixes.length} auto-corre\xE7\xE3o(\xF5es), ${output.suggestions.length} sugest\xE3o(\xF5es), ${output.errors.length} erro(s)`, {
4391
+ details: { fixes: output.fixes.length, suggestions: output.suggestions.length, errors: output.errors.length }
4392
+ });
4393
+ }
4394
+
3251
4395
  // src/index.ts
3252
4396
  var __dirname2 = fileURLToPath3(new URL(".", import.meta.url));
3253
- var pkg = JSON.parse(readFileSync11(join13(resolve16(__dirname2, ".."), "package.json"), "utf-8"));
3254
- var program = new Command4();
4397
+ var pkg = JSON.parse(readFileSync17(join19(resolve23(__dirname2, ".."), "package.json"), "utf-8"));
4398
+ var program = new Command9();
3255
4399
  program.name("letra").description("SDD-agnostic memory framework for AI coding agents").version(pkg.version);
3256
4400
  program.command("init [path]").option("--yes", "Skip prompts and use defaults").option("--serve", "Open web UI after init (starts flow serve)").description("Initialize .letra/ directory with templates").action((path, options) => init(path, { ...options }));
3257
4401
  var specCmd = program.command("spec").description("Manage specs");
3258
4402
  specCmd.command("new <name>").option("--template <type>", "Template type: web-api, cli-tool, mobile-feature").description("Create a new spec from template").action((name, options) => specNew(name, { ...options }));
4403
+ specCmd.command("link <item-id> <spec-name>").description("Link an existing spec to an item").action((itemId, specName) => specLink(itemId, specName));
3259
4404
  program.command("lint [path]").description("Validate spec format and completeness").action(lint);
3260
4405
  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 }));
4406
+ program.command("diagnose [path]").description("Detect and fix drifts between specs, code, and workflow").action((path) => diagnose(path));
4407
+ program.addCommand(acCommand());
3261
4408
  program.addCommand(decisionCommand());
3262
4409
  program.addCommand(flowCommand());
3263
4410
  program.addCommand(focus_default());
4411
+ program.addCommand(health_default());
4412
+ program.addCommand(log_default());
4413
+ program.addCommand(pulse_default());
4414
+ program.addCommand(sitrep_default());
4415
+ program.addCommand(sync_default());
3264
4416
  program.parse();