@letra-ai/cli 0.4.0 → 0.4.1

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,8 +1,14 @@
1
1
  #!/usr/bin/env node
2
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
+ }) : x)(function(x) {
5
+ if (typeof require !== "undefined") return require.apply(this, arguments);
6
+ throw Error('Dynamic require of "' + x + '" is not supported');
7
+ });
2
8
 
3
9
  // src/index.ts
4
- import { readFileSync as readFileSync11 } from "fs";
5
- import { join as join13, resolve as resolve16 } from "path";
10
+ import { readFileSync as readFileSync18 } from "fs";
11
+ import { join as join24, resolve as resolve17 } from "path";
6
12
  import { fileURLToPath as fileURLToPath3 } from "url";
7
13
  import { Command as Command4 } from "commander";
8
14
 
@@ -90,12 +96,12 @@ import ora from "ora";
90
96
  function askText(query, defaultValue) {
91
97
  if (!process.stdin.isTTY) return Promise.resolve(defaultValue);
92
98
  const rl = createInterface({ input: process.stdin, output: process.stdout });
93
- return new Promise((resolve17) => {
99
+ return new Promise((resolve18) => {
94
100
  const formatted = `${chalk2.cyan(query)} ${chalk2.gray(`(default: ${defaultValue})`)}
95
101
  > `;
96
102
  rl.question(formatted, (answer) => {
97
103
  rl.close();
98
- resolve17(answer.trim() || defaultValue);
104
+ resolve18(answer.trim() || defaultValue);
99
105
  });
100
106
  });
101
107
  }
@@ -834,110 +840,365 @@ async function backlogImportLinearAction(targetPath, team, options) {
834
840
  }
835
841
 
836
842
  // 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";
843
+ import { resolve as resolve8 } from "path";
844
+ import chalk9 from "chalk";
845
+
846
+ // src/adapters/generate.ts
847
+ import { existsSync as existsSync8, mkdirSync as mkdirSync3, writeFileSync as writeFileSync6 } from "fs";
848
+ import { join as join8 } from "path";
839
849
  import chalk8 from "chalk";
840
- function now6() {
841
- return (/* @__PURE__ */ new Date()).toISOString();
850
+
851
+ // src/adapters/builder.ts
852
+ import { existsSync as existsSync7 } from "fs";
853
+ import { join as join7 } from "path";
854
+
855
+ // src/adapters/ac-counter.ts
856
+ import { existsSync as existsSync5, readFileSync as readFileSync5 } from "fs";
857
+ import { join as join5 } from "path";
858
+ var PENDING_PATTERN = /-\s*\[ \]\s*\*\*(.+?)\*\*/g;
859
+ var DONE_PATTERN = /-\s*\[[xX]\]\s*\*\*(.+?)\*\*/g;
860
+ function countInText(text) {
861
+ const pendingMatches = text.match(PENDING_PATTERN) || [];
862
+ const doneMatches = text.match(DONE_PATTERN) || [];
863
+ const pending = pendingMatches.length;
864
+ const total = pending + doneMatches.length;
865
+ return { pending, total };
842
866
  }
843
- function resolveStage(workflow, input) {
844
- const lower = input.toLowerCase();
845
- for (const stage of workflow.stages) {
846
- if (stage.id === lower) return stage.id;
847
- if (stage.name.toLowerCase() === lower) return stage.id;
867
+ function countACs(specDir) {
868
+ const acceptanceFile = join5(specDir, "acceptance.md");
869
+ const specFile = join5(specDir, "spec.md");
870
+ let acceptancePending = 0;
871
+ let acceptanceTotal = 0;
872
+ let specPending = 0;
873
+ let specTotal = 0;
874
+ let hasAcceptance = false;
875
+ let hasSpec = false;
876
+ if (existsSync5(acceptanceFile)) {
877
+ hasAcceptance = true;
878
+ const content = readFileSync5(acceptanceFile, "utf-8");
879
+ const counts = countInText(content);
880
+ acceptancePending = counts.pending;
881
+ acceptanceTotal = counts.total;
882
+ }
883
+ if (existsSync5(specFile)) {
884
+ hasSpec = true;
885
+ const content = readFileSync5(specFile, "utf-8");
886
+ const match = content.match(/## Acceptance Criteria\s+([\s\S]*?)(?=\n## |\n*$)/);
887
+ const sectionContent = match ? match[1] : "";
888
+ const counts = countInText(sectionContent);
889
+ specPending = counts.pending;
890
+ specTotal = counts.total;
891
+ }
892
+ const drift = hasAcceptance && hasSpec && acceptanceTotal !== specTotal;
893
+ if (hasAcceptance) {
894
+ return {
895
+ pending: acceptancePending,
896
+ total: acceptanceTotal,
897
+ specCount: specTotal,
898
+ acceptanceCount: acceptanceTotal,
899
+ drift
900
+ };
848
901
  }
849
- return null;
902
+ return {
903
+ pending: specPending,
904
+ total: specTotal,
905
+ specCount: specTotal,
906
+ acceptanceCount: 0,
907
+ drift: false
908
+ };
909
+ }
910
+
911
+ // src/adapters/focus-sync.ts
912
+ import { existsSync as existsSync6, readFileSync as readFileSync6, unlinkSync, writeFileSync as writeFileSync5 } from "fs";
913
+ import { join as join6 } from "path";
914
+ function extractOutcome(rootDir, specName) {
915
+ const specFile = join6(rootDir, ".letra", "specs", specName, "spec.md");
916
+ if (!existsSync6(specFile)) return null;
917
+ const content = readFileSync6(specFile, "utf-8");
918
+ const match = content.match(/## Outcome\s+([\s\S]*?)(?=\n## |\n*$)/);
919
+ return match ? match[1].trim() : null;
920
+ }
921
+ function writeFocusFile(rootDir, specName, itemId) {
922
+ const focusFile = join6(rootDir, ".letra", "focus.md");
923
+ const outcome = extractOutcome(rootDir, specName) || specName;
924
+ const content = [
925
+ `# Focus: ${specName}`,
926
+ "",
927
+ `**Path**: .letra/specs/${specName}/`,
928
+ `**Item**: ${itemId}`,
929
+ `**Outcome**: ${outcome}`,
930
+ ""
931
+ ].join("\n");
932
+ writeFileSync5(focusFile, content, "utf-8");
933
+ }
934
+ function clearFocusFile(rootDir) {
935
+ const focusFile = join6(rootDir, ".letra", "focus.md");
936
+ if (existsSync6(focusFile)) {
937
+ unlinkSync(focusFile);
938
+ }
939
+ }
940
+ function readFocusFile(rootDir) {
941
+ const focusFile = join6(rootDir, ".letra", "focus.md");
942
+ if (!existsSync6(focusFile)) return null;
943
+ const content = readFileSync6(focusFile, "utf-8");
944
+ const specMatch = content.match(/# Focus:\s*(.+)/);
945
+ const itemMatch = content.match(/\*\*Item\*\*:\s*(.+)/);
946
+ const outcomeMatch = content.match(/\*\*Outcome\*\*:\s*([\s\S]*?)(?=\n\*\*|\n*$)/);
947
+ if (!specMatch) return null;
948
+ return {
949
+ specName: specMatch[1].trim(),
950
+ itemId: itemMatch ? itemMatch[1].trim() : "",
951
+ outcome: outcomeMatch ? outcomeMatch[1].trim() : ""
952
+ };
953
+ }
954
+
955
+ // src/adapters/builder.ts
956
+ function buildHarnessSnapshot(root, options) {
957
+ const hasFocus = existsSync7(join7(root, ".letra", "focus.md"));
958
+ if (!options.workflow || !options.activeStageId) {
959
+ return {
960
+ workflowName: "letra",
961
+ hasWorkflow: false,
962
+ items: [],
963
+ hasFocus,
964
+ primaryItemId: null,
965
+ focusSpec: null,
966
+ focusPath: null
967
+ };
968
+ }
969
+ const { workflow, activeStageId } = options;
970
+ const stage = workflow.stages.find((s) => s.id === activeStageId);
971
+ const stageItems = workflow.items.filter((item) => item.stage === activeStageId);
972
+ let primaryItemId = null;
973
+ if (options.primaryItemId && stageItems.some((i) => i.id === options.primaryItemId)) {
974
+ primaryItemId = options.primaryItemId;
975
+ } else if (stageItems.length > 0) {
976
+ primaryItemId = stageItems[0].id;
977
+ }
978
+ const acDrifts = [];
979
+ const items = stageItems.map((item) => {
980
+ const harnessItem = {
981
+ id: item.id,
982
+ description: item.description,
983
+ spec: item.spec
984
+ };
985
+ if (item.spec) {
986
+ harnessItem.specPath = `.letra/specs/${item.spec}/spec.md`;
987
+ harnessItem.acceptancePath = `.letra/specs/${item.spec}/acceptance.md`;
988
+ const specDir = join7(root, ".letra", "specs", item.spec);
989
+ const acCount = countACs(specDir);
990
+ harnessItem.acPending = acCount.pending;
991
+ harnessItem.acTotal = acCount.total;
992
+ if (acCount.drift) {
993
+ acDrifts.push({
994
+ spec: item.spec,
995
+ specCount: acCount.specCount,
996
+ acceptanceCount: acCount.acceptanceCount
997
+ });
998
+ }
999
+ }
1000
+ if (item.tasks) {
1001
+ harnessItem.tasksTotal = item.tasks.length;
1002
+ harnessItem.tasksOpen = item.tasks.filter((t) => !t.done).length;
1003
+ } else {
1004
+ harnessItem.tasksTotal = 0;
1005
+ harnessItem.tasksOpen = 0;
1006
+ }
1007
+ return harnessItem;
1008
+ });
1009
+ let focusSpec = null;
1010
+ let focusPath = null;
1011
+ const parsedFocus = readFocusFile(root);
1012
+ if (parsedFocus) {
1013
+ focusSpec = parsedFocus.specName;
1014
+ focusPath = `.letra/specs/${parsedFocus.specName}/`;
1015
+ } else {
1016
+ const primaryItem = items.find((i) => i.id === primaryItemId);
1017
+ if (primaryItem?.spec) {
1018
+ focusSpec = primaryItem.spec;
1019
+ focusPath = `.letra/specs/${primaryItem.spec}/`;
1020
+ }
1021
+ }
1022
+ return {
1023
+ workflowName: workflow.name,
1024
+ hasWorkflow: true,
1025
+ activeStage: stage ? { id: stage.id, name: stage.name } : { id: activeStageId, name: activeStageId },
1026
+ items,
1027
+ hasFocus,
1028
+ primaryItemId,
1029
+ focusSpec,
1030
+ focusPath,
1031
+ acDrifts: acDrifts.length > 0 ? acDrifts : void 0
1032
+ };
850
1033
  }
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
1034
 
858
- ## Workflow
1035
+ // src/adapters/formatters.ts
1036
+ var L1_FILES = [".letra/context.md", ".letra/constitution.md", ".letra/glossary.md"];
1037
+ function formatL1(snapshot, format) {
1038
+ if (format === "at") {
1039
+ const lines2 = ["# Context", ...L1_FILES.map((path) => `@${path}`)];
1040
+ if (snapshot.hasFocus) lines2.push("@.letra/focus.md");
1041
+ return lines2.join("\n");
1042
+ }
1043
+ const lines = [
1044
+ "Read the following files before starting any task:",
1045
+ ...L1_FILES.map((path) => `- ${path}`)
1046
+ ];
1047
+ if (snapshot.hasFocus) {
1048
+ lines.push("- .letra/focus.md (defines current session focus)");
1049
+ } else {
1050
+ lines.push("- .letra/focus.md (if exists, defines current session focus)");
1051
+ }
1052
+ return lines.join("\n");
1053
+ }
1054
+ function formatL2(snapshot) {
1055
+ if (!snapshot.hasWorkflow || !snapshot.activeStage) return null;
1056
+ const itemsBlock = snapshot.items.length > 0 ? snapshot.items.map((item) => {
1057
+ let line = `- ${item.id}: ${item.description}`;
1058
+ if (item.spec) {
1059
+ line += `
1060
+ - spec: ${item.specPath}
1061
+ - acceptance: ${item.acceptancePath}`;
1062
+ }
1063
+ return line;
1064
+ }).join("\n") : "(nenhum item ativo neste estagio)";
1065
+ return `## Workflow
859
1066
 
860
- **Estagio atual:** ${currentStageName}
1067
+ **Estagio atual:** ${snapshot.activeStage.name}
861
1068
 
862
1069
  ### Itens neste estagio
863
1070
 
864
- ${itemsBlock}
865
-
866
- ### Regras
1071
+ ${itemsBlock}`;
1072
+ }
1073
+ function formatL3(snapshot) {
1074
+ if (!snapshot.hasWorkflow) return null;
1075
+ const primaryItem = snapshot.items.find((i) => i.id === snapshot.primaryItemId);
1076
+ const primaryLine = primaryItem ? `**Item primario:** ${primaryItem.id}${primaryItem.spec ? ` (${primaryItem.spec})` : ""}` : "**Item primario:** nenhum";
1077
+ let acPending = 0;
1078
+ let acTotal = 0;
1079
+ let tasksOpen = 0;
1080
+ let tasksTotal = 0;
1081
+ if (primaryItem) {
1082
+ acPending = primaryItem.acPending ?? 0;
1083
+ acTotal = primaryItem.acTotal ?? 0;
1084
+ tasksOpen = primaryItem.tasksOpen ?? 0;
1085
+ tasksTotal = primaryItem.tasksTotal ?? 0;
1086
+ }
1087
+ const lines = [
1088
+ "## Sinais de trabalho",
1089
+ "",
1090
+ primaryLine,
1091
+ `**ACs:** ${acPending}/${acTotal} pendentes`,
1092
+ `**Tasks:** ${tasksOpen}/${tasksTotal} abertas`
1093
+ ];
1094
+ if (primaryItem?.spec && snapshot.acDrifts) {
1095
+ const drift = snapshot.acDrifts.find((d) => d.spec === primaryItem.spec);
1096
+ if (drift) {
1097
+ lines.push(
1098
+ `\u26A0 ac-source-drift: spec.md=${drift.specCount}, acceptance.md=${drift.acceptanceCount}`
1099
+ );
1100
+ }
1101
+ }
1102
+ return lines.join("\n");
1103
+ }
1104
+ function formatRules(snapshot) {
1105
+ if (snapshot.hasWorkflow) {
1106
+ return `## Regras
867
1107
 
868
1108
  - Leia as specs em .letra/specs/ antes de codificar
869
1109
  - Execute \`letra validate\` para verificar acceptance criteria
870
1110
  - Siga a constitution.md rigorosamente
871
- - Ao concluir, mova o item com \`letra flow move <id> --to <proximo_estagio>\`
872
- `;
1111
+ - Ao concluir, mova o item com \`letra flow move <id> --to <proximo_estagio>\``;
1112
+ }
1113
+ return `# Rules
1114
+ - Always read specs in .letra/specs/ before writing code
1115
+ - Run \`letra validate\` to check acceptance criteria
1116
+ - Follow the constitution.md rules strictly
1117
+ - Use formal tone in all generated content`;
873
1118
  }
874
- function generateAdapters(root, tools, content) {
875
- const adapters = [];
876
- const header = `# Gerado por letra flow move. Nao edite manualmente.
1119
+ function formatAdapterContent(snapshot, format, options) {
1120
+ const title = snapshot.hasWorkflow ? `# Letra Context \u2014 ${snapshot.workflowName}` : `# Letra Context \u2014 ${options.displayName} Adapter`;
1121
+ const sections = [title, formatL1(snapshot, format)];
1122
+ const l2 = formatL2(snapshot);
1123
+ if (l2) sections.push(l2);
1124
+ const l3 = formatL3(snapshot);
1125
+ if (l3) sections.push(l3);
1126
+ sections.push(formatRules(snapshot));
1127
+ return `${sections.join("\n\n")}
877
1128
  `;
1129
+ }
1130
+
1131
+ // src/adapters/generate.ts
1132
+ var ADAPTER_HEADER = {
1133
+ init: "# Generated by letra init. Do not edit manually.\n",
1134
+ "flow-move": "# Gerado por letra flow move. Nao edite manualmente.\n",
1135
+ focus: "# Gerado por letra focus. Nao edite manualmente.\n"
1136
+ };
1137
+ var TOOL_TARGETS = {
1138
+ cursor: { path: ".cursorrules", format: "at", displayName: "Cursor" },
1139
+ "claude-code": { path: "CLAUDE.md", format: "text", displayName: "Claude Code" },
1140
+ windsurf: { path: ".windsurfrules", format: "at", displayName: "Windsurf" },
1141
+ vscode: {
1142
+ path: ".github/copilot-instructions.md",
1143
+ format: "text",
1144
+ displayName: "VSCode Copilot"
1145
+ },
1146
+ opencode: { path: "AGENTS.md", format: "text", displayName: "OpenCode" }
1147
+ };
1148
+ function generateAdapters(root, tools, options) {
1149
+ const snapshot = buildHarnessSnapshot(root, options);
1150
+ const header = ADAPTER_HEADER[options.source];
1151
+ const verb = options.verb ?? (options.source === "init" ? "Created" : "Updated");
878
1152
  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;
1153
+ const target = TOOL_TARGETS[tool];
1154
+ if (!target) continue;
1155
+ const content = formatAdapterContent(snapshot, target.format, {
1156
+ source: options.source,
1157
+ displayName: target.displayName
1158
+ });
1159
+ const filePath = join8(root, target.path);
1160
+ const dir = join8(filePath, "..");
1161
+ if (!existsSync8(dir)) mkdirSync3(dir, { recursive: true });
1162
+ writeFileSync6(filePath, header + content);
1163
+ if (!options.quiet) {
1164
+ console.log(
1165
+ ` ${chalk8.gray(verb)} ${filePath.replace(`${root}/`, "").replace(`${root}\\`, "")}`
1166
+ );
913
1167
  }
914
1168
  }
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}/`, "")}`);
1169
+ }
1170
+
1171
+ // src/commands/flow-move.ts
1172
+ function now6() {
1173
+ return (/* @__PURE__ */ new Date()).toISOString();
1174
+ }
1175
+ function resolveStage(workflow, input) {
1176
+ const lower = input.toLowerCase();
1177
+ for (const stage of workflow.stages) {
1178
+ if (stage.id === lower) return stage.id;
1179
+ if (stage.name.toLowerCase() === lower) return stage.id;
920
1180
  }
1181
+ return null;
921
1182
  }
922
1183
  function flowMove(root, itemId, targetStageInput) {
923
1184
  const workflow = loadWorkflow(root);
924
1185
  if (!workflow) {
925
- console.log(chalk8.red("No workflow found. Run 'letra flow init --quick' first"));
1186
+ console.log(chalk9.red("No workflow found. Run 'letra flow init --quick' first"));
926
1187
  process.exit(1);
927
1188
  }
928
1189
  const item = workflow.items.find((i) => i.id === itemId) || workflow.items.find((i) => i.description === itemId);
929
1190
  if (!item) {
930
- console.log(chalk8.red(`Item "${itemId}" not found`));
1191
+ console.log(chalk9.red(`Item "${itemId}" not found`));
931
1192
  process.exit(1);
932
1193
  }
933
1194
  const targetStageId = resolveStage(workflow, targetStageInput);
934
1195
  if (!targetStageId) {
935
1196
  const valid = workflow.stages.map((s) => `${s.id} (${s.name})`).join(", ");
936
- console.log(chalk8.red(`Stage "${targetStageInput}" not found. Valid stages: ${valid}`));
1197
+ console.log(chalk9.red(`Stage "${targetStageInput}" not found. Valid stages: ${valid}`));
937
1198
  process.exit(1);
938
1199
  }
939
1200
  if (item.stage === targetStageId) {
940
- console.log(chalk8.yellow(`Item ${itemId} is already in stage "${targetStageId}"`));
1201
+ console.log(chalk9.yellow(`Item ${itemId} is already in stage "${targetStageId}"`));
941
1202
  return;
942
1203
  }
943
1204
  const fromStage = workflow.stages.find((s) => s.id === item.stage)?.name || item.stage;
@@ -945,14 +1206,23 @@ function flowMove(root, itemId, targetStageInput) {
945
1206
  item.stage = targetStageId;
946
1207
  workflow.updatedAt = now6();
947
1208
  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);
1209
+ generateAdapters(root, workflow.tools, {
1210
+ source: "flow-move",
1211
+ workflow: {
1212
+ name: workflow.name,
1213
+ stages: workflow.stages,
1214
+ items: workflow.items
1215
+ },
1216
+ activeStageId: targetStageId,
1217
+ primaryItemId: itemId
1218
+ });
1219
+ if (item.spec) {
1220
+ writeFocusFile(root, item.spec, item.id);
1221
+ }
952
1222
  console.log(
953
- ` ${chalk8.green("\u2713")} Item ${chalk8.cyan(itemId)} moved: ${chalk8.yellow(fromStage)} \u2192 ${chalk8.green(toStage)}`
1223
+ ` ${chalk9.green("\u2713")} Item ${chalk9.cyan(itemId)} moved: ${chalk9.yellow(fromStage)} \u2192 ${chalk9.green(toStage)}`
954
1224
  );
955
- console.log(` ${chalk8.gray("Adapters regenerated for:")} ${workflow.tools.join(", ")}`);
1225
+ console.log(` ${chalk9.gray("Adapters regenerated for:")} ${workflow.tools.join(", ")}`);
956
1226
  }
957
1227
  function flowMoveAction(targetPath, itemId, options) {
958
1228
  const root = resolve8(process.cwd(), targetPath || ".");
@@ -960,29 +1230,618 @@ function flowMoveAction(targetPath, itemId, options) {
960
1230
  }
961
1231
 
962
1232
  // 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";
1233
+ import { existsSync as existsSync16, mkdirSync as mkdirSync6, readFileSync as readFileSync12, readdirSync as readdirSync6, watch, writeFileSync as writeFileSync8 } from "fs";
964
1234
  import { createServer } from "http";
965
- import { dirname, extname, join as join6, resolve as resolve9 } from "path";
1235
+ import { dirname, extname, join as join17, resolve as resolve9 } from "path";
966
1236
  import { fileURLToPath } from "url";
1237
+
1238
+ // src/diagnostics/engine.ts
1239
+ import { existsSync as existsSync15 } from "fs";
1240
+ import { join as join16 } from "path";
1241
+
1242
+ // src/diagnostics/snapshot.ts
1243
+ import {
1244
+ readFileSync as readFileSync7,
1245
+ writeFileSync as writeFileSync7,
1246
+ mkdirSync as mkdirSync4,
1247
+ existsSync as existsSync9,
1248
+ readdirSync as readdirSync3,
1249
+ rmSync
1250
+ } from "fs";
1251
+ import { join as join10 } from "path";
1252
+ var SNAPSHOTS_DIR = ".letra/snapshots";
1253
+ var MAX_SNAPSHOTS = 20;
1254
+ var TTL_MS = 7 * 24 * 60 * 60 * 1e3;
1255
+ var SnapshotStore = class {
1256
+ rootDir;
1257
+ snapshotsDir;
1258
+ constructor(rootDir) {
1259
+ this.rootDir = rootDir;
1260
+ this.snapshotsDir = join10(rootDir, SNAPSHOTS_DIR);
1261
+ if (!existsSync9(this.snapshotsDir)) {
1262
+ mkdirSync4(this.snapshotsDir, { recursive: true });
1263
+ }
1264
+ this.cleanup();
1265
+ this.enforceMax();
1266
+ }
1267
+ async save(diagnosticId, diagnosticTitle, files) {
1268
+ if (this.isDuplicate(diagnosticId, files)) {
1269
+ return null;
1270
+ }
1271
+ const id = `${Date.now()}_${diagnosticId}`;
1272
+ const snapshot = {
1273
+ id,
1274
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1275
+ diagnosticId,
1276
+ diagnosticTitle,
1277
+ files
1278
+ };
1279
+ writeFileSync7(
1280
+ join10(this.snapshotsDir, `${id}.json`),
1281
+ JSON.stringify(snapshot, null, 0),
1282
+ "utf-8"
1283
+ );
1284
+ this.enforceMax();
1285
+ return id;
1286
+ }
1287
+ async restore(snapshotId) {
1288
+ const filePath = join10(this.snapshotsDir, `${snapshotId}.json`);
1289
+ if (!existsSync9(filePath)) {
1290
+ return { ok: false, restoredFiles: [] };
1291
+ }
1292
+ const snapshot = JSON.parse(readFileSync7(filePath, "utf-8"));
1293
+ const restoredFiles = [];
1294
+ for (const file of snapshot.files) {
1295
+ const absolutePath = join10(this.rootDir, file.path);
1296
+ writeFileSync7(absolutePath, file.before, "utf-8");
1297
+ restoredFiles.push(file.path);
1298
+ }
1299
+ rmSync(filePath);
1300
+ return { ok: true, restoredFiles };
1301
+ }
1302
+ list() {
1303
+ if (!existsSync9(this.snapshotsDir)) return [];
1304
+ return readdirSync3(this.snapshotsDir).filter((f) => f.endsWith(".json")).map((f) => {
1305
+ const content = readFileSync7(join10(this.snapshotsDir, f), "utf-8");
1306
+ return JSON.parse(content);
1307
+ }).sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
1308
+ }
1309
+ isDuplicate(diagnosticId, files) {
1310
+ const last = this.getLastForDiagnostic(diagnosticId);
1311
+ if (!last) return false;
1312
+ if (last.files.length !== files.length) return false;
1313
+ for (let i = 0; i < files.length; i++) {
1314
+ if (last.files[i]?.after !== files[i]?.after) return false;
1315
+ }
1316
+ return true;
1317
+ }
1318
+ getLastForDiagnostic(diagnosticId) {
1319
+ if (!existsSync9(this.snapshotsDir)) return null;
1320
+ const entries = readdirSync3(this.snapshotsDir).filter(
1321
+ (f) => f.endsWith(".json") && f.includes(`_${diagnosticId}`)
1322
+ );
1323
+ if (entries.length === 0) return null;
1324
+ entries.sort().reverse();
1325
+ try {
1326
+ const content = readFileSync7(join10(this.snapshotsDir, entries[0]), "utf-8");
1327
+ return JSON.parse(content);
1328
+ } catch {
1329
+ return null;
1330
+ }
1331
+ }
1332
+ enforceMax() {
1333
+ if (!existsSync9(this.snapshotsDir)) return;
1334
+ const entries = readdirSync3(this.snapshotsDir).filter((f) => f.endsWith(".json")).sort();
1335
+ while (entries.length > MAX_SNAPSHOTS) {
1336
+ const oldest = entries.shift();
1337
+ if (oldest) {
1338
+ rmSync(join10(this.snapshotsDir, oldest));
1339
+ }
1340
+ }
1341
+ }
1342
+ cleanup() {
1343
+ if (!existsSync9(this.snapshotsDir)) return;
1344
+ const cutoff = Date.now() - TTL_MS;
1345
+ for (const file of readdirSync3(this.snapshotsDir)) {
1346
+ if (!file.endsWith(".json")) continue;
1347
+ try {
1348
+ const filePath = join10(this.snapshotsDir, file);
1349
+ const snapshot = JSON.parse(readFileSync7(filePath, "utf-8"));
1350
+ if (new Date(snapshot.timestamp).getTime() < cutoff) {
1351
+ rmSync(filePath);
1352
+ }
1353
+ } catch {
1354
+ }
1355
+ }
1356
+ }
1357
+ };
1358
+
1359
+ // src/diagnostics/detectors/ac-stale.ts
1360
+ import { readFileSync as readFileSync8, existsSync as existsSync10 } from "fs";
1361
+ import { join as join11 } from "path";
1362
+ import { readdirSync as readdirSync4 } from "fs";
1363
+ var STALE_AC_PATTERN = /-\s\[ \]\s\*\*`([^`]+)`\*\*/g;
1364
+ var acStaleDetector = {
1365
+ name: "ac-stale",
1366
+ async run(rootDir) {
1367
+ const results = [];
1368
+ const specsDir = join11(rootDir, ".letra", "specs");
1369
+ if (!existsSync10(specsDir)) return results;
1370
+ const specDirs = readdirSync4(specsDir, { withFileTypes: true }).filter(
1371
+ (d) => d.isDirectory() && !d.name.startsWith("_")
1372
+ );
1373
+ for (const dir of specDirs) {
1374
+ const specFile = join11(specsDir, dir.name, "spec.md");
1375
+ if (!existsSync10(specFile)) continue;
1376
+ const content = readFileSync8(specFile, "utf-8");
1377
+ const matches = content.matchAll(STALE_AC_PATTERN);
1378
+ for (const match of matches) {
1379
+ const command = match[1].trim();
1380
+ if (!command) continue;
1381
+ const commandWords = command.split(/\s+/);
1382
+ const camelCaseName = commandWords.map((w, i) => i === 0 ? w : w.charAt(0).toUpperCase() + w.slice(1)).join("");
1383
+ const pascalCaseName = commandWords.map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("");
1384
+ const foundInSource = searchInSource(rootDir, [
1385
+ command,
1386
+ camelCaseName,
1387
+ pascalCaseName
1388
+ ]);
1389
+ if (foundInSource) {
1390
+ results.push({
1391
+ id: `ac-stale_${dir.name}_${command.replace(/\s+/g, "-")}`,
1392
+ type: "info",
1393
+ title: `AC "${command}" marcado [ ] mas implementado`,
1394
+ description: `O acceptance criteria "${command}" do spec ${dir.name} est\xE1 marcado como n\xE3o feito ([ ]), mas o c\xF3digo-fonte cont\xE9m implementa\xE7\xE3o correspondente.`,
1395
+ certainty: 0.9,
1396
+ detector: "ac-stale",
1397
+ autoFix: async () => {
1398
+ const newContent = content.replace(
1399
+ new RegExp(
1400
+ `(- \\[ \\] \\*\\*\`)(${escapeRegex(command)}(\\s[^*]+)?\\*\\*)`
1401
+ ),
1402
+ (m) => m.replace("[ ]", "[x]")
1403
+ );
1404
+ const before = readFileSync8(specFile, "utf-8");
1405
+ return {
1406
+ files: [
1407
+ {
1408
+ path: `.letra/specs/${dir.name}/spec.md`,
1409
+ before,
1410
+ after: newContent
1411
+ }
1412
+ ],
1413
+ snapshotId: ""
1414
+ };
1415
+ }
1416
+ });
1417
+ }
1418
+ }
1419
+ }
1420
+ return results;
1421
+ }
1422
+ };
1423
+ function searchInSource(rootDir, terms) {
1424
+ const searchDirs = ["packages/cli/src", "packages/client/src", "packages/ui/src"];
1425
+ for (const searchDir of searchDirs) {
1426
+ const dir = join11(rootDir, searchDir);
1427
+ if (!existsSync10(dir)) continue;
1428
+ try {
1429
+ const files = walkDir(dir);
1430
+ for (const file of files) {
1431
+ const content = readFileSync8(file, "utf-8");
1432
+ for (const term of terms) {
1433
+ if (content.includes(term)) return true;
1434
+ }
1435
+ }
1436
+ } catch {
1437
+ }
1438
+ }
1439
+ return false;
1440
+ }
1441
+ function walkDir(dir) {
1442
+ const files = [];
1443
+ try {
1444
+ for (const entry of readdirSync4(dir, { withFileTypes: true })) {
1445
+ const fullPath = join11(dir, entry.name);
1446
+ if (entry.isDirectory() && entry.name !== "node_modules") {
1447
+ files.push(...walkDir(fullPath));
1448
+ } else if (entry.isFile() && (entry.name.endsWith(".ts") || entry.name.endsWith(".tsx"))) {
1449
+ files.push(fullPath);
1450
+ }
1451
+ }
1452
+ } catch {
1453
+ }
1454
+ return files;
1455
+ }
1456
+ function escapeRegex(s) {
1457
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1458
+ }
1459
+
1460
+ // src/diagnostics/detectors/missing-dir.ts
1461
+ import { existsSync as existsSync11, mkdirSync as mkdirSync5 } from "fs";
1462
+ import { join as join12 } from "path";
1463
+ var REQUIRED_DIRS = [
1464
+ {
1465
+ path: ".letra/templates",
1466
+ spec: "spec-templates-domain",
1467
+ description: "templates customizados de specs"
1468
+ },
1469
+ { path: ".letra/brand", spec: "flow-serve", description: "logos SVG do Letra" }
1470
+ ];
1471
+ var missingDirDetector = {
1472
+ name: "missing-dir",
1473
+ async run(rootDir) {
1474
+ const results = [];
1475
+ for (const required of REQUIRED_DIRS) {
1476
+ const dirPath = join12(rootDir, required.path);
1477
+ if (existsSync11(dirPath)) continue;
1478
+ results.push({
1479
+ id: `missing-dir_${required.path.replace(/[/.]/g, "-")}`,
1480
+ type: "info",
1481
+ title: `Diret\xF3rio ausente: ${required.path}/`,
1482
+ description: `O diret\xF3rio ${required.path}/ \xE9 referenciado pelo spec ${required.spec} (${required.description}), mas n\xE3o existe.`,
1483
+ certainty: 1,
1484
+ detector: "missing-dir",
1485
+ autoFix: async () => ({
1486
+ files: [],
1487
+ snapshotId: ""
1488
+ })
1489
+ });
1490
+ }
1491
+ for (const r of results) {
1492
+ const originalAutoFix = r.autoFix;
1493
+ if (!originalAutoFix) continue;
1494
+ r.autoFix = async () => {
1495
+ const dirs = [];
1496
+ for (const required of REQUIRED_DIRS) {
1497
+ const dirPath = join12(rootDir, required.path);
1498
+ if (existsSync11(dirPath)) continue;
1499
+ mkdirSync5(dirPath, { recursive: true });
1500
+ dirs.push(required.path);
1501
+ }
1502
+ return {
1503
+ files: [],
1504
+ snapshotId: ""
1505
+ };
1506
+ };
1507
+ }
1508
+ return results;
1509
+ }
1510
+ };
1511
+
1512
+ // src/diagnostics/detectors/dead-icons.ts
1513
+ import { readFileSync as readFileSync9, existsSync as existsSync12 } from "fs";
1514
+ import { join as join13 } from "path";
1515
+ import { readdirSync as readdirSync5 } from "fs";
1516
+ var ICON_USAGE_PATTERN = /<Icon\s+name="([^"]+)"/g;
1517
+ var ICON_DEF_PATTERN = /"([a-z-]+)":\s*\(/g;
1518
+ var deadIconsDetector = {
1519
+ name: "dead-icons",
1520
+ async run(rootDir) {
1521
+ const results = [];
1522
+ const iconFiles = findIconFiles(rootDir);
1523
+ if (iconFiles.length === 0) return results;
1524
+ const definedIcons = /* @__PURE__ */ new Set();
1525
+ const usedIcons = /* @__PURE__ */ new Set();
1526
+ for (const file of iconFiles) {
1527
+ const content = readFileSync9(file, "utf-8");
1528
+ const defs = content.matchAll(ICON_DEF_PATTERN);
1529
+ for (const d of defs) {
1530
+ definedIcons.add(d[1]);
1531
+ }
1532
+ const usages = content.matchAll(ICON_USAGE_PATTERN);
1533
+ for (const u of usages) {
1534
+ usedIcons.add(u[1]);
1535
+ }
1536
+ }
1537
+ const srcDir = join13(rootDir, "packages", "client", "src");
1538
+ if (existsSync12(srcDir)) {
1539
+ const files = walkDir2(srcDir);
1540
+ for (const file of files) {
1541
+ const content = readFileSync9(file, "utf-8");
1542
+ const usages = content.matchAll(ICON_USAGE_PATTERN);
1543
+ for (const u of usages) {
1544
+ usedIcons.add(u[1]);
1545
+ }
1546
+ }
1547
+ }
1548
+ for (const iconName of usedIcons) {
1549
+ if (definedIcons.has(iconName)) continue;
1550
+ results.push({
1551
+ id: `dead-icons_${iconName}`,
1552
+ type: "warning",
1553
+ title: `\xCDcone "${iconName}" referenciado mas n\xE3o definido`,
1554
+ description: `O \xEDcone "${iconName}" \xE9 usado em <Icon name="${iconName}" /> mas n\xE3o est\xE1 definido no ICONS map. Renderiza null silenciosamente.`,
1555
+ certainty: 1,
1556
+ detector: "dead-icons",
1557
+ autoFix: async () => {
1558
+ const fixes = [];
1559
+ for (const file of iconFiles) {
1560
+ const content = readFileSync9(file, "utf-8");
1561
+ if (!content.includes("const ICONS")) continue;
1562
+ const lines = content.split("\n");
1563
+ const insertLine = lines.findIndex(
1564
+ (l) => l.includes("];") || l.includes("};")
1565
+ );
1566
+ if (insertLine === -1) continue;
1567
+ const indent = " ";
1568
+ const iconSvg = `${indent}"${iconName}": () => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/></svg>,`;
1569
+ const before = content;
1570
+ const afterLines = [...lines];
1571
+ afterLines.splice(insertLine, 0, iconSvg);
1572
+ const after = afterLines.join("\n");
1573
+ fixes.push({
1574
+ path: file.replace(`${rootDir}\\`, "").replace(/\\/g, "/"),
1575
+ before,
1576
+ after
1577
+ });
1578
+ }
1579
+ return { files: fixes, snapshotId: "" };
1580
+ }
1581
+ });
1582
+ }
1583
+ return results;
1584
+ }
1585
+ };
1586
+ function findIconFiles(rootDir) {
1587
+ const candidates = [
1588
+ join13(rootDir, "packages", "client", "src", "components", "ui", "icon.tsx"),
1589
+ join13(rootDir, "packages", "ui", "src", "icon.tsx")
1590
+ ];
1591
+ return candidates.filter((f) => existsSync12(f));
1592
+ }
1593
+ function walkDir2(dir) {
1594
+ const files = [];
1595
+ try {
1596
+ for (const entry of readdirSync5(dir, { withFileTypes: true })) {
1597
+ const fullPath = join13(dir, entry.name);
1598
+ if (entry.isDirectory() && entry.name !== "node_modules") {
1599
+ files.push(...walkDir2(fullPath));
1600
+ } else if (entry.isFile() && (entry.name.endsWith(".tsx") || entry.name.endsWith(".ts"))) {
1601
+ files.push(fullPath);
1602
+ }
1603
+ }
1604
+ } catch {
1605
+ }
1606
+ return files;
1607
+ }
1608
+
1609
+ // src/diagnostics/detectors/stage-drift.ts
1610
+ import { readFileSync as readFileSync10, existsSync as existsSync13 } from "fs";
1611
+ import { join as join14 } from "path";
1612
+ var STALE_AC_PATTERN2 = /-\s\[ \]\s\*\*`([^`]+)`\*\*/g;
1613
+ var DONE_AC_PATTERN = /-\s\[x\]\s\*\*`([^`]+)`\*\*/g;
1614
+ var stageDriftDetector = {
1615
+ name: "stage-drift",
1616
+ async run(rootDir) {
1617
+ const results = [];
1618
+ const workflowFile = join14(rootDir, ".letra", "workflow.json");
1619
+ if (!existsSync13(workflowFile)) return results;
1620
+ const workflow = JSON.parse(readFileSync10(workflowFile, "utf-8"));
1621
+ const items = workflow.items || [];
1622
+ const stages = workflow.stages || [];
1623
+ const doneStageIds = stages.filter((s) => s.zone === "done").map((s) => s.id);
1624
+ const reviewStageIds = stages.filter(
1625
+ (s) => s.name?.toLowerCase() === "review" || s.id === "review"
1626
+ ).map((s) => s.id);
1627
+ for (const item of items) {
1628
+ if (!item.spec) continue;
1629
+ const specDir = join14(rootDir, ".letra", "specs", item.spec);
1630
+ const specFile = join14(specDir, "spec.md");
1631
+ if (!existsSync13(specFile)) continue;
1632
+ const content = readFileSync10(specFile, "utf-8");
1633
+ const staleMatches = [...content.matchAll(STALE_AC_PATTERN2)];
1634
+ const doneMatches = [...content.matchAll(DONE_AC_PATTERN)];
1635
+ const totalACs = staleMatches.length + doneMatches.length;
1636
+ if (totalACs === 0) continue;
1637
+ const pctDone = doneMatches.length / totalACs;
1638
+ const isInReview = reviewStageIds.includes(item.stage);
1639
+ const isInBacklog = item.stage === "backlog";
1640
+ if (pctDone === 1 && (isInReview || isInBacklog)) {
1641
+ results.push({
1642
+ id: `stage-drift_${item.id}`,
1643
+ type: "info",
1644
+ title: `${item.id} (${item.description}) \u2014 100% ACs prontos`,
1645
+ description: `O item ${item.id} (${item.description}) tem ${doneMatches.length}/${totalACs} ACs implementados. Est\xE1 em "${item.stage}" mas deveria estar em "done".`,
1646
+ certainty: 0.85,
1647
+ detector: "stage-drift",
1648
+ autoFix: async () => {
1649
+ const before = readFileSync10(workflowFile, "utf-8");
1650
+ const newWorkflow = JSON.parse(before);
1651
+ const target = newWorkflow.items.find(
1652
+ (i) => i.id === item.id
1653
+ );
1654
+ if (target) {
1655
+ target.stage = doneStageIds[0] || "done";
1656
+ target.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1657
+ }
1658
+ const after = JSON.stringify(newWorkflow, null, 2);
1659
+ return {
1660
+ files: [{ path: ".letra/workflow.json", before, after }],
1661
+ snapshotId: ""
1662
+ };
1663
+ }
1664
+ });
1665
+ } else if (pctDone > 0 && pctDone < 1 && isInBacklog) {
1666
+ results.push({
1667
+ id: `stage-drift_${item.id}_partial`,
1668
+ type: "info",
1669
+ title: `${item.id} (${item.description}) \u2014 ${doneMatches.length}/${totalACs} ACs prontos`,
1670
+ description: `O item ${item.id} tem ${doneMatches.length}/${totalACs} ACs implementados mas est\xE1 em backlog. Considere mover para "code".`,
1671
+ certainty: 0.7,
1672
+ detector: "stage-drift"
1673
+ });
1674
+ }
1675
+ }
1676
+ return results;
1677
+ }
1678
+ };
1679
+
1680
+ // src/diagnostics/detectors/harness-stale.ts
1681
+ import { existsSync as existsSync14, readFileSync as readFileSync11 } from "fs";
1682
+ import { join as join15 } from "path";
1683
+ var ADAPTER_FILES = {
1684
+ cursor: { path: ".cursorrules", format: "at" },
1685
+ "claude-code": { path: "CLAUDE.md", format: "text" },
1686
+ windsurf: { path: ".windsurfrules", format: "at" },
1687
+ vscode: { path: ".github/copilot-instructions.md", format: "text" },
1688
+ opencode: { path: "AGENTS.md", format: "text" }
1689
+ };
1690
+ var harnessStaleDetector = {
1691
+ name: "harness-stale",
1692
+ async run(rootDir) {
1693
+ const results = [];
1694
+ const workflowFile = join15(rootDir, ".letra", "workflow.json");
1695
+ let tools = ["cursor", "opencode", "vscode"];
1696
+ if (existsSync14(workflowFile)) {
1697
+ try {
1698
+ const wf = JSON.parse(readFileSync11(workflowFile, "utf-8"));
1699
+ if (Array.isArray(wf.tools)) {
1700
+ tools = wf.tools;
1701
+ }
1702
+ } catch {
1703
+ }
1704
+ }
1705
+ for (const tool of tools) {
1706
+ const info = ADAPTER_FILES[tool];
1707
+ if (!info) continue;
1708
+ const filePath = join15(rootDir, info.path);
1709
+ if (!existsSync14(filePath)) continue;
1710
+ const content = readFileSync11(filePath, "utf-8");
1711
+ let isStale = false;
1712
+ if (info.format === "at") {
1713
+ if (!content.includes("@.letra/context.md") || !content.includes("@.letra/constitution.md")) {
1714
+ isStale = true;
1715
+ }
1716
+ } else {
1717
+ if (!content.includes(".letra/context.md") || !content.includes(".letra/constitution.md")) {
1718
+ isStale = true;
1719
+ }
1720
+ }
1721
+ if (isStale) {
1722
+ results.push({
1723
+ id: `harness-stale_${tool}`,
1724
+ type: "warning",
1725
+ title: `Adapter desatualizado: ${tool}`,
1726
+ description: `O adaptador ${info.path} do ${tool} existe mas est\xE1 sem as refer\xEAncias de contexto globais (L1). Execute 'letra flow move' ou 'letra focus' para regener\xE1-lo.`,
1727
+ certainty: 0.85,
1728
+ detector: "harness-stale"
1729
+ });
1730
+ }
1731
+ }
1732
+ return results;
1733
+ }
1734
+ };
1735
+
1736
+ // src/diagnostics/engine.ts
1737
+ var DiagnosticEngine = class {
1738
+ rootDir;
1739
+ snapshots;
1740
+ detectors = [
1741
+ acStaleDetector,
1742
+ missingDirDetector,
1743
+ deadIconsDetector,
1744
+ stageDriftDetector,
1745
+ harnessStaleDetector
1746
+ ];
1747
+ lastOutput = { fixes: [], suggestions: [], errors: [] };
1748
+ appliedFixes = /* @__PURE__ */ new Set();
1749
+ constructor(rootDir) {
1750
+ this.rootDir = rootDir;
1751
+ this.snapshots = new SnapshotStore(rootDir);
1752
+ }
1753
+ async runAll() {
1754
+ const output = { fixes: [], suggestions: [], errors: [] };
1755
+ const newApplied = /* @__PURE__ */ new Set();
1756
+ for (const detector of this.detectors) {
1757
+ try {
1758
+ const results = await detector.run(this.rootDir);
1759
+ for (const result of results) {
1760
+ if (result.autoFix && result.certainty >= 0.9) {
1761
+ if (this.appliedFixes.has(result.id)) {
1762
+ continue;
1763
+ }
1764
+ try {
1765
+ const fix = await result.autoFix();
1766
+ const snapshotId = await this.snapshots.save(
1767
+ result.id,
1768
+ result.title,
1769
+ fix.files
1770
+ );
1771
+ newApplied.add(result.id);
1772
+ if (snapshotId) {
1773
+ output.fixes.push({
1774
+ id: result.id,
1775
+ title: result.title,
1776
+ description: result.description,
1777
+ snapshotId
1778
+ });
1779
+ }
1780
+ } catch (fixError) {
1781
+ output.errors.push(`Auto-fix falhou para ${result.id}: ${fixError}`);
1782
+ }
1783
+ } else {
1784
+ output.suggestions.push({
1785
+ id: result.id,
1786
+ title: result.title,
1787
+ description: result.description,
1788
+ type: result.type,
1789
+ detector: result.detector
1790
+ });
1791
+ }
1792
+ }
1793
+ } catch (detError) {
1794
+ output.errors.push(`Detector ${detector.name} falhou: ${detError}`);
1795
+ }
1796
+ }
1797
+ this.appliedFixes = newApplied;
1798
+ this.lastOutput = output;
1799
+ return output;
1800
+ }
1801
+ getLastOutput() {
1802
+ return this.lastOutput;
1803
+ }
1804
+ async undo(snapshotId) {
1805
+ return this.snapshots.restore(snapshotId);
1806
+ }
1807
+ listSnapshots() {
1808
+ return this.snapshots.list();
1809
+ }
1810
+ ensureDirs() {
1811
+ const requiredDirs = [".letra/templates", ".letra/brand", ".letra/snapshots"];
1812
+ for (const dir of requiredDirs) {
1813
+ const fullPath = join16(this.rootDir, dir);
1814
+ if (!existsSync15(fullPath)) {
1815
+ try {
1816
+ const { mkdirSync: mkdirSync9 } = __require("fs");
1817
+ mkdirSync9(fullPath, { recursive: true });
1818
+ } catch {
1819
+ }
1820
+ }
1821
+ }
1822
+ }
1823
+ };
1824
+
1825
+ // src/commands/flow-serve.ts
967
1826
  var DEFAULT_PORT = 3e3;
968
1827
  function loadSpecs(root, workflow) {
969
1828
  const result = [];
970
1829
  if (workflow?.specLinks) {
971
1830
  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") });
1831
+ const filePath = join17(root, link.path);
1832
+ if (existsSync16(filePath)) {
1833
+ result.push({ id, content: readFileSync12(filePath, "utf-8") });
975
1834
  }
976
1835
  }
977
1836
  }
978
- const specsDir = join6(root, ".letra", "specs");
1837
+ const specsDir = join17(root, ".letra", "specs");
979
1838
  const registered = new Set(result.map((s) => s.id));
980
- if (existsSync6(specsDir)) {
981
- for (const entry of readdirSync3(specsDir, { withFileTypes: true })) {
1839
+ if (existsSync16(specsDir)) {
1840
+ for (const entry of readdirSync6(specsDir, { withFileTypes: true })) {
982
1841
  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") });
1842
+ const specPath = join17(specsDir, entry.name, "spec.md");
1843
+ if (existsSync16(specPath)) {
1844
+ result.push({ id: entry.name, content: readFileSync12(specPath, "utf-8") });
986
1845
  }
987
1846
  }
988
1847
  }
@@ -1047,14 +1906,17 @@ function createWorkflowFromTemplate(root, templateId, options) {
1047
1906
  var FlowServer = class {
1048
1907
  server;
1049
1908
  watcher;
1909
+ diagnosticsTimer;
1050
1910
  clients = /* @__PURE__ */ new Set();
1051
1911
  root;
1052
1912
  port;
1053
1913
  loadWorkflow;
1914
+ engine;
1054
1915
  constructor(root, port = DEFAULT_PORT) {
1055
1916
  this.root = root;
1056
1917
  this.port = port;
1057
1918
  this.loadWorkflow = () => loadWorkflow(root);
1919
+ this.engine = new DiagnosticEngine(root);
1058
1920
  }
1059
1921
  handleRequest = (req, res) => {
1060
1922
  const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
@@ -1146,9 +2008,9 @@ var FlowServer = class {
1146
2008
  res.end(JSON.stringify({ error: "id and content required" }));
1147
2009
  return;
1148
2010
  }
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");
2011
+ const specDir = join17(this.root, ".letra", "specs", id);
2012
+ if (!existsSync16(specDir)) mkdirSync6(specDir, { recursive: true });
2013
+ writeFileSync8(join17(specDir, "spec.md"), content, "utf-8");
1152
2014
  const wf = this.loadWorkflow();
1153
2015
  if (wf) {
1154
2016
  if (!wf.specLinks) wf.specLinks = {};
@@ -1173,9 +2035,9 @@ var FlowServer = class {
1173
2035
  res.end(JSON.stringify({ error: "spec id required" }));
1174
2036
  return;
1175
2037
  }
1176
- const specDir = join6(this.root, ".letra", "specs", specId);
1177
- if (existsSync6(specDir)) {
1178
- writeFileSync6(join6(specDir, "spec.md"), "", "utf-8");
2038
+ const specDir = join17(this.root, ".letra", "specs", specId);
2039
+ if (existsSync16(specDir)) {
2040
+ writeFileSync8(join17(specDir, "spec.md"), "", "utf-8");
1179
2041
  }
1180
2042
  const wf = this.loadWorkflow();
1181
2043
  if (wf?.specLinks) {
@@ -1207,9 +2069,9 @@ var FlowServer = class {
1207
2069
  res.end(JSON.stringify({ error: "content required" }));
1208
2070
  return;
1209
2071
  }
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");
2072
+ const specDir = join17(this.root, ".letra", "specs", specId);
2073
+ if (!existsSync16(specDir)) mkdirSync6(specDir, { recursive: true });
2074
+ writeFileSync8(join17(specDir, "spec.md"), content, "utf-8");
1213
2075
  const wf = this.loadWorkflow();
1214
2076
  if (wf) {
1215
2077
  wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
@@ -1227,10 +2089,10 @@ var FlowServer = class {
1227
2089
  }
1228
2090
  if (path.match(/^\/api\/specs\/[^/]+\/validate$/) && req.method === "POST") {
1229
2091
  const specId = path.replace("/api/specs/", "").split("/")[0];
1230
- const specDir = join6(this.root, ".letra", "specs", specId);
1231
- const specFile = join6(specDir, "spec.md");
2092
+ const specDir = join17(this.root, ".letra", "specs", specId);
2093
+ const specFile = join17(specDir, "spec.md");
1232
2094
  const issues = [];
1233
- if (!existsSync6(specFile)) {
2095
+ if (!existsSync16(specFile)) {
1234
2096
  res.writeHead(200, { "Content-Type": "application/json" });
1235
2097
  res.end(
1236
2098
  JSON.stringify({
@@ -1241,7 +2103,7 @@ var FlowServer = class {
1241
2103
  );
1242
2104
  return;
1243
2105
  }
1244
- const content = readFileSync5(specFile, "utf-8");
2106
+ const content = readFileSync12(specFile, "utf-8");
1245
2107
  const requiredSections = [
1246
2108
  "Outcome",
1247
2109
  "Constraints",
@@ -1434,9 +2296,9 @@ var FlowServer = class {
1434
2296
  return;
1435
2297
  }
1436
2298
  if (path === "/api/focus") {
1437
- const focusFile = join6(this.root, ".letra", "focus.md");
1438
- if (existsSync6(focusFile)) {
1439
- const content = readFileSync5(focusFile, "utf-8");
2299
+ const focusFile = join17(this.root, ".letra", "focus.md");
2300
+ if (existsSync16(focusFile)) {
2301
+ const content = readFileSync12(focusFile, "utf-8");
1440
2302
  res.writeHead(200, { "Content-Type": "application/json" });
1441
2303
  const lines = content.split("\n").filter((l) => l.trim());
1442
2304
  res.end(
@@ -1454,15 +2316,15 @@ var FlowServer = class {
1454
2316
  }
1455
2317
  if (path === "/api/context") {
1456
2318
  const file = url.searchParams.get("file") || "context.md";
1457
- const letraDir = join6(this.root, ".letra");
2319
+ const letraDir = join17(this.root, ".letra");
1458
2320
  const allowedFiles = ["context.md", "constitution.md", "glossary.md"];
1459
2321
  if (file === "decisions") {
1460
- const decisionsDir = join6(letraDir, "decisions");
2322
+ const decisionsDir = join17(letraDir, "decisions");
1461
2323
  const files = [];
1462
- if (existsSync6(decisionsDir)) {
1463
- const names = readdirSync3(decisionsDir).filter((f) => f.endsWith(".md"));
2324
+ if (existsSync16(decisionsDir)) {
2325
+ const names = readdirSync6(decisionsDir).filter((f) => f.endsWith(".md"));
1464
2326
  for (const name of names.sort().reverse()) {
1465
- const content2 = readFileSync5(join6(decisionsDir, name), "utf-8");
2327
+ const content2 = readFileSync12(join17(decisionsDir, name), "utf-8");
1466
2328
  files.push({ name, content: content2 });
1467
2329
  }
1468
2330
  }
@@ -1475,29 +2337,69 @@ var FlowServer = class {
1475
2337
  res.end(JSON.stringify({ error: `Invalid file: ${file}` }));
1476
2338
  return;
1477
2339
  }
1478
- const filePath = join6(letraDir, file);
1479
- if (!existsSync6(filePath)) {
2340
+ const filePath = join17(letraDir, file);
2341
+ if (!existsSync16(filePath)) {
1480
2342
  res.writeHead(404, { "Content-Type": "application/json" });
1481
2343
  res.end(JSON.stringify({ error: `File not found: ${file}` }));
1482
2344
  return;
1483
2345
  }
1484
- const content = readFileSync5(filePath, "utf-8");
2346
+ const content = readFileSync12(filePath, "utf-8");
1485
2347
  res.writeHead(200, { "Content-Type": "text/plain" });
1486
2348
  res.end(content);
1487
2349
  return;
1488
2350
  }
2351
+ if (path === "/api/diagnostics" && req.method === "GET") {
2352
+ const output = this.engine.getLastOutput();
2353
+ res.writeHead(200, { "Content-Type": "application/json" });
2354
+ res.end(JSON.stringify(output));
2355
+ return;
2356
+ }
2357
+ if (path === "/api/diagnostics/snapshots" && req.method === "GET") {
2358
+ const snapshots = this.engine.listSnapshots();
2359
+ res.writeHead(200, { "Content-Type": "application/json" });
2360
+ res.end(JSON.stringify({ snapshots }));
2361
+ return;
2362
+ }
2363
+ if (path === "/api/diagnostics/scan" && req.method === "POST") {
2364
+ this.engine.runAll().then((output) => {
2365
+ this.broadcastDiagnostics(output);
2366
+ res.writeHead(200, { "Content-Type": "application/json" });
2367
+ res.end(JSON.stringify(output));
2368
+ }).catch((e) => {
2369
+ res.writeHead(500, { "Content-Type": "application/json" });
2370
+ res.end(JSON.stringify({ error: e.message }));
2371
+ });
2372
+ return;
2373
+ }
2374
+ if (path.match(/^\/api\/diagnostics\/undo\/[^/]+$/) && req.method === "POST") {
2375
+ const snapshotId = path.replace("/api/diagnostics/undo/", "");
2376
+ this.engine.undo(snapshotId).then((result) => {
2377
+ if (!result.ok) {
2378
+ res.writeHead(404, { "Content-Type": "application/json" });
2379
+ res.end(JSON.stringify({ error: "Snapshot not found" }));
2380
+ return;
2381
+ }
2382
+ this.broadcast();
2383
+ res.writeHead(200, { "Content-Type": "application/json" });
2384
+ res.end(JSON.stringify(result));
2385
+ }).catch((e) => {
2386
+ res.writeHead(500, { "Content-Type": "application/json" });
2387
+ res.end(JSON.stringify({ error: e.message }));
2388
+ });
2389
+ return;
2390
+ }
1489
2391
  this.serveClient(path, req, res);
1490
2392
  };
1491
2393
  clientDir = null;
1492
2394
  serveClient(path, req, res) {
1493
2395
  if (!this.clientDir) {
1494
2396
  const cliDir = dirname(fileURLToPath(import.meta.url));
1495
- const builtIn = join6(cliDir, "client");
1496
- const monorepoDev = join6(this.root, "packages", "client", "dist");
2397
+ const builtIn = join17(cliDir, "client");
2398
+ const monorepoDev = join17(this.root, "packages", "client", "dist");
1497
2399
  const candidates = [builtIn, monorepoDev];
1498
2400
  for (const dir of candidates) {
1499
- const idx = join6(dir, "index.html");
1500
- if (existsSync6(idx)) {
2401
+ const idx = join17(dir, "index.html");
2402
+ if (existsSync16(idx)) {
1501
2403
  this.clientDir = dir;
1502
2404
  break;
1503
2405
  }
@@ -1507,9 +2409,9 @@ var FlowServer = class {
1507
2409
  this.proxyToVite(req, res);
1508
2410
  return;
1509
2411
  }
1510
- let filePath = join6(this.clientDir, path === "/" ? "index.html" : path);
1511
- if (!existsSync6(filePath)) {
1512
- filePath = join6(this.clientDir, "index.html");
2412
+ let filePath = join17(this.clientDir, path === "/" ? "index.html" : path);
2413
+ if (!existsSync16(filePath)) {
2414
+ filePath = join17(this.clientDir, "index.html");
1513
2415
  }
1514
2416
  const ext = extname(filePath);
1515
2417
  const mime = {
@@ -1523,7 +2425,7 @@ var FlowServer = class {
1523
2425
  };
1524
2426
  const contentType = mime[ext] ?? "application/octet-stream";
1525
2427
  res.writeHead(200, { "Content-Type": contentType });
1526
- res.end(readFileSync5(filePath));
2428
+ res.end(readFileSync12(filePath));
1527
2429
  }
1528
2430
  proxyToVite(req, res) {
1529
2431
  const proxyUrl = `http://localhost:5173${req.url}`;
@@ -1555,6 +2457,20 @@ var FlowServer = class {
1555
2457
  }
1556
2458
  }
1557
2459
  }
2460
+ broadcastDiagnostics(output) {
2461
+ if (this.clients.size === 0) return;
2462
+ const data = `event: diagnostics-updated
2463
+ data: ${JSON.stringify({ fixes: output.fixes.length, suggestions: output.suggestions.length, errors: output.errors.length })}
2464
+
2465
+ `;
2466
+ for (const client of this.clients) {
2467
+ try {
2468
+ client.write(data);
2469
+ } catch {
2470
+ this.clients.delete(client);
2471
+ }
2472
+ }
2473
+ }
1558
2474
  async fireWebhooks(event, payload) {
1559
2475
  const wf = this.loadWorkflow();
1560
2476
  if (!wf?.webhooks || wf.webhooks.length === 0) return;
@@ -1582,23 +2498,35 @@ var FlowServer = class {
1582
2498
  saveWorkflow(this.root, wf);
1583
2499
  }
1584
2500
  start() {
1585
- return new Promise((resolve17, reject) => {
2501
+ return new Promise((resolve18, reject) => {
1586
2502
  this.server = createServer(this.handleRequest);
1587
2503
  this.server.listen(this.port, () => {
1588
- const wfPath = join6(this.root, ".letra", "workflow.json");
1589
- if (existsSync6(wfPath)) {
2504
+ const wfPath = join17(this.root, ".letra", "workflow.json");
2505
+ if (existsSync16(wfPath)) {
1590
2506
  try {
1591
2507
  this.watcher = watch(wfPath, () => this.broadcast());
1592
2508
  } catch {
1593
2509
  }
1594
2510
  }
1595
- resolve17();
2511
+ this.engine.ensureDirs();
2512
+ this.engine.runAll().then((output) => {
2513
+ this.broadcastDiagnostics(output);
2514
+ }).catch(() => {
2515
+ });
2516
+ this.diagnosticsTimer = setInterval(() => {
2517
+ this.engine.runAll().then((output) => {
2518
+ this.broadcastDiagnostics(output);
2519
+ }).catch(() => {
2520
+ });
2521
+ }, 3e4);
2522
+ resolve18();
1596
2523
  });
1597
2524
  this.server.on("error", reject);
1598
2525
  });
1599
2526
  }
1600
2527
  stop() {
1601
2528
  if (this.watcher) this.watcher.close();
2529
+ if (this.diagnosticsTimer) clearInterval(this.diagnosticsTimer);
1602
2530
  if (this.server) this.server.close();
1603
2531
  for (const client of this.clients) {
1604
2532
  client.destroy();
@@ -1632,10 +2560,10 @@ async function flowServeAction(targetPath, options) {
1632
2560
  } catch {
1633
2561
  }
1634
2562
  }
1635
- await new Promise((resolve17) => {
2563
+ await new Promise((resolve18) => {
1636
2564
  process.on("SIGINT", () => {
1637
2565
  server.stop();
1638
- resolve17();
2566
+ resolve18();
1639
2567
  });
1640
2568
  });
1641
2569
  } catch (err) {
@@ -1645,9 +2573,9 @@ async function flowServeAction(targetPath, options) {
1645
2573
  }
1646
2574
 
1647
2575
  // src/commands/flow-visualize.ts
1648
- import { writeFileSync as writeFileSync7 } from "fs";
2576
+ import { writeFileSync as writeFileSync9 } from "fs";
1649
2577
  import { resolve as resolve10 } from "path";
1650
- import chalk9 from "chalk";
2578
+ import chalk10 from "chalk";
1651
2579
  var MERMAID_LIVE = "https://mermaid.live/edit#";
1652
2580
  function generateMermaid(workflow) {
1653
2581
  const sorted = [...workflow.stages].sort((a, b) => a.order - b.order);
@@ -1697,7 +2625,7 @@ ${mermaid}
1697
2625
  function flowVisualize(root, options) {
1698
2626
  const workflow = loadWorkflow(root);
1699
2627
  if (!workflow) {
1700
- console.log(chalk9.yellow("No workflow found. Run 'letra flow init --quick' first"));
2628
+ console.log(chalk10.yellow("No workflow found. Run 'letra flow init --quick' first"));
1701
2629
  return;
1702
2630
  }
1703
2631
  const mermaid = generateMermaid(workflow);
@@ -1720,11 +2648,11 @@ ${mermaid}
1720
2648
  `;
1721
2649
  label = "Diagram file";
1722
2650
  }
1723
- writeFileSync7(outputPath, content);
2651
+ writeFileSync9(outputPath, content);
1724
2652
  console.log(`${label} saved to ${options.output}`);
1725
2653
  } else {
1726
2654
  console.log(mermaid);
1727
- console.log(chalk9.dim(`
2655
+ console.log(chalk10.dim(`
1728
2656
  Copy to ${MERMAID_LIVE} to render`));
1729
2657
  }
1730
2658
  }
@@ -1785,52 +2713,79 @@ function flowCommand() {
1785
2713
  }
1786
2714
 
1787
2715
  // 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";
2716
+ import { existsSync as existsSync17, readFileSync as readFileSync13 } from "fs";
2717
+ import { join as join18, resolve as resolve11 } from "path";
2718
+ import chalk11 from "chalk";
1791
2719
  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
- }
1799
2720
  function focus_default() {
1800
2721
  return new Command3("focus").argument("[spec]", "Spec name to focus on").option("--clear", "Remove focus file").action((spec, options) => {
1801
2722
  const root = resolve11(process.cwd());
1802
- const focusFile = join7(root, ".letra", "focus.md");
2723
+ const focusFile = join18(root, ".letra", "focus.md");
1803
2724
  if (options.clear) {
1804
- if (existsSync7(focusFile)) {
1805
- unlinkSync(focusFile);
1806
- console.log(chalk10.green("Focus removed."));
2725
+ if (existsSync17(focusFile)) {
2726
+ clearFocusFile(root);
2727
+ console.log(chalk11.green("Focus removed."));
1807
2728
  } else {
1808
- console.log(chalk10.yellow("No focus to remove."));
2729
+ console.log(chalk11.yellow("No focus to remove."));
2730
+ }
2731
+ const workflow = loadWorkflow(root);
2732
+ if (workflow) {
2733
+ const codeStage = workflow.stages.find(
2734
+ (s) => s.id === "code" || s.name.toLowerCase() === "code"
2735
+ );
2736
+ const activeStageId = codeStage ? codeStage.id : workflow.stages[0]?.id;
2737
+ generateAdapters(root, workflow.tools, {
2738
+ source: "focus",
2739
+ workflow: {
2740
+ name: workflow.name,
2741
+ stages: workflow.stages,
2742
+ items: workflow.items
2743
+ },
2744
+ activeStageId
2745
+ });
1809
2746
  }
1810
2747
  return;
1811
2748
  }
1812
2749
  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`));
2750
+ const specDir = join18(root, ".letra", "specs", spec);
2751
+ const specFile = join18(specDir, "spec.md");
2752
+ if (!existsSync17(specFile)) {
2753
+ console.log(chalk11.red(`Spec "${spec}" not found`));
1817
2754
  process.exit(1);
1818
2755
  }
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}".`));
2756
+ const workflow = loadWorkflow(root);
2757
+ let itemId = "";
2758
+ let activeStageId = "code";
2759
+ if (workflow) {
2760
+ const itemWithSpec = workflow.items.find((item) => item.spec === spec);
2761
+ if (itemWithSpec) {
2762
+ itemId = itemWithSpec.id;
2763
+ activeStageId = itemWithSpec.stage;
2764
+ } else {
2765
+ const codeStage = workflow.stages.find(
2766
+ (s) => s.id === "code" || s.name.toLowerCase() === "code"
2767
+ );
2768
+ activeStageId = codeStage ? codeStage.id : workflow.stages[0]?.id;
2769
+ }
2770
+ }
2771
+ writeFocusFile(root, spec, itemId);
2772
+ console.log(chalk11.green(`Focus set to "${spec}".`));
2773
+ if (workflow) {
2774
+ generateAdapters(root, workflow.tools, {
2775
+ source: "focus",
2776
+ workflow: {
2777
+ name: workflow.name,
2778
+ stages: workflow.stages,
2779
+ items: workflow.items
2780
+ },
2781
+ activeStageId,
2782
+ primaryItemId: itemId || void 0
2783
+ });
2784
+ }
1830
2785
  return;
1831
2786
  }
1832
- if (existsSync7(focusFile)) {
1833
- console.log(readFileSync6(focusFile, "utf-8"));
2787
+ if (existsSync17(focusFile)) {
2788
+ console.log(readFileSync13(focusFile, "utf-8"));
1834
2789
  } else {
1835
2790
  console.log("Nenhum foco definido.");
1836
2791
  }
@@ -1838,28 +2793,28 @@ function focus_default() {
1838
2793
  }
1839
2794
 
1840
2795
  // 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";
2796
+ import { existsSync as existsSync18, mkdirSync as mkdirSync7, writeFileSync as writeFileSync10 } from "fs";
2797
+ import { join as join19, resolve as resolve12 } from "path";
1843
2798
  import { createInterface as createInterface2 } from "readline";
1844
2799
  import { fileURLToPath as fileURLToPath2 } from "url";
1845
- import chalk11 from "chalk";
2800
+ import chalk12 from "chalk";
1846
2801
  import ora2 from "ora";
1847
2802
  var __dirname = fileURLToPath2(new URL(".", import.meta.url));
1848
2803
  function ask(query, options) {
1849
2804
  if (!process.stdin.isTTY) return Promise.resolve(options[0]);
1850
2805
  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(" ")}
2806
+ return new Promise((resolve18) => {
2807
+ const formatted = `${chalk12.cyan(query)} ${options.map((o) => chalk12.gray(`(${o})`)).join(" ")}
1853
2808
  > `;
1854
2809
  rl.question(formatted, (answer) => {
1855
2810
  rl.close();
1856
2811
  const trimmed = answer.trim().toLowerCase();
1857
2812
  if (trimmed && options.some((o) => o.toLowerCase().startsWith(trimmed))) {
1858
- resolve17(options.find((o) => o.toLowerCase().startsWith(trimmed)) ?? options[0]);
2813
+ resolve18(options.find((o) => o.toLowerCase().startsWith(trimmed)) ?? options[0]);
1859
2814
  } else if (trimmed && options.includes(trimmed)) {
1860
- resolve17(trimmed);
2815
+ resolve18(trimmed);
1861
2816
  } else {
1862
- resolve17(options[0]);
2817
+ resolve18(options[0]);
1863
2818
  }
1864
2819
  });
1865
2820
  });
@@ -1921,53 +2876,53 @@ ${format === "at" ? "# Context\n@.letra/context.md\n@.letra/constitution.md\n@.l
1921
2876
  switch (tool) {
1922
2877
  case "cursor":
1923
2878
  adapters.push({
1924
- path: join8(root, ".cursorrules"),
2879
+ path: join19(root, ".cursorrules"),
1925
2880
  content: baseContent("Cursor", "at")
1926
2881
  });
1927
2882
  break;
1928
2883
  case "claude-code":
1929
2884
  adapters.push({
1930
- path: join8(root, "CLAUDE.md"),
2885
+ path: join19(root, "CLAUDE.md"),
1931
2886
  content: baseContent("Claude Code", "text")
1932
2887
  });
1933
2888
  break;
1934
2889
  case "windsurf":
1935
2890
  adapters.push({
1936
- path: join8(root, ".windsurfrules"),
2891
+ path: join19(root, ".windsurfrules"),
1937
2892
  content: baseContent("Windsurf", "at")
1938
2893
  });
1939
2894
  break;
1940
2895
  case "vscode":
1941
2896
  adapters.push({
1942
- path: join8(root, ".github", "copilot-instructions.md"),
2897
+ path: join19(root, ".github", "copilot-instructions.md"),
1943
2898
  content: baseContent("VSCode Copilot", "text")
1944
2899
  });
1945
2900
  break;
1946
2901
  case "opencode":
1947
2902
  adapters.push({
1948
- path: join8(root, "AGENTS.md"),
2903
+ path: join19(root, "AGENTS.md"),
1949
2904
  content: baseContent("OpenCode", "text")
1950
2905
  });
1951
2906
  break;
1952
2907
  }
1953
2908
  }
1954
2909
  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}/`, "")}`);
2910
+ const dir = join19(path, "..");
2911
+ if (!existsSync18(dir)) mkdirSync7(dir, { recursive: true });
2912
+ writeFileSync10(path, content);
2913
+ console.log(` ${chalk12.gray("Created")} ${path.replace(`${root}/`, "")}`);
1959
2914
  }
1960
2915
  }
1961
2916
  async function init(targetPath, options) {
1962
2917
  const root = resolve12(process.cwd(), targetPath || ".");
1963
- const letraDir = join8(root, ".letra");
1964
- if (existsSync8(letraDir)) {
2918
+ const letraDir = join19(root, ".letra");
2919
+ if (existsSync18(letraDir)) {
1965
2920
  if (options?.serve) {
1966
- console.log(chalk11.cyan(".letra/ already exists \u2014 starting UI..."));
2921
+ console.log(chalk12.cyan(".letra/ already exists \u2014 starting UI..."));
1967
2922
  await flowServeAction(targetPath, { open: true });
1968
2923
  return;
1969
2924
  }
1970
- console.log(chalk11.yellow(".letra/ already exists"));
2925
+ console.log(chalk12.yellow(".letra/ already exists"));
1971
2926
  return;
1972
2927
  }
1973
2928
  const spinner = ora2("Initializing Letra...").start();
@@ -1992,9 +2947,9 @@ async function init(targetPath, options) {
1992
2947
  tool = answer.toLowerCase();
1993
2948
  spinner.start();
1994
2949
  }
1995
- mkdirSync5(join8(letraDir, "decisions"), { recursive: true });
1996
- mkdirSync5(join8(letraDir, "specs", "_template"), { recursive: true });
1997
- mkdirSync5(join8(letraDir, "adapters"), { recursive: true });
2950
+ mkdirSync7(join19(letraDir, "decisions"), { recursive: true });
2951
+ mkdirSync7(join19(letraDir, "specs", "_template"), { recursive: true });
2952
+ mkdirSync7(join19(letraDir, "adapters"), { recursive: true });
1998
2953
  const templateFiles = {
1999
2954
  "context.md": `# Context
2000
2955
 
@@ -2070,9 +3025,9 @@ Captura dire\xE7\xE3o, inten\xE7\xE3o e contexto, enriquecendo prompts de agente
2070
3025
  `
2071
3026
  };
2072
3027
  for (const [file, content] of Object.entries(templateFiles)) {
2073
- writeFileSync9(join8(letraDir, file), content, "utf-8");
3028
+ writeFileSync10(join19(letraDir, file), content, "utf-8");
2074
3029
  }
2075
- const specTemplate = join8(letraDir, "specs", "_template.md");
3030
+ const specTemplate = join19(letraDir, "specs", "_template.md");
2076
3031
  const specContent = `# Spec Template
2077
3032
 
2078
3033
  > Updated: YYYY-MM-DD
@@ -2092,16 +3047,16 @@ O que explicitamente N\xC3O est\xE1 neste escopo.
2092
3047
  ## Context
2093
3048
  Por que estamos construindo isso.
2094
3049
  `;
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`);
3050
+ writeFileSync10(specTemplate, specContent);
3051
+ const configPath = join19(letraDir, "config.json");
3052
+ writeFileSync10(configPath, adaptConfig(projectType));
3053
+ console.log(` ${chalk12.gray("Created")} .letra/config.json`);
2099
3054
  const tools = adaptersForTool(tool);
2100
3055
  generateAdapterFiles(root, tools);
2101
3056
  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");
3057
+ const vscodeDir = join19(root, ".vscode");
3058
+ if (!existsSync18(vscodeDir)) mkdirSync7(vscodeDir, { recursive: true });
3059
+ const vscodeSettingsPath = join19(vscodeDir, "settings.json");
2105
3060
  const vscodeSettingsContent = `{
2106
3061
  "editor.formatOnSave": true,
2107
3062
  "editor.defaultFormatter": "esbenp.prettier-vscode",
@@ -2111,32 +3066,32 @@ Por que estamos construindo isso.
2111
3066
  "files.autoSave": "onFocusChange"
2112
3067
  }
2113
3068
  `;
2114
- writeFileSync9(vscodeSettingsPath, vscodeSettingsContent);
2115
- console.log(` ${chalk11.gray("Created")} .vscode/settings.json`);
3069
+ writeFileSync10(vscodeSettingsPath, vscodeSettingsContent);
3070
+ console.log(` ${chalk12.gray("Created")} .vscode/settings.json`);
2116
3071
  }
2117
- spinner.succeed(chalk11.green(".letra/ initialized successfully"));
3072
+ spinner.succeed(chalk12.green(".letra/ initialized successfully"));
2118
3073
  console.log("");
2119
3074
  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`);
3075
+ console.log(` ${chalk12.cyan("letra spec new <name>")} Create your first spec`);
3076
+ console.log(` ${chalk12.cyan("letra lint")} Validate specs`);
3077
+ console.log(` ${chalk12.cyan("letra init --serve")} Open web UI to configure workflow`);
2123
3078
  if (options?.serve) {
2124
3079
  console.log(`
2125
- ${chalk11.cyan("Opening web UI...")}
3080
+ ${chalk12.cyan("Opening web UI...")}
2126
3081
  `);
2127
3082
  await flowServeAction(targetPath, { open: true });
2128
3083
  return;
2129
3084
  }
2130
3085
  } catch (error) {
2131
- spinner.fail(chalk11.red("Failed to initialize Letra"));
3086
+ spinner.fail(chalk12.red("Failed to initialize Letra"));
2132
3087
  process.exit(1);
2133
3088
  }
2134
3089
  }
2135
3090
 
2136
3091
  // 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";
3092
+ import { existsSync as existsSync19, readFileSync as readFileSync14, readdirSync as readdirSync8 } from "fs";
3093
+ import { join as join20, resolve as resolve13 } from "path";
3094
+ import chalk13 from "chalk";
2140
3095
  var REQUIRED_SECTIONS = [
2141
3096
  "## Outcome",
2142
3097
  "## Constraints",
@@ -2146,24 +3101,24 @@ var REQUIRED_SECTIONS = [
2146
3101
  ];
2147
3102
  async function lint(targetPath) {
2148
3103
  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."));
3104
+ const specsDir = join20(root, ".letra", "specs");
3105
+ if (!existsSync19(specsDir)) {
3106
+ console.log(chalk13.red("Error: .letra/specs/ not found. Run 'letra init' first."));
2152
3107
  process.exit(1);
2153
3108
  }
2154
3109
  const results = [];
2155
3110
  let totalErrors = 0;
2156
3111
  let totalWarnings = 0;
2157
- const entries = readdirSync5(specsDir, { withFileTypes: true });
3112
+ const entries = readdirSync8(specsDir, { withFileTypes: true });
2158
3113
  for (const entry of entries) {
2159
3114
  if (!entry.isDirectory() || entry.name.startsWith("_")) continue;
2160
- const specFile = join9(specsDir, entry.name, "spec.md");
3115
+ const specFile = join20(specsDir, entry.name, "spec.md");
2161
3116
  const errors = [];
2162
3117
  const warnings = [];
2163
- if (!existsSync9(specFile)) {
3118
+ if (!existsSync19(specFile)) {
2164
3119
  errors.push("Missing spec.md");
2165
3120
  } else {
2166
- const content = readFileSync7(specFile, "utf-8");
3121
+ const content = readFileSync14(specFile, "utf-8");
2167
3122
  for (const section of REQUIRED_SECTIONS) {
2168
3123
  if (!content.includes(section)) {
2169
3124
  errors.push(`Missing section: ${section}`);
@@ -2184,22 +3139,22 @@ async function lint(targetPath) {
2184
3139
  }
2185
3140
  }
2186
3141
  if (results.length === 0) {
2187
- console.log(chalk12.green("All specs are valid"));
3142
+ console.log(chalk13.green("All specs are valid"));
2188
3143
  process.exit(0);
2189
3144
  }
2190
3145
  console.log("");
2191
3146
  for (const result of results) {
2192
- console.log(chalk12.bold(`
3147
+ console.log(chalk13.bold(`
2193
3148
  Spec: ${result.file}`));
2194
3149
  for (const error of result.errors) {
2195
- console.log(chalk12.red(` \u2717 ${error}`));
3150
+ console.log(chalk13.red(` \u2717 ${error}`));
2196
3151
  }
2197
3152
  for (const warning of result.warnings) {
2198
- console.log(chalk12.yellow(` \u26A0 ${warning}`));
3153
+ console.log(chalk13.yellow(` \u26A0 ${warning}`));
2199
3154
  }
2200
3155
  }
2201
3156
  console.log(
2202
- chalk12.gray(
3157
+ chalk13.gray(
2203
3158
  `
2204
3159
  ${results.length} spec(s) with issues: ${totalErrors} error(s), ${totalWarnings} warning(s)`
2205
3160
  )
@@ -2208,9 +3163,9 @@ ${results.length} spec(s) with issues: ${totalErrors} error(s), ${totalWarnings}
2208
3163
  }
2209
3164
 
2210
3165
  // 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";
3166
+ import { existsSync as existsSync20, mkdirSync as mkdirSync8, readFileSync as readFileSync15, readdirSync as readdirSync9, writeFileSync as writeFileSync11 } from "fs";
3167
+ import { join as join21, resolve as resolve14 } from "path";
3168
+ import chalk14 from "chalk";
2214
3169
  import ora3 from "ora";
2215
3170
  var builtInTemplates = {
2216
3171
  "web-api": {
@@ -2321,9 +3276,9 @@ Template para features mobile nativas. Adaptado para o framework espec\xEDfico (
2321
3276
  };
2322
3277
  function listTemplates(root) {
2323
3278
  const names = Object.keys(builtInTemplates);
2324
- const customDir = join10(root, ".letra", "templates");
2325
- if (existsSync10(customDir)) {
2326
- for (const file of readdirSync6(customDir)) {
3279
+ const customDir = join21(root, ".letra", "templates");
3280
+ if (existsSync20(customDir)) {
3281
+ for (const file of readdirSync9(customDir)) {
2327
3282
  if (file.endsWith(".md")) {
2328
3283
  const name = file.replace(/\.md$/, "");
2329
3284
  if (!names.includes(name)) names.push(name);
@@ -2335,11 +3290,11 @@ function listTemplates(root) {
2335
3290
  function findTemplate(root, type) {
2336
3291
  const lower = type.toLowerCase();
2337
3292
  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}
3293
+ const customFile = join21(root, ".letra", "templates", `${type}.md`);
3294
+ const customAcceptance = join21(root, ".letra", "templates", `${type}-acceptance.md`);
3295
+ if (existsSync20(customFile)) {
3296
+ const spec = readFileSync15(customFile, "utf-8");
3297
+ const acceptance = existsSync20(customAcceptance) ? readFileSync15(customAcceptance, "utf-8") : `# Acceptance Criteria \u2014 ${type}
2343
3298
 
2344
3299
  - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
2345
3300
  `;
@@ -2352,32 +3307,32 @@ function applyPlaceholders(content, name, date) {
2352
3307
  }
2353
3308
  async function specNew(name, options) {
2354
3309
  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."));
3310
+ const letraDir = join21(root, ".letra");
3311
+ const specDir = join21(letraDir, "specs", name);
3312
+ if (!existsSync20(letraDir)) {
3313
+ console.log(chalk14.red(".letra/ not found. Run 'letra init' first."));
2359
3314
  process.exit(1);
2360
3315
  }
2361
- if (existsSync10(specDir)) {
2362
- console.log(chalk13.yellow(`Spec "${name}" already exists`));
3316
+ if (existsSync20(specDir)) {
3317
+ console.log(chalk14.yellow(`Spec "${name}" already exists`));
2363
3318
  return;
2364
3319
  }
2365
3320
  const templateType = options?.template || "_default";
2366
3321
  const template = templateType === "_default" ? null : findTemplate(root, templateType);
2367
3322
  if (options?.template && !template) {
2368
3323
  const available = listTemplates(root).join(", ");
2369
- console.log(chalk13.red(`Template "${options.template}" not found. Available: ${available}`));
3324
+ console.log(chalk14.red(`Template "${options.template}" not found. Available: ${available}`));
2370
3325
  process.exit(1);
2371
3326
  }
2372
3327
  const spinner = ora3(`Creating spec "${name}"...`).start();
2373
3328
  try {
2374
3329
  const today2 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
2375
- mkdirSync6(specDir, { recursive: true });
3330
+ mkdirSync8(specDir, { recursive: true });
2376
3331
  if (template) {
2377
3332
  const specContent = applyPlaceholders(template.spec, name, today2);
2378
3333
  const acceptanceContent = applyPlaceholders(template.acceptance, name, today2);
2379
- writeFileSync10(join10(specDir, "spec.md"), specContent);
2380
- writeFileSync10(join10(specDir, "acceptance.md"), acceptanceContent);
3334
+ writeFileSync11(join21(specDir, "spec.md"), specContent);
3335
+ writeFileSync11(join21(specDir, "acceptance.md"), acceptanceContent);
2381
3336
  } else {
2382
3337
  const specContent = `# Spec: ${name}
2383
3338
 
@@ -2402,12 +3357,12 @@ Por que estamos construindo isso. Trade-offs considerados.
2402
3357
 
2403
3358
  - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
2404
3359
  `;
2405
- writeFileSync10(join10(specDir, "spec.md"), specContent);
2406
- writeFileSync10(join10(specDir, "acceptance.md"), acceptanceContent);
3360
+ writeFileSync11(join21(specDir, "spec.md"), specContent);
3361
+ writeFileSync11(join21(specDir, "acceptance.md"), acceptanceContent);
2407
3362
  }
2408
- spinner.succeed(chalk13.green(`Spec "${name}" created at .letra/specs/${name}/`));
3363
+ spinner.succeed(chalk14.green(`Spec "${name}" created at .letra/specs/${name}/`));
2409
3364
  } catch (error) {
2410
- spinner.fail(chalk13.red("Failed to create spec"));
3365
+ spinner.fail(chalk14.red("Failed to create spec"));
2411
3366
  process.exit(1);
2412
3367
  }
2413
3368
  }
@@ -2415,21 +3370,21 @@ Por que estamos construindo isso. Trade-offs considerados.
2415
3370
  // src/commands/validate.ts
2416
3371
  import { execSync } from "child_process";
2417
3372
  import {
2418
- existsSync as existsSync12,
3373
+ existsSync as existsSync22,
2419
3374
  mkdtempSync,
2420
- readFileSync as readFileSync10,
2421
- readdirSync as readdirSync7,
2422
- rmSync,
2423
- statSync as statSync2,
3375
+ readFileSync as readFileSync17,
3376
+ readdirSync as readdirSync10,
3377
+ rmSync as rmSync2,
3378
+ statSync as statSync3,
2424
3379
  watch as watch2
2425
3380
  } from "fs";
2426
3381
  import { tmpdir } from "os";
2427
- import { join as join12, resolve as resolve15 } from "path";
2428
- import chalk14 from "chalk";
3382
+ import { join as join23, resolve as resolve15 } from "path";
3383
+ import chalk15 from "chalk";
2429
3384
 
2430
3385
  // src/config.ts
2431
- import { existsSync as existsSync11, readFileSync as readFileSync9 } from "fs";
2432
- import { join as join11 } from "path";
3386
+ import { existsSync as existsSync21, readFileSync as readFileSync16 } from "fs";
3387
+ import { join as join22 } from "path";
2433
3388
  var DEFAULT_HEURISTICS = {
2434
3389
  "conteudo-minimo": { severity: "warning", minChars: 50 },
2435
3390
  "consistencia-terminologia": { severity: "warning" },
@@ -2444,14 +3399,14 @@ var DEFAULT_HEURISTICS = {
2444
3399
  "validate-conflict": { severity: "warning" }
2445
3400
  };
2446
3401
  function loadConfig(root) {
2447
- const configPath = join11(root, ".letra", "config.json");
3402
+ const configPath = join22(root, ".letra", "config.json");
2448
3403
  const heuristics = {};
2449
3404
  for (const [key, value] of Object.entries(DEFAULT_HEURISTICS)) {
2450
3405
  heuristics[key] = { ...value };
2451
3406
  }
2452
- if (existsSync11(configPath)) {
3407
+ if (existsSync21(configPath)) {
2453
3408
  try {
2454
- const raw = JSON.parse(readFileSync9(configPath, "utf-8"));
3409
+ const raw = JSON.parse(readFileSync16(configPath, "utf-8"));
2455
3410
  if (raw.heuristics && typeof raw.heuristics === "object") {
2456
3411
  for (const [key, value] of Object.entries(raw.heuristics)) {
2457
3412
  if (heuristics[key]) {
@@ -2518,11 +3473,11 @@ var lowConfidenceMarkers = [
2518
3473
  "teoricamente"
2519
3474
  ];
2520
3475
  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");
3476
+ const cfg = config ?? loadConfig(join23(specDir, "..", "..", ".."));
3477
+ const specFile = join23(specDir, "spec.md");
3478
+ const glossaryFile = join23(specDir, "..", "..", "glossary.md");
3479
+ if (!existsSync22(specFile)) return { status: "FAIL", note: "(spec.md not found)" };
3480
+ const specContent = readFileSync17(specFile, "utf-8");
2526
3481
  const now7 = /* @__PURE__ */ new Date();
2527
3482
  if (label.includes("Conte\xFAdo M\xEDnimo")) {
2528
3483
  const outcomeMatch = specContent.match(/## Outcome\s+([\s\S]*?)(?=\n## )/);
@@ -2542,13 +3497,13 @@ function checkSpecContent(specDir, label, description, config) {
2542
3497
  };
2543
3498
  }
2544
3499
  if (label.includes("Consist\xEAncia de Terminologia") || label.includes("Terminologia")) {
2545
- if (!existsSync12(glossaryFile)) {
3500
+ if (!existsSync22(glossaryFile)) {
2546
3501
  return {
2547
3502
  status: "PASS",
2548
3503
  note: "(no glossary to check against)"
2549
3504
  };
2550
3505
  }
2551
- const glossaryContent = readFileSync10(glossaryFile, "utf-8");
3506
+ const glossaryContent = readFileSync17(glossaryFile, "utf-8");
2552
3507
  const terms = glossaryContent.match(/\*\*(.+?)\*\*/g) || [];
2553
3508
  const extractedTerms = terms.map((t) => t.replace(/\*\*/g, "").trim()).filter((t) => t.length > 3);
2554
3509
  const missingTerms = extractedTerms.filter(
@@ -2586,7 +3541,7 @@ function checkSpecContent(specDir, label, description, config) {
2586
3541
  };
2587
3542
  }
2588
3543
  if (label.includes("Drift Temporal") || label.includes("Temporal")) {
2589
- const stat = statSync2(specFile);
3544
+ const stat = statSync3(specFile);
2590
3545
  const daysOld = Math.floor((now7.getTime() - stat.mtimeMs) / (1e3 * 60 * 60 * 24));
2591
3546
  const heurConfig = getHeuristicConfig(cfg, label);
2592
3547
  const maxDays = heurConfig.maxDays ?? 30;
@@ -2769,13 +3724,13 @@ function detectConflict(textA, textB) {
2769
3724
  }
2770
3725
  function checkConflicts(specsDir, config) {
2771
3726
  const results = [];
2772
- const entries = readdirSync7(specsDir, { withFileTypes: true });
3727
+ const entries = readdirSync10(specsDir, { withFileTypes: true });
2773
3728
  const specDirs = entries.filter((e) => e.isDirectory() && !e.name.startsWith("_")).map((e) => e.name);
2774
3729
  const specs = [];
2775
3730
  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");
3731
+ const acceptanceFile = join23(specsDir, dir, "acceptance.md");
3732
+ if (!existsSync22(acceptanceFile)) continue;
3733
+ const content = readFileSync17(acceptanceFile, "utf-8");
2779
3734
  const acLines = content.match(/- \[[ x]\] \*\*(.+?)\*\*: (.+)/g) || [];
2780
3735
  const acs = acLines.map((line) => {
2781
3736
  const m = line.match(/- \[[ x]\] \*\*(.+?)\*\*: (.+)/);
@@ -2825,11 +3780,11 @@ function out(format, level, spec, label, message, note) {
2825
3780
  if (format === "junit") {
2826
3781
  return;
2827
3782
  }
2828
- const icon = level === "pass" ? chalk14.green("\u2713") : level === "fail" ? chalk14.red("\u2717") : level === "warning" ? chalk14.yellow("\u26A0") : "";
3783
+ const icon = level === "pass" ? chalk15.green("\u2713") : level === "fail" ? chalk15.red("\u2717") : level === "warning" ? chalk15.yellow("\u26A0") : "";
2829
3784
  if (level === "info") {
2830
3785
  console.log(` ${message}`);
2831
3786
  } else {
2832
- console.log(` [${icon}] ${chalk14.cyan(label)}: ${message} ${chalk14.gray(note)}`);
3787
+ console.log(` [${icon}] ${chalk15.cyan(label)}: ${message} ${chalk15.gray(note)}`);
2833
3788
  }
2834
3789
  }
2835
3790
  function buildJunitXml(results) {
@@ -2870,7 +3825,7 @@ function flushResults(results, format, specGroups, totalPass, totalFail, totalWa
2870
3825
  }
2871
3826
  }
2872
3827
  console.log(
2873
- chalk14.gray(
3828
+ chalk15.gray(
2874
3829
  `
2875
3830
  Results: ${totalPass} passed, ${totalFail} failed${totalWarning > 0 ? `, ${totalWarning} warnings` : ""}`
2876
3831
  )
@@ -2878,47 +3833,47 @@ Results: ${totalPass} passed, ${totalFail} failed${totalWarning > 0 ? `, ${total
2878
3833
  }
2879
3834
  async function validate(targetPath, options) {
2880
3835
  const root = resolve15(process.cwd(), targetPath || ".");
2881
- const specsDir = join12(root, ".letra", "specs");
3836
+ const specsDir = join23(root, ".letra", "specs");
2882
3837
  const fmt = options?.format || "text";
2883
- if (!existsSync12(specsDir)) {
3838
+ if (!existsSync22(specsDir)) {
2884
3839
  const msg = "Error: .letra/specs/ not found. Run 'letra init' first.";
2885
3840
  if (fmt === "github-annotation") {
2886
3841
  console.log(`::error file=,title=Init Required::${msg}`);
2887
3842
  } else {
2888
- console.log(chalk14.red(msg));
3843
+ console.log(chalk15.red(msg));
2889
3844
  }
2890
3845
  process.exit(1);
2891
3846
  }
2892
3847
  async function runValidation() {
2893
3848
  const config = loadConfig(root);
2894
- const entries = readdirSync7(specsDir, { withFileTypes: true });
3849
+ const entries = readdirSync10(specsDir, { withFileTypes: true });
2895
3850
  let totalPass = 0;
2896
3851
  let totalFail = 0;
2897
3852
  let totalWarning = 0;
2898
3853
  const specGroups = /* @__PURE__ */ new Map();
2899
3854
  const allResults = [];
2900
- const entryPoint = join12(root, "src/index.ts");
3855
+ const entryPoint = join23(root, "src/index.ts");
2901
3856
  const opts = {
2902
3857
  stdio: "pipe",
2903
3858
  encoding: "utf-8",
2904
3859
  shell: process.platform === "win32" ? "cmd.exe" : true
2905
3860
  };
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");
3861
+ const ciFile = join23(root, ".github", "workflows", "ci.yml");
3862
+ const cursorRulesFile = join23(root, ".cursorrules");
3863
+ const copilotFile = join23(root, ".github", "copilot-instructions.md");
3864
+ const vscodeSettingsFile = join23(root, ".vscode", "settings.json");
2910
3865
  if (fmt !== "junit") {
2911
3866
  out(fmt, "info", null, "", "\nLetra Validation\n", "");
2912
3867
  }
2913
3868
  for (const entry of entries) {
2914
3869
  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");
3870
+ const acceptanceFile = join23(specsDir, entry.name, "acceptance.md");
3871
+ const specFile = join23(specsDir, entry.name, "spec.md");
2917
3872
  let content;
2918
- if (existsSync12(acceptanceFile)) {
2919
- content = readFileSync10(acceptanceFile, "utf-8");
2920
- } else if (existsSync12(specFile)) {
2921
- content = readFileSync10(specFile, "utf-8");
3873
+ if (existsSync22(acceptanceFile)) {
3874
+ content = readFileSync17(acceptanceFile, "utf-8");
3875
+ } else if (existsSync22(specFile)) {
3876
+ content = readFileSync17(specFile, "utf-8");
2922
3877
  } else {
2923
3878
  out(
2924
3879
  fmt,
@@ -2931,7 +3886,7 @@ async function validate(targetPath, options) {
2931
3886
  continue;
2932
3887
  }
2933
3888
  const criteriaLines = content.match(/- \[ \] \*\*(.+?)\*\*: (.+)/g) || [];
2934
- const specContent = existsSync12(specFile) ? readFileSync10(specFile, "utf-8") : null;
3889
+ const specContent = existsSync22(specFile) ? readFileSync17(specFile, "utf-8") : null;
2935
3890
  out(fmt, "info", entry.name, "", `Spec: ${entry.name}`, "");
2936
3891
  if (criteriaLines.length === 0) {
2937
3892
  out(fmt, "info", entry.name, "", "No criteria found", "");
@@ -2948,7 +3903,7 @@ async function validate(targetPath, options) {
2948
3903
  let intelligenceResult = null;
2949
3904
  try {
2950
3905
  intelligenceResult = checkSpecContent(
2951
- join12(specsDir, entry.name),
3906
+ join23(specsDir, entry.name),
2952
3907
  label,
2953
3908
  description,
2954
3909
  config
@@ -2957,42 +3912,42 @@ async function validate(targetPath, options) {
2957
3912
  status = intelligenceResult.status;
2958
3913
  note = intelligenceResult.note;
2959
3914
  } else if (label.includes("letra init")) {
2960
- const tmp = mkdtempSync(join12(tmpdir(), "letra-test-"));
3915
+ const tmp = mkdtempSync(join23(tmpdir(), "letra-test-"));
2961
3916
  execSync(`npx tsx "${entryPoint}" init "${tmp}"`, { ...opts });
2962
- if (existsSync12(join12(tmp, ".letra", "context.md"))) status = "PASS";
2963
- rmSync(tmp, { recursive: true });
3917
+ if (existsSync22(join23(tmp, ".letra", "context.md"))) status = "PASS";
3918
+ rmSync2(tmp, { recursive: true });
2964
3919
  } else if (label.includes("letra spec")) {
2965
- const tmp = mkdtempSync(join12(tmpdir(), "letra-test-"));
3920
+ const tmp = mkdtempSync(join23(tmpdir(), "letra-test-"));
2966
3921
  execSync(`npx tsx "${entryPoint}" init "${tmp}"`, { ...opts });
2967
3922
  execSync(`npx tsx "${entryPoint}" spec smoke-test`, {
2968
3923
  ...opts,
2969
3924
  cwd: tmp
2970
3925
  });
2971
- if (existsSync12(join12(tmp, ".letra", "specs", "smoke-test", "spec.md")))
3926
+ if (existsSync22(join23(tmp, ".letra", "specs", "smoke-test", "spec.md")))
2972
3927
  status = "PASS";
2973
- rmSync(tmp, { recursive: true });
3928
+ rmSync2(tmp, { recursive: true });
2974
3929
  } else if (label.includes("letra lint")) {
2975
3930
  execSync(`npx tsx "${entryPoint}" lint`, { ...opts });
2976
3931
  status = "PASS";
2977
3932
  } else if (label.includes("letra validate")) {
2978
3933
  status = "PASS";
2979
- } else if (label.includes("Workflow Ativo") || label.includes("CI") && existsSync12(ciFile)) {
3934
+ } else if (label.includes("Workflow Ativo") || label.includes("CI") && existsSync22(ciFile)) {
2980
3935
  status = "PASS";
2981
3936
  } else if (label.includes("Lint Gate") || label.includes("Lint")) {
2982
- const ciContent = readFileSync10(ciFile, "utf-8");
3937
+ const ciContent = readFileSync17(ciFile, "utf-8");
2983
3938
  if (ciContent.includes("letra lint") || ciContent.includes("lint"))
2984
3939
  status = "PASS";
2985
3940
  } else if (label.includes("Test Gate") || label.includes("Test")) {
2986
- const ciContent = readFileSync10(ciFile, "utf-8");
3941
+ const ciContent = readFileSync17(ciFile, "utf-8");
2987
3942
  if (ciContent.includes("npm test") || ciContent.includes("vitest") || ciContent.includes("test"))
2988
3943
  status = "PASS";
2989
3944
  } else if (label.includes("Valida\xE7\xE3o de Formato") || label.includes("Formato")) {
2990
- const ciContent = readFileSync10(ciFile, "utf-8");
3945
+ const ciContent = readFileSync17(ciFile, "utf-8");
2991
3946
  if (ciContent.includes("tsc") || ciContent.includes("typecheck"))
2992
3947
  status = "PASS";
2993
3948
  } else if (label.includes("Distribui\xE7\xE3o npm") || label.includes("npm")) {
2994
3949
  const pkgJson = JSON.parse(
2995
- readFileSync10(join12(root, "package.json"), "utf-8")
3950
+ readFileSync17(join23(root, "package.json"), "utf-8")
2996
3951
  );
2997
3952
  if (pkgJson.bin && pkgJson.name) {
2998
3953
  status = "PASS";
@@ -3004,47 +3959,47 @@ async function validate(targetPath, options) {
3004
3959
  status = "PASS";
3005
3960
  note = "(npm distribution preferred)";
3006
3961
  } 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");
3962
+ if (existsSync22(cursorRulesFile)) {
3963
+ const rulesContent = readFileSync17(cursorRulesFile, "utf-8");
3009
3964
  if (rulesContent.includes(".letra/context.md") && rulesContent.includes(".letra/constitution.md")) {
3010
3965
  status = "PASS";
3011
3966
  }
3012
3967
  }
3013
3968
  } else if (label.includes("Inje\xE7\xE3o de Contexto")) {
3014
- if (existsSync12(cursorRulesFile)) {
3015
- const rulesContent = readFileSync10(cursorRulesFile, "utf-8");
3969
+ if (existsSync22(cursorRulesFile)) {
3970
+ const rulesContent = readFileSync17(cursorRulesFile, "utf-8");
3016
3971
  if (rulesContent.includes("@.letra/")) status = "PASS";
3017
- } else if (existsSync12(copilotFile)) {
3018
- const copilotContent = readFileSync10(copilotFile, "utf-8");
3972
+ } else if (existsSync22(copilotFile)) {
3973
+ const copilotContent = readFileSync17(copilotFile, "utf-8");
3019
3974
  if (copilotContent.includes(".letra/")) status = "PASS";
3020
3975
  }
3021
3976
  } else if (label.includes("Acesso a Valida\xE7\xE3o")) {
3022
- if (existsSync12(cursorRulesFile)) {
3023
- const rulesContent = readFileSync10(cursorRulesFile, "utf-8");
3977
+ if (existsSync22(cursorRulesFile)) {
3978
+ const rulesContent = readFileSync17(cursorRulesFile, "utf-8");
3024
3979
  if (rulesContent.includes("letra validate")) status = "PASS";
3025
3980
  }
3026
3981
  } else if (label.includes("N\xE3o-intrusivo")) {
3027
- if (existsSync12(cursorRulesFile) || existsSync12(copilotFile)) {
3982
+ if (existsSync22(cursorRulesFile) || existsSync22(copilotFile)) {
3028
3983
  status = "PASS";
3029
3984
  }
3030
3985
  } else if (label.includes("Gera\xE7\xE3o de Instru\xE7\xF5es")) {
3031
- if (existsSync12(copilotFile)) {
3032
- const copilotContent = readFileSync10(copilotFile, "utf-8");
3986
+ if (existsSync22(copilotFile)) {
3987
+ const copilotContent = readFileSync17(copilotFile, "utf-8");
3033
3988
  if (copilotContent.includes(".letra/context.md") && copilotContent.includes(".letra/constitution.md")) {
3034
3989
  status = "PASS";
3035
3990
  }
3036
3991
  }
3037
3992
  } else if (label.includes("Settings do Editor")) {
3038
- if (existsSync12(vscodeSettingsFile)) {
3039
- const settingsContent = readFileSync10(vscodeSettingsFile, "utf-8");
3993
+ if (existsSync22(vscodeSettingsFile)) {
3994
+ const settingsContent = readFileSync17(vscodeSettingsFile, "utf-8");
3040
3995
  if (settingsContent.includes("editor.formatOnSave")) {
3041
3996
  status = "PASS";
3042
3997
  }
3043
3998
  }
3044
3999
  } 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");
4000
+ const configFile = join23(root, ".letra", "config.json");
4001
+ if (existsSync22(configFile)) {
4002
+ const cfgContent = readFileSync17(configFile, "utf-8");
3048
4003
  try {
3049
4004
  const parsed = JSON.parse(cfgContent);
3050
4005
  if (parsed.heuristics) {
@@ -3223,14 +4178,14 @@ async function validate(targetPath, options) {
3223
4178
  const exitCode = await runValidation();
3224
4179
  if (options?.watch) {
3225
4180
  let timer = null;
3226
- console.log(chalk14.gray("\nWatching for changes... (Ctrl+C to stop)"));
4181
+ console.log(chalk15.gray("\nWatching for changes... (Ctrl+C to stop)"));
3227
4182
  const watcher = watch2(specsDir, { recursive: true });
3228
4183
  watcher.on("change", () => {
3229
4184
  if (timer) clearTimeout(timer);
3230
4185
  timer = setTimeout(async () => {
3231
4186
  console.clear();
3232
4187
  const code = await runValidation();
3233
- console.log(chalk14.gray("\nWatching for changes... (Ctrl+C to stop)"));
4188
+ console.log(chalk15.gray("\nWatching for changes... (Ctrl+C to stop)"));
3234
4189
  }, 300);
3235
4190
  });
3236
4191
  process.on("SIGINT", () => {
@@ -3248,9 +4203,60 @@ async function validate(targetPath, options) {
3248
4203
  }
3249
4204
  }
3250
4205
 
4206
+ // src/commands/diagnose.ts
4207
+ import { resolve as resolve16 } from "path";
4208
+ async function diagnose(targetPath) {
4209
+ const root = resolve16(process.cwd(), targetPath ?? ".");
4210
+ const engine = new DiagnosticEngine(root);
4211
+ engine.ensureDirs();
4212
+ console.log("\n\u{1F50D} Auto-diagn\xF3stico do Letra\n");
4213
+ const output = await engine.runAll();
4214
+ if (output.fixes.length > 0) {
4215
+ console.log(`\u2705 ${output.fixes.length} auto-corre\xE7\xE3o(\xF5es) aplicada(s):
4216
+ `);
4217
+ for (const fix of output.fixes) {
4218
+ console.log(` \u2022 ${fix.title}`);
4219
+ }
4220
+ console.log();
4221
+ }
4222
+ if (output.suggestions.length > 0) {
4223
+ console.log(`\u{1F4A1} ${output.suggestions.length} sugest\xE3o(\xF5es):
4224
+ `);
4225
+ for (const s of output.suggestions) {
4226
+ console.log(` \u2022 [${s.type}] ${s.title}`);
4227
+ console.log(` ${s.description}`);
4228
+ }
4229
+ console.log();
4230
+ }
4231
+ if (output.errors.length > 0) {
4232
+ console.log(`\u274C ${output.errors.length} erro(s) nos detectores:
4233
+ `);
4234
+ for (const err of output.errors) {
4235
+ console.log(` \u2022 ${err}`);
4236
+ }
4237
+ console.log();
4238
+ }
4239
+ if (output.fixes.length === 0 && output.suggestions.length === 0 && output.errors.length === 0) {
4240
+ console.log(" Nenhum problema detectado. Tudo ok.\n");
4241
+ }
4242
+ const snapshots = engine.listSnapshots();
4243
+ if (snapshots.length > 0) {
4244
+ console.log(`\u{1F4E6} ${snapshots.length} snapshots dispon\xEDveis para undo:`);
4245
+ for (const snap of snapshots.slice(0, 5)) {
4246
+ console.log(
4247
+ ` \u2022 ${snap.id} \u2014 ${snap.diagnosticTitle} (${new Date(snap.timestamp).toLocaleString()})`
4248
+ );
4249
+ }
4250
+ if (snapshots.length > 5) {
4251
+ console.log(` ... e mais ${snapshots.length - 5}`);
4252
+ }
4253
+ console.log();
4254
+ }
4255
+ }
4256
+
3251
4257
  // src/index.ts
3252
4258
  var __dirname2 = fileURLToPath3(new URL(".", import.meta.url));
3253
- var pkg = JSON.parse(readFileSync11(join13(resolve16(__dirname2, ".."), "package.json"), "utf-8"));
4259
+ var pkg = JSON.parse(readFileSync18(join24(resolve17(__dirname2, ".."), "package.json"), "utf-8"));
3254
4260
  var program = new Command4();
3255
4261
  program.name("letra").description("SDD-agnostic memory framework for AI coding agents").version(pkg.version);
3256
4262
  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 }));
@@ -3258,6 +4264,7 @@ var specCmd = program.command("spec").description("Manage specs");
3258
4264
  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 }));
3259
4265
  program.command("lint [path]").description("Validate spec format and completeness").action(lint);
3260
4266
  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 }));
4267
+ program.command("diagnose [path]").description("Detect and fix drifts between specs, code, and workflow").action((path) => diagnose(path));
3261
4268
  program.addCommand(decisionCommand());
3262
4269
  program.addCommand(flowCommand());
3263
4270
  program.addCommand(focus_default());