@letra-ai/cli 0.4.1 → 0.6.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.
Files changed (96) hide show
  1. package/dist/chunk-4QDEU6KP.js +2765 -0
  2. package/dist/chunk-6HSUVCTR.js +363 -0
  3. package/dist/chunk-BKAUN5QH.js +300 -0
  4. package/dist/chunk-BTPFUKHG.js +275 -0
  5. package/dist/chunk-EDD55PWL.js +119 -0
  6. package/dist/chunk-ELBTIPYN.js +256 -0
  7. package/dist/chunk-IEFSLCJL.js +837 -0
  8. package/dist/chunk-JMIC5NKB.js +235 -0
  9. package/dist/chunk-KGQLHMGZ.js +4494 -0
  10. package/dist/chunk-MJ2QXNH6.js +130 -0
  11. package/dist/chunk-MSF44WWE.js +443 -0
  12. package/dist/chunk-PDX44BCA.js +11 -0
  13. package/dist/chunk-QIVKP3EY.js +362 -0
  14. package/dist/client/assets/index-BuABgOyz.js +232 -0
  15. package/dist/client/assets/index-CpseCZh9.css +1 -0
  16. package/dist/client/favicon.svg +15 -3
  17. package/dist/client/index.html +10 -5
  18. package/dist/fallback-UXSZ4LNR.js +47 -0
  19. package/dist/flow-serve-MTB6KZMR.js +19 -0
  20. package/dist/focus-sync-3D3XWCTI.js +17 -0
  21. package/dist/generate-N22QOXUF.js +20 -0
  22. package/dist/harness/default/v0.1.0/flows/sdlc.yaml +179 -0
  23. package/dist/harness/default/v0.1.0/gates/all-acs-passing.yaml +8 -0
  24. package/dist/harness/default/v0.1.0/gates/has-spec-file.yaml +7 -0
  25. package/dist/harness/default/v0.1.0/gates/human-approved-code.yaml +8 -0
  26. package/dist/harness/default/v0.1.0/gates/human-approved-spec.yaml +8 -0
  27. package/dist/harness/default/v0.1.0/gates/security-clear.yaml +8 -0
  28. package/dist/harness/default/v0.1.0/policies/sdlc-default.json +20 -0
  29. package/dist/harness/default/v0.1.0/roles/analyst.yaml +9 -0
  30. package/dist/harness/default/v0.1.0/roles/builder.yaml +9 -0
  31. package/dist/harness/default/v0.1.0/roles/pr-bot.yaml +8 -0
  32. package/dist/harness/default/v0.1.0/roles/reviewer.yaml +10 -0
  33. package/dist/harness/default/v0.1.0/roles/security.yaml +8 -0
  34. package/dist/harness/default/v0.1.1/flows/flow-main.yaml +61 -0
  35. package/dist/harness/default/v0.1.1/flows/sdlc.yaml +179 -0
  36. package/dist/harness/default/v0.1.1/gates/all-acs-passing.yaml +8 -0
  37. package/dist/harness/default/v0.1.1/gates/has-spec-file.yaml +7 -0
  38. package/dist/harness/default/v0.1.1/gates/human-approved-code.yaml +8 -0
  39. package/dist/harness/default/v0.1.1/gates/human-approved-spec.yaml +8 -0
  40. package/dist/harness/default/v0.1.1/gates/security-clear.yaml +8 -0
  41. package/dist/harness/default/v0.1.1/policies/sdlc-default.json +20 -0
  42. package/dist/harness/default/v0.1.1/roles/analyst.yaml +9 -0
  43. package/dist/harness/default/v0.1.1/roles/builder.yaml +9 -0
  44. package/dist/harness/default/v0.1.1/roles/pr-bot.yaml +8 -0
  45. package/dist/harness/default/v0.1.1/roles/reviewer.yaml +10 -0
  46. package/dist/harness/default/v0.1.1/roles/security.yaml +8 -0
  47. package/dist/harness/default/v0.1.2/flows/flow-main.yaml +86 -0
  48. package/dist/harness/default/v0.1.2/flows/sdlc.yaml +179 -0
  49. package/dist/harness/default/v0.1.2/gates/all-acs-passing.yaml +8 -0
  50. package/dist/harness/default/v0.1.2/gates/has-spec-file.yaml +7 -0
  51. package/dist/harness/default/v0.1.2/gates/human-approved-code.yaml +8 -0
  52. package/dist/harness/default/v0.1.2/gates/human-approved-spec.yaml +8 -0
  53. package/dist/harness/default/v0.1.2/gates/security-clear.yaml +8 -0
  54. package/dist/harness/default/v0.1.2/policies/sdlc-default.json +20 -0
  55. package/dist/harness/default/v0.1.2/roles/analyst.yaml +9 -0
  56. package/dist/harness/default/v0.1.2/roles/builder.yaml +9 -0
  57. package/dist/harness/default/v0.1.2/roles/pr-bot.yaml +8 -0
  58. package/dist/harness/default/v0.1.2/roles/reviewer.yaml +10 -0
  59. package/dist/harness/default/v0.1.2/roles/security.yaml +8 -0
  60. package/dist/harness/default/v0.1.3/flows/flow-main.yaml +90 -0
  61. package/dist/harness/default/v0.1.3/flows/sdlc.yaml +179 -0
  62. package/dist/harness/default/v0.1.3/gates/all-acs-passing.yaml +8 -0
  63. package/dist/harness/default/v0.1.3/gates/has-spec-file.yaml +7 -0
  64. package/dist/harness/default/v0.1.3/gates/human-approved-code.yaml +9 -0
  65. package/dist/harness/default/v0.1.3/gates/human-approved-spec.yaml +9 -0
  66. package/dist/harness/default/v0.1.3/gates/security-clear.yaml +8 -0
  67. package/dist/harness/default/v0.1.3/policies/sdlc-default.json +20 -0
  68. package/dist/harness/default/v0.1.3/roles/analyst.yaml +9 -0
  69. package/dist/harness/default/v0.1.3/roles/builder.yaml +9 -0
  70. package/dist/harness/default/v0.1.3/roles/pr-bot.yaml +8 -0
  71. package/dist/harness/default/v0.1.3/roles/reviewer.yaml +10 -0
  72. package/dist/harness/default/v0.1.3/roles/security.yaml +8 -0
  73. package/dist/harness/default/v0.2.0/executors/registry.yaml +51 -0
  74. package/dist/harness/default/v0.2.0/flows/flow-main.yaml +247 -0
  75. package/dist/harness/default/v0.2.0/gates/code-reviewed.yaml +7 -0
  76. package/dist/harness/default/v0.2.0/gates/human-approved.yaml +10 -0
  77. package/dist/harness/default/v0.2.0/gates/security-clear.yaml +7 -0
  78. package/dist/harness/default/v0.2.0/gates/spec-approved.yaml +10 -0
  79. package/dist/harness/default/v0.2.0/policies/sdlc-default.json +20 -0
  80. package/dist/harness/default/v0.2.0/roles/analyst.yaml +16 -0
  81. package/dist/harness/default/v0.2.0/roles/implementer.yaml +17 -0
  82. package/dist/harness/default/v0.2.0/roles/reviewer.yaml +17 -0
  83. package/dist/harness/default/v0.2.0/roles/security.yaml +17 -0
  84. package/dist/health-record-YDVXEVLR.js +21 -0
  85. package/dist/index.js +2595 -3046
  86. package/dist/init-wizard-NODBBNKO.js +178 -0
  87. package/dist/push-5JEYSXBY.js +116 -0
  88. package/dist/registry-6VPIA3EG.js +18 -0
  89. package/dist/server-FUP3APZA.js +415 -0
  90. package/dist/service-OGF7BMCQ.js +21 -0
  91. package/dist/session-log-WTQ5JBEN.js +21 -0
  92. package/dist/sitrep-DJXTP3JO.js +16 -0
  93. package/package.json +11 -2
  94. package/dist/client/assets/index-9KbFvLoH.css +0 -1
  95. package/dist/client/assets/index-s9Re0Bnf.js +0 -84
  96. package/tsup.config.ts +0 -11
@@ -0,0 +1,275 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ loadWorkflow
4
+ } from "./chunk-4QDEU6KP.js";
5
+ import {
6
+ logEntry
7
+ } from "./chunk-BKAUN5QH.js";
8
+ import {
9
+ getSummary,
10
+ loadHealthRecord
11
+ } from "./chunk-MJ2QXNH6.js";
12
+ import {
13
+ getLetraDir2 as getLetraDir,
14
+ resolveWorkspaceRoot
15
+ } from "./chunk-6HSUVCTR.js";
16
+
17
+ // src/commands/sitrep.ts
18
+ import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from "fs";
19
+ import { join } from "path";
20
+ import chalk from "chalk";
21
+ import { Command } from "commander";
22
+ var START_MARKER = "<!-- sitrep:start -->";
23
+ var END_MARKER = "<!-- sitrep:end -->";
24
+ function getRecentDecisions(root, max) {
25
+ const dir = join(getLetraDir(root), "decisions");
26
+ if (!existsSync(dir)) return [];
27
+ try {
28
+ const files = readdirSync(dir).filter((f) => f.endsWith(".md")).map((f) => ({
29
+ name: f,
30
+ mtime: statSync(join(dir, f)).mtimeMs
31
+ })).sort((a, b) => b.mtime - a.mtime).slice(0, max);
32
+ return files.map((f) => ({
33
+ title: f.name.replace(/\.md$/, "").replace(/-/g, " "),
34
+ date: new Date(f.mtime).toLocaleDateString("pt-BR")
35
+ }));
36
+ } catch {
37
+ return [];
38
+ }
39
+ }
40
+ function countItemACs(root, specName) {
41
+ const specDir = join(getLetraDir(root), "specs", specName);
42
+ const acceptanceFile = join(specDir, "acceptance.md");
43
+ const specFile = join(specDir, "spec.md");
44
+ const countInText = (text) => {
45
+ const pending = (text.match(/-\s*\[ \]\s*\*\*(.+?)\*\*/g) || []).length;
46
+ const done = (text.match(/-\s*\[[xX]\]\s*\*\*(.+?)\*\*/g) || []).length;
47
+ return { pending, total: pending + done };
48
+ };
49
+ if (existsSync(acceptanceFile)) {
50
+ return countInText(readFileSync(acceptanceFile, "utf-8"));
51
+ }
52
+ if (existsSync(specFile)) {
53
+ const content = readFileSync(specFile, "utf-8");
54
+ const match = content.match(/## Acceptance Criteria\s+([\s\S]*?)(?=\n## |\n*$)/);
55
+ return match ? countInText(match[1]) : { pending: 0, total: 0 };
56
+ }
57
+ return { pending: 0, total: 0 };
58
+ }
59
+ function findCurrentItem(workflow) {
60
+ const activeStages = workflow.stages.filter(
61
+ (s) => s.zone === "doing" || !s.zone && s.order > 0 && s.order < workflow.stages.length - 1
62
+ ).map((s) => s.id);
63
+ const stageSet = new Set(activeStages);
64
+ if (stageSet.size === 0) {
65
+ const mid = Math.floor(workflow.stages.length / 2);
66
+ const stage = workflow.stages[mid];
67
+ if (stage) stageSet.add(stage.id);
68
+ }
69
+ const items = workflow.items.filter((i) => stageSet.has(i.stage));
70
+ if (items.length === 0) return null;
71
+ return items.reduce((a, b) => new Date(a.createdAt) > new Date(b.createdAt) ? a : b);
72
+ }
73
+ function getStageName(stageId, workflow) {
74
+ if (!workflow) return stageId;
75
+ return workflow.stages?.find((s) => s.id === stageId)?.name ?? stageId;
76
+ }
77
+ function extractSection(content, heading) {
78
+ const esc = heading.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
79
+ const regex = new RegExp(`## ${esc}\\s+([\\s\\S]*?)(?=\\n## |\\n*$)`);
80
+ const match = content.match(regex);
81
+ return match ? match[1].trim() : null;
82
+ }
83
+ function buildSitrepBlock(data) {
84
+ const lines = [];
85
+ if (data.currentItem) {
86
+ lines.push(`**Est\xE1gio**: ${getStageName(data.currentItem.stage, data.workflow)}`);
87
+ const item = data.currentItem;
88
+ let itemLine = `**Item atual**: ${item.id} \u2014 ${item.description}`;
89
+ if (item.spec) itemLine += ` (spec: ${item.spec})`;
90
+ lines.push(itemLine);
91
+ if (data.acCounts) {
92
+ const { pending, total } = data.acCounts;
93
+ const done = total - pending;
94
+ lines.push(`**ACs**: ${pending}/${total} pendentes | ${done} feito(s)`);
95
+ }
96
+ } else if (data.workflow) {
97
+ lines.push("**Est\xE1gio**: sem item ativo");
98
+ } else {
99
+ lines.push("**Est\xE1gio**: sem workflow definido");
100
+ }
101
+ const s = data.alertSummary;
102
+ const alertParts = [];
103
+ if (s.novo > 0) alertParts.push(`${s.novo} novo(s)`);
104
+ if (s.ciente > 0) alertParts.push(`${s.ciente} em acompanhamento`);
105
+ if (s.resolvido > 0) alertParts.push(`${s.resolvido} resolvido(s)`);
106
+ lines.push(`**Alertas**: ${alertParts.length > 0 ? alertParts.join(" \xB7 ") : "0 alertas"}`);
107
+ if (s.alta > 0) {
108
+ lines.push(`\u26A0 ${s.alta} alerta(s) de severidade alta`);
109
+ }
110
+ if (data.decisions.length > 0) {
111
+ const decStr = data.decisions.map((d) => `"${d.title}" (${d.date})`).join(", ");
112
+ lines.push(`**\xDAltimas decis\xF5es**: ${decStr}`);
113
+ }
114
+ return lines.join("\n");
115
+ }
116
+ function rewriteContextFile(content, dynamicBlock, stack, restricoes, porques) {
117
+ const headerMatch = content.match(/^# Context[\s\S]*?(?=\n## )/);
118
+ const header = headerMatch ? headerMatch[0].trim() : "# Context";
119
+ const intent = extractSection(content, "Intent");
120
+ const dominio = extractSection(content, "Dom\xEDnio");
121
+ const ignoreIdx = content.indexOf("<!-- sitrep:ignore -->");
122
+ let ignoredContent = "";
123
+ if (ignoreIdx !== -1) {
124
+ ignoredContent = content.slice(ignoreIdx);
125
+ }
126
+ const sections = [header];
127
+ if (intent) {
128
+ sections.push(`## Intent
129
+
130
+ ${intent}`);
131
+ }
132
+ if (dominio) {
133
+ sections.push(`## Dom\xEDnio
134
+
135
+ ${dominio}`);
136
+ }
137
+ sections.push(`${START_MARKER}
138
+ ${dynamicBlock}
139
+ ${END_MARKER}`);
140
+ if (stack) {
141
+ sections.push(`## Stack
142
+
143
+ ${stack}`);
144
+ }
145
+ if (restricoes) {
146
+ sections.push(`## Restri\xE7\xF5es Reais
147
+
148
+ ${restricoes}`);
149
+ }
150
+ if (porques) {
151
+ sections.push(`## Porqu\xEAs
152
+
153
+ ${porques}`);
154
+ }
155
+ let result = `${sections.join("\n\n")}
156
+ `;
157
+ if (ignoredContent) {
158
+ result += `
159
+ ${ignoredContent}
160
+ `;
161
+ }
162
+ return result;
163
+ }
164
+ function showDiff(original, modified) {
165
+ const origLines = original.split("\n");
166
+ const modLines = modified.split("\n");
167
+ const maxLen = Math.max(origLines.length, modLines.length);
168
+ for (let i = 0; i < maxLen; i++) {
169
+ const o = origLines[i] ?? "";
170
+ const m = modLines[i] ?? "";
171
+ if (o !== m) {
172
+ if (i < origLines.length) {
173
+ console.log(chalk.red(`- ${o}`));
174
+ }
175
+ if (i < modLines.length) {
176
+ console.log(chalk.green(`+ ${m}`));
177
+ }
178
+ }
179
+ }
180
+ }
181
+ function logChanges(original, modified) {
182
+ if (original === modified) {
183
+ console.log(chalk.gray(" Nenhuma altera\xE7\xE3o necess\xE1ria."));
184
+ return;
185
+ }
186
+ const sections = [];
187
+ if (original.match(/^> Updated:.*$/m) !== modified.match(/^> Updated:.*$/m)) {
188
+ sections.push("Updated");
189
+ }
190
+ const origHasSitrep = original.includes(START_MARKER);
191
+ const modHasSitrep = modified.includes(START_MARKER);
192
+ if (origHasSitrep !== modHasSitrep) {
193
+ sections.push(modHasSitrep ? "Bloco sitrep (inserido)" : "Bloco sitrep (removido)");
194
+ } else if (origHasSitrep) {
195
+ sections.push("Bloco sitrep (atualizado)");
196
+ }
197
+ if (sections.length > 0) {
198
+ console.log(chalk.gray(` Se\xE7\xF5es alteradas: ${sections.join(", ")}`));
199
+ } else {
200
+ console.log(chalk.gray(" Apenas data atualizada."));
201
+ }
202
+ }
203
+ async function sitrep(rootPath, options) {
204
+ const contextFile = join(getLetraDir(rootPath), "context.md");
205
+ if (!existsSync(contextFile)) {
206
+ if (!options?.quiet) console.log(chalk.yellow("Aviso: .letra/context.md n\xE3o encontrado"));
207
+ return;
208
+ }
209
+ const workflow = loadWorkflow(rootPath);
210
+ const healthRecord = loadHealthRecord(rootPath);
211
+ const alertSummary = getSummary(healthRecord);
212
+ let currentItem = null;
213
+ let acCounts = null;
214
+ if (workflow) {
215
+ currentItem = findCurrentItem(workflow);
216
+ if (currentItem?.spec) {
217
+ acCounts = countItemACs(rootPath, currentItem.spec);
218
+ }
219
+ }
220
+ const decisions = getRecentDecisions(rootPath, 4);
221
+ const data = {
222
+ stage: currentItem?.stage ?? "sem item ativo",
223
+ currentItem,
224
+ acCounts,
225
+ alertSummary,
226
+ decisions,
227
+ workflow
228
+ };
229
+ const dynamicBlock = buildSitrepBlock(data);
230
+ const originalContent = readFileSync(contextFile, "utf-8");
231
+ const stack = extractSection(originalContent, "Stack");
232
+ const restricoes = extractSection(originalContent, "Restri\xE7\xF5es Reais");
233
+ const porques = extractSection(originalContent, "Porqu\xEAs");
234
+ const withUpdated = originalContent.replace(
235
+ /^(> Updated:).*$/m,
236
+ `$1 ${(/* @__PURE__ */ new Date()).toISOString()}`
237
+ );
238
+ const newContent = rewriteContextFile(withUpdated, dynamicBlock, stack, restricoes, porques);
239
+ if (options?.dryRun) {
240
+ console.log(chalk.bold("\n\u{1F4CB} Simula\xE7\xE3o de atualiza\xE7\xE3o \u2014 dry-run\n"));
241
+ showDiff(originalContent, newContent);
242
+ return;
243
+ }
244
+ writeFileSync(contextFile, newContent, "utf-8");
245
+ if (!options?.quiet) {
246
+ console.log(chalk.green("\u2713 Situa\xE7\xE3o atualizada em .letra/context.md"));
247
+ logChanges(originalContent, newContent);
248
+ }
249
+ if (!options?.skipLog) {
250
+ logEntry(rootPath, "sitrep", "context.md atualizado com estado do workspace", {
251
+ details: {
252
+ hasItem: !!currentItem,
253
+ itemId: currentItem?.id,
254
+ alertsNovo: alertSummary.novo
255
+ }
256
+ });
257
+ }
258
+ }
259
+ function sitrep_default() {
260
+ const cmd = new Command("sitrep").description(
261
+ "Atualizar .letra/context.md com estado real do workspace"
262
+ );
263
+ cmd.option("--dry-run", "Exibir diff sem modificar o arquivo").action(
264
+ async (options) => {
265
+ const resolution = resolveWorkspaceRoot(process.cwd());
266
+ await sitrep(resolution.workspaceRoot, options);
267
+ }
268
+ );
269
+ return cmd;
270
+ }
271
+
272
+ export {
273
+ sitrep,
274
+ sitrep_default
275
+ };
@@ -0,0 +1,119 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ getLetraDir2 as getLetraDir
4
+ } from "./chunk-6HSUVCTR.js";
5
+
6
+ // src/adapters/focus-sync.ts
7
+ import { existsSync, readFileSync, unlinkSync, writeFileSync } from "fs";
8
+ import { join } from "path";
9
+ import { pathToFileURL } from "url";
10
+ function syncFocus(rootDir, workflow, recommendedActions = []) {
11
+ const focusFile = join(getLetraDir(rootDir), "focus.md");
12
+ const focusData = readFocusFile(rootDir);
13
+ let cleared = false;
14
+ let generated = false;
15
+ let diverged = false;
16
+ if (focusData && workflow) {
17
+ const itemExists = workflow.items.some((i) => i.id === focusData.itemId);
18
+ if (!itemExists) {
19
+ clearFocusFile(rootDir);
20
+ cleared = true;
21
+ } else {
22
+ const item = workflow.items.find((i) => i.id === focusData.itemId);
23
+ if (item?.spec && item.spec !== focusData.specName) {
24
+ diverged = true;
25
+ }
26
+ }
27
+ }
28
+ if (!focusData && workflow) {
29
+ const activeItem = findActiveItem(workflow);
30
+ if (activeItem?.spec) {
31
+ writeFocusFile(rootDir, activeItem.spec, activeItem.id, recommendedActions);
32
+ generated = true;
33
+ }
34
+ }
35
+ if (focusData && !workflow) {
36
+ clearFocusFile(rootDir);
37
+ cleared = true;
38
+ }
39
+ return { cleared, generated, diverged };
40
+ }
41
+ function findActiveItem(workflow) {
42
+ const activeStages = workflow.stages.filter(
43
+ (s) => s.zone === "doing" || !s.zone && s.order > 0 && s.order < workflow.stages.length - 1
44
+ ).map((s) => s.id);
45
+ const stageSet = new Set(activeStages);
46
+ if (stageSet.size === 0) {
47
+ const mid = Math.floor(workflow.stages.length / 2);
48
+ const stage = workflow.stages[mid];
49
+ if (stage) stageSet.add(stage.id);
50
+ }
51
+ const items = workflow.items.filter((i) => stageSet.has(i.stage));
52
+ if (items.length === 0) return null;
53
+ return items.reduce((a, b) => new Date(a.createdAt) > new Date(b.createdAt) ? a : b);
54
+ }
55
+ function extractOutcome(rootDir, specName) {
56
+ const specFile = join(getLetraDir(rootDir), "specs", specName, "spec.md");
57
+ if (!existsSync(specFile)) return null;
58
+ const content = readFileSync(specFile, "utf-8");
59
+ const match = content.match(/## Outcome\s+([\s\S]*?)(?=\n## |\n*$)/);
60
+ return match ? match[1].trim() : null;
61
+ }
62
+ function writeFocusFile(rootDir, specName, itemId, recommendedActions = []) {
63
+ const focusFile = join(getLetraDir(rootDir), "focus.md");
64
+ const outcome = extractOutcome(rootDir, specName) || specName;
65
+ const letraDir = getLetraDir(rootDir);
66
+ const content = [
67
+ `# Focus: ${specName}`,
68
+ "",
69
+ `**Path**: .letra/specs/${specName}/`,
70
+ `**Item**: ${itemId}`,
71
+ `**Outcome**: ${outcome}`,
72
+ "",
73
+ ...recommendedActions.length > 0 ? [
74
+ "## A\xE7\xF5es Recomendadas",
75
+ "",
76
+ ...recommendedActions.map((action) => {
77
+ const detail = action.description ? `${action.label}: ${action.description}` : action.label;
78
+ return `- \`${action.command}\` \u2014 ${detail}`;
79
+ }),
80
+ ""
81
+ ] : [],
82
+ "## Links",
83
+ "",
84
+ `- [Spec: ${specName}](${pathToFileURL(join(letraDir, "specs", specName, "spec.md")).href})`,
85
+ `- [${itemId}](${pathToFileURL(join(letraDir, "workflow.json")).href})`,
86
+ `- [Constitution](${pathToFileURL(join(letraDir, "constitution.md")).href})`,
87
+ `- [Constraints](${pathToFileURL(join(letraDir, "constraints.md")).href})`,
88
+ ""
89
+ ].join("\n");
90
+ writeFileSync(focusFile, content, "utf-8");
91
+ }
92
+ function clearFocusFile(rootDir) {
93
+ const focusFile = join(getLetraDir(rootDir), "focus.md");
94
+ if (existsSync(focusFile)) {
95
+ unlinkSync(focusFile);
96
+ }
97
+ }
98
+ function readFocusFile(rootDir) {
99
+ const focusFile = join(getLetraDir(rootDir), "focus.md");
100
+ if (!existsSync(focusFile)) return null;
101
+ const content = readFileSync(focusFile, "utf-8");
102
+ const specMatch = content.match(/# Focus:\s*(.+)/);
103
+ const itemMatch = content.match(/\*\*Item\*\*:\s*(.+)/);
104
+ const outcomeMatch = content.match(/\*\*Outcome\*\*:\s*([\s\S]*?)(?=\n\*\*|\n## |\n*$)/);
105
+ if (!specMatch) return null;
106
+ return {
107
+ specName: specMatch[1].trim(),
108
+ itemId: itemMatch ? itemMatch[1].trim() : "",
109
+ outcome: outcomeMatch ? outcomeMatch[1].trim() : ""
110
+ };
111
+ }
112
+
113
+ export {
114
+ syncFocus,
115
+ extractOutcome,
116
+ writeFocusFile,
117
+ clearFocusFile,
118
+ readFocusFile
119
+ };
@@ -0,0 +1,256 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ resolveActiveFlowFor
4
+ } from "./chunk-MSF44WWE.js";
5
+ import {
6
+ DEFAULT_HARNESS_VERSION,
7
+ parseSimpleYaml,
8
+ resolveHarnessRoot
9
+ } from "./chunk-4QDEU6KP.js";
10
+ import {
11
+ queryLog
12
+ } from "./chunk-BKAUN5QH.js";
13
+ import {
14
+ writeFocusFile
15
+ } from "./chunk-EDD55PWL.js";
16
+ import {
17
+ getLetraDir2 as getLetraDir
18
+ } from "./chunk-6HSUVCTR.js";
19
+
20
+ // src/adapters/focus-recommendations.ts
21
+ var ACTIVITY_ORDER = ["design", "implement", "review", "diagnose", "gate"];
22
+ function collectFocusRecommendations(workflow, flow, itemId) {
23
+ const item = workflow.items.find((candidate) => candidate.id === itemId);
24
+ if (!item || !flow) return [];
25
+ const stage = flow.stages.find((candidate) => candidate.id === item.stage);
26
+ if (!stage?.activity) return [];
27
+ const sortedStages = [...flow.stages].sort((left, right) => left.order - right.order);
28
+ const stageIndex = sortedStages.findIndex((candidate) => candidate.id === stage.id);
29
+ const nextStageId = stageIndex >= 0 ? sortedStages[stageIndex + 1]?.id : void 0;
30
+ const seen = /* @__PURE__ */ new Set();
31
+ const recommendations = [];
32
+ for (const kind of ACTIVITY_ORDER) {
33
+ for (const hint of stage.activity[kind]?.commands ?? []) {
34
+ const command = hint.command.replaceAll("<ITEM-ID>", item.id).replaceAll("<NEXT-STAGE>", nextStageId ?? "<NEXT-STAGE>");
35
+ if (seen.has(command)) continue;
36
+ seen.add(command);
37
+ recommendations.push({
38
+ command,
39
+ label: hint.label,
40
+ description: hint.description
41
+ });
42
+ }
43
+ }
44
+ return recommendations;
45
+ }
46
+ function resolveFocusRecommendations(root, itemId) {
47
+ const resolution = resolveActiveFlowFor(root);
48
+ if (!resolution.workflow) return [];
49
+ return collectFocusRecommendations(resolution.workflow, resolution.flow, itemId);
50
+ }
51
+ function writeFocusWithRecommendations(root, specName, itemId) {
52
+ writeFocusFile(root, specName, itemId, resolveFocusRecommendations(root, itemId));
53
+ }
54
+
55
+ // src/harness/gate-checker.ts
56
+ import { existsSync, readFileSync, readdirSync } from "fs";
57
+ import { join } from "path";
58
+ function loadGateStatusFromDisk(root, gateId) {
59
+ const candidates = [
60
+ join(getLetraDir(root), "harness", "gates"),
61
+ join(root, ".letra", "harness", "gates")
62
+ ];
63
+ for (const gatesDir of candidates) {
64
+ if (!existsSync(gatesDir)) continue;
65
+ const files = [join(gatesDir, `${gateId}.yaml`), join(gatesDir, `${gateId}.yml`)];
66
+ for (const f of files) {
67
+ if (existsSync(f)) {
68
+ const raw = parseSimpleYaml(readFileSync(f, "utf-8"));
69
+ return {
70
+ blocksHandoff: raw.blocksHandoff === true,
71
+ status: raw.status === "approved" ? "approved" : "pending"
72
+ };
73
+ }
74
+ }
75
+ }
76
+ return null;
77
+ }
78
+ function loadManifestGates(root) {
79
+ const candidates = [
80
+ join(getLetraDir(root), "harness", DEFAULT_HARNESS_VERSION),
81
+ join(resolveHarnessRoot(root, DEFAULT_HARNESS_VERSION))
82
+ ];
83
+ const gates = {};
84
+ for (const harnessDir of candidates) {
85
+ const gatesDir = join(harnessDir, "gates");
86
+ if (!existsSync(gatesDir)) continue;
87
+ for (const file of readdirSync(gatesDir)) {
88
+ if (!file.endsWith(".yaml")) continue;
89
+ try {
90
+ const raw = parseSimpleYaml(readFileSync(join(gatesDir, file), "utf-8"));
91
+ const id = String(raw.id ?? file.replace(/\.ya?ml$/, ""));
92
+ gates[id] = {
93
+ id,
94
+ name: String(raw.name ?? id),
95
+ type: ["human", "automated", "external"].includes(raw.type) ? raw.type : "automated",
96
+ blocking: raw.blocking === true,
97
+ blocksHandoff: raw.blocksHandoff === true,
98
+ policyRef: typeof raw.policyRef === "string" ? raw.policyRef : void 0,
99
+ description: String(raw.description ?? ""),
100
+ decisions: raw.decisions && typeof raw.decisions === "object" ? Object.fromEntries(
101
+ Object.entries(raw.decisions).filter(
102
+ ([, v]) => typeof v === "string" && v.trim()
103
+ ).map(([k, v]) => [k, v.trim()])
104
+ ) : void 0
105
+ };
106
+ } catch {
107
+ }
108
+ }
109
+ if (Object.keys(gates).length > 0) break;
110
+ }
111
+ return gates;
112
+ }
113
+ var GateChecker = class {
114
+ root;
115
+ manifestGates;
116
+ constructor(root, manifest) {
117
+ this.root = root;
118
+ this.manifestGates = manifest?.gates ?? loadManifestGates(root);
119
+ }
120
+ getGate(gateId) {
121
+ return this.manifestGates[gateId];
122
+ }
123
+ getRuntimeStatus(gateId) {
124
+ return loadGateStatusFromDisk(this.root, gateId);
125
+ }
126
+ checkBlocksHandoff(gateId) {
127
+ const gate = this.getGate(gateId);
128
+ if (gate) return gate.blocksHandoff === true;
129
+ const status = this.getRuntimeStatus(gateId);
130
+ if (status) return status.blocksHandoff;
131
+ return false;
132
+ }
133
+ checkHandoffAllowed(gateId, item) {
134
+ if (!gateId) return { allowed: true };
135
+ const blocksHandoff = this.checkBlocksHandoff(gateId);
136
+ if (!blocksHandoff) {
137
+ return { allowed: true };
138
+ }
139
+ const gateResult = this.check(gateId, item);
140
+ if (!gateResult.allowed) {
141
+ return {
142
+ ...gateResult,
143
+ blocksHandoff: true
144
+ };
145
+ }
146
+ const runtime = this.getRuntimeStatus(gateId);
147
+ if (runtime && runtime.status !== "approved") {
148
+ return {
149
+ allowed: false,
150
+ reason: `Gate "${gateId}" blocks handoff and is not approved`,
151
+ blocksHandoff: true
152
+ };
153
+ }
154
+ return { allowed: true };
155
+ }
156
+ check(gateId, item) {
157
+ const gate = this.getGate(gateId);
158
+ if (!gate) {
159
+ return this.checkByConvention(gateId, item);
160
+ }
161
+ switch (gate.type) {
162
+ case "human":
163
+ return this.checkHumanGate(gate);
164
+ case "automated":
165
+ return this.checkAutomatedGate(gate, item);
166
+ case "external":
167
+ return this.checkExternalGate(gate);
168
+ default:
169
+ return { allowed: true };
170
+ }
171
+ }
172
+ checkByConvention(gateId, item) {
173
+ if (gateId === "has-spec-file") return this.checkHasSpecFile(item);
174
+ if (gateId === "all-acs-passing") return this.checkAllAcsPassing(item);
175
+ return { allowed: true };
176
+ }
177
+ checkHumanGate(gate) {
178
+ const runtime = this.getRuntimeStatus(gate.id);
179
+ if (!runtime) {
180
+ return { allowed: false, reason: `Gate "${gate.id}" n\xE3o encontrado` };
181
+ }
182
+ if (runtime.status !== "approved") {
183
+ const decisionLabel = gate.decisions?.approve ?? "aprova\xE7\xE3o";
184
+ return { allowed: false, reason: `Gate "${gate.id}" pendente de ${decisionLabel}` };
185
+ }
186
+ return { allowed: true };
187
+ }
188
+ checkAutomatedGate(gate, item) {
189
+ if (gate.id === "has-spec-file") return this.checkHasSpecFile(item);
190
+ if (gate.id === "all-acs-passing") return this.checkAllAcsPassing(item);
191
+ const runtime = this.getRuntimeStatus(gate.id);
192
+ if (!runtime) {
193
+ return { allowed: false, reason: `Gate "${gate.id}" n\xE3o encontrado` };
194
+ }
195
+ if (runtime.status !== "approved") {
196
+ return { allowed: false, reason: `Gate "${gate.id}" pendente de aprova\xE7\xE3o` };
197
+ }
198
+ return { allowed: true };
199
+ }
200
+ checkExternalGate(gate) {
201
+ const runtime = this.getRuntimeStatus(gate.id);
202
+ if (!runtime) {
203
+ return { allowed: false, reason: `Gate "${gate.id}" n\xE3o encontrado` };
204
+ }
205
+ if (runtime.status !== "approved") {
206
+ return { allowed: false, reason: `Gate "${gate.id}" pendente de valida\xE7\xE3o externa` };
207
+ }
208
+ return { allowed: true };
209
+ }
210
+ checkHasSpecFile(item) {
211
+ if (!item.spec) {
212
+ return { allowed: false, reason: "Item sem spec vinculada" };
213
+ }
214
+ const specDir = join(getLetraDir(this.root), "specs", item.spec);
215
+ if (!existsSync(specDir)) {
216
+ return { allowed: false, reason: `Pasta de spec n\xE3o encontrada: ${item.spec}` };
217
+ }
218
+ return { allowed: true };
219
+ }
220
+ checkAllAcsPassing(item) {
221
+ if (!item.spec) {
222
+ return { allowed: false, reason: "Item sem spec vinculada" };
223
+ }
224
+ const specPath = join(getLetraDir(this.root), "specs", item.spec, "spec.md");
225
+ if (!existsSync(specPath)) {
226
+ return { allowed: false, reason: `Spec n\xE3o encontrada: ${item.spec}` };
227
+ }
228
+ const content = readFileSync(specPath, "utf-8");
229
+ const pending = (content.match(/^- \[ \]/gm) || []).length;
230
+ if (pending > 0) {
231
+ return {
232
+ allowed: false,
233
+ reason: `${pending} AC(s) pendente(s) em "${item.spec}"`
234
+ };
235
+ }
236
+ const done = (content.match(/^- \[[xX]\]/gm) || []).length;
237
+ const logEntries = queryLog(this.root, {
238
+ itemId: item.id,
239
+ action: "ac_done",
240
+ limit: 999
241
+ });
242
+ if (done > logEntries.length) {
243
+ return {
244
+ allowed: false,
245
+ reason: `${done - logEntries.length} AC(s) marcado(s) sem confirma\xE7\xE3o "ac done"`
246
+ };
247
+ }
248
+ return { allowed: true };
249
+ }
250
+ };
251
+
252
+ export {
253
+ resolveFocusRecommendations,
254
+ writeFocusWithRecommendations,
255
+ GateChecker
256
+ };