@letra-ai/cli 0.5.3 → 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 (100) 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 +16 -4
  17. package/dist/client/index.html +25 -20
  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 +1932 -2528
  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 +37 -28
  94. package/dist/chunk-56GTTLC4.js +0 -1322
  95. package/dist/chunk-QWT5M4XU.js +0 -643
  96. package/dist/client/assets/index-CuLfFw4K.js +0 -85
  97. package/dist/client/assets/index-iyLqZcWx.css +0 -1
  98. package/dist/generate-BF5R5GGA.js +0 -7
  99. package/dist/sitrep-SI6ZFIAM.js +0 -10
  100. package/tsup.config.ts +0 -11
@@ -0,0 +1,2765 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ logEntry
4
+ } from "./chunk-BKAUN5QH.js";
5
+ import {
6
+ ADAPTER_ARTIFACTS,
7
+ ADAPTER_REGISTRY,
8
+ adapterDiagnosticFiles,
9
+ adapterInstructionTargets,
10
+ instructionArtifactsForAdapters
11
+ } from "./chunk-JMIC5NKB.js";
12
+ import {
13
+ readFocusFile
14
+ } from "./chunk-EDD55PWL.js";
15
+ import {
16
+ loadHealthRecord,
17
+ mergeScanResults,
18
+ saveHealthRecord
19
+ } from "./chunk-MJ2QXNH6.js";
20
+ import {
21
+ getLetraDir,
22
+ getLetraDir2
23
+ } from "./chunk-6HSUVCTR.js";
24
+ import {
25
+ __require
26
+ } from "./chunk-PDX44BCA.js";
27
+
28
+ // src/adapters/generate.ts
29
+ import { existsSync as existsSync16, mkdirSync as mkdirSync5, readFileSync as readFileSync12, writeFileSync as writeFileSync5 } from "fs";
30
+ import { join as join15 } from "path";
31
+ import chalk2 from "chalk";
32
+
33
+ // src/security/workspace-boundary.ts
34
+ import { existsSync, realpathSync } from "fs";
35
+ import { dirname, isAbsolute, relative, resolve } from "path";
36
+ function isInside(root, candidate) {
37
+ const rel = relative(root, candidate);
38
+ return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
39
+ }
40
+ function createWorkspaceBoundary(root) {
41
+ const requestedRoot = resolve(root);
42
+ const realRoot = realpathSync(requestedRoot);
43
+ function assertPath(path) {
44
+ const requestedPath = resolve(path);
45
+ if (!isInside(requestedRoot, requestedPath)) {
46
+ throw new Error(`Path is outside the workspace boundary: ${requestedPath}`);
47
+ }
48
+ const candidate = resolve(realRoot, relative(requestedRoot, requestedPath));
49
+ let existingAncestor = candidate;
50
+ while (!existsSync(existingAncestor)) {
51
+ const parent = dirname(existingAncestor);
52
+ if (parent === existingAncestor) break;
53
+ existingAncestor = parent;
54
+ }
55
+ const realAncestor = realpathSync(existingAncestor);
56
+ if (!isInside(realRoot, realAncestor)) {
57
+ throw new Error(`Path resolves outside the workspace boundary: ${requestedPath}`);
58
+ }
59
+ if (existsSync(candidate)) {
60
+ const realCandidate = realpathSync(candidate);
61
+ if (!isInside(realRoot, realCandidate)) {
62
+ throw new Error(`Path resolves outside the workspace boundary: ${requestedPath}`);
63
+ }
64
+ return realCandidate;
65
+ }
66
+ return candidate;
67
+ }
68
+ const letraDir = resolve(requestedRoot, ".letra");
69
+ if (existsSync(letraDir)) assertPath(letraDir);
70
+ return { root: realRoot, assertPath };
71
+ }
72
+
73
+ // src/adapters/builder.ts
74
+ import { existsSync as existsSync15, readFileSync as readFileSync11 } from "fs";
75
+ import { join as join14 } from "path";
76
+ import { pathToFileURL } from "url";
77
+
78
+ // src/harness/loader.ts
79
+ import { readdirSync as readdirSync2, existsSync as existsSync3, readFileSync } from "fs";
80
+ import { basename, join as join2 } from "path";
81
+
82
+ // src/harness/parse.ts
83
+ function parseSimpleYaml(text) {
84
+ const root = {};
85
+ const stack = [{ obj: root, indent: -1 }];
86
+ const lines = text.split(/\r?\n/);
87
+ for (const raw of lines) {
88
+ const trimmed = raw.trim();
89
+ if (!trimmed || trimmed.startsWith("#")) continue;
90
+ const indent = raw.length - trimmed.length;
91
+ while (stack.length > 1 && stack[stack.length - 1].indent >= indent) {
92
+ stack.pop();
93
+ }
94
+ const parent = stack[stack.length - 1].obj;
95
+ const listMatch = trimmed.match(/^- \s*(.*)/);
96
+ if (listMatch) {
97
+ const content = listMatch[1].trim();
98
+ const containerKey = stack[stack.length - 1].containerKey;
99
+ if (!containerKey) continue;
100
+ const arr = Array.isArray(parent[containerKey]) ? parent[containerKey] : [];
101
+ parent[containerKey] = arr;
102
+ const kv = content.match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
103
+ if (kv) {
104
+ const obj = {};
105
+ obj[kv[1]] = parseValue(kv[2]);
106
+ arr.push(obj);
107
+ stack.push({ obj, indent, containerKey });
108
+ } else {
109
+ arr.push(parseValue(content));
110
+ }
111
+ continue;
112
+ }
113
+ const kvMatch = trimmed.match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
114
+ if (kvMatch) {
115
+ const key = kvMatch[1];
116
+ const val = kvMatch[2].trim();
117
+ if (!val) {
118
+ const obj = {};
119
+ parent[key] = obj;
120
+ stack.push({ obj, indent, containerKey: key });
121
+ } else {
122
+ parent[key] = parseValue(val);
123
+ stack[stack.length - 1].containerKey = key;
124
+ }
125
+ }
126
+ }
127
+ return normalize(root);
128
+ }
129
+ function normalize(value) {
130
+ if (Array.isArray(value)) return value.map(normalize);
131
+ if (value && typeof value === "object") {
132
+ const obj = value;
133
+ for (const [k, v] of Object.entries(obj)) {
134
+ obj[k] = normalize(v);
135
+ }
136
+ unwrapSingleKeyArrays(obj);
137
+ return obj;
138
+ }
139
+ return value;
140
+ }
141
+ function unwrapSingleKeyArrays(obj) {
142
+ for (const key of Object.keys(obj)) {
143
+ const value = obj[key];
144
+ if (value && typeof value === "object" && !Array.isArray(value)) {
145
+ const inner = value;
146
+ const entries = Object.entries(inner);
147
+ if (entries.length === 1 && entries[0][0] === key && Array.isArray(entries[0][1])) {
148
+ obj[key] = entries[0][1];
149
+ }
150
+ }
151
+ }
152
+ }
153
+ function parseValue(raw) {
154
+ if (raw === "true") return true;
155
+ if (raw === "false") return false;
156
+ if (raw === "null" || raw === "~") return null;
157
+ if (/^-?\d+$/.test(raw)) return Number.parseInt(raw, 10);
158
+ if (/^-?\d+\.\d+$/.test(raw)) return Number.parseFloat(raw);
159
+ if (raw.startsWith('"') && raw.endsWith('"') || raw.startsWith("'") && raw.endsWith("'"))
160
+ return raw.slice(1, -1);
161
+ if (raw.startsWith("[") && raw.endsWith("]") || raw.startsWith("{") && raw.endsWith("}")) {
162
+ try {
163
+ return JSON.parse(raw);
164
+ } catch {
165
+ }
166
+ }
167
+ return raw;
168
+ }
169
+
170
+ // src/workspace/resolution.ts
171
+ import { existsSync as existsSync2, mkdirSync, readdirSync, cpSync } from "fs";
172
+ import { join, dirname as dirname2 } from "path";
173
+ import { fileURLToPath } from "url";
174
+ function getDefaultHarnessSource(version) {
175
+ const distDir = dirname2(fileURLToPath(import.meta.url));
176
+ return join(distDir, "..", "harness", "default", version);
177
+ }
178
+ function getHarnessPath(version) {
179
+ return join(getLetraDir(), "shared-harness", version);
180
+ }
181
+ function ensureSharedHarness(version) {
182
+ const harnessPath = getHarnessPath(version);
183
+ if (existsSync2(harnessPath)) return harnessPath;
184
+ const source = getDefaultHarnessSource(version);
185
+ mkdirSync(harnessPath, { recursive: true });
186
+ if (existsSync2(source)) {
187
+ for (const entry of readdirSync(source)) {
188
+ cpSync(join(source, entry), join(harnessPath, entry), { recursive: true, force: true });
189
+ }
190
+ }
191
+ return harnessPath;
192
+ }
193
+
194
+ // src/harness/loader.ts
195
+ var DEFAULT_HARNESS_VERSION = "v0.2.0";
196
+ function resolveHarnessRoot(cwd, version = DEFAULT_HARNESS_VERSION) {
197
+ const candidates = [
198
+ join2(getLetraDir2(cwd), "harness", version),
199
+ join2(cwd, "..", ".leta", "harness", version)
200
+ ];
201
+ for (const p of candidates) {
202
+ if (existsSync3(p)) return p;
203
+ }
204
+ return candidates[0];
205
+ }
206
+ function unwrapStages(value) {
207
+ if (Array.isArray(value)) return value;
208
+ if (value && typeof value === "object" && Array.isArray(value.stages))
209
+ return value.stages;
210
+ return [];
211
+ }
212
+ function normalizeGateDecisions(value) {
213
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
214
+ const raw = value;
215
+ const decisions = {};
216
+ for (const decision of ["approve", "request-changes", "reject"]) {
217
+ if (typeof raw[decision] === "string" && raw[decision].trim()) {
218
+ decisions[decision] = raw[decision].trim();
219
+ }
220
+ }
221
+ return Object.keys(decisions).length > 0 ? decisions : void 0;
222
+ }
223
+ function normalizePhaseTransitions(value) {
224
+ if (!Array.isArray(value)) return void 0;
225
+ const transitions = value.map((entry) => {
226
+ if (!entry || typeof entry !== "object") return null;
227
+ const raw = entry;
228
+ const target = typeof raw.target === "string" ? raw.target : null;
229
+ if (!target) return null;
230
+ return {
231
+ target,
232
+ gate: typeof raw.gate === "string" ? raw.gate : void 0,
233
+ auto: raw.auto === true
234
+ };
235
+ }).filter((entry) => entry !== null);
236
+ return transitions.length > 0 ? transitions : void 0;
237
+ }
238
+ function normalizePhaseActions(value) {
239
+ if (!Array.isArray(value)) return void 0;
240
+ const actions = value.map((entry) => {
241
+ if (!entry || typeof entry !== "object") return null;
242
+ const raw = entry;
243
+ switch (raw.type) {
244
+ case "agent-prompt":
245
+ return typeof raw.prompt === "string" ? { type: "agent-prompt", prompt: raw.prompt } : null;
246
+ case "command":
247
+ return typeof raw.cmd === "string" ? { type: "command", cmd: raw.cmd } : null;
248
+ case "generate-report":
249
+ return typeof raw.template === "string" ? {
250
+ type: "generate-report",
251
+ template: raw.template
252
+ } : null;
253
+ case "notify-human":
254
+ return typeof raw.message === "string" ? { type: "notify-human", message: raw.message } : null;
255
+ case "wait-human":
256
+ return typeof raw.gate === "string" ? { type: "wait-human", gate: raw.gate } : null;
257
+ default:
258
+ return null;
259
+ }
260
+ }).filter((entry) => entry !== null);
261
+ return actions.length > 0 ? actions : void 0;
262
+ }
263
+ function normalizePhaseHarness(value) {
264
+ if (!value || typeof value !== "object") return void 0;
265
+ const raw = value;
266
+ const checks = Array.isArray(raw.checks) ? raw.checks.map(String) : typeof raw.checks === "string" ? raw.checks.split(",").map((entry) => entry.trim()).filter(Boolean) : void 0;
267
+ const tools = Array.isArray(raw.tools) ? raw.tools.map(String) : typeof raw.tools === "string" ? raw.tools.split(",").map((entry) => entry.trim()).filter(Boolean) : void 0;
268
+ const config = {};
269
+ if (typeof raw.instructions === "string") config.instructions = raw.instructions;
270
+ if (checks && checks.length > 0) config.checks = checks;
271
+ if (tools && tools.length > 0) config.tools = tools;
272
+ const activity = normalizeStageActivity(raw.activity);
273
+ if (activity) config.activity = activity;
274
+ const review = normalizeReviewExpectation(raw.review);
275
+ const gate = normalizeGateExpectation(raw.gate);
276
+ if (review) config.review = review;
277
+ if (gate) config.gate = gate;
278
+ return Object.keys(config).length > 0 ? config : void 0;
279
+ }
280
+ function normalizeReferenceHints(value) {
281
+ if (!Array.isArray(value)) return void 0;
282
+ const hints = value.flatMap((entry) => {
283
+ if (!entry || typeof entry !== "object") return [];
284
+ const raw = entry;
285
+ return typeof raw.path === "string" && typeof raw.reason === "string" ? [{ path: raw.path, reason: raw.reason }] : [];
286
+ });
287
+ return hints;
288
+ }
289
+ function normalizeActionHints(value) {
290
+ if (!Array.isArray(value)) return void 0;
291
+ const hints = value.flatMap((entry) => {
292
+ if (!entry || typeof entry !== "object") return [];
293
+ const raw = entry;
294
+ return typeof raw.label === "string" && typeof raw.description === "string" ? [{ label: raw.label, description: raw.description }] : [];
295
+ });
296
+ return hints;
297
+ }
298
+ function normalizeCommandHints(value) {
299
+ if (!Array.isArray(value)) return void 0;
300
+ const hints = value.flatMap((entry) => {
301
+ if (!entry || typeof entry !== "object") return [];
302
+ const raw = entry;
303
+ return typeof raw.command === "string" && typeof raw.label === "string" ? [
304
+ {
305
+ command: raw.command,
306
+ label: raw.label,
307
+ description: typeof raw.description === "string" ? raw.description : void 0
308
+ }
309
+ ] : [];
310
+ });
311
+ return hints;
312
+ }
313
+ function applyCommonActivityHints(raw, config) {
314
+ if (typeof raw.objective === "string") config.objective = raw.objective;
315
+ const mustRead = normalizeReferenceHints(raw.mustRead);
316
+ if (mustRead !== void 0) config.mustRead = mustRead;
317
+ if (Array.isArray(raw.mustNotDo)) {
318
+ config.mustNotDo = raw.mustNotDo.map(String);
319
+ }
320
+ const nextActions = normalizeActionHints(raw.nextActions);
321
+ if (nextActions !== void 0) config.nextActions = nextActions;
322
+ const commands = normalizeCommandHints(raw.commands);
323
+ if (commands !== void 0) config.commands = commands;
324
+ }
325
+ function normalizeActivityHint(value) {
326
+ if (!value || typeof value !== "object") return void 0;
327
+ const raw = value;
328
+ const config = {};
329
+ applyCommonActivityHints(raw, config);
330
+ return Object.keys(config).length > 0 ? config : void 0;
331
+ }
332
+ function normalizeReviewExpectation(value) {
333
+ if (!value || typeof value !== "object") return void 0;
334
+ const raw = value;
335
+ const config = {};
336
+ applyCommonActivityHints(raw, config);
337
+ if (typeof raw.label === "string") config.label = raw.label;
338
+ if (typeof raw.emphasis === "string") config.emphasis = raw.emphasis;
339
+ if (typeof raw.riskFocus === "string") config.riskFocus = raw.riskFocus;
340
+ if (typeof raw.evidencePrompt === "string") config.evidencePrompt = raw.evidencePrompt;
341
+ if (typeof raw.signalCode === "string") config.signalCode = raw.signalCode;
342
+ return Object.keys(config).length > 0 ? config : void 0;
343
+ }
344
+ function normalizeGateExpectation(value) {
345
+ if (!value || typeof value !== "object") return void 0;
346
+ const raw = value;
347
+ const config = {};
348
+ applyCommonActivityHints(raw, config);
349
+ if (typeof raw.label === "string") config.label = raw.label;
350
+ if (typeof raw.evidence === "string") config.evidence = raw.evidence;
351
+ if (typeof raw.decision === "string") config.decision = raw.decision;
352
+ if (typeof raw.signalCode === "string") config.signalCode = raw.signalCode;
353
+ return Object.keys(config).length > 0 ? config : void 0;
354
+ }
355
+ function normalizeStageActivity(value) {
356
+ if (!value || typeof value !== "object") return void 0;
357
+ const raw = value;
358
+ const config = {};
359
+ const design = normalizeActivityHint(raw.design);
360
+ const implement = normalizeActivityHint(raw.implement);
361
+ const review = normalizeReviewExpectation(raw.review);
362
+ const diagnose = normalizeActivityHint(raw.diagnose);
363
+ const gate = normalizeGateExpectation(raw.gate);
364
+ if (design) config.design = design;
365
+ if (implement) config.implement = implement;
366
+ if (review) config.review = review;
367
+ if (diagnose) config.diagnose = diagnose;
368
+ if (gate) config.gate = gate;
369
+ return Object.keys(config).length > 0 ? config : void 0;
370
+ }
371
+ function normalizeStagePhases(value) {
372
+ if (!value || typeof value !== "object") return void 0;
373
+ const raw = value;
374
+ const initialState = typeof raw.initialState === "string" ? raw.initialState : null;
375
+ const rawStates = raw.states;
376
+ if (!initialState || !rawStates || typeof rawStates !== "object") return void 0;
377
+ const states = Object.entries(rawStates).reduce((acc, [phaseId, entry]) => {
378
+ if (!entry || typeof entry !== "object") return acc;
379
+ const rawPhase = entry;
380
+ const id = typeof rawPhase.id === "string" ? rawPhase.id : phaseId;
381
+ const label = typeof rawPhase.label === "string" ? rawPhase.label : id;
382
+ const description = typeof rawPhase.description === "string" ? rawPhase.description : "";
383
+ acc[id] = {
384
+ id,
385
+ label,
386
+ description,
387
+ actions: normalizePhaseActions(rawPhase.actions),
388
+ transitions: normalizePhaseTransitions(rawPhase.transitions),
389
+ harness: normalizePhaseHarness(rawPhase.harness)
390
+ };
391
+ return acc;
392
+ }, {});
393
+ if (!states[initialState]) return void 0;
394
+ return { initialState, states };
395
+ }
396
+ function loadHarness(root) {
397
+ const harnessDir = root;
398
+ if (!existsSync3(harnessDir)) return null;
399
+ const flowsDir = join2(harnessDir, "flows");
400
+ const gatesDir = join2(harnessDir, "gates");
401
+ const rolesDir = join2(harnessDir, "roles");
402
+ const policiesDir = join2(harnessDir, "policies");
403
+ if (!existsSync3(flowsDir) || !existsSync3(gatesDir) || !existsSync3(rolesDir)) return null;
404
+ const flows = {};
405
+ if (existsSync3(flowsDir)) {
406
+ for (const file of readdirSync2(flowsDir)) {
407
+ if (!file.endsWith(".yaml")) continue;
408
+ const raw = parseSimpleYaml(readFileSync(join2(flowsDir, file), "utf-8"));
409
+ flows[String(raw.id)] = {
410
+ id: String(raw.id),
411
+ version: String(raw.version ?? "0.0.0"),
412
+ name: String(raw.name ?? raw.id),
413
+ description: String(raw.description ?? ""),
414
+ defaultPolicy: String(raw.defaultPolicy ?? ""),
415
+ stages: unwrapStages(raw.stages).map((s) => ({
416
+ id: String(s.id ?? ""),
417
+ name: String(s.name ?? s.id ?? ""),
418
+ order: typeof s.order === "number" ? s.order : Number(s.order ?? 0),
419
+ zone: ["todo", "doing", "done"].includes(s.zone) ? s.zone : void 0,
420
+ description: String(s.description ?? ""),
421
+ agents: Array.isArray(s.agents) ? s.agents.map((a) => String(a)) : typeof s.agents === "string" ? s.agents.split(",").map((a) => a.trim()).filter(Boolean) : [],
422
+ gate: typeof s.gate === "string" && s.gate.trim() ? s.gate.trim() : null,
423
+ preferredExecutor: typeof s.preferredExecutor === "string" ? s.preferredExecutor : void 0,
424
+ phases: normalizeStagePhases(s.phases),
425
+ activity: normalizeStageActivity(s.activity)
426
+ }))
427
+ };
428
+ }
429
+ }
430
+ const gates = {};
431
+ if (existsSync3(gatesDir)) {
432
+ for (const file of readdirSync2(gatesDir)) {
433
+ if (!file.endsWith(".yaml")) continue;
434
+ const raw = parseSimpleYaml(readFileSync(join2(gatesDir, file), "utf-8"));
435
+ gates[String(raw.id)] = {
436
+ id: String(raw.id),
437
+ name: String(raw.name ?? raw.id),
438
+ type: ["human", "automated", "external"].includes(raw.type) ? raw.type : "automated",
439
+ blocking: raw.blocking === true,
440
+ blocksHandoff: raw.blocksHandoff === true,
441
+ policyRef: raw.policyRef ?? void 0,
442
+ description: String(raw.description ?? ""),
443
+ decisions: normalizeGateDecisions(raw.decisions)
444
+ };
445
+ }
446
+ }
447
+ const roles = {};
448
+ if (existsSync3(rolesDir)) {
449
+ for (const file of readdirSync2(rolesDir)) {
450
+ if (!file.endsWith(".yaml")) continue;
451
+ const raw = parseSimpleYaml(readFileSync(join2(rolesDir, file), "utf-8"));
452
+ const capabilities = Array.isArray(raw.capabilities) ? raw.capabilities.map(String) : typeof raw.capabilities === "string" ? raw.capabilities.split(",").map((a) => a.trim()).filter(Boolean) : [];
453
+ const handoff = raw.handoff && typeof raw.handoff === "object" ? (() => {
454
+ const h = raw.handoff;
455
+ return {
456
+ blocksHandoff: h.blocksHandoff === true,
457
+ allowedTargets: Array.isArray(h.allowedTargets) ? h.allowedTargets.map(String) : [],
458
+ requireEvidence: h.requireEvidence === true,
459
+ ttlMinutes: typeof h.ttlMinutes === "number" ? h.ttlMinutes : void 0
460
+ };
461
+ })() : void 0;
462
+ roles[String(raw.id)] = {
463
+ id: String(raw.id),
464
+ label: String(raw.label ?? raw.id),
465
+ description: String(raw.description ?? ""),
466
+ allowedStages: Array.isArray(raw.allowedStages) ? raw.allowedStages.map(String) : typeof raw.allowedStages === "string" ? raw.allowedStages.split(",").map((a) => a.trim()).filter(Boolean) : [],
467
+ capabilities,
468
+ handoff,
469
+ promptTemplate: typeof raw["prompt-template"] === "string" ? raw["prompt-template"] : void 0
470
+ };
471
+ }
472
+ }
473
+ const policies = {};
474
+ if (existsSync3(policiesDir)) {
475
+ for (const file of readdirSync2(policiesDir)) {
476
+ if (!file.endsWith(".json")) continue;
477
+ try {
478
+ const p = JSON.parse(readFileSync(join2(policiesDir, file), "utf-8"));
479
+ policies[String(p.id)] = p;
480
+ } catch {
481
+ }
482
+ }
483
+ }
484
+ const executorsDir = join2(harnessDir, "executors");
485
+ let executors;
486
+ if (existsSync3(executorsDir)) {
487
+ const registryPath = join2(executorsDir, "registry.yaml");
488
+ if (existsSync3(registryPath)) {
489
+ try {
490
+ const raw = parseSimpleYaml(readFileSync(registryPath, "utf-8"));
491
+ const executorList = Array.isArray(raw.executors) ? raw.executors.map((e) => ({
492
+ id: String(e.id ?? ""),
493
+ label: String(e.label ?? e.id ?? ""),
494
+ capabilities: Array.isArray(e.capabilities) ? e.capabilities.map(String) : [],
495
+ notification: Array.isArray(e.notification) ? e.notification.filter(
496
+ (n) => ["sse", "polling", "file-watch"].includes(n)
497
+ ) : [],
498
+ heartbeat: e.heartbeat === true,
499
+ maxExecutionTime: typeof e.maxExecutionTime === "number" ? e.maxExecutionTime : 1800,
500
+ priority: typeof e.priority === "number" ? e.priority : 0
501
+ })) : [];
502
+ const stagePreferences = raw.stageExecutorPreferences && typeof raw.stageExecutorPreferences === "object" ? Object.entries(
503
+ raw.stageExecutorPreferences
504
+ ).reduce((acc, [stage, value]) => {
505
+ acc[stage] = Array.isArray(value) ? value.map(String) : [];
506
+ return acc;
507
+ }, {}) : {};
508
+ executors = {
509
+ executors: executorList,
510
+ stageExecutorPreferences: stagePreferences
511
+ };
512
+ } catch {
513
+ }
514
+ }
515
+ }
516
+ return {
517
+ version: basename(harnessDir).replace(/^v/, ""),
518
+ flows,
519
+ gates,
520
+ roles,
521
+ policies,
522
+ executors
523
+ };
524
+ }
525
+
526
+ // src/commands/flow-init.ts
527
+ import { existsSync as existsSync14, mkdirSync as mkdirSync4, readFileSync as readFileSync10, writeFileSync as writeFileSync4 } from "fs";
528
+ import { basename as basename2, join as join13, resolve as resolve2 } from "path";
529
+ import { createInterface } from "readline";
530
+ import chalk from "chalk";
531
+ import ora from "ora";
532
+
533
+ // src/adapters/formatters.ts
534
+ var L1_FILES = [
535
+ ".letra/context.md",
536
+ ".letra/constitution.md",
537
+ ".letra/glossary.md",
538
+ ".letra/constraints.md"
539
+ ];
540
+ function formatL1(snapshot, format) {
541
+ if (format === "at") {
542
+ const lines2 = L1_FILES.map((path) => `@${path}`);
543
+ if (snapshot.hasFocus) lines2.push("@.letra/focus.md");
544
+ return lines2.join("\n");
545
+ }
546
+ const lines = [...L1_FILES.map((path) => `- ${path}`)];
547
+ if (snapshot.hasFocus) {
548
+ lines.push("- .letra/focus.md");
549
+ } else {
550
+ lines.push("- .letra/focus.md");
551
+ }
552
+ return lines.join("\n");
553
+ }
554
+ function formatMarkdownReferences(snapshot) {
555
+ const links = snapshot.referenceLinks;
556
+ const lines = [
557
+ `- [Context](${links.context})`,
558
+ `- [Constitution](${links.constitution})`,
559
+ `- [Glossary](${links.glossary})`,
560
+ `- [Constraints](${links.constraints})`
561
+ ];
562
+ if (links.focus) lines.push(`- [Focus](${links.focus})`);
563
+ if (links.spec && snapshot.focusSpec) {
564
+ lines.push(`- [Spec: ${snapshot.focusSpec}](${links.spec})`);
565
+ }
566
+ if (snapshot.primaryItemId) {
567
+ lines.push(`- [${snapshot.primaryItemId}](${links.workflow})`);
568
+ }
569
+ return lines.join("\n");
570
+ }
571
+ function formatDate(iso) {
572
+ if (!iso) return "";
573
+ try {
574
+ return new Date(iso).toLocaleString("pt-BR");
575
+ } catch {
576
+ return "";
577
+ }
578
+ }
579
+ function formatProtocol(snapshot) {
580
+ if (!snapshot.hasWorkflow) return null;
581
+ const primaryItem = snapshot.primaryItemId ? snapshot.items.find((i) => i.id === snapshot.primaryItemId) : snapshot.items[0];
582
+ const acLine = snapshot.totalACs > 0 ? `ACs: ${snapshot.pendingACs}/${snapshot.totalACs} pendentes` : "";
583
+ const lines = [
584
+ "PASSO OBRIGAT\xD3RIO #1: letra pulse \u2014 verificar estado do workspace",
585
+ "PASSO OBRIGAT\xD3RIO #2: Leia .letra/context.md \u2014 contexto completo do projeto",
586
+ "PASSO OBRIGAT\xD3RIO #3: Leia .letra/focus.md \u2014 foco e outcome da sess\xE3o"
587
+ ];
588
+ if (snapshot.focusSpec) {
589
+ lines.push(
590
+ `PASSO OBRIGAT\xD3RIO #4: Leia .letra/specs/${snapshot.focusSpec}/spec.md \u2014 ACs do item`
591
+ );
592
+ } else if (primaryItem?.spec) {
593
+ lines.push(
594
+ `PASSO OBRIGAT\xD3RIO #4: Leia .letra/specs/${primaryItem.spec}/spec.md \u2014 ACs do item`
595
+ );
596
+ } else {
597
+ lines.push(
598
+ "PASSO OBRIGAT\xD3RIO #4: Identifique o item ativo via `letra pulse` e leia sua spec"
599
+ );
600
+ }
601
+ return lines.join("\n");
602
+ }
603
+ function formatFocus(snapshot) {
604
+ if (!snapshot.hasWorkflow) return null;
605
+ const primaryItem = snapshot.primaryItemId ? snapshot.items.find((i) => i.id === snapshot.primaryItemId) : snapshot.items[0];
606
+ if (!primaryItem) return null;
607
+ const lines = [`Item: ${primaryItem.id} \xB7 ${primaryItem.description}`];
608
+ if (snapshot.focusSpec) lines.push(`Spec: ${snapshot.focusSpec}`);
609
+ if (snapshot.activeStage) {
610
+ const stageLine = `Est\xE1gio: ${snapshot.activeStage.name}`;
611
+ if (snapshot.nextStage) {
612
+ lines.push(`${stageLine} \u2192 ${snapshot.nextStage.name}`);
613
+ } else {
614
+ lines.push(stageLine);
615
+ }
616
+ }
617
+ if (snapshot.totalACs > 0) {
618
+ lines.push(`ACs: ${snapshot.pendingACs}/${snapshot.totalACs} pendentes`);
619
+ }
620
+ return lines.join("\n");
621
+ }
622
+ function formatAlerts(snapshot) {
623
+ if (!snapshot.alerts || snapshot.alerts.length === 0) return null;
624
+ const lines = [];
625
+ for (const alert of snapshot.alerts) {
626
+ if (alert.id === "...") {
627
+ lines.push(` ${alert.title}`);
628
+ continue;
629
+ }
630
+ const severityLabel = alert.severity === "alta" ? "alta" : alert.severity === "media" ? "m\xE9dia" : "baixa";
631
+ lines.push(`Alerta \xB7 severidade ${severityLabel}`);
632
+ lines.push(` ID: ${alert.id}`);
633
+ lines.push(` O que: ${alert.title}`);
634
+ lines.push(` Onde: ${alert.source}`);
635
+ lines.push(` Desde: ${formatDate(alert.detectedAt)}`);
636
+ lines.push(` A\xE7\xE3o: \`letra health ack ${alert.id}\``);
637
+ lines.push("");
638
+ }
639
+ return lines.join("\n");
640
+ }
641
+ function formatProhibitionRules() {
642
+ return [
643
+ "**Viola\xE7\xE3o = Erro Grave**",
644
+ "",
645
+ "- N\xE3o edite workflow.json manualmente \u2014 use `letra flow` e `letra focus`",
646
+ "- N\xE3o crie specs fora de .letra/specs/ \u2014 use `letra spec new`",
647
+ "- N\xE3o pule os passos obrigat\xF3rios de in\xEDcio acima",
648
+ "- Execute `letra validate` antes de mover item entre est\xE1gios",
649
+ "- Siga a constitution.md rigorosamente"
650
+ ].join("\n");
651
+ }
652
+ function formatExecutionFlow() {
653
+ return [
654
+ "**Loop por AC**:",
655
+ " 1. Implemente o AC no c\xF3digo",
656
+ " 2. `letra ac done <AC-ID>` \u2014 marca como conclu\xEDdo no spec.md",
657
+ " 3. `letra validate` \u2014 verifica se ACs est\xE3o consistentes",
658
+ " 4. Repita at\xE9 todos os ACs do item estarem conclu\xEDdos",
659
+ "",
660
+ "**Ao concluir todos ACs**:",
661
+ " \u2192 `letra pulse` \u2014 confirma estado",
662
+ " \u2192 `letra sitrep` \u2014 atualiza context.md",
663
+ " \u2192 `letra flow move <ITEM-ID> --auto` \u2014 avan\xE7a para pr\xF3ximo est\xE1gio"
664
+ ].join("\n");
665
+ }
666
+ function formatHarnessDirection(snapshot, format) {
667
+ const dir = snapshot.harnessDirection;
668
+ if (!dir) return null;
669
+ const itemId = snapshot.primaryItemId;
670
+ const item = itemId ? snapshot.items.find((i) => i.id === itemId) : null;
671
+ const stageId = snapshot.activeStage?.id;
672
+ const stageName = snapshot.activeStage?.name;
673
+ const version = dir.harnessVersion;
674
+ if (!itemId && snapshot.hasWorkflow) {
675
+ if (format === "at") {
676
+ return [
677
+ "# harness-direction:start",
678
+ "## Dire\xE7\xE3o do Harness",
679
+ "",
680
+ "@aviso: Nenhum item em andamento. Consulte o backlog para priorizar.",
681
+ "# harness-direction:end"
682
+ ].join("\n");
683
+ }
684
+ return [
685
+ "<!-- harness-direction:start -->",
686
+ "**Aviso**: Nenhum item em andamento. Consulte o backlog para priorizar.",
687
+ "<!-- harness-direction:end -->"
688
+ ].join("\n");
689
+ }
690
+ const hasActivity = dir.activities.length > 0 && dir.activities.some(
691
+ (a) => a.objective || a.commands && a.commands.length > 0 || a.mustNotDo && a.mustNotDo.length > 0 || a.nextActions && a.nextActions.length > 0
692
+ );
693
+ if (!hasActivity) {
694
+ const roleLabel2 = dir.roleIds.length > 0 ? dir.roleIds.join(", ") : null;
695
+ const itemLabel2 = item ? `${item.id} \u2014 ${item.description} (${stageName ?? stageId})` : null;
696
+ if (format === "at") {
697
+ const lines = ["# harness-direction:start", "## Dire\xE7\xE3o do Harness", ""];
698
+ const metaParts = [
699
+ version ? `@harness: ${version}` : "",
700
+ roleLabel2 ? `papel: ${roleLabel2}` : "",
701
+ stageId ? `est\xE1gios: ${stageId}` : ""
702
+ ].filter(Boolean);
703
+ if (metaParts.length > 0) lines.push(metaParts.join(" | "));
704
+ if (itemLabel2) lines.push(`@item: ${itemLabel2}`);
705
+ lines.push("@aviso: Est\xE1gio sem activity configurada no harness.");
706
+ lines.push("# harness-direction:end");
707
+ return lines.join("\n");
708
+ }
709
+ const body2 = [];
710
+ const meta = [
711
+ version ? `**Vers\xE3o**: ${version}` : "",
712
+ roleLabel2 ? `**Papel**: ${roleLabel2}` : "",
713
+ stageId ? `**Est\xE1gios**: ${stageId}` : ""
714
+ ].filter(Boolean).join(" | ");
715
+ if (meta) body2.push(meta);
716
+ if (itemLabel2) body2.push(`**Item**: ${itemLabel2}`);
717
+ body2.push("_Est\xE1gio sem activity configurada no harness._");
718
+ return `<!-- harness-direction:start -->
719
+ ${body2.join("\n")}
720
+ <!-- harness-direction:end -->`;
721
+ }
722
+ const gateActivities = dir.activities.filter((a) => a.kind === "gate");
723
+ const workActivities = dir.activities.filter((a) => a.kind !== "gate");
724
+ const aggObjective = workActivities.find((a) => a.objective)?.objective ?? gateActivities.find((a) => a.objective)?.objective;
725
+ const aggCommands = workActivities.length > 0 ? workActivities.flatMap((a) => a.commands ?? []) : gateActivities.flatMap((a) => a.commands ?? []);
726
+ const aggMustNotDo = workActivities.length > 0 ? workActivities.flatMap((a) => a.mustNotDo ?? []) : gateActivities.flatMap((a) => a.mustNotDo ?? []);
727
+ const aggNextActions = workActivities.length > 0 ? workActivities.flatMap((a) => a.nextActions ?? []) : gateActivities.flatMap((a) => a.nextActions ?? []);
728
+ const gateSub = gateActivities.length > 0 && (gateActivities.some(
729
+ (a) => a.objective && !workActivities.some((w) => w.objective === a.objective)
730
+ ) || gateActivities.some((a) => a.commands && a.commands.length > 0) || gateActivities.some((a) => a.nextActions && a.nextActions.length > 0)) ? {
731
+ objective: gateActivities.find(
732
+ (a) => a.objective && !workActivities.some((w) => w.objective === a.objective)
733
+ )?.objective,
734
+ commands: gateActivities.flatMap((a) => a.commands ?? []),
735
+ mustNotDo: gateActivities.flatMap((a) => a.mustNotDo ?? []),
736
+ nextActions: gateActivities.flatMap((a) => a.nextActions ?? [])
737
+ } : null;
738
+ const pendingIds = dir.pendingACIds ?? [];
739
+ const resolvedItemId = dir.primaryItemId ?? snapshot.primaryItemId ?? snapshot.items[0]?.id;
740
+ const resolvedCommands = [];
741
+ for (const cmd of aggCommands) {
742
+ const hasAcPlaceholder = cmd.command.includes("<AC-ID>");
743
+ const hasItemPlaceholder = cmd.command.includes("<ITEM-ID>");
744
+ if (hasAcPlaceholder && pendingIds.length === 0) continue;
745
+ if (hasItemPlaceholder && !resolvedItemId) continue;
746
+ if (hasAcPlaceholder) {
747
+ for (const acId of pendingIds) {
748
+ resolvedCommands.push({
749
+ ...cmd,
750
+ command: cmd.command.replace("<AC-ID>", acId).replace("<ITEM-ID>", resolvedItemId ?? acId)
751
+ });
752
+ }
753
+ } else if (hasItemPlaceholder) {
754
+ resolvedCommands.push({
755
+ ...cmd,
756
+ command: cmd.command.replace("<ITEM-ID>", resolvedItemId)
757
+ });
758
+ } else {
759
+ resolvedCommands.push(cmd);
760
+ }
761
+ }
762
+ const roleLabel = dir.roleIds.length > 0 ? dir.roleIds.join(", ") : null;
763
+ const stagesLabel = stageId ?? null;
764
+ const itemLabel = item ? `${item.id} \u2014 ${item.description} (${stageName ?? stageId})` : null;
765
+ if (format === "at") {
766
+ const lines = ["# harness-direction:start", "## Dire\xE7\xE3o do Harness", ""];
767
+ const metaParts = [
768
+ version ? `@harness: ${version}` : "",
769
+ roleLabel ? `papel: ${roleLabel}` : "",
770
+ stagesLabel ? `est\xE1gios: ${stagesLabel}` : ""
771
+ ].filter(Boolean);
772
+ if (metaParts.length > 0) lines.push(metaParts.join(" | "));
773
+ if (itemLabel) lines.push(`@item: ${itemLabel}`);
774
+ if (aggObjective) lines.push(`@objetivo: ${aggObjective}`);
775
+ if (resolvedCommands.length > 0) {
776
+ lines.push(`@comandos: ${resolvedCommands.map((c) => c.command).join(" | ")}`);
777
+ }
778
+ if (aggMustNotDo.length > 0) {
779
+ lines.push(`@proibi\xE7\xF5es: ${aggMustNotDo.join(" | ")}`);
780
+ }
781
+ if (aggNextActions.length > 0) {
782
+ lines.push(
783
+ `@proximas: ${aggNextActions.slice(0, 2).map((a) => a.label).join(" | ")}`
784
+ );
785
+ }
786
+ if (gateSub) {
787
+ if (gateSub.objective) lines.push(`@gate: ${gateSub.objective}`);
788
+ if (gateSub.commands.length > 0)
789
+ lines.push(`@gate-comandos: ${gateSub.commands.map((c) => c.command).join(" | ")}`);
790
+ if (gateSub.nextActions.length > 0)
791
+ lines.push(
792
+ `@gate-proximas: ${gateSub.nextActions.slice(0, 2).map((a) => a.label).join(" | ")}`
793
+ );
794
+ }
795
+ lines.push("# harness-direction:end");
796
+ return lines.join("\n");
797
+ }
798
+ const body = [];
799
+ if (roleLabel || version || stagesLabel) {
800
+ const meta = [
801
+ version ? `**Vers\xE3o**: ${version}` : "",
802
+ roleLabel ? `**Papel**: ${roleLabel}` : "",
803
+ stagesLabel ? `**Est\xE1gios**: ${stagesLabel}` : ""
804
+ ].filter(Boolean).join(" | ");
805
+ body.push(meta);
806
+ }
807
+ if (itemLabel) body.push(`**Item**: ${itemLabel}`);
808
+ if (aggObjective) body.push(`**Objetivo**: ${aggObjective}`);
809
+ if (resolvedCommands.length > 0) {
810
+ body.push("**Comandos**:");
811
+ for (const c of resolvedCommands) {
812
+ body.push(`- \`${c.command}\` \u2014 ${c.label}`);
813
+ }
814
+ }
815
+ if (aggMustNotDo.length > 0) {
816
+ body.push(`**Proibi\xE7\xF5es**: ${aggMustNotDo.join(" ")}`);
817
+ }
818
+ if (aggNextActions.length > 0) {
819
+ body.push("**Pr\xF3ximas a\xE7\xF5es**:");
820
+ aggNextActions.slice(0, 2).forEach((a, i) => {
821
+ body.push(`${i + 1}. ${a.label}${a.description ? ` \u2014 ${a.description}` : ""}`);
822
+ });
823
+ }
824
+ if (gateSub) {
825
+ body.push("");
826
+ body.push("**Gate**");
827
+ if (gateSub.objective) body.push(`_${gateSub.objective}_`);
828
+ if (gateSub.commands.length > 0) {
829
+ for (const c of gateSub.commands) {
830
+ body.push(`- \`${c.command}\` \u2014 ${c.label}`);
831
+ }
832
+ }
833
+ if (gateSub.nextActions.length > 0) {
834
+ gateSub.nextActions.slice(0, 2).forEach((a, i) => {
835
+ body.push(
836
+ `${i + 1 + aggNextActions.slice(0, 2).length}. ${a.label}${a.description ? ` \u2014 ${a.description}` : ""}`
837
+ );
838
+ });
839
+ }
840
+ }
841
+ if (body.length === 0) return null;
842
+ return `<!-- harness-direction:start -->
843
+ ${body.join("\n")}
844
+ <!-- harness-direction:end -->`;
845
+ }
846
+ function formatCommands() {
847
+ return [
848
+ "**Leitura (seguro \u2014 n\xE3o muda nada):**",
849
+ " `letra pulse` \u2014 Overview do workspace",
850
+ " `letra health` \u2014 Alertas ativos",
851
+ " `letra flow board` \u2014 Todas as colunas do fluxo",
852
+ " `letra flow backlog` \u2014 Itens no backlog",
853
+ " `letra validate` \u2014 Validar specs e ACs",
854
+ "",
855
+ "**Escrita (muda estado):**",
856
+ " `letra health ack <id>` \u2014 Reconhecer alerta",
857
+ " `letra health dismiss <id>` \u2014 Descartar alerta",
858
+ " `letra health scan` \u2014 Re-executar verifica\xE7\xF5es",
859
+ " `letra sitrep` \u2014 Atualizar context.md",
860
+ " `letra flow move <id> --to <s>` \u2014 Mover item entre est\xE1gios",
861
+ " `letra focus <spec>` \u2014 Definir foco",
862
+ " `letra focus --clear` \u2014 Limpar foco"
863
+ ].join("\n");
864
+ }
865
+ function formatCompletionChecklist(snapshot) {
866
+ if (!snapshot.hasWorkflow) return null;
867
+ return [
868
+ "1. `letra pulse --json` \u2014 veja itens, ACs, alertas, backlog",
869
+ "",
870
+ "2. Decida o estado:",
871
+ "",
872
+ " **CONTINUE** (backlog tem itens OU item atual tem ACs pendentes):",
873
+ " \u2192 Relate o progresso: quais ACs fez, o que falta, onde parou",
874
+ " \u2192 Se sess\xE3o >30 min, pare e relate. Caso contr\xE1rio, continue.",
875
+ "",
876
+ " **BLOCKED** (backlog vazio, item sem ACs pendentes, aguardando humano):",
877
+ ' \u2192 Relate "Trabalho conclu\xEDdo, aguardando revis\xE3o"',
878
+ " \u2192 Liste o que foi feito e decis\xF5es necess\xE1rias",
879
+ "",
880
+ " **ALL_DONE** (todos os itens em Done, backlog vazio):",
881
+ " \u2192 Relate miss\xE3o completa: itens conclu\xEDdos, o que foi constru\xEDdo, pr\xF3ximos passos"
882
+ ].join("\n");
883
+ }
884
+ function formatContinuity(snapshot) {
885
+ if (!snapshot.lastSession) return null;
886
+ return [
887
+ `\xDAltima atividade: ${snapshot.lastSession.lastDate}`,
888
+ `A\xE7\xF5es:
889
+ \u2022 ${snapshot.lastSession.actionsSummary}`
890
+ ].join("\n");
891
+ }
892
+ function formatAdapterContent(snapshot, format, options) {
893
+ const title = snapshot.hasWorkflow ? `# Letra Session \u2014 ${snapshot.workflowName}` : `# Letra Context \u2014 ${options.displayName} Adapter`;
894
+ const sections = [];
895
+ if (!snapshot.hasWorkflow) {
896
+ sections.push(title);
897
+ if (format === "at") {
898
+ sections.push(L1_FILES.map((p) => `@${p}`).join("\n"));
899
+ } else {
900
+ sections.push(
901
+ `Read the following files before starting any task:
902
+ ${L1_FILES.map((p) => `- ${p}`).join("\n")}`
903
+ );
904
+ }
905
+ if (snapshot.hasFocus)
906
+ sections[1] += format === "at" ? "\n@.letra/focus.md" : "\n- .letra/focus.md";
907
+ sections.push(`## Refer\xEAncias
908
+
909
+ ${formatMarkdownReferences(snapshot)}`);
910
+ sections.push(...["", formatRulesText()]);
911
+ return sections.join("\n");
912
+ }
913
+ sections.push(title);
914
+ const protocol = formatProtocol(snapshot);
915
+ if (protocol) sections.push(protocol);
916
+ const focus = formatFocus(snapshot);
917
+ if (focus) {
918
+ sections.push(`## Foco Atual
919
+
920
+ ${focus}`);
921
+ }
922
+ const phase = formatPhase(snapshot);
923
+ if (phase) {
924
+ sections.push(`## Fase Atual
925
+
926
+ ${phase}`);
927
+ }
928
+ const dir = formatHarnessDirection(snapshot, format);
929
+ if (dir) {
930
+ sections.push(`## Dire\xE7\xE3o do Harness
931
+
932
+ ${dir}`);
933
+ }
934
+ const hasGrave = snapshot.alerts?.some((a) => a.severity === "alta");
935
+ if (hasGrave) {
936
+ const graveAlerts = snapshot.alerts?.filter((a) => a.severity === "alta") || [];
937
+ sections.push(
938
+ `## \u26A0 ATEN\xC7\xC3O \u2014 Problema Grave
939
+
940
+ ${formatAlerts({ ...snapshot, alerts: graveAlerts })}`
941
+ );
942
+ }
943
+ const alerts = formatAlerts(snapshot);
944
+ if (alerts && !hasGrave) {
945
+ sections.push(`## Alertas
946
+
947
+ ${alerts}`);
948
+ } else if (alerts && hasGrave) {
949
+ const nonGrave = snapshot.alerts?.filter((a) => a.severity !== "alta");
950
+ if (nonGrave && nonGrave.length > 0) {
951
+ sections.push(`## Alertas
952
+
953
+ ${formatAlerts({ ...snapshot, alerts: nonGrave })}`);
954
+ }
955
+ }
956
+ sections.push(`## Regras (Viola\xE7\xE3o = Erro Grave)
957
+
958
+ ${formatProhibitionRules()}`);
959
+ if (snapshot.hasWorkflow) {
960
+ sections.push(`## Fluxo de Execu\xE7\xE3o
961
+
962
+ ${formatExecutionFlow()}`);
963
+ }
964
+ const handoffStr = formatHandoff(snapshot);
965
+ if (handoffStr) {
966
+ sections.push(`## Ap\xF3s completar uma a\xE7\xE3o
967
+
968
+ ${handoffStr}`);
969
+ }
970
+ sections.push(`## Comandos
971
+
972
+ ${formatCommands()}`);
973
+ const continuity = formatContinuity(snapshot);
974
+ if (continuity) {
975
+ sections.push(`## Continuidade
976
+
977
+ ${continuity}`);
978
+ }
979
+ sections.push(`## Checklist de Encerramento
980
+
981
+ ${formatCompletionChecklist(snapshot)}`);
982
+ const refs = formatL1(snapshot, format);
983
+ sections.push(`## Arquivos de Contexto
984
+
985
+ ${refs}`);
986
+ sections.push(`## Refer\xEAncias
987
+
988
+ ${formatMarkdownReferences(snapshot)}`);
989
+ return `${sections.join("\n\n")}
990
+ `;
991
+ }
992
+ function formatPhase(snapshot) {
993
+ if (!snapshot.currentPhase) return null;
994
+ const p = snapshot.currentPhase;
995
+ let out = `${p.label} \u2014 ${p.description}`;
996
+ if (p.harness?.instructions) {
997
+ out += `
998
+ Instru\xE7\xF5es: ${p.harness.instructions}`;
999
+ }
1000
+ if (p.harness?.checks && p.harness.checks.length > 0) {
1001
+ out += `
1002
+ Verifica\xE7\xF5es:
1003
+ ${p.harness.checks.map((c) => `- ${c}`).join("\n ")}`;
1004
+ }
1005
+ return out;
1006
+ }
1007
+ function formatHandoff(snapshot) {
1008
+ if (!snapshot.handoff || snapshot.handoff.disabled) return null;
1009
+ const h = snapshot.handoff;
1010
+ const lines = [];
1011
+ for (const step of h.steps) {
1012
+ lines.push(`- \`${step.command}\` \u2014 ${step.label}`);
1013
+ if (step.recovery) {
1014
+ lines.push(` \u274C Se falhar: ${step.recovery}`);
1015
+ }
1016
+ }
1017
+ if (h.nextStageName) {
1018
+ lines.push("", "Ap\xF3s mover, verifique o novo est\xE1gio com `letra pulse`");
1019
+ }
1020
+ return lines.join("\n");
1021
+ }
1022
+ function formatRulesText() {
1023
+ return [
1024
+ "# Rules",
1025
+ "- Always read specs in .letra/specs/ before writing code",
1026
+ "- Run `letra validate` to check acceptance criteria",
1027
+ "- Execute `letra ac done <ID>` after implementing each AC",
1028
+ "- Follow the constitution.md rules strictly",
1029
+ "- Use formal tone in all generated content"
1030
+ ].join("\n");
1031
+ }
1032
+
1033
+ // src/adapters/hermes.ts
1034
+ function buildHermesSnapshot(root) {
1035
+ const workflow = loadWorkflow(root);
1036
+ if (!workflow) {
1037
+ return buildHarnessSnapshot(root, { source: "init" });
1038
+ }
1039
+ const activeItemId = workflow.primaryItemId || workflow.items[0]?.id;
1040
+ const activeItem = workflow.items.find((item) => item.id === activeItemId) || null;
1041
+ return buildHarnessSnapshot(root, {
1042
+ source: "init",
1043
+ workflow: {
1044
+ name: workflow.name,
1045
+ stages: workflow.stages,
1046
+ items: workflow.items
1047
+ },
1048
+ activeStageId: activeItem?.stage || workflow.stages[0]?.id,
1049
+ primaryItemId: activeItemId
1050
+ });
1051
+ }
1052
+ function formatHermesContent(snapshot) {
1053
+ return formatAdapterContent(snapshot, "text", {
1054
+ source: "init",
1055
+ displayName: "Hermes Agent"
1056
+ });
1057
+ }
1058
+ function generateHermesAdapter(root) {
1059
+ const snapshot = buildHermesSnapshot(root);
1060
+ if (!snapshot.hasWorkflow) {
1061
+ return null;
1062
+ }
1063
+ return formatHermesContent(snapshot);
1064
+ }
1065
+
1066
+ // src/diagnostics/engine.ts
1067
+ import { existsSync as existsSync13, writeFileSync as writeFileSync3 } from "fs";
1068
+ import { join as join12 } from "path";
1069
+
1070
+ // src/diagnostics/snapshot.ts
1071
+ import {
1072
+ readFileSync as readFileSync2,
1073
+ writeFileSync,
1074
+ mkdirSync as mkdirSync2,
1075
+ existsSync as existsSync4,
1076
+ readdirSync as readdirSync3,
1077
+ rmSync
1078
+ } from "fs";
1079
+ import { join as join3 } from "path";
1080
+ var SNAPSHOTS_DIR = "snapshots";
1081
+ var MAX_SNAPSHOTS = 20;
1082
+ var TTL_MS = 30 * 24 * 60 * 60 * 1e3;
1083
+ var SnapshotStore = class {
1084
+ rootDir;
1085
+ snapshotsDir;
1086
+ constructor(rootDir) {
1087
+ this.rootDir = rootDir;
1088
+ this.snapshotsDir = join3(getLetraDir2(rootDir), SNAPSHOTS_DIR);
1089
+ if (!existsSync4(this.snapshotsDir)) {
1090
+ mkdirSync2(this.snapshotsDir, { recursive: true });
1091
+ }
1092
+ this.cleanup();
1093
+ this.enforceMax();
1094
+ }
1095
+ async save(diagnosticId, diagnosticTitle, files) {
1096
+ if (this.isDuplicate(diagnosticId, files)) {
1097
+ return null;
1098
+ }
1099
+ const id = `${Date.now()}_${diagnosticId}`;
1100
+ const snapshot = {
1101
+ id,
1102
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1103
+ diagnosticId,
1104
+ diagnosticTitle,
1105
+ files
1106
+ };
1107
+ writeFileSync(
1108
+ join3(this.snapshotsDir, `${id}.json`),
1109
+ JSON.stringify(snapshot, null, 0),
1110
+ "utf-8"
1111
+ );
1112
+ this.enforceMax();
1113
+ return id;
1114
+ }
1115
+ async restore(snapshotId) {
1116
+ const filePath = join3(this.snapshotsDir, `${snapshotId}.json`);
1117
+ if (!existsSync4(filePath)) {
1118
+ return { ok: false, restoredFiles: [] };
1119
+ }
1120
+ const snapshot = JSON.parse(readFileSync2(filePath, "utf-8"));
1121
+ const restoredFiles = [];
1122
+ for (const file of snapshot.files) {
1123
+ const absolutePath = join3(this.rootDir, file.path);
1124
+ writeFileSync(absolutePath, file.before, "utf-8");
1125
+ restoredFiles.push(file.path);
1126
+ }
1127
+ return { ok: true, restoredFiles };
1128
+ }
1129
+ async redo(snapshotId) {
1130
+ const filePath = join3(this.snapshotsDir, `${snapshotId}.json`);
1131
+ if (!existsSync4(filePath)) {
1132
+ return { ok: false, redoneFiles: [] };
1133
+ }
1134
+ const snapshot = JSON.parse(readFileSync2(filePath, "utf-8"));
1135
+ const redoneFiles = [];
1136
+ for (const file of snapshot.files) {
1137
+ const absolutePath = join3(this.rootDir, file.path);
1138
+ writeFileSync(absolutePath, file.after, "utf-8");
1139
+ redoneFiles.push(file.path);
1140
+ }
1141
+ return { ok: true, redoneFiles };
1142
+ }
1143
+ list() {
1144
+ if (!existsSync4(this.snapshotsDir)) return [];
1145
+ return readdirSync3(this.snapshotsDir).filter((f) => f.endsWith(".json")).map((f) => {
1146
+ const content = readFileSync2(join3(this.snapshotsDir, f), "utf-8");
1147
+ return JSON.parse(content);
1148
+ }).sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
1149
+ }
1150
+ isDuplicate(diagnosticId, files) {
1151
+ const last = this.getLastForDiagnostic(diagnosticId);
1152
+ if (!last) return false;
1153
+ if (last.files.length !== files.length) return false;
1154
+ for (let i = 0; i < files.length; i++) {
1155
+ if (last.files[i]?.after !== files[i]?.after) return false;
1156
+ }
1157
+ return true;
1158
+ }
1159
+ getLastForDiagnostic(diagnosticId) {
1160
+ if (!existsSync4(this.snapshotsDir)) return null;
1161
+ const entries = readdirSync3(this.snapshotsDir).filter(
1162
+ (f) => f.endsWith(".json") && f.includes(`_${diagnosticId}`)
1163
+ );
1164
+ if (entries.length === 0) return null;
1165
+ entries.sort().reverse();
1166
+ try {
1167
+ const content = readFileSync2(join3(this.snapshotsDir, entries[0]), "utf-8");
1168
+ return JSON.parse(content);
1169
+ } catch {
1170
+ return null;
1171
+ }
1172
+ }
1173
+ enforceMax() {
1174
+ if (!existsSync4(this.snapshotsDir)) return;
1175
+ const entries = readdirSync3(this.snapshotsDir).filter((f) => f.endsWith(".json")).sort();
1176
+ while (entries.length > MAX_SNAPSHOTS) {
1177
+ const oldest = entries.shift();
1178
+ if (oldest) {
1179
+ rmSync(join3(this.snapshotsDir, oldest));
1180
+ }
1181
+ }
1182
+ }
1183
+ cleanup() {
1184
+ if (!existsSync4(this.snapshotsDir)) return;
1185
+ const cutoff = Date.now() - TTL_MS;
1186
+ for (const file of readdirSync3(this.snapshotsDir)) {
1187
+ if (!file.endsWith(".json")) continue;
1188
+ try {
1189
+ const filePath = join3(this.snapshotsDir, file);
1190
+ const snapshot = JSON.parse(readFileSync2(filePath, "utf-8"));
1191
+ if (new Date(snapshot.timestamp).getTime() < cutoff) {
1192
+ rmSync(filePath);
1193
+ }
1194
+ } catch {
1195
+ }
1196
+ }
1197
+ }
1198
+ };
1199
+
1200
+ // src/diagnostics/detectors/ac-stale.ts
1201
+ import { readFileSync as readFileSync4, existsSync as existsSync6 } from "fs";
1202
+ import { join as join5 } from "path";
1203
+ import { readdirSync as readdirSync5 } from "fs";
1204
+
1205
+ // src/diagnostics/shared/file-search.ts
1206
+ import { existsSync as existsSync5, readFileSync as readFileSync3, readdirSync as readdirSync4 } from "fs";
1207
+ import { join as join4 } from "path";
1208
+ var AC_SEARCH_EXTENSIONS = [
1209
+ ".ts",
1210
+ ".tsx",
1211
+ ".js",
1212
+ ".jsx",
1213
+ ".mjs",
1214
+ ".cjs",
1215
+ ".json",
1216
+ ".yaml",
1217
+ ".yml"
1218
+ ];
1219
+ function searchInSource(rootDir, terms, extensions = AC_SEARCH_EXTENSIONS, targetDirs) {
1220
+ const searchDirs = targetDirs ?? ["packages/cli/src", "packages/client/src", "packages/ui/src"];
1221
+ for (const searchDir of searchDirs) {
1222
+ const dir = join4(rootDir, searchDir);
1223
+ if (!existsSync5(dir)) continue;
1224
+ try {
1225
+ const files = walkDir(dir, extensions);
1226
+ for (const file of files) {
1227
+ const content = readFileSync3(file, "utf-8");
1228
+ for (const term of terms) {
1229
+ if (content.includes(term)) return true;
1230
+ }
1231
+ }
1232
+ } catch {
1233
+ }
1234
+ }
1235
+ return false;
1236
+ }
1237
+ function walkDir(dir, extensions = [".ts", ".tsx"]) {
1238
+ const files = [];
1239
+ try {
1240
+ for (const entry of readdirSync4(dir, { withFileTypes: true })) {
1241
+ const fullPath = join4(dir, entry.name);
1242
+ if (entry.isDirectory() && entry.name !== "node_modules") {
1243
+ files.push(...walkDir(fullPath, extensions));
1244
+ } else if (entry.isFile() && extensions.some((ext) => entry.name.endsWith(ext))) {
1245
+ files.push(fullPath);
1246
+ }
1247
+ }
1248
+ } catch {
1249
+ }
1250
+ return files;
1251
+ }
1252
+ function escapeRegex(s) {
1253
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1254
+ }
1255
+
1256
+ // src/diagnostics/detectors/ac-stale.ts
1257
+ var STALE_AC_PATTERN = /-\s\[ \]\s\*\*`([^`]+)`\*\*/g;
1258
+ function toCamelCase(words) {
1259
+ return words.map((w, i) => i === 0 ? w : w.charAt(0).toUpperCase() + w.slice(1)).join("");
1260
+ }
1261
+ function toPascalCase(words) {
1262
+ return words.map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("");
1263
+ }
1264
+ var acStaleDetector = {
1265
+ name: "ac-stale",
1266
+ devOnly: true,
1267
+ async run(rootDir) {
1268
+ const results = [];
1269
+ const specsDir = join5(getLetraDir2(rootDir), "specs");
1270
+ if (!existsSync6(specsDir)) return results;
1271
+ const specDirs = readdirSync5(specsDir, { withFileTypes: true }).filter(
1272
+ (d) => d.isDirectory() && !d.name.startsWith("_")
1273
+ );
1274
+ for (const dir of specDirs) {
1275
+ const specFile = join5(specsDir, dir.name, "spec.md");
1276
+ if (!existsSync6(specFile)) continue;
1277
+ const content = readFileSync4(specFile, "utf-8");
1278
+ const matches = content.matchAll(STALE_AC_PATTERN);
1279
+ for (const match of matches) {
1280
+ const command = match[1].trim();
1281
+ if (!command) continue;
1282
+ const commandWords = command.split(/\s+/);
1283
+ const camelCaseName = toCamelCase(commandWords);
1284
+ const pascalCaseName = toPascalCase(commandWords);
1285
+ const foundInSource = searchInSource(rootDir, [
1286
+ command,
1287
+ camelCaseName,
1288
+ pascalCaseName
1289
+ ]);
1290
+ if (foundInSource) {
1291
+ results.push({
1292
+ id: `ac-stale_${dir.name}_${command.replace(/\s+/g, "-")}`,
1293
+ type: "info",
1294
+ title: `AC "${command}" marcado [ ] mas implementado`,
1295
+ 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.`,
1296
+ certainty: 0.9,
1297
+ detector: "ac-stale",
1298
+ autoFix: async () => {
1299
+ const newContent = content.replace(
1300
+ new RegExp(
1301
+ `(- \\[ \\] \\*\\*\`)(${escapeRegex(command)}(\\s[^*]+)?\\*\\*)`
1302
+ ),
1303
+ (m) => m.replace("[ ]", "[x]")
1304
+ );
1305
+ const before = readFileSync4(specFile, "utf-8");
1306
+ return {
1307
+ files: [
1308
+ {
1309
+ path: `.letra/specs/${dir.name}/spec.md`,
1310
+ before,
1311
+ after: newContent
1312
+ }
1313
+ ],
1314
+ snapshotId: ""
1315
+ };
1316
+ }
1317
+ });
1318
+ }
1319
+ }
1320
+ }
1321
+ return results;
1322
+ }
1323
+ };
1324
+
1325
+ // src/diagnostics/detectors/missing-dir.ts
1326
+ import { existsSync as existsSync7, mkdirSync as mkdirSync3 } from "fs";
1327
+ import { join as join6 } from "path";
1328
+ var REQUIRED_DIRS = [
1329
+ {
1330
+ path: "templates",
1331
+ spec: "spec-templates-domain",
1332
+ description: "templates customizados de specs"
1333
+ },
1334
+ { path: "brand", spec: "flow-serve", description: "logos SVG do Letra" }
1335
+ ];
1336
+ var missingDirDetector = {
1337
+ name: "missing-dir",
1338
+ async run(rootDir) {
1339
+ const results = [];
1340
+ const dataDir = getLetraDir2(rootDir);
1341
+ for (const required of REQUIRED_DIRS) {
1342
+ const dirPath = join6(dataDir, required.path);
1343
+ if (existsSync7(dirPath)) continue;
1344
+ results.push({
1345
+ id: `missing-dir_${required.path.replace(/[/.]/g, "-")}`,
1346
+ type: "info",
1347
+ title: `Diret\xF3rio ausente: ${required.path}/`,
1348
+ description: `O diret\xF3rio ${required.path}/ \xE9 referenciado pelo spec ${required.spec} (${required.description}), mas n\xE3o existe no dataDir do workspace.`,
1349
+ certainty: 1,
1350
+ detector: "missing-dir",
1351
+ autoFix: async () => ({
1352
+ files: [],
1353
+ snapshotId: ""
1354
+ })
1355
+ });
1356
+ }
1357
+ for (const r of results) {
1358
+ const originalAutoFix = r.autoFix;
1359
+ if (!originalAutoFix) continue;
1360
+ r.autoFix = async () => {
1361
+ const dirs = [];
1362
+ for (const required of REQUIRED_DIRS) {
1363
+ const dirPath = join6(dataDir, required.path);
1364
+ if (existsSync7(dirPath)) continue;
1365
+ mkdirSync3(dirPath, { recursive: true });
1366
+ dirs.push(required.path);
1367
+ }
1368
+ return {
1369
+ files: [],
1370
+ snapshotId: ""
1371
+ };
1372
+ };
1373
+ }
1374
+ return results;
1375
+ }
1376
+ };
1377
+
1378
+ // src/diagnostics/detectors/stage-drift.ts
1379
+ import { readFileSync as readFileSync5, existsSync as existsSync8 } from "fs";
1380
+ import { join as join7 } from "path";
1381
+ var STALE_AC_PATTERN2 = /-\s\[ \]\s\*\*`([^`]+)`\*\*/g;
1382
+ var DONE_AC_PATTERN = /-\s\[x\]\s\*\*`([^`]+)`\*\*/g;
1383
+ var stageDriftDetector = {
1384
+ name: "stage-drift",
1385
+ async run(rootDir) {
1386
+ const results = [];
1387
+ const workflowFile = join7(getLetraDir2(rootDir), "workflow.json");
1388
+ if (!existsSync8(workflowFile)) return results;
1389
+ const workflow = JSON.parse(readFileSync5(workflowFile, "utf-8"));
1390
+ const items = workflow.items || [];
1391
+ const stages = workflow.stages || [];
1392
+ const doneStageIds = stages.filter((s) => s.zone === "done").map((s) => s.id);
1393
+ const reviewStageIds = stages.filter(
1394
+ (s) => s.name?.toLowerCase() === "review" || s.id === "review"
1395
+ ).map((s) => s.id);
1396
+ for (const item of items) {
1397
+ if (!item.spec) continue;
1398
+ const specDir = join7(getLetraDir2(rootDir), "specs", item.spec);
1399
+ const specFile = join7(specDir, "spec.md");
1400
+ if (!existsSync8(specFile)) continue;
1401
+ const content = readFileSync5(specFile, "utf-8");
1402
+ const staleMatches = [...content.matchAll(STALE_AC_PATTERN2)];
1403
+ const doneMatches = [...content.matchAll(DONE_AC_PATTERN)];
1404
+ const totalACs = staleMatches.length + doneMatches.length;
1405
+ if (totalACs === 0) continue;
1406
+ const pctDone = doneMatches.length / totalACs;
1407
+ const isInReview = reviewStageIds.includes(item.stage);
1408
+ const isInBacklog = item.stage === "backlog";
1409
+ if (pctDone === 1 && (isInReview || isInBacklog)) {
1410
+ results.push({
1411
+ id: `stage-drift_${item.id}`,
1412
+ type: "info",
1413
+ title: `${item.id} (${item.description}) \u2014 100% ACs prontos`,
1414
+ description: `O item ${item.id} (${item.description}) tem ${doneMatches.length}/${totalACs} ACs implementados. Est\xE1 em "${item.stage}" mas deveria estar em "done".`,
1415
+ certainty: 0.85,
1416
+ detector: "stage-drift",
1417
+ autoFix: async () => {
1418
+ const before = readFileSync5(workflowFile, "utf-8");
1419
+ const newWorkflow = JSON.parse(before);
1420
+ const target = newWorkflow.items.find(
1421
+ (i) => i.id === item.id
1422
+ );
1423
+ if (target) {
1424
+ target.stage = doneStageIds[0] || "done";
1425
+ target.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1426
+ }
1427
+ const after = JSON.stringify(newWorkflow, null, 2);
1428
+ return {
1429
+ files: [{ path: ".letra/workflow.json", before, after }],
1430
+ snapshotId: ""
1431
+ };
1432
+ }
1433
+ });
1434
+ } else if (pctDone > 0 && pctDone < 1 && isInBacklog) {
1435
+ const doingStage = stages.find((s) => s.zone === "doing") ?? stages.find((_s, i) => i > 0);
1436
+ const stageHint = doingStage ? `"${doingStage.name || doingStage.id}"` : "o pr\xF3ximo est\xE1gio";
1437
+ results.push({
1438
+ id: `stage-drift_${item.id}_partial`,
1439
+ type: "info",
1440
+ title: `${item.id} (${item.description}) \u2014 ${doneMatches.length}/${totalACs} ACs prontos`,
1441
+ description: `O item ${item.id} tem ${doneMatches.length}/${totalACs} ACs implementados mas est\xE1 em backlog. Considere mover para ${stageHint}.`,
1442
+ certainty: 0.7,
1443
+ detector: "stage-drift"
1444
+ });
1445
+ }
1446
+ }
1447
+ return results;
1448
+ }
1449
+ };
1450
+
1451
+ // src/diagnostics/detectors/harness-stale.ts
1452
+ import { existsSync as existsSync9, readFileSync as readFileSync6 } from "fs";
1453
+ import { join as join8 } from "path";
1454
+ var ADAPTER_FILES = adapterDiagnosticFiles();
1455
+ var harnessStaleDetector = {
1456
+ name: "harness-stale",
1457
+ async run(rootDir) {
1458
+ const results = [];
1459
+ const workflowFile = join8(getLetraDir2(rootDir), "workflow.json");
1460
+ let tools = ["cursor", "opencode", "vscode"];
1461
+ let workflow;
1462
+ if (existsSync9(workflowFile)) {
1463
+ try {
1464
+ const wf = JSON.parse(readFileSync6(workflowFile, "utf-8"));
1465
+ if (Array.isArray(wf.tools)) {
1466
+ tools = wf.tools;
1467
+ }
1468
+ workflow = wf;
1469
+ } catch {
1470
+ }
1471
+ }
1472
+ const staleTools = [];
1473
+ for (const tool of tools) {
1474
+ const info = ADAPTER_FILES[tool];
1475
+ if (!info) continue;
1476
+ const filePath = join8(rootDir, info.path);
1477
+ if (!existsSync9(filePath)) continue;
1478
+ const content = readFileSync6(filePath, "utf-8");
1479
+ let isStale = false;
1480
+ if (info.format === "at") {
1481
+ if (!content.includes("@.letra/context.md") || !content.includes("@.letra/constitution.md")) {
1482
+ isStale = true;
1483
+ }
1484
+ } else {
1485
+ if (!content.includes(".letra/context.md") || !content.includes(".letra/constitution.md")) {
1486
+ isStale = true;
1487
+ }
1488
+ }
1489
+ if (isStale) staleTools.push(tool);
1490
+ }
1491
+ if (staleTools.length > 0) {
1492
+ const doneStageIds = new Set(
1493
+ (workflow?.stages || []).filter((s) => s.id === "done" || s.zone === "done").map((s) => s.id)
1494
+ );
1495
+ const backlogStageIds = new Set(
1496
+ (workflow?.stages || []).filter((s) => s.id === "backlog" || s.zone === "todo").map((s) => s.id)
1497
+ );
1498
+ let activeStageId;
1499
+ let primaryItemId;
1500
+ if (workflow) {
1501
+ const activeItem = workflow.items.find(
1502
+ (i) => !doneStageIds.has(i.stage) && !backlogStageIds.has(i.stage)
1503
+ );
1504
+ if (activeItem) {
1505
+ activeStageId = activeItem.stage;
1506
+ primaryItemId = activeItem.id;
1507
+ }
1508
+ }
1509
+ results.push({
1510
+ id: "harness-stale_all",
1511
+ type: "info",
1512
+ title: `Adaptadores desatualizados: ${staleTools.join(", ")}`,
1513
+ description: `Regenerando ${staleTools.length} adaptador(es) sem refer\xEAncias L1.`,
1514
+ certainty: 1,
1515
+ detector: "harness-stale",
1516
+ autoFix: async () => {
1517
+ const files = [];
1518
+ for (const tool of staleTools) {
1519
+ const info = ADAPTER_FILES[tool];
1520
+ if (!info) continue;
1521
+ const fp = join8(rootDir, info.path);
1522
+ if (existsSync9(fp)) {
1523
+ files.push({
1524
+ path: info.path.replace(/\\/g, "/"),
1525
+ before: readFileSync6(fp, "utf-8"),
1526
+ after: ""
1527
+ });
1528
+ }
1529
+ }
1530
+ const { generateAdapters: generateAdapters2 } = await import("./generate-N22QOXUF.js");
1531
+ generateAdapters2(rootDir, tools, {
1532
+ source: "flow-move",
1533
+ workflow,
1534
+ activeStageId,
1535
+ primaryItemId,
1536
+ quiet: true,
1537
+ verb: "Updated"
1538
+ });
1539
+ for (const file of files) {
1540
+ file.after = readFileSync6(join8(rootDir, file.path), "utf-8");
1541
+ }
1542
+ return { files, snapshotId: "" };
1543
+ }
1544
+ });
1545
+ }
1546
+ return results;
1547
+ }
1548
+ };
1549
+
1550
+ // src/diagnostics/detectors/ac-false-pos.ts
1551
+ import { readFileSync as readFileSync7, existsSync as existsSync10, readdirSync as readdirSync6 } from "fs";
1552
+ import { join as join9 } from "path";
1553
+ var DONE_AC_PATTERN2 = /-\s\[x\]\s\*\*`([^`]+)`\*\*/g;
1554
+ function toCamelCase2(words) {
1555
+ return words.map((w, i) => i === 0 ? w : w.charAt(0).toUpperCase() + w.slice(1)).join("");
1556
+ }
1557
+ function toPascalCase2(words) {
1558
+ return words.map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("");
1559
+ }
1560
+ function toKebabCase(words) {
1561
+ return words.join("-");
1562
+ }
1563
+ function toSnakeCase(words) {
1564
+ return words.join("_");
1565
+ }
1566
+ function extractSearchTerms(command) {
1567
+ const words = command.split(/\s+/);
1568
+ const terms = [command];
1569
+ if (words.length > 1) {
1570
+ terms.push(toCamelCase2(words));
1571
+ terms.push(toPascalCase2(words));
1572
+ terms.push(toKebabCase(words));
1573
+ terms.push(toSnakeCase(words));
1574
+ }
1575
+ const baseCommand = words[0];
1576
+ if (baseCommand) {
1577
+ terms.push(baseCommand);
1578
+ const baseWords = baseCommand.split(/[\s-_]+/);
1579
+ if (baseWords.length > 1) {
1580
+ terms.push(toCamelCase2(baseWords));
1581
+ terms.push(toKebabCase(baseWords));
1582
+ }
1583
+ }
1584
+ const nonFlagWords = words.filter((w) => !w.startsWith("-"));
1585
+ if (nonFlagWords.length < words.length && nonFlagWords.length > 0) {
1586
+ terms.push(nonFlagWords.join(" "));
1587
+ if (nonFlagWords.length > 1) {
1588
+ terms.push(toCamelCase2(nonFlagWords));
1589
+ terms.push(toKebabCase(nonFlagWords));
1590
+ }
1591
+ }
1592
+ if (nonFlagWords.length > 1) {
1593
+ const subCommandWords = nonFlagWords.slice(1);
1594
+ for (const word of subCommandWords) {
1595
+ if (word.length >= 3) {
1596
+ terms.push(word);
1597
+ }
1598
+ }
1599
+ if (subCommandWords.length > 1) {
1600
+ terms.push(toCamelCase2(subCommandWords));
1601
+ terms.push(toKebabCase(subCommandWords));
1602
+ terms.push(toSnakeCase(subCommandWords));
1603
+ }
1604
+ const parentWords = nonFlagWords.slice(0, -1);
1605
+ if (parentWords.length >= 1) {
1606
+ const lastWord = nonFlagWords[nonFlagWords.length - 1];
1607
+ if (lastWord.length >= 2) {
1608
+ terms.push(toCamelCase2([...parentWords, lastWord]));
1609
+ terms.push(toKebabCase([...parentWords, lastWord]));
1610
+ terms.push(toSnakeCase([...parentWords, lastWord]));
1611
+ }
1612
+ }
1613
+ }
1614
+ return [...new Set(terms)].filter((t) => t.length > 2);
1615
+ }
1616
+ function isApiEndpoint(command) {
1617
+ return /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+/i.test(command);
1618
+ }
1619
+ function extractApiPath(command) {
1620
+ const match = command.match(/^(?:GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+(.+)$/i);
1621
+ if (!match) return [];
1622
+ const path = match[1].trim();
1623
+ const terms = [path];
1624
+ if (path !== "/") {
1625
+ const parts = path.split("/").filter(Boolean);
1626
+ terms.push(...parts);
1627
+ }
1628
+ return [...new Set(terms)].filter((t) => t.length > 1);
1629
+ }
1630
+ var acFalsePosDetector = {
1631
+ name: "ac-false-pos",
1632
+ devOnly: true,
1633
+ async run(rootDir) {
1634
+ const results = [];
1635
+ const specsDir = join9(getLetraDir2(rootDir), "specs");
1636
+ if (!existsSync10(specsDir)) return results;
1637
+ const specDirs = readdirSync6(specsDir, { withFileTypes: true }).filter(
1638
+ (d) => d.isDirectory() && !d.name.startsWith("_")
1639
+ );
1640
+ for (const dir of specDirs) {
1641
+ const specFile = join9(specsDir, dir.name, "spec.md");
1642
+ if (!existsSync10(specFile)) continue;
1643
+ const content = readFileSync7(specFile, "utf-8");
1644
+ const matches = [...content.matchAll(DONE_AC_PATTERN2)];
1645
+ for (const match of matches) {
1646
+ const command = match[1].trim();
1647
+ if (!command) continue;
1648
+ let searchTerms;
1649
+ if (isApiEndpoint(command)) {
1650
+ searchTerms = extractApiPath(command);
1651
+ if (searchTerms.length === 0) continue;
1652
+ } else {
1653
+ searchTerms = extractSearchTerms(command);
1654
+ }
1655
+ const foundInSource = searchInSource(rootDir, searchTerms);
1656
+ if (!foundInSource) {
1657
+ results.push({
1658
+ id: `ac-false-pos_${dir.name}_${command.replace(/\s+/g, "-")}`,
1659
+ type: "warning",
1660
+ title: `AC "${command}" marcado [x] mas n\xE3o encontrado no c\xF3digo`,
1661
+ description: `O acceptance criteria "${command}" do spec ${dir.name} est\xE1 marcado como feito ([x]), mas o c\xF3digo-fonte n\xE3o cont\xE9m implementa\xE7\xE3o correspondente. Pode ser um falso positivo.`,
1662
+ certainty: 0.7,
1663
+ detector: "ac-false-pos"
1664
+ });
1665
+ }
1666
+ }
1667
+ }
1668
+ return results;
1669
+ }
1670
+ };
1671
+
1672
+ // src/diagnostics/detectors/missing-spec-link.ts
1673
+ import { existsSync as existsSync11, readFileSync as readFileSync8, readdirSync as readdirSync7 } from "fs";
1674
+ import { join as join10 } from "path";
1675
+ var missingSpecLinkDetector = {
1676
+ name: "missing-spec-link",
1677
+ async run(rootDir) {
1678
+ const results = [];
1679
+ const workflowFile = join10(getLetraDir2(rootDir), "workflow.json");
1680
+ if (!existsSync11(workflowFile)) return results;
1681
+ const workflow = JSON.parse(readFileSync8(workflowFile, "utf-8"));
1682
+ const items = workflow.items || [];
1683
+ const stages = workflow.stages || [];
1684
+ const specLinks = workflow.specLinks || {};
1685
+ const backlogStageIds = new Set(
1686
+ stages.filter(
1687
+ (s) => s.zone === "todo" || s.id === "backlog"
1688
+ ).map((s) => s.id)
1689
+ );
1690
+ for (const item of items) {
1691
+ if (backlogStageIds.has(item.stage)) continue;
1692
+ if (!item.spec) {
1693
+ results.push({
1694
+ id: `missing-spec-link_${item.id}`,
1695
+ type: "info",
1696
+ title: `${item.id}: sem spec linkada`,
1697
+ description: `O item ${item.id} (${item.description}) est\xE1 em "${item.stage}" mas n\xE3o tem spec associada. Link usando: letra flow edit ${item.id} --spec <nome>`,
1698
+ certainty: 0.9,
1699
+ detector: "missing-spec-link",
1700
+ autoFix: async () => {
1701
+ const kebab = item.description.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
1702
+ const specsDir = join10(getLetraDir2(rootDir), "specs");
1703
+ if (!existsSync11(specsDir)) return { files: [], snapshotId: "no-op" };
1704
+ const specDirs = readdirSync7(specsDir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name);
1705
+ const exact = specDirs.find((d) => d === kebab);
1706
+ if (exact) {
1707
+ const before = readFileSync8(workflowFile, "utf-8");
1708
+ const wf = JSON.parse(before);
1709
+ const target = wf.items.find((i) => i.id === item.id);
1710
+ if (target) {
1711
+ target.spec = exact;
1712
+ if (!wf.specLinks) wf.specLinks = {};
1713
+ wf.specLinks[exact] = { path: `.letra/specs/${exact}/spec.md` };
1714
+ wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1715
+ return {
1716
+ files: [
1717
+ {
1718
+ path: ".letra/workflow.json",
1719
+ before,
1720
+ after: JSON.stringify(wf, null, 2)
1721
+ }
1722
+ ],
1723
+ snapshotId: "auto-fix"
1724
+ };
1725
+ }
1726
+ }
1727
+ const partial = specDirs.find(
1728
+ (d) => kebab.includes(d) || d.includes(kebab)
1729
+ );
1730
+ if (partial) {
1731
+ const before = readFileSync8(workflowFile, "utf-8");
1732
+ const wf = JSON.parse(before);
1733
+ const target = wf.items.find((i) => i.id === item.id);
1734
+ if (target) {
1735
+ target.spec = partial;
1736
+ if (!wf.specLinks) wf.specLinks = {};
1737
+ wf.specLinks[partial] = { path: `.letra/specs/${partial}/spec.md` };
1738
+ wf.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1739
+ return {
1740
+ files: [
1741
+ {
1742
+ path: ".letra/workflow.json",
1743
+ before,
1744
+ after: JSON.stringify(wf, null, 2)
1745
+ }
1746
+ ],
1747
+ snapshotId: "auto-fix"
1748
+ };
1749
+ }
1750
+ }
1751
+ return { files: [], snapshotId: "no-op" };
1752
+ }
1753
+ });
1754
+ continue;
1755
+ }
1756
+ const specPath = join10(getLetraDir2(rootDir), "specs", item.spec, "spec.md");
1757
+ if (!existsSync11(specPath)) {
1758
+ results.push({
1759
+ id: `missing-spec-link_${item.id}_notfound`,
1760
+ type: "warning",
1761
+ title: `${item.id}: spec linkada n\xE3o encontrada em disco`,
1762
+ description: `Item ${item.id} referencia spec "${item.spec}" mas ${specPath} n\xE3o existe.`,
1763
+ certainty: 0.9,
1764
+ detector: "missing-spec-link"
1765
+ });
1766
+ continue;
1767
+ }
1768
+ if (!specLinks[item.spec]) {
1769
+ results.push({
1770
+ id: `missing-spec-link_${item.id}_unregistered`,
1771
+ type: "info",
1772
+ title: `${item.id}: spec n\xE3o registrada em specLinks`,
1773
+ description: `Item ${item.id} tem spec="${item.spec}" mas specLinks n\xE3o cont\xE9m entrada para "${item.spec}".`,
1774
+ certainty: 0.7,
1775
+ detector: "missing-spec-link"
1776
+ });
1777
+ }
1778
+ }
1779
+ return results;
1780
+ }
1781
+ };
1782
+
1783
+ // src/diagnostics/detectors/focus-stale.ts
1784
+ import { existsSync as existsSync12, readFileSync as readFileSync9 } from "fs";
1785
+ import { join as join11 } from "path";
1786
+ var focusStaleDetector = {
1787
+ name: "focus-stale",
1788
+ async run(rootDir) {
1789
+ const results = [];
1790
+ const focusFile = join11(getLetraDir2(rootDir), "focus.md");
1791
+ if (!existsSync12(focusFile)) return results;
1792
+ const focusContent = readFileSync9(focusFile, "utf-8");
1793
+ const firstLine = focusContent.split("\n")[0]?.trim() ?? "";
1794
+ const specMatch = firstLine.match(/^#\s*Focus:\s*(.+)$/i);
1795
+ if (!specMatch) return results;
1796
+ const focusSpec = specMatch[1].trim();
1797
+ const specDir = join11(getLetraDir2(rootDir), "specs", focusSpec);
1798
+ if (!existsSync12(specDir)) {
1799
+ results.push({
1800
+ id: `focus-stale_missing-dir_${focusSpec}`,
1801
+ type: "warning",
1802
+ title: `focusSpec "${focusSpec}" n\xE3o encontrada em disco`,
1803
+ description: `focus.md referencia a spec "${focusSpec}" mas o diret\xF3rio .letra/specs/${focusSpec}/ n\xE3o existe. Use 'letra focus --clear' para limpar o foco.`,
1804
+ certainty: 1,
1805
+ detector: "focus-stale"
1806
+ });
1807
+ return results;
1808
+ }
1809
+ const workflowFile = join11(getLetraDir2(rootDir), "workflow.json");
1810
+ if (!existsSync12(workflowFile)) return results;
1811
+ const workflow = JSON.parse(readFileSync9(workflowFile, "utf-8"));
1812
+ const specLinks = workflow.specLinks || {};
1813
+ if (!specLinks[focusSpec]) {
1814
+ results.push({
1815
+ id: `focus-stale_unregistered_${focusSpec}`,
1816
+ type: "info",
1817
+ title: `focusSpec "${focusSpec}" n\xE3o registrada em specLinks`,
1818
+ description: `focus.md referencia a spec "${focusSpec}" mas specLinks n\xE3o cont\xE9m entrada para ela.`,
1819
+ certainty: 0.7,
1820
+ detector: "focus-stale"
1821
+ });
1822
+ }
1823
+ return results;
1824
+ }
1825
+ };
1826
+
1827
+ // src/diagnostics/engine.ts
1828
+ var DiagnosticEngine = class {
1829
+ rootDir;
1830
+ snapshots;
1831
+ projectType;
1832
+ detectors = [
1833
+ acStaleDetector,
1834
+ acFalsePosDetector,
1835
+ missingDirDetector,
1836
+ stageDriftDetector,
1837
+ harnessStaleDetector,
1838
+ missingSpecLinkDetector,
1839
+ focusStaleDetector
1840
+ ];
1841
+ lastOutput = {
1842
+ fixes: [],
1843
+ suggestions: [],
1844
+ errors: []
1845
+ };
1846
+ lastResults = [];
1847
+ appliedFixes = /* @__PURE__ */ new Set();
1848
+ constructor(rootDir, projectType = "software") {
1849
+ this.rootDir = rootDir;
1850
+ this.projectType = projectType;
1851
+ this.snapshots = new SnapshotStore(rootDir);
1852
+ }
1853
+ getLastResults() {
1854
+ return [...this.lastResults];
1855
+ }
1856
+ async runAll() {
1857
+ const output = { fixes: [], suggestions: [], errors: [] };
1858
+ const newApplied = /* @__PURE__ */ new Set();
1859
+ const allResults = [];
1860
+ for (const detector of this.detectors) {
1861
+ if (detector.devOnly && this.projectType !== "software") {
1862
+ continue;
1863
+ }
1864
+ try {
1865
+ const results = await detector.run(this.rootDir);
1866
+ allResults.push(...results);
1867
+ for (const result of results) {
1868
+ if (result.autoFix && result.certainty >= 0.9) {
1869
+ if (this.appliedFixes.has(result.id)) {
1870
+ continue;
1871
+ }
1872
+ try {
1873
+ const fix = await result.autoFix();
1874
+ if (fix.files.length === 0) continue;
1875
+ const snapshotId = await this.snapshots.save(
1876
+ result.id,
1877
+ result.title,
1878
+ fix.files
1879
+ );
1880
+ for (const file of fix.files) {
1881
+ const absPath = join12(this.rootDir, file.path);
1882
+ if (file.path === ".letra/workflow.json") {
1883
+ const workflow = JSON.parse(file.after);
1884
+ writeWorkflow(this.rootDir, {
1885
+ workflow,
1886
+ source: "stage-drift",
1887
+ skipSitrep: true,
1888
+ quiet: true,
1889
+ skipEngine: true
1890
+ });
1891
+ } else {
1892
+ writeFileSync3(absPath, file.after, "utf-8");
1893
+ }
1894
+ }
1895
+ newApplied.add(result.id);
1896
+ if (snapshotId) {
1897
+ output.fixes.push({
1898
+ id: result.id,
1899
+ title: result.title,
1900
+ description: result.description,
1901
+ snapshotId
1902
+ });
1903
+ }
1904
+ } catch (fixError) {
1905
+ output.errors.push(`Auto-fix falhou para ${result.id}: ${fixError}`);
1906
+ }
1907
+ } else {
1908
+ output.suggestions.push({
1909
+ id: result.id,
1910
+ title: result.title,
1911
+ description: result.description,
1912
+ type: result.type,
1913
+ detector: result.detector
1914
+ });
1915
+ }
1916
+ }
1917
+ } catch (detError) {
1918
+ output.errors.push(`Detector ${detector.name} falhou: ${detError}`);
1919
+ }
1920
+ }
1921
+ this.appliedFixes = newApplied;
1922
+ this.lastOutput = output;
1923
+ this.lastResults = allResults;
1924
+ return output;
1925
+ }
1926
+ getLastOutput() {
1927
+ return this.lastOutput;
1928
+ }
1929
+ async undo(snapshotId) {
1930
+ return this.snapshots.restore(snapshotId);
1931
+ }
1932
+ async redo(snapshotId) {
1933
+ return this.snapshots.redo(snapshotId);
1934
+ }
1935
+ listSnapshots() {
1936
+ return this.snapshots.list();
1937
+ }
1938
+ ensureDirs() {
1939
+ const requiredDirs = ["templates", "brand", "snapshots"];
1940
+ const dataDir = getLetraDir2(this.rootDir);
1941
+ for (const dir of requiredDirs) {
1942
+ const fullPath = join12(dataDir, dir);
1943
+ if (!existsSync13(fullPath)) {
1944
+ try {
1945
+ const { mkdirSync: mkdirSync6 } = __require("fs");
1946
+ mkdirSync6(fullPath, { recursive: true });
1947
+ } catch {
1948
+ }
1949
+ }
1950
+ }
1951
+ }
1952
+ };
1953
+
1954
+ // src/commands/flow-init.ts
1955
+ function askText(query, defaultValue) {
1956
+ if (!process.stdin.isTTY) return Promise.resolve(defaultValue);
1957
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
1958
+ return new Promise((resolve3) => {
1959
+ const formatted = `${chalk.cyan(query)} ${chalk.gray(`(default: ${defaultValue})`)}
1960
+ > `;
1961
+ rl.question(formatted, (answer) => {
1962
+ rl.close();
1963
+ resolve3(answer.trim() || defaultValue);
1964
+ });
1965
+ });
1966
+ }
1967
+ function detectExistingTools(root) {
1968
+ return Object.values(ADAPTER_REGISTRY).filter((adapter) => adapter.detectionPaths.some((path) => existsSync14(join13(root, path)))).map((adapter) => adapter.id);
1969
+ }
1970
+ function detectProjectName(root) {
1971
+ const pkgPath = join13(root, "package.json");
1972
+ if (existsSync14(pkgPath)) {
1973
+ try {
1974
+ const pkg = JSON.parse(readFileSync10(pkgPath, "utf-8"));
1975
+ if (pkg.name) return pkg.name.replace(/^@[^/]+\//, "");
1976
+ } catch {
1977
+ }
1978
+ }
1979
+ return resolve2(root).split(/[\\/]/).pop() || "meu-projeto";
1980
+ }
1981
+ function stagesFromInput(input) {
1982
+ return input.split(",").map((s, i) => {
1983
+ const trimmed = s.trim();
1984
+ if (!trimmed) return null;
1985
+ return {
1986
+ id: trimmed.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, ""),
1987
+ name: trimmed.charAt(0).toUpperCase() + trimmed.slice(1),
1988
+ order: i
1989
+ };
1990
+ }).filter((s) => s !== null);
1991
+ }
1992
+ function now() {
1993
+ return (/* @__PURE__ */ new Date()).toISOString();
1994
+ }
1995
+ function cloneStagePhases(phases) {
1996
+ if (!phases) return void 0;
1997
+ return {
1998
+ initialState: phases.initialState,
1999
+ states: Object.fromEntries(
2000
+ Object.entries(phases.states).map(([phaseId, phaseDef]) => [
2001
+ phaseId,
2002
+ {
2003
+ ...phaseDef,
2004
+ actions: phaseDef.actions ? phaseDef.actions.map((action) => ({ ...action })) : void 0,
2005
+ transitions: phaseDef.transitions ? phaseDef.transitions.map((transition) => ({ ...transition })) : void 0,
2006
+ harness: phaseDef.harness ? {
2007
+ ...phaseDef.harness,
2008
+ tools: phaseDef.harness.tools ? [...phaseDef.harness.tools] : void 0,
2009
+ checks: phaseDef.harness.checks ? [...phaseDef.harness.checks] : void 0
2010
+ } : void 0
2011
+ }
2012
+ ])
2013
+ )
2014
+ };
2015
+ }
2016
+ function stageFromTemplateStage(stage) {
2017
+ return {
2018
+ id: stage.id,
2019
+ name: stage.name,
2020
+ order: stage.order,
2021
+ zone: stage.zone,
2022
+ phases: cloneStagePhases(stage.phases)
2023
+ };
2024
+ }
2025
+ function workflowFilePath(root) {
2026
+ return join13(getLetraDir2(root), "workflow.json");
2027
+ }
2028
+ function normalizedPath(path) {
2029
+ return path.replace(/\\/g, "/");
2030
+ }
2031
+ function locationLabel(path, fallback) {
2032
+ const name = basename2(normalizedPath(path));
2033
+ return name || fallback;
2034
+ }
2035
+ function migrateTargetsToLocations(workflow) {
2036
+ let migrated = false;
2037
+ const locations = Array.isArray(workflow.locations) ? workflow.locations.map((location, index) => ({
2038
+ id: location.id || `loc-${index + 1}`,
2039
+ path: normalizedPath(location.path),
2040
+ label: location.label || locationLabel(location.path, `Projeto ${index + 1}`),
2041
+ adapters: Array.isArray(location.adapters) ? [...new Set(location.adapters)] : []
2042
+ })) : [];
2043
+ if (Array.isArray(workflow.locations)) {
2044
+ migrated = workflow.locations.some(
2045
+ (location, index) => location.path !== locations[index]?.path || location.label !== locations[index]?.label || !Array.isArray(location.adapters)
2046
+ );
2047
+ }
2048
+ const byPath = new Map(locations.map((location) => [normalizedPath(location.path), location]));
2049
+ if (Array.isArray(workflow.targets) && workflow.targets.length > 0) {
2050
+ for (const target of workflow.targets) {
2051
+ const targetPath = normalizedPath(target.path);
2052
+ const targetAdapters = Array.isArray(target.adapters) ? target.adapters : [];
2053
+ const existing = byPath.get(targetPath);
2054
+ if (existing) {
2055
+ existing.adapters = [.../* @__PURE__ */ new Set([...existing.adapters, ...targetAdapters])];
2056
+ } else {
2057
+ const location = {
2058
+ id: target.id?.replace(/^target-/, "loc-") || `loc-${locations.length + 1}`,
2059
+ path: targetPath,
2060
+ label: locationLabel(targetPath, `Projeto ${locations.length + 1}`),
2061
+ adapters: [...new Set(targetAdapters)]
2062
+ };
2063
+ locations.push(location);
2064
+ byPath.set(targetPath, location);
2065
+ }
2066
+ }
2067
+ workflow.targets = void 0;
2068
+ migrated = true;
2069
+ }
2070
+ if (Array.isArray(workflow.locations) || migrated) {
2071
+ workflow.locations = locations;
2072
+ }
2073
+ return { workflow, migrated };
2074
+ }
2075
+ function loadWorkflow(root) {
2076
+ const filePath = workflowFilePath(root);
2077
+ if (!existsSync14(filePath)) return null;
2078
+ try {
2079
+ const workflow = JSON.parse(readFileSync10(filePath, "utf-8"));
2080
+ const result = migrateTargetsToLocations(workflow);
2081
+ if (result.migrated) {
2082
+ result.workflow.updatedAt = now();
2083
+ writeFileSync4(filePath, JSON.stringify(result.workflow, null, 2), "utf-8");
2084
+ }
2085
+ return result.workflow;
2086
+ } catch {
2087
+ return null;
2088
+ }
2089
+ }
2090
+ function saveWorkflow(root, workflow) {
2091
+ const dir = getLetraDir2(root);
2092
+ if (!existsSync14(dir)) mkdirSync4(dir, { recursive: true });
2093
+ const filePath = workflowFilePath(root);
2094
+ if (existsSync14(filePath)) {
2095
+ const backupDir = join13(getLetraDir2(root), "backups");
2096
+ if (!existsSync14(backupDir)) mkdirSync4(backupDir, { recursive: true });
2097
+ const ts = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
2098
+ const backupPath = join13(backupDir, `workflow-${ts}.json`);
2099
+ try {
2100
+ const existing = readFileSync10(filePath, "utf-8");
2101
+ writeFileSync4(backupPath, existing, "utf-8");
2102
+ } catch {
2103
+ }
2104
+ }
2105
+ writeFileSync4(filePath, JSON.stringify(workflow, null, 2));
2106
+ }
2107
+ var ADAPTER_TARGETS = {
2108
+ cursor: ".cursorrules",
2109
+ opencode: "AGENTS.md",
2110
+ vscode: ".github/copilot-instructions.md",
2111
+ "claude-code": "CLAUDE.md",
2112
+ windsurf: ".windsurfrules",
2113
+ hermes: ".hermes/instructions.md"
2114
+ };
2115
+ async function writeWorkflow(root, options) {
2116
+ const {
2117
+ workflow,
2118
+ source,
2119
+ primaryItemId,
2120
+ skipAdapters,
2121
+ skipSitrep,
2122
+ skipLog,
2123
+ skipEngine,
2124
+ quiet,
2125
+ confineAdapterWrites,
2126
+ resolution
2127
+ } = options;
2128
+ if (!workflow.items || !Array.isArray(workflow.items)) {
2129
+ return { ok: false, filesUpdated: [], error: "workflow.items must be an array" };
2130
+ }
2131
+ if (!workflow.stages || !Array.isArray(workflow.stages)) {
2132
+ return { ok: false, filesUpdated: [], error: "workflow.stages must be an array" };
2133
+ }
2134
+ const filesUpdated = [];
2135
+ let graveIssueCount = 0;
2136
+ if (primaryItemId) workflow.primaryItemId = primaryItemId;
2137
+ saveWorkflow(root, workflow);
2138
+ filesUpdated.push(".letra/workflow.json");
2139
+ if (!skipEngine) {
2140
+ try {
2141
+ const engine = new DiagnosticEngine(resolution?.workspaceDir ?? root);
2142
+ const diagOutput = await engine.runAll();
2143
+ const rawResults = engine.getLastResults();
2144
+ const hrRoot = resolution?.workspaceDir ?? root;
2145
+ const healthRecord = loadHealthRecord(hrRoot);
2146
+ mergeScanResults(healthRecord, rawResults);
2147
+ saveHealthRecord(hrRoot, healthRecord);
2148
+ graveIssueCount = diagOutput.suggestions.filter((s) => s.type === "error").length;
2149
+ if (diagOutput.errors.length > 0) {
2150
+ graveIssueCount += diagOutput.errors.length;
2151
+ }
2152
+ if (!quiet) {
2153
+ const totalIssues = diagOutput.fixes.length + diagOutput.suggestions.length;
2154
+ if (totalIssues > 0) {
2155
+ console.log(
2156
+ chalk.gray(
2157
+ ` Diagn\xF3stico: ${totalIssues} issue(s), ${diagOutput.fixes.length} auto-corrigido(s)`
2158
+ )
2159
+ );
2160
+ }
2161
+ }
2162
+ } catch (e) {
2163
+ if (!quiet) {
2164
+ console.log(chalk.yellow(` Diagn\xF3stico ignorado: ${e}`));
2165
+ }
2166
+ }
2167
+ }
2168
+ if (!skipAdapters && workflow.tools && workflow.tools.length > 0) {
2169
+ const activeStage = primaryItemId ? workflow.items.find((i) => i.id === primaryItemId)?.stage : workflow.items[0]?.stage;
2170
+ const adapterOpts = {
2171
+ source: "flow-move",
2172
+ workflow: {
2173
+ name: workflow.name,
2174
+ stages: workflow.stages,
2175
+ items: workflow.items
2176
+ },
2177
+ activeStageId: activeStage || workflow.stages[0]?.id || "backlog",
2178
+ primaryItemId: primaryItemId || workflow.items[0]?.id,
2179
+ graveIssueCount: graveIssueCount > 0 ? graveIssueCount : void 0,
2180
+ workspaceDir: resolution?.workspaceDir,
2181
+ quiet,
2182
+ confineWrites: confineAdapterWrites
2183
+ };
2184
+ generateAdapters(root, workflow.tools, adapterOpts);
2185
+ if (workflow.tools.includes("hermes")) {
2186
+ const hermesContent = generateHermesAdapter(root);
2187
+ if (hermesContent) {
2188
+ const hermesPath = join13(root, ".hermes", "instructions.md");
2189
+ const hermesDir = join13(hermesPath, "..");
2190
+ if (!existsSync14(hermesDir)) mkdirSync4(hermesDir, { recursive: true });
2191
+ writeFileSync4(hermesPath, hermesContent, "utf-8");
2192
+ filesUpdated.push(".hermes/instructions.md");
2193
+ }
2194
+ }
2195
+ for (const tool of workflow.tools) {
2196
+ const target = ADAPTER_TARGETS[tool];
2197
+ if (target) filesUpdated.push(target);
2198
+ }
2199
+ }
2200
+ if (!skipSitrep) {
2201
+ try {
2202
+ const { sitrep } = await import("./sitrep-DJXTP3JO.js");
2203
+ await sitrep(resolution?.workspaceDir ?? root, { quiet: true, skipLog: true });
2204
+ } catch {
2205
+ }
2206
+ }
2207
+ if (!skipLog) {
2208
+ try {
2209
+ logEntry(
2210
+ resolution?.workspaceDir ?? root,
2211
+ "system",
2212
+ `workflow_updated via ${source}`
2213
+ );
2214
+ } catch {
2215
+ }
2216
+ }
2217
+ return { ok: true, filesUpdated };
2218
+ }
2219
+ async function flowInit(root, options) {
2220
+ if (!process.stdin.isTTY && !options?.quick) {
2221
+ console.log(chalk.yellow("Non-TTY: usando defaults. Passe --quick para confirmar."));
2222
+ return flowInitQuick(root);
2223
+ }
2224
+ if (options?.quick) {
2225
+ return flowInitQuick(root, options.template);
2226
+ }
2227
+ const name = await askText("Workflow name?", detectProjectName(root));
2228
+ const stagesInput = await askText(
2229
+ "Stages (comma-separated)?",
2230
+ "backlog, design, code, review, done"
2231
+ );
2232
+ const stages = stagesFromInput(stagesInput);
2233
+ const detected = detectExistingTools(root);
2234
+ const defaultTools = detected.length > 0 ? detected.join(", ") : "hermes, opencode";
2235
+ const toolsInput = await askText("Tools (comma-separated)?", defaultTools);
2236
+ const tools = toolsInput.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
2237
+ const templateDefault = "none";
2238
+ const templateInput = await askText(
2239
+ "Spec template? (web-api/cli-tool/mobile-feature/campanha-marketing/pesquisa/evento/none)",
2240
+ templateDefault
2241
+ );
2242
+ const template = templateInput.trim().toLowerCase() === "none" ? void 0 : templateInput.trim().toLowerCase();
2243
+ const locationsInput = await askText("Location paths (comma-separated, or leave empty)?", "");
2244
+ const locations = [];
2245
+ if (locationsInput.trim()) {
2246
+ for (const raw of locationsInput.split(",")) {
2247
+ const t = raw.trim();
2248
+ if (!t) continue;
2249
+ locations.push({
2250
+ id: t.replace(/[^a-z0-9-_]+/gi, "-").replace(/^-+|-+$/g, "").toLowerCase() || `loc-${locations.length + 1}`,
2251
+ path: normalizedPath(t),
2252
+ label: locationLabel(t, `Projeto ${locations.length + 1}`),
2253
+ adapters: []
2254
+ });
2255
+ }
2256
+ }
2257
+ const workflow = {
2258
+ version: "1.0",
2259
+ name,
2260
+ createdAt: now(),
2261
+ updatedAt: now(),
2262
+ stages,
2263
+ items: [],
2264
+ tools
2265
+ };
2266
+ if (template) workflow.template = template;
2267
+ if (template) workflow.harnessVersion = DEFAULT_HARNESS_VERSION;
2268
+ if (locations.length > 0) workflow.locations = locations;
2269
+ return workflow;
2270
+ }
2271
+ async function flowInitQuick(root, templateId = "flow-main") {
2272
+ const defaultName = detectProjectName(root);
2273
+ const harness = loadHarness(resolveHarnessRoot(root));
2274
+ const template = harness?.flows?.[templateId];
2275
+ const templateStages = template?.stages;
2276
+ const stages = templateStages && templateStages.length > 0 ? templateStages.map(stageFromTemplateStage) : [
2277
+ { id: "backlog", name: "Backlog", order: 0, zone: "todo" },
2278
+ { id: "design", name: "Design", order: 1, zone: "doing" },
2279
+ { id: "code", name: "Code", order: 2, zone: "doing" },
2280
+ { id: "review", name: "Review", order: 3, zone: "doing" },
2281
+ { id: "done", name: "Done", order: 4, zone: "done" }
2282
+ ];
2283
+ const tools = detectExistingTools(root);
2284
+ if (tools.length === 0) {
2285
+ tools.push("hermes", "opencode");
2286
+ }
2287
+ const workflow = {
2288
+ version: "1.0",
2289
+ name: defaultName,
2290
+ createdAt: now(),
2291
+ updatedAt: now(),
2292
+ stages,
2293
+ items: [],
2294
+ tools,
2295
+ template: template?.id ?? templateId,
2296
+ harnessVersion: DEFAULT_HARNESS_VERSION
2297
+ };
2298
+ return workflow;
2299
+ }
2300
+ async function flowInitAction(targetPath, options) {
2301
+ const root = resolve2(process.cwd(), targetPath || ".");
2302
+ const filePath = workflowFilePath(root);
2303
+ if (existsSync14(filePath)) {
2304
+ console.log(chalk.yellow("Workflow already exists at .letra/workflow.json"));
2305
+ return;
2306
+ }
2307
+ const spinner = ora("Setting up workflow...").start();
2308
+ try {
2309
+ spinner.stop();
2310
+ const workflow = await flowInit(root, options);
2311
+ spinner.start();
2312
+ writeWorkflow(root, { workflow, source: "flow-init", skipSitrep: true });
2313
+ spinner.succeed(chalk.green("Workflow created at .letra/workflow.json"));
2314
+ console.log("");
2315
+ console.log(` Name: ${chalk.cyan(workflow.name)}`);
2316
+ console.log(` Stages: ${chalk.cyan(workflow.stages.map((s) => s.name).join(" \u2192 "))}`);
2317
+ console.log(` Tools: ${chalk.cyan(workflow.tools.join(", "))}`);
2318
+ console.log("");
2319
+ console.log(" Next steps:");
2320
+ console.log(
2321
+ ` ${chalk.cyan("letra flow backlog add <desc>")} Add items to your backlog`
2322
+ );
2323
+ console.log(` ${chalk.cyan("letra flow board")} View your board`);
2324
+ } catch (error) {
2325
+ spinner.fail(chalk.red("Failed to create workflow"));
2326
+ process.exit(1);
2327
+ }
2328
+ }
2329
+
2330
+ // src/adapters/builder.ts
2331
+ function countACs(stateDir, specName) {
2332
+ if (!specName) return { pending: 0, total: 0, pendingIds: [] };
2333
+ let specDir = join14(stateDir, "specs", specName);
2334
+ if (!existsSync15(specDir)) {
2335
+ const legacyDir = join14(getLetraDir2(stateDir), "specs", specName);
2336
+ if (!existsSync15(legacyDir)) return { pending: 0, total: 0, pendingIds: [] };
2337
+ specDir = legacyDir;
2338
+ }
2339
+ let content = "";
2340
+ const acceptancePath = join14(specDir, "acceptance.md");
2341
+ const specPath = join14(specDir, "spec.md");
2342
+ if (existsSync15(acceptancePath)) {
2343
+ content = readFileSync11(acceptancePath, "utf-8");
2344
+ } else if (existsSync15(specPath)) {
2345
+ content = readFileSync11(specPath, "utf-8");
2346
+ const acMatch = content.match(/## Acceptance Criteria\s+([\s\S]*?)(?=\n## |\n*$)/);
2347
+ if (acMatch) content = acMatch[1];
2348
+ else return { pending: 0, total: 0, pendingIds: [] };
2349
+ } else {
2350
+ return { pending: 0, total: 0, pendingIds: [] };
2351
+ }
2352
+ const total = (content.match(/- \[.?] \*\*AC/g) || []).length;
2353
+ const pending = (content.match(/- \[ ] \*\*AC/g) || []).length;
2354
+ const pendingIds = [...content.matchAll(/-\s\[ \]\s\*\*([^*]+)\*\*/g)].map((m) => m[1]);
2355
+ return { pending, total, pendingIds };
2356
+ }
2357
+ function loadLastSession(stateDir) {
2358
+ let logPath = join14(stateDir, "session-log.json");
2359
+ if (!existsSync15(logPath)) {
2360
+ const legacy = join14(getLetraDir2(stateDir), "session-log.json");
2361
+ if (!existsSync15(legacy)) return null;
2362
+ logPath = legacy;
2363
+ }
2364
+ try {
2365
+ const log = JSON.parse(readFileSync11(logPath, "utf-8"));
2366
+ const entries = log.entries || [];
2367
+ if (entries.length === 0) return null;
2368
+ const lastEntry = entries[0];
2369
+ const actions = entries.slice(0, 5).map(
2370
+ (e) => `${e.action}: ${e.description?.slice(0, 50)}`
2371
+ );
2372
+ return {
2373
+ lastDate: new Date(lastEntry.timestamp).toLocaleString("pt-BR"),
2374
+ actionsSummary: actions.join("\n \u2022 ")
2375
+ };
2376
+ } catch {
2377
+ return null;
2378
+ }
2379
+ }
2380
+ function loadHarnessDirection(root, activeStageId) {
2381
+ const workflow = loadWorkflow(root);
2382
+ if (!workflow) return null;
2383
+ const version = workflow.harnessVersion ?? DEFAULT_HARNESS_VERSION;
2384
+ const harnessRoot = resolveHarnessRoot(root, version);
2385
+ const harness = loadHarness(harnessRoot);
2386
+ if (!harness) return null;
2387
+ const templateId = workflow.template ?? "flow-main";
2388
+ const flow = harness.flows?.[templateId];
2389
+ if (!flow) return null;
2390
+ const stageDef = flow.stages?.find((s) => s.id === activeStageId);
2391
+ if (!stageDef) return null;
2392
+ const activities = [];
2393
+ const activityConfig = stageDef.activity;
2394
+ if (activityConfig) {
2395
+ const kinds = ["design", "implement", "review", "diagnose", "gate"];
2396
+ for (const kind of kinds) {
2397
+ const hint = activityConfig[kind];
2398
+ if (!hint) continue;
2399
+ activities.push({
2400
+ kind,
2401
+ objective: hint.objective,
2402
+ mustNotDo: hint.mustNotDo,
2403
+ commands: hint.commands?.map((c) => ({
2404
+ command: c.command ?? "",
2405
+ label: c.label ?? "",
2406
+ description: c.description
2407
+ })),
2408
+ nextActions: hint.nextActions?.map((a) => ({
2409
+ label: a.label ?? "",
2410
+ description: a.description ?? ""
2411
+ }))
2412
+ });
2413
+ }
2414
+ }
2415
+ return {
2416
+ harnessVersion: version,
2417
+ roleIds: stageDef.agents ?? [],
2418
+ activities
2419
+ };
2420
+ }
2421
+ function buildHarnessSnapshot(root, options) {
2422
+ const isWorkspace = options.workspaceDir !== void 0;
2423
+ const stateDir = isWorkspace ? options.workspaceDir ?? root : root;
2424
+ const dotLetra = isWorkspace ? stateDir : getLetraDir2(stateDir);
2425
+ const hasFocus = existsSync15(join14(dotLetra, "focus.md"));
2426
+ const buildReferenceLinks = (specName) => ({
2427
+ context: pathToFileURL(join14(dotLetra, "context.md")).href,
2428
+ constitution: pathToFileURL(join14(dotLetra, "constitution.md")).href,
2429
+ glossary: pathToFileURL(join14(dotLetra, "glossary.md")).href,
2430
+ constraints: pathToFileURL(join14(dotLetra, "constraints.md")).href,
2431
+ focus: hasFocus ? pathToFileURL(join14(dotLetra, "focus.md")).href : null,
2432
+ spec: specName ? pathToFileURL(join14(dotLetra, "specs", specName, "spec.md")).href : null,
2433
+ workflow: pathToFileURL(join14(dotLetra, "workflow.json")).href
2434
+ });
2435
+ if (!options.workflow || !options.activeStageId) {
2436
+ return {
2437
+ workflowName: "letra",
2438
+ hasWorkflow: false,
2439
+ items: [],
2440
+ hasFocus,
2441
+ primaryItemId: null,
2442
+ focusSpec: null,
2443
+ focusPath: null,
2444
+ referenceLinks: buildReferenceLinks(null),
2445
+ pendingACs: 0,
2446
+ totalACs: 0
2447
+ };
2448
+ }
2449
+ const { workflow, activeStageId } = options;
2450
+ const stage = workflow.stages.find((s) => s.id === activeStageId);
2451
+ const stageItems = workflow.items.filter((item) => item.stage === activeStageId);
2452
+ let nextStage;
2453
+ if (stage) {
2454
+ const hasOrder = workflow.stages.some((s) => s.order !== void 0);
2455
+ const sorted = hasOrder ? [...workflow.stages].sort((a, b) => (a.order ?? 0) - (b.order ?? 0)) : workflow.stages;
2456
+ const currentIdx = sorted.findIndex((s) => s.id === stage.id);
2457
+ if (currentIdx >= 0 && currentIdx < sorted.length - 1) {
2458
+ const ns = sorted[currentIdx + 1];
2459
+ nextStage = { id: ns.id, name: ns.name };
2460
+ }
2461
+ }
2462
+ let primaryItemId = null;
2463
+ if (options.primaryItemId && stageItems.some((i) => i.id === options.primaryItemId)) {
2464
+ primaryItemId = options.primaryItemId;
2465
+ } else if (stageItems.length > 0) {
2466
+ primaryItemId = stageItems[0].id;
2467
+ }
2468
+ const items = stageItems.map((item) => ({
2469
+ id: item.id,
2470
+ description: item.description,
2471
+ spec: item.spec,
2472
+ claimedBy: item.claimedBy,
2473
+ claimedAt: item.claimedAt
2474
+ }));
2475
+ let focusSpec = null;
2476
+ let focusPath = null;
2477
+ const parsedFocus = readFocusFile(root);
2478
+ if (parsedFocus) {
2479
+ focusSpec = parsedFocus.specName;
2480
+ focusPath = `${isWorkspace ? "specs/" : ".letra/specs/"}${parsedFocus.specName}/`;
2481
+ } else {
2482
+ const primaryItem = items.find((i) => i.id === primaryItemId);
2483
+ if (primaryItem?.spec) {
2484
+ focusSpec = primaryItem.spec;
2485
+ focusPath = `${isWorkspace ? "specs/" : ".letra/specs/"}${primaryItem.spec}/`;
2486
+ }
2487
+ }
2488
+ const acCounts = countACs(dotLetra, focusSpec);
2489
+ const lastSession = loadLastSession(dotLetra);
2490
+ const healthRecord = loadHealthRecord(root);
2491
+ const novoAlerts = healthRecord.entries.filter((e) => e.status === "novo").slice(0, 5).map((e) => ({
2492
+ id: e.id,
2493
+ severity: e.severity,
2494
+ title: e.title,
2495
+ source: e.source,
2496
+ detectedAt: e.detectedAt
2497
+ }));
2498
+ const totalNovo = healthRecord.entries.filter((e) => e.status === "novo").length;
2499
+ let currentPhase;
2500
+ if (primaryItemId && stage) {
2501
+ const primaryItemData = workflow.items.find((i) => i.id === primaryItemId);
2502
+ const phaseId = primaryItemData?.currentPhase;
2503
+ if (phaseId) {
2504
+ const stagePhases = stage.phases ?? null;
2505
+ if (stagePhases?.states?.[phaseId]) {
2506
+ const phaseDef = stagePhases.states[phaseId];
2507
+ currentPhase = {
2508
+ id: phaseDef.id,
2509
+ label: phaseDef.label,
2510
+ description: phaseDef.description,
2511
+ harness: phaseDef.harness
2512
+ };
2513
+ }
2514
+ }
2515
+ }
2516
+ let handoff;
2517
+ if (primaryItemId) {
2518
+ const rawHandoff = workflow.handoff;
2519
+ const handoffEnabled = rawHandoff === false ? false : rawHandoff?.enabled !== false;
2520
+ if (handoffEnabled) {
2521
+ const defaultSteps = [
2522
+ {
2523
+ command: "letra validate",
2524
+ label: "validate",
2525
+ recovery: "letra diagnose \u2014 encontrar e corrigir problemas"
2526
+ },
2527
+ {
2528
+ command: "letra pulse",
2529
+ label: "pulse",
2530
+ recovery: "letra health \u2014 checar alertas ativos"
2531
+ },
2532
+ {
2533
+ command: "letra sitrep",
2534
+ label: "sitrep",
2535
+ recovery: "corrija o erro e tente novamente"
2536
+ },
2537
+ {
2538
+ command: `letra flow move ${primaryItemId} --to ${nextStage?.id || "proximo_estagio"}`,
2539
+ label: "flow move",
2540
+ recovery: "letra validate \u2014 verificar ACs pendentes"
2541
+ },
2542
+ {
2543
+ command: "npm run build",
2544
+ label: "build",
2545
+ recovery: "corrija erros de compila\xE7\xE3o"
2546
+ }
2547
+ ];
2548
+ const skipSteps = Array.isArray(
2549
+ rawHandoff?.skipSteps
2550
+ ) ? rawHandoff.skipSteps : [];
2551
+ const customSteps = Array.isArray(
2552
+ rawHandoff?.customSteps
2553
+ ) ? rawHandoff.customSteps : [];
2554
+ const filtered = defaultSteps.filter((s) => !skipSteps.includes(s.label));
2555
+ const steps = [...filtered, ...customSteps];
2556
+ handoff = {
2557
+ steps,
2558
+ primaryItemId,
2559
+ nextStageName: nextStage?.name
2560
+ };
2561
+ }
2562
+ }
2563
+ const pendingACIds = acCounts.pendingIds;
2564
+ const harnessDirection = loadHarnessDirection(root, activeStageId) ?? void 0;
2565
+ if (harnessDirection && pendingACIds.length > 0) {
2566
+ harnessDirection.pendingACIds = pendingACIds;
2567
+ }
2568
+ if (harnessDirection && primaryItemId) {
2569
+ harnessDirection.primaryItemId = primaryItemId;
2570
+ }
2571
+ return {
2572
+ workflowName: workflow.name,
2573
+ hasWorkflow: true,
2574
+ activeStage: stage ? { id: stage.id, name: stage.name } : { id: activeStageId, name: activeStageId },
2575
+ nextStage,
2576
+ items,
2577
+ hasFocus,
2578
+ primaryItemId,
2579
+ focusSpec,
2580
+ focusPath,
2581
+ referenceLinks: buildReferenceLinks(focusSpec),
2582
+ pendingACs: acCounts.pending,
2583
+ totalACs: acCounts.total,
2584
+ lastSession,
2585
+ alerts: novoAlerts.length > 0 ? [
2586
+ ...novoAlerts,
2587
+ ...totalNovo > 5 ? [
2588
+ {
2589
+ id: "...",
2590
+ severity: "",
2591
+ title: `e mais ${totalNovo - 5} alertas`,
2592
+ source: "",
2593
+ detectedAt: ""
2594
+ }
2595
+ ] : []
2596
+ ] : void 0,
2597
+ currentPhase,
2598
+ handoff,
2599
+ harnessDirection
2600
+ };
2601
+ }
2602
+
2603
+ // src/adapters/codex-bootstrap.ts
2604
+ var MANAGED_START = "# letra:codex-mcp:start";
2605
+ var MANAGED_END = "# letra:codex-mcp:end";
2606
+ var MCP_BLOCK = [
2607
+ MANAGED_START,
2608
+ "[mcp_servers.letra]",
2609
+ 'command = "letra"',
2610
+ 'args = ["mcp", "serve", "--stdio"]',
2611
+ "enabled = true",
2612
+ "required = false",
2613
+ MANAGED_END
2614
+ ].join("\n");
2615
+ function mergeCodexProjectConfig(content) {
2616
+ const start = content.indexOf(MANAGED_START);
2617
+ const end = content.indexOf(MANAGED_END);
2618
+ if (start >= 0 !== end >= 0 || start >= 0 && end < start) {
2619
+ throw new Error("The Letra-managed Codex MCP section is malformed.");
2620
+ }
2621
+ if (start >= 0 && end >= 0) {
2622
+ const blockEnd = end + MANAGED_END.length;
2623
+ return `${content.slice(0, start)}${MCP_BLOCK}${content.slice(blockEnd)}`;
2624
+ }
2625
+ if (/^\s*\[mcp_servers\.letra\]\s*$/m.test(content)) {
2626
+ throw new Error(
2627
+ 'The existing "mcp_servers.letra" table is not managed by Letra and will not be overwritten.'
2628
+ );
2629
+ }
2630
+ if (content.length === 0) return `${MCP_BLOCK}
2631
+ `;
2632
+ const separator = content.endsWith("\n\n") ? "" : content.endsWith("\n") ? "\n" : "\n\n";
2633
+ return `${content}${separator}${MCP_BLOCK}
2634
+ `;
2635
+ }
2636
+ function renderLetraHarnessSkill() {
2637
+ return [
2638
+ "---",
2639
+ "name: letra-harness",
2640
+ "description: Consulte e siga a dire\xE7\xE3o vigente do harness Letra ao implementar, revisar, validar ou avan\xE7ar trabalho no workspace.",
2641
+ "---",
2642
+ "",
2643
+ "# Letra Harness",
2644
+ "",
2645
+ "1. Consulte `get_direction` antes de planejar a atividade.",
2646
+ "2. Confirme a spec e o AC vigente antes da primeira escrita.",
2647
+ "3. Proteja o comportamento existente com teste de regress\xE3o.",
2648
+ "4. Trabalhe somente dentro das permiss\xF5es e proibi\xE7\xF5es retornadas.",
2649
+ "5. Consulte novamente `get_direction` antes de concluir ou solicitar transi\xE7\xE3o.",
2650
+ "6. Use apenas ferramentas de muta\xE7\xE3o fornecidas pelo Letra para alterar o estado can\xF4nico.",
2651
+ "",
2652
+ "## Fallback quando o MCP estiver indispon\xEDvel",
2653
+ "",
2654
+ "1. Execute `letra direction --json` e trate a resposta como modo degradado.",
2655
+ '2. Use a revis\xE3o retornada ao executar `letra operation validate --expected-revision <REVISION> --reason "<MOTIVO>"`.',
2656
+ "3. Para concluir ou avan\xE7ar, use os subcomandos controlados de `letra operation`; nunca contorne o harness.",
2657
+ "4. Execute novamente `letra direction --json` antes de cada muta\xE7\xE3o.",
2658
+ "",
2659
+ "Esta skill define procedimento. Item, stage, AC e pr\xF3xima a\xE7\xE3o sempre v\xEAm do contexto vivo.",
2660
+ ""
2661
+ ].join("\n");
2662
+ }
2663
+ function appendCodexLiveContextInstructions(content) {
2664
+ return [
2665
+ content.trimEnd(),
2666
+ "",
2667
+ "## Contexto vivo do Letra para Codex",
2668
+ "",
2669
+ "- Consulte `get_direction` antes de planejar, antes da primeira escrita e antes de concluir.",
2670
+ "- A resposta com revis\xE3o mais recente prevalece sobre snapshots textuais deste arquivo.",
2671
+ "- Se `get_direction` estiver indispon\xEDvel, execute `letra direction --json`; a resposta declara modo degradado e mant\xE9m a autoridade do harness.",
2672
+ "- No fallback, valide e altere estado somente por `letra operation`, sempre com a revis\xE3o retornada.",
2673
+ "- N\xE3o conclua AC nem solicite transi\xE7\xE3o por caminhos que contornem o harness.",
2674
+ ""
2675
+ ].join("\n");
2676
+ }
2677
+
2678
+ // src/adapters/generate.ts
2679
+ var ADAPTER_HEADER = {
2680
+ init: "# Generated by letra init. Do not edit manually.\n",
2681
+ "flow-move": "# Gerado por letra flow move. Nao edite manualmente.\n",
2682
+ focus: "# Gerado por letra focus. Nao edite manualmente.\n",
2683
+ "flow-ac": "# Gerado por letra ac. Nao edite manualmente.\n"
2684
+ };
2685
+ var TOOL_TARGETS = adapterInstructionTargets();
2686
+ function renderAdapterFiles(root, tools, options) {
2687
+ const snapshot = buildHarnessSnapshot(root, options);
2688
+ let header = ADAPTER_HEADER[options.source];
2689
+ if (options.graveIssueCount && options.graveIssueCount > 0) {
2690
+ const warn = `
2691
+ ### \u26A0 ATEN\xC7\xC3O: ${options.graveIssueCount} problema(s) grave(s) detectado(s) pelo diagn\xF3stico autom\xE1tico
2692
+ Execute \`letra health\` para detalhes e \`letra health ack <id>\` para reconhecer.
2693
+ `;
2694
+ header += warn;
2695
+ }
2696
+ const files = [];
2697
+ for (const artifact of instructionArtifactsForAdapters(tools)) {
2698
+ let content = formatAdapterContent(snapshot, artifact.format, {
2699
+ source: options.source,
2700
+ displayName: artifact.displayName
2701
+ });
2702
+ if (artifact.id === "agents-md-shared" && tools.includes("codex")) {
2703
+ content = appendCodexLiveContextInstructions(content);
2704
+ }
2705
+ files.push({
2706
+ tool: artifact.tool,
2707
+ artifactId: artifact.id,
2708
+ path: artifact.path,
2709
+ content: header + content
2710
+ });
2711
+ }
2712
+ if (tools.includes("codex")) {
2713
+ const configArtifact = ADAPTER_ARTIFACTS["codex-project-config"];
2714
+ const configPath = join15(root, configArtifact.path);
2715
+ const existingConfig = existsSync16(configPath) ? readFileSync12(configPath, "utf-8") : "";
2716
+ files.push({
2717
+ tool: "codex",
2718
+ artifactId: configArtifact.id,
2719
+ path: configArtifact.path,
2720
+ content: mergeCodexProjectConfig(existingConfig)
2721
+ });
2722
+ const skillArtifact = ADAPTER_ARTIFACTS["letra-harness-skill"];
2723
+ files.push({
2724
+ tool: "codex",
2725
+ artifactId: skillArtifact.id,
2726
+ path: skillArtifact.path,
2727
+ content: renderLetraHarnessSkill()
2728
+ });
2729
+ }
2730
+ return files;
2731
+ }
2732
+ function generateAdapters(root, tools, options) {
2733
+ const boundary = options.confineWrites ? createWorkspaceBoundary(root) : null;
2734
+ const verb = options.verb ?? (options.source === "init" ? "Created" : "Updated");
2735
+ for (const file of renderAdapterFiles(root, tools, options)) {
2736
+ const requestedPath = join15(root, file.path);
2737
+ const filePath = boundary?.assertPath(requestedPath) ?? requestedPath;
2738
+ const dir = join15(filePath, "..");
2739
+ if (!existsSync16(dir)) mkdirSync5(dir, { recursive: true });
2740
+ writeFileSync5(filePath, file.content);
2741
+ if (!options.quiet) {
2742
+ console.log(` ${chalk2.gray(verb)} ${file.path}`);
2743
+ }
2744
+ }
2745
+ }
2746
+
2747
+ export {
2748
+ createWorkspaceBoundary,
2749
+ parseSimpleYaml,
2750
+ ensureSharedHarness,
2751
+ DEFAULT_HARNESS_VERSION,
2752
+ resolveHarnessRoot,
2753
+ loadHarness,
2754
+ TOOL_TARGETS,
2755
+ renderAdapterFiles,
2756
+ generateAdapters,
2757
+ DiagnosticEngine,
2758
+ detectExistingTools,
2759
+ detectProjectName,
2760
+ stageFromTemplateStage,
2761
+ loadWorkflow,
2762
+ saveWorkflow,
2763
+ writeWorkflow,
2764
+ flowInitAction
2765
+ };