@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,4494 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ GateChecker,
4
+ resolveFocusRecommendations,
5
+ writeFocusWithRecommendations
6
+ } from "./chunk-ELBTIPYN.js";
7
+ import {
8
+ resolveActiveFlow,
9
+ resolveActiveFlowFor,
10
+ resolveAgentDirection
11
+ } from "./chunk-MSF44WWE.js";
12
+ import {
13
+ sitrep
14
+ } from "./chunk-BTPFUKHG.js";
15
+ import {
16
+ DEFAULT_HARNESS_VERSION,
17
+ DiagnosticEngine,
18
+ detectExistingTools,
19
+ detectProjectName,
20
+ ensureSharedHarness,
21
+ generateAdapters,
22
+ loadHarness,
23
+ loadWorkflow,
24
+ renderAdapterFiles,
25
+ resolveHarnessRoot,
26
+ stageFromTemplateStage,
27
+ writeWorkflow
28
+ } from "./chunk-4QDEU6KP.js";
29
+ import {
30
+ loadSessionLog,
31
+ logEntry,
32
+ queryLog,
33
+ queryLogWithMeta
34
+ } from "./chunk-BKAUN5QH.js";
35
+ import {
36
+ ADAPTER_REGISTRY,
37
+ supportedAdapterTools
38
+ } from "./chunk-JMIC5NKB.js";
39
+ import {
40
+ clearFocusFile,
41
+ readFocusFile,
42
+ syncFocus
43
+ } from "./chunk-EDD55PWL.js";
44
+ import {
45
+ ackEntry,
46
+ dismissEntry,
47
+ getActiveEntries,
48
+ getSummary,
49
+ loadHealthRecord,
50
+ mergeScanResults,
51
+ saveHealthRecord
52
+ } from "./chunk-MJ2QXNH6.js";
53
+ import {
54
+ LINK_FILE,
55
+ clearWorkspaceCache,
56
+ ensureExternalWorkspaceLayout,
57
+ getLetraDir,
58
+ getLetraDir2,
59
+ getWorkspacesDir,
60
+ listWorkspaces,
61
+ resolveWorkspaceRoot,
62
+ slugifyWorkspaceName
63
+ } from "./chunk-6HSUVCTR.js";
64
+ import {
65
+ __require
66
+ } from "./chunk-PDX44BCA.js";
67
+
68
+ // src/commands/flow-serve.ts
69
+ import { createServer } from "http";
70
+ import { existsSync as existsSync15 } from "fs";
71
+ import { resolve as resolve7 } from "path";
72
+
73
+ // src/commands/pulse.ts
74
+ import { existsSync, readFileSync } from "fs";
75
+ import { resolve, join } from "path";
76
+ import { execSync } from "child_process";
77
+ import { pathToFileURL } from "url";
78
+ import chalk from "chalk";
79
+ import { Command } from "commander";
80
+ function daysSince(date) {
81
+ return Math.floor((Date.now() - date.getTime()) / (1e3 * 60 * 60 * 24));
82
+ }
83
+ function daysInStage(item) {
84
+ return daysSince(new Date(item.createdAt));
85
+ }
86
+ function findCurrentItem(workflow) {
87
+ const activeStages = workflow.stages.filter(
88
+ (s) => s.zone === "doing" || !s.zone && s.order > 0 && s.order < workflow.stages.length - 1
89
+ ).map((s) => s.id);
90
+ const stageSet = new Set(activeStages);
91
+ if (stageSet.size === 0) {
92
+ const middle = Math.floor(workflow.stages.length / 2);
93
+ const stage = workflow.stages[middle];
94
+ if (stage) stageSet.add(stage.id);
95
+ }
96
+ const items = workflow.items.filter((i) => stageSet.has(i.stage));
97
+ if (items.length === 0) return null;
98
+ return items.reduce((a, b) => new Date(a.createdAt) > new Date(b.createdAt) ? a : b);
99
+ }
100
+ function findNextBacklog(workflow) {
101
+ const firstStage = workflow.stages[0];
102
+ if (!firstStage) return null;
103
+ const items = workflow.items.filter((i) => i.stage === firstStage.id);
104
+ if (items.length === 0) return null;
105
+ return items.reduce((a, b) => new Date(a.createdAt) < new Date(b.createdAt) ? a : b);
106
+ }
107
+ function getStageName(workflow, stageId) {
108
+ return workflow.stages.find((s) => s.id === stageId)?.name ?? stageId;
109
+ }
110
+ function countSpecACs(stateDir, specName) {
111
+ let specDir = join(stateDir, "specs", specName);
112
+ if (!existsSync(specDir)) {
113
+ specDir = join(getLetraDir2(stateDir), "specs", specName);
114
+ }
115
+ const specFile = join(specDir, "spec.md");
116
+ if (!existsSync(specFile)) return { pending: 0, done: 0, total: 0 };
117
+ try {
118
+ const content = readFileSync(specFile, "utf-8");
119
+ const boldPending = content.match(/-\s*\[ \]\s*\*\*AC[-]?\d+\*\*/g) || [];
120
+ const boldDone = content.match(/-\s*\[[xX]\]\s*\*\*AC[-]?\d+\*\*/g) || [];
121
+ if (boldPending.length > 0 || boldDone.length > 0) {
122
+ return {
123
+ pending: boldPending.length,
124
+ done: boldDone.length,
125
+ total: boldPending.length + boldDone.length
126
+ };
127
+ }
128
+ const genericPending = content.match(/^- \[ \]\s+AC[-]?\d+/gm) || [];
129
+ const genericDone = content.match(/^- \[[xX]\]\s+AC[-]?\d+/gm) || [];
130
+ return {
131
+ pending: genericPending.length,
132
+ done: genericDone.length,
133
+ total: genericPending.length + genericDone.length
134
+ };
135
+ } catch {
136
+ return { pending: 0, done: 0, total: 0 };
137
+ }
138
+ }
139
+ function getTaskCounts(item) {
140
+ if (!item.tasks || item.tasks.length === 0) return { open: 0, done: 0, total: 0 };
141
+ const done = item.tasks.filter((t) => t.done).length;
142
+ return { open: item.tasks.length - done, done, total: item.tasks.length };
143
+ }
144
+ async function pulse(rootPath, options) {
145
+ const resolution = resolveWorkspaceRoot(rootPath);
146
+ const statePath = resolution.workspaceDir;
147
+ const workflow = loadWorkflow(resolution.targetDir);
148
+ const name = workflow?.name ?? "meu-projeto";
149
+ const legacyWarning = resolution.type === "local" && existsSync(join(resolution.workspaceRoot, ".letra", "workflow.json")) ? "Workspace legado local detectado. Migre para um workspace externo com `letra migrate`." : void 0;
150
+ if (!workflow) {
151
+ const empty = {
152
+ workspace: name,
153
+ dataDir: statePath,
154
+ locationPath: resolution.locationPath,
155
+ legacyWarning,
156
+ pulseAt: (/* @__PURE__ */ new Date()).toISOString(),
157
+ currentItem: null,
158
+ handoff: null,
159
+ alerts: { novo: 0, acknowledged: 0, resolved: 0, dismissed: 0, highSeverity: 0 },
160
+ lastUpdated: null,
161
+ daysIdle: null,
162
+ nextItem: null
163
+ };
164
+ if (options?.json) {
165
+ console.log(JSON.stringify(empty, null, 2));
166
+ } else {
167
+ renderPulseText(empty, false, statePath);
168
+ }
169
+ return empty;
170
+ }
171
+ const healthRecord = loadHealthRecord(resolution.type === "local" ? rootPath : statePath);
172
+ const summary = getSummary(healthRecord);
173
+ const currentItem = findCurrentItem(workflow);
174
+ let acCounts = { pending: 0, done: 0, total: 0 };
175
+ if (currentItem?.spec) {
176
+ const specRoot = resolution.type === "local" ? rootPath : statePath;
177
+ acCounts = countSpecACs(specRoot, currentItem.spec);
178
+ }
179
+ const pulseData = {
180
+ workspace: name,
181
+ dataDir: statePath,
182
+ locationPath: resolution.locationPath,
183
+ legacyWarning,
184
+ pulseAt: (/* @__PURE__ */ new Date()).toISOString(),
185
+ currentItem: currentItem ? {
186
+ id: currentItem.id,
187
+ description: currentItem.description,
188
+ stage: currentItem.stage,
189
+ stageName: getStageName(workflow, currentItem.stage),
190
+ daysInStage: daysInStage(currentItem),
191
+ spec: currentItem.spec ?? null,
192
+ acs: acCounts,
193
+ tasks: getTaskCounts(currentItem),
194
+ claimedBy: currentItem.claimedBy,
195
+ claimedAt: currentItem.claimedAt
196
+ } : null,
197
+ alerts: {
198
+ novo: summary.novo,
199
+ acknowledged: summary.ciente,
200
+ resolved: summary.resolvido,
201
+ dismissed: summary.descartado,
202
+ highSeverity: summary.alta
203
+ },
204
+ handoff: currentItem?.handoff ? {
205
+ itemId: currentItem.id,
206
+ from: currentItem.handoff.from,
207
+ to: currentItem.handoff.to,
208
+ summary: currentItem.handoff.summary,
209
+ expiresAt: currentItem.handoff.expiresAt
210
+ } : null,
211
+ lastUpdated: workflow.updatedAt ?? null,
212
+ daysIdle: workflow.updatedAt ? daysSince(new Date(workflow.updatedAt)) : null,
213
+ nextItem: findNextBacklog(workflow) ? {
214
+ id: findNextBacklog(workflow)?.id ?? "",
215
+ description: findNextBacklog(workflow)?.description ?? "",
216
+ stage: findNextBacklog(workflow)?.stage ?? ""
217
+ } : null
218
+ };
219
+ const focusRoot = resolution.type === "local" ? rootPath : statePath;
220
+ const focusResult = syncFocus(
221
+ focusRoot,
222
+ workflow,
223
+ currentItem ? resolveFocusRecommendations(focusRoot, currentItem.id) : []
224
+ );
225
+ if (focusResult.cleared) {
226
+ console.log(
227
+ chalk.yellow(" focus.md limpo \u2014 item referenciado n\xE3o encontrado no workflow")
228
+ );
229
+ }
230
+ const focusData = readFocusFile(focusRoot);
231
+ let focusDiverged = false;
232
+ if (focusData && currentItem?.spec && focusData.specName !== currentItem.spec) {
233
+ focusDiverged = true;
234
+ }
235
+ if (options?.json) {
236
+ const pulseJson = { ...pulseData, focusDiverged };
237
+ console.log(JSON.stringify(pulseJson, null, 2));
238
+ } else {
239
+ renderPulseText(pulseData, focusDiverged, statePath);
240
+ }
241
+ return pulseData;
242
+ }
243
+ function renderPulseText(data, focusDiverged = false, statePath) {
244
+ const dateStr = new Date(data.pulseAt).toLocaleDateString("pt-BR", {
245
+ day: "2-digit",
246
+ month: "2-digit",
247
+ year: "numeric",
248
+ hour: "2-digit",
249
+ minute: "2-digit"
250
+ });
251
+ console.log(`
252
+ ${chalk.bold("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557")}`);
253
+ console.log(`${chalk.bold("\u2551 Pulso do Workspace")} `);
254
+ console.log(`${chalk.bold("\u2551")} ${chalk.gray(`${data.workspace} \xB7 ${dateStr}`)}`);
255
+ console.log(`${chalk.bold("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D")}
256
+ `);
257
+ if (data.legacyWarning) {
258
+ console.log(` ${chalk.yellow(data.legacyWarning)}`);
259
+ console.log();
260
+ }
261
+ if (data.currentItem) {
262
+ const ci = data.currentItem;
263
+ console.log(` ${chalk.bold("Item em andamento:")}`);
264
+ if (statePath) {
265
+ console.log(
266
+ ` ${chalk.gray(`Workflow: ${pathToFileURL(join(statePath, "workflow.json")).href}`)}`
267
+ );
268
+ }
269
+ console.log(` ${chalk.cyan(ci.id)} \xB7 ${ci.description}`);
270
+ const agentInfo = ci.claimedBy ? ` \u{1F916} Agent: ${ci.claimedBy}` : "";
271
+ console.log(
272
+ ` ${chalk.gray(`Est\xE1gio: ${ci.stageName} \xB7 ${ci.daysInStage} dia(s) no est\xE1gio${agentInfo}`)}`
273
+ );
274
+ console.log(
275
+ ` ${chalk.gray(`ACs: ${ci.acs.pending}/${ci.acs.total} pendentes (${ci.acs.done} feito(s))`)}`
276
+ );
277
+ if (ci.tasks.total > 0) {
278
+ console.log(
279
+ ` ${chalk.gray(`Tasks: ${ci.tasks.open}/${ci.tasks.total} abertas (${ci.tasks.done} feita(s))`)}`
280
+ );
281
+ }
282
+ if (ci.spec) {
283
+ const specReference = statePath ? pathToFileURL(join(statePath, "specs", ci.spec, "spec.md")).href : `.letra/specs/${ci.spec}/spec.md`;
284
+ console.log(` ${chalk.gray(`Spec: ${specReference}`)}`);
285
+ } else {
286
+ console.log(` ${chalk.yellow("\u26A0 sem spec associada")}`);
287
+ }
288
+ } else {
289
+ console.log(` ${chalk.yellow("Nenhum item em andamento.")}`);
290
+ }
291
+ console.log();
292
+ if (data.handoff) {
293
+ const h = data.handoff;
294
+ const isExpired = new Date(h.expiresAt) < /* @__PURE__ */ new Date();
295
+ const status = isExpired ? chalk.red("EXPIRADO") : chalk.green("ATIVO");
296
+ console.log(` ${chalk.bold("Handoff pendente:")}`);
297
+ console.log(` ${chalk.cyan(h.itemId)} \xB7 ${h.from} \u2192 ${h.to} [${status}]`);
298
+ console.log(` ${chalk.gray(h.summary)}`);
299
+ console.log(
300
+ ` ${chalk.gray(`Expira: ${new Date(h.expiresAt).toLocaleString("pt-BR")}`)}`
301
+ );
302
+ console.log();
303
+ }
304
+ const alerts = data.alerts;
305
+ if (alerts.novo > 0 || alerts.acknowledged > 0 || alerts.resolved > 0) {
306
+ console.log(` ${chalk.bold("Alertas:")}`);
307
+ console.log(
308
+ ` ${chalk.red(`${alerts.novo} novo(s)`)} \xB7 ${chalk.yellow(`${alerts.acknowledged} em acompanhamento`)} \xB7 ${chalk.gray(`${alerts.resolved} resolvido(s)`)}`
309
+ );
310
+ if (alerts.highSeverity > 0) {
311
+ console.log(
312
+ ` ${chalk.red.bold(`\u26A0 ${alerts.highSeverity} alerta(s) de severidade alta`)}`
313
+ );
314
+ }
315
+ console.log(` ${chalk.gray("\u2192 Corra `letra health` para detalhes")}`);
316
+ } else {
317
+ console.log(` ${chalk.gray("Nenhum alerta ativo.")}`);
318
+ }
319
+ console.log();
320
+ if (data.lastUpdated) {
321
+ const idle = data.daysIdle !== null ? `(${data.daysIdle} dia(s) parado)` : "";
322
+ console.log(
323
+ ` ${chalk.gray(`\xDAltima atualiza\xE7\xE3o: ${new Date(data.lastUpdated).toLocaleDateString("pt-BR")} ${idle}`)}`
324
+ );
325
+ }
326
+ if (data.nextItem) {
327
+ console.log(
328
+ ` ${chalk.gray(`Pr\xF3ximo item na fila: ${data.nextItem.id} \xB7 ${data.nextItem.description} (${data.nextItem.stage})`)}`
329
+ );
330
+ }
331
+ if (focusDiverged) {
332
+ console.log(
333
+ ` ${chalk.red.bold("\u26A0 Foco dessincronizado!")} focus.md aponta para spec diferente do item ativo`
334
+ );
335
+ console.log(` ${chalk.gray("\u2192 Corra `letra focus <spec>` para corrigir")}`);
336
+ }
337
+ console.log();
338
+ }
339
+ function runTargetCommand(root, label, cmdStr) {
340
+ if (!cmdStr) return null;
341
+ try {
342
+ const out = execSync(cmdStr, { cwd: root, encoding: "utf-8", timeout: 6e4 });
343
+ const lines = out.trim().split("\n").slice(-3).join("\n");
344
+ return `${label}: OK
345
+ ${lines}`;
346
+ } catch (e) {
347
+ return `${label}: FALHA \u2014 ${e.stderr?.slice(0, 200) || e.message?.slice(0, 200) || "erro"}`;
348
+ }
349
+ }
350
+ function pulse_default() {
351
+ const cmd = new Command("pulse").description("Pulse do workspace \u2014 overview de uma olhada s\xF3");
352
+ cmd.option("--json", "Output in JSON format").option("--build", "Run build command from target config").option("--test", "Run test command from target config").action(async (options) => {
353
+ const root = resolve(process.cwd());
354
+ const data = await pulse(root, options);
355
+ if (options.build || options.test) {
356
+ const resolution = resolveWorkspaceRoot(root);
357
+ const workflow = loadWorkflow(resolution.targetDir);
358
+ const location = workflow?.locations?.[0];
359
+ if (options.build) {
360
+ const result = runTargetCommand(
361
+ location?.path || root,
362
+ "Build",
363
+ location?.buildCommand ?? null
364
+ );
365
+ if (result) console.log(chalk.gray(result));
366
+ }
367
+ if (options.test) {
368
+ const result = runTargetCommand(
369
+ location?.path || root,
370
+ "Test",
371
+ location?.testCommand ?? null
372
+ );
373
+ if (result) console.log(chalk.gray(result));
374
+ }
375
+ }
376
+ });
377
+ return cmd;
378
+ }
379
+
380
+ // src/flow-serve/events.ts
381
+ var FlowServerEvents = class {
382
+ clients = /* @__PURE__ */ new Set();
383
+ handleSse(req, res) {
384
+ res.writeHead(200, {
385
+ "Content-Type": "text/event-stream",
386
+ "Cache-Control": "no-cache",
387
+ Connection: "keep-alive"
388
+ });
389
+ res.write("event: connected\ndata: {}\n\n");
390
+ this.clients.add(res);
391
+ req.on("close", () => this.clients.delete(res));
392
+ }
393
+ broadcastWorkflowUpdated() {
394
+ this.broadcast("workflow-updated", {});
395
+ }
396
+ broadcastDiagnosticsUpdated(payload) {
397
+ this.broadcast("diagnostics-updated", payload);
398
+ }
399
+ broadcastSystemActionUpdated(payload) {
400
+ this.broadcast("system-action-updated", payload);
401
+ }
402
+ broadcastHandoff(payload) {
403
+ this.broadcast("handoff", payload);
404
+ }
405
+ close() {
406
+ for (const client of this.clients) {
407
+ client.destroy();
408
+ }
409
+ this.clients.clear();
410
+ }
411
+ broadcast(event, payload) {
412
+ if (this.clients.size === 0) return;
413
+ const data = `event: ${event}
414
+ data: ${JSON.stringify(payload)}
415
+
416
+ `;
417
+ for (const client of this.clients) {
418
+ try {
419
+ client.write(data);
420
+ } catch {
421
+ this.clients.delete(client);
422
+ }
423
+ }
424
+ }
425
+ };
426
+
427
+ // src/flow-serve/diagnostics.ts
428
+ function diagnosticSuggestionsFromOutput(output) {
429
+ return output.suggestions.map((suggestion) => ({
430
+ id: suggestion.id,
431
+ type: suggestion.type,
432
+ title: suggestion.title,
433
+ description: suggestion.description,
434
+ certainty: 0.8,
435
+ detector: suggestion.detector
436
+ }));
437
+ }
438
+ async function runDiagnosticsAndSyncHealth(engine, root) {
439
+ const output = await engine.runAll();
440
+ const record = loadHealthRecord(root);
441
+ mergeScanResults(record, diagnosticSuggestionsFromOutput(output));
442
+ saveHealthRecord(root, record);
443
+ return output;
444
+ }
445
+
446
+ // src/flow-serve/specs.ts
447
+ import { existsSync as existsSync3, mkdirSync, readFileSync as readFileSync3, readdirSync, writeFileSync } from "fs";
448
+ import { join as join2 } from "path";
449
+
450
+ // src/validation/structure.ts
451
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
452
+ var REQUIRED_SECTIONS = [
453
+ "## Outcome",
454
+ "## Constraints",
455
+ "## Exclusions",
456
+ "## Acceptance Criteria",
457
+ "## Context"
458
+ ];
459
+ function checkRequiredSections(content) {
460
+ return REQUIRED_SECTIONS.filter((section) => !content.includes(section));
461
+ }
462
+ function checkSpecLength(content, maxChars = 3e3) {
463
+ return content.length > maxChars ? `Spec exceeds ${maxChars} chars (should be thin \u2014 max 1 page)` : null;
464
+ }
465
+ function checkChecklist(content) {
466
+ const hasChecklist = /-\s*\[[ x]\]\s*\*\*/i.test(content);
467
+ if (!hasChecklist && content.includes("## Acceptance Criteria")) {
468
+ return "Acceptance Criteria section exists but has no checklist items";
469
+ }
470
+ return null;
471
+ }
472
+ function validateSpecStructure(specFile) {
473
+ const errors = [];
474
+ const warnings = [];
475
+ if (!existsSync2(specFile)) {
476
+ errors.push("Missing spec.md");
477
+ return { errors, warnings };
478
+ }
479
+ const content = readFileSync2(specFile, "utf-8");
480
+ const missingSections = checkRequiredSections(content);
481
+ errors.push(...missingSections.map((s) => `Missing section: ${s}`));
482
+ const lengthWarning = checkSpecLength(content);
483
+ if (lengthWarning) warnings.push(lengthWarning);
484
+ const checklistError = checkChecklist(content);
485
+ if (checklistError) errors.push(checklistError);
486
+ return { errors, warnings };
487
+ }
488
+
489
+ // src/flow-serve/specs.ts
490
+ function loadResolvedSpecs(root, workflow) {
491
+ const result = [];
492
+ if (workflow?.specLinks) {
493
+ for (const [id, link] of Object.entries(workflow.specLinks)) {
494
+ const filePath = join2(root, link.path);
495
+ if (existsSync3(filePath)) {
496
+ result.push({ id, content: readFileSync3(filePath, "utf-8") });
497
+ }
498
+ }
499
+ }
500
+ const specsDir = join2(getLetraDir2(root), "specs");
501
+ const registered = new Set(result.map((entry) => entry.id));
502
+ if (!existsSync3(specsDir)) return result;
503
+ for (const entry of readdirSync(specsDir, { withFileTypes: true })) {
504
+ if (!entry.isDirectory() || registered.has(entry.name)) continue;
505
+ const specPath = join2(specsDir, entry.name, "spec.md");
506
+ if (!existsSync3(specPath)) continue;
507
+ result.push({ id: entry.name, content: readFileSync3(specPath, "utf-8") });
508
+ }
509
+ return result;
510
+ }
511
+ function readAllowedContextFile(workspaceDir, file) {
512
+ const allowedFiles = /* @__PURE__ */ new Set(["context.md", "constitution.md", "glossary.md"]);
513
+ if (!allowedFiles.has(file)) return null;
514
+ const filePath = join2(workspaceDir, file);
515
+ if (!existsSync3(filePath)) return null;
516
+ return readFileSync3(filePath, "utf-8");
517
+ }
518
+ function writeSpec(workspaceDir, id, content) {
519
+ const specDir = join2(workspaceDir, "specs", id);
520
+ if (!existsSync3(specDir)) mkdirSync(specDir, { recursive: true });
521
+ writeFileSync(join2(specDir, "spec.md"), content, "utf-8");
522
+ }
523
+ function clearSpec(workspaceDir, id) {
524
+ const specFile = join2(workspaceDir, "specs", id, "spec.md");
525
+ if (existsSync3(specFile)) writeFileSync(specFile, "", "utf-8");
526
+ }
527
+ function validateSpec(workspaceDir, id) {
528
+ const specFile = join2(workspaceDir, "specs", id, "spec.md");
529
+ if (!existsSync3(specFile)) {
530
+ return {
531
+ id,
532
+ issues: [{ type: "error", msg: "spec.md not found" }],
533
+ valid: false
534
+ };
535
+ }
536
+ const { errors, warnings } = validateSpecStructure(specFile);
537
+ const issues = [
538
+ ...errors.map((msg) => ({ type: "error", msg })),
539
+ ...warnings.map((msg) => ({ type: "warning", msg }))
540
+ ];
541
+ return { id, issues, valid: errors.length === 0 };
542
+ }
543
+
544
+ // src/flow-serve/context.ts
545
+ import { existsSync as existsSync5, readFileSync as readFileSync5, readdirSync as readdirSync2 } from "fs";
546
+ import { join as join4 } from "path";
547
+
548
+ // src/activity-context/compatibility.ts
549
+ var OBJECTIVES = {
550
+ design: "Definir dire\xE7\xE3o, escopo e restri\xE7\xF5es da pr\xF3xima mudan\xE7a.",
551
+ implement: "Executar a mudan\xE7a com foco no item ativo e nos crit\xE9rios da spec.",
552
+ review: "Avaliar alinhamento entre implementa\xE7\xE3o, spec, riscos e evid\xEAncias.",
553
+ diagnose: "Entender diverg\xEAncias, alertas e sinais operacionais do workspace.",
554
+ gate: "Preparar uma decis\xE3o humana com evid\xEAncias claras e riscos expl\xEDcitos."
555
+ };
556
+ var MUST_NOT_DO = {
557
+ design: [
558
+ "N\xE3o implementar c\xF3digo sem spec e dire\xE7\xE3o aprovadas.",
559
+ "N\xE3o mover decis\xF5es estruturais sem revis\xE3o humana."
560
+ ],
561
+ implement: [
562
+ "N\xE3o editar `workflow.json` manualmente.",
563
+ "N\xE3o implementar fora do escopo da spec ativa."
564
+ ],
565
+ review: [
566
+ "N\xE3o focar em novas features fora do diff/spec analisado.",
567
+ "N\xE3o aprovar sem checar riscos, ACs e sinais ativos."
568
+ ],
569
+ diagnose: [
570
+ "N\xE3o ignorar alertas de alta severidade sem registrar decis\xE3o.",
571
+ "N\xE3o tratar sintoma sem identificar a fonte de drift."
572
+ ],
573
+ gate: [
574
+ "N\xE3o avan\xE7ar est\xE1gio sem evid\xEAncias suficientes.",
575
+ "N\xE3o substituir decis\xE3o humana por automa\xE7\xE3o silenciosa."
576
+ ]
577
+ };
578
+ function compatibilityReferences(activity, context) {
579
+ const references = [
580
+ { path: ".letra/context.md", reason: "Contexto operacional do workspace" },
581
+ { path: ".letra/constitution.md", reason: "Regras n\xE3o negoci\xE1veis do Letra" }
582
+ ];
583
+ if (context.hasFocus) {
584
+ references.push({ path: ".letra/focus.md", reason: "Foco e outcome da sess\xE3o atual" });
585
+ }
586
+ if (context.specName) {
587
+ references.push({
588
+ path: `.letra/specs/${context.specName}/spec.md`,
589
+ reason: "Spec e crit\xE9rios do trabalho atual"
590
+ });
591
+ }
592
+ if (activity === "review" || activity === "gate") {
593
+ references.push({
594
+ path: ".letra/session-log.json",
595
+ reason: "Evid\xEAncias recentes e trilha operacional da sess\xE3o"
596
+ });
597
+ }
598
+ if (activity === "diagnose") {
599
+ references.push({
600
+ path: ".letra/health-record.json",
601
+ reason: "Estado persistente dos alertas ativos"
602
+ });
603
+ }
604
+ if (!context.hasCurrentItem) {
605
+ references.push({
606
+ path: ".letra/workflow.json",
607
+ reason: "Fonte de verdade para triagem e escolha do pr\xF3ximo item"
608
+ });
609
+ }
610
+ return references;
611
+ }
612
+ function currentItemActions(activity, context) {
613
+ const specRef = context.specName ? `spec \`${context.specName}\`` : "spec ativa";
614
+ switch (activity) {
615
+ case "design":
616
+ return [
617
+ {
618
+ label: "Revisar outcome",
619
+ description: `Validar objetivo e bordas da ${specRef}.`
620
+ },
621
+ {
622
+ label: "Fechar restri\xE7\xF5es",
623
+ description: "Transformar ambiguidades em constraints ou exclusions expl\xEDcitas."
624
+ },
625
+ {
626
+ label: "Preparar decis\xF5es",
627
+ description: "Listar escolhas arquiteturais ou de produto que exigem confirma\xE7\xE3o humana."
628
+ }
629
+ ];
630
+ case "implement":
631
+ return [
632
+ {
633
+ label: "Executar item ativo",
634
+ description: `Implementar o pr\xF3ximo passo observando os ACs da ${specRef}.`
635
+ },
636
+ {
637
+ label: "Evitar drift",
638
+ description: "Comparar a solu\xE7\xE3o proposta com foco, contexto e regras da constitution."
639
+ },
640
+ {
641
+ label: "Checar restri\xE7\xF5es",
642
+ description: "Confirmar limites de escopo antes de alterar estado, API ou arquitetura."
643
+ }
644
+ ];
645
+ case "review":
646
+ return [
647
+ {
648
+ label: "Comparar com spec",
649
+ description: context.review ? `Checar ${context.review.emphasis} contra a ${specRef}.` : `Checar ader\xEAncia do trabalho contra a ${specRef}.`
650
+ },
651
+ {
652
+ label: "Listar riscos",
653
+ description: context.review?.riskFocus ?? "Destacar bugs, regress\xF5es e viola\xE7\xF5es de processo antes de aprovar."
654
+ },
655
+ {
656
+ label: "Cobrar evid\xEAncias",
657
+ description: context.review?.evidencePrompt ?? "Verificar se testes, sinais e logs recentes sustentam a revis\xE3o."
658
+ }
659
+ ];
660
+ case "diagnose":
661
+ return [
662
+ {
663
+ label: "Ler sinais ativos",
664
+ description: "Inspecionar diverg\xEAncias entre foco, workflow e health."
665
+ },
666
+ {
667
+ label: "Definir causa raiz",
668
+ description: "Separar problemas de estado, spec e execu\xE7\xE3o."
669
+ },
670
+ {
671
+ label: "Priorizar impacto",
672
+ description: "Atacar primeiro inconsist\xEAncias que bloqueiam a atividade atual."
673
+ }
674
+ ];
675
+ case "gate":
676
+ return [
677
+ {
678
+ label: "Preparar evid\xEAncias",
679
+ description: context.gate ? `Reunir ${context.gate.evidence} para ${context.gate.label.toLowerCase()}.` : "Reunir sinais, riscos e estado do item para decis\xE3o humana."
680
+ },
681
+ {
682
+ label: "Explicitar decis\xE3o",
683
+ description: "Declarar claramente o que precisa ser aprovado ou bloqueado."
684
+ },
685
+ {
686
+ label: "Responder gate",
687
+ description: context.gate ? `Informar que a decis\xE3o esperada agora \xE9: ${context.gate.decision}.` : "Informar qual aprova\xE7\xE3o humana \xE9 esperada e por qu\xEA."
688
+ }
689
+ ];
690
+ }
691
+ }
692
+ function getCompatibilityActivityIntent(activity, context) {
693
+ return {
694
+ objective: OBJECTIVES[activity],
695
+ mustRead: compatibilityReferences(activity, context),
696
+ mustNotDo: [...MUST_NOT_DO[activity]],
697
+ nextActions: context.hasCurrentItem ? currentItemActions(activity, context) : [
698
+ {
699
+ label: "Triar item",
700
+ description: "Escolher ou criar um item ativo antes de aprofundar a execu\xE7\xE3o."
701
+ },
702
+ {
703
+ label: "Confirmar foco",
704
+ description: "Validar se a sess\xE3o deve seguir descoberta, design ou backlog."
705
+ }
706
+ ]
707
+ };
708
+ }
709
+
710
+ // src/activity-context/intent.ts
711
+ function slug(value) {
712
+ return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
713
+ }
714
+ function activityHint(config, activity) {
715
+ return config?.[activity];
716
+ }
717
+ function cloneHint(hint) {
718
+ if (!hint) return void 0;
719
+ return {
720
+ ...hint,
721
+ mustRead: hint.mustRead?.map((reference) => ({ ...reference })),
722
+ mustNotDo: hint.mustNotDo ? [...hint.mustNotDo] : void 0,
723
+ nextActions: hint.nextActions?.map((action) => ({ ...action }))
724
+ };
725
+ }
726
+ function mergeHints(base, override) {
727
+ if (!base) return cloneHint(override);
728
+ if (!override) return cloneHint(base);
729
+ return {
730
+ ...cloneHint(base),
731
+ ...cloneHint(override),
732
+ mustRead: override.mustRead ? override.mustRead.map((reference) => ({ ...reference })) : base.mustRead?.map((reference) => ({ ...reference })),
733
+ mustNotDo: override.mustNotDo ? [...override.mustNotDo] : base.mustNotDo ? [...base.mustNotDo] : void 0,
734
+ nextActions: override.nextActions ? override.nextActions.map((action) => ({ ...action })) : base.nextActions?.map((action) => ({ ...action }))
735
+ };
736
+ }
737
+ function resolveReview(sources, stageHint, phaseHint) {
738
+ const config = mergeHints(stageHint, phaseHint);
739
+ const phase = sources.activePhaseDef;
740
+ const stageName = sources.activeFlowStage?.name;
741
+ if (!config && !phase && !stageName) return null;
742
+ const label = config?.label ?? phase?.label ?? stageName ?? "Review atual";
743
+ const emphasis = config?.emphasis ?? sources.activePhaseHarness?.checks?.join(", ") ?? sources.activePhaseHarness?.instructions ?? phase?.description ?? "ader\xEAncia \xE0 spec, riscos e evid\xEAncias do trabalho entregue";
744
+ return {
745
+ config,
746
+ label,
747
+ emphasis,
748
+ code: config?.signalCode ?? `review-${slug(config?.label ?? phase?.id ?? stageName ?? "current")}`
749
+ };
750
+ }
751
+ function resolveGate(sources, stageHint, phaseHint) {
752
+ const config = mergeHints(stageHint, phaseHint);
753
+ const stageName = sources.activeFlowStage?.name;
754
+ const gate = sources.activeFlowStage?.gate;
755
+ if (!config && !gate && !stageName) return null;
756
+ const label = config?.label ?? gate?.name ?? (stageName ? `Aprova\xE7\xE3o humana para ${stageName}` : "Aprova\xE7\xE3o humana do est\xE1gio atual");
757
+ return {
758
+ config,
759
+ label,
760
+ evidence: config?.evidence ?? gate?.description ?? "estado do item, riscos e evid\xEAncias relevantes do workflow",
761
+ decision: config?.decision ?? label,
762
+ code: config?.signalCode ?? `gate-${slug(stageName ?? label) || "current"}`
763
+ };
764
+ }
765
+ function phaseActivityConfig(sources) {
766
+ return sources.activePhaseHarness?.activity;
767
+ }
768
+ function specializedPhaseHint(sources, activity) {
769
+ if (activity === "review") {
770
+ return sources.activePhaseHarness?.review;
771
+ }
772
+ if (activity === "gate") {
773
+ return sources.activePhaseHarness?.gate;
774
+ }
775
+ return void 0;
776
+ }
777
+ function setSection(intent, key, hint, source) {
778
+ const value = hint[key];
779
+ if (value === void 0) return;
780
+ intent[key] = Array.isArray(value) ? value.map((entry) => typeof entry === "object" ? { ...entry } : entry) : value;
781
+ intent.provenance[key] = source;
782
+ }
783
+ function resolveActivityIntent(activity, sources) {
784
+ const stageConfig = sources.activeFlowStage?.activity;
785
+ const stageHint = activityHint(stageConfig, activity);
786
+ const phaseDeclaredHint = activityHint(phaseActivityConfig(sources), activity);
787
+ const phaseHint = mergeHints(specializedPhaseHint(sources, activity), phaseDeclaredHint);
788
+ const review = activity === "review" ? resolveReview(
789
+ sources,
790
+ stageHint,
791
+ phaseHint
792
+ ) : null;
793
+ const gate = activity === "gate" ? resolveGate(
794
+ sources,
795
+ stageHint,
796
+ phaseHint
797
+ ) : null;
798
+ const compatibilityContext = {
799
+ specName: sources.spec?.name ?? null,
800
+ hasFocus: !!sources.focus,
801
+ hasCurrentItem: !!sources.currentItem,
802
+ review: review ? {
803
+ emphasis: review.emphasis,
804
+ riskFocus: review.config?.riskFocus,
805
+ evidencePrompt: review.config?.evidencePrompt
806
+ } : void 0,
807
+ gate: gate ? { label: gate.label, evidence: gate.evidence, decision: gate.decision } : void 0
808
+ };
809
+ const compatibility = getCompatibilityActivityIntent(activity, compatibilityContext);
810
+ const intent = {
811
+ ...compatibility,
812
+ provenance: {
813
+ objective: "compatibility",
814
+ mustRead: "compatibility",
815
+ mustNotDo: "compatibility",
816
+ nextActions: "compatibility"
817
+ },
818
+ warnings: [],
819
+ signal: review ? { code: review.code, message: `Review atual: ${review.label}.` } : gate ? { code: gate.code, message: `Gate esperado: ${gate.label}.` } : null
820
+ };
821
+ if (stageHint) {
822
+ setSection(intent, "objective", stageHint, "stage");
823
+ setSection(intent, "mustRead", stageHint, "stage");
824
+ setSection(intent, "mustNotDo", stageHint, "stage");
825
+ setSection(intent, "nextActions", stageHint, "stage");
826
+ }
827
+ if (phaseHint) {
828
+ setSection(intent, "objective", phaseHint, "phase");
829
+ setSection(intent, "mustRead", phaseHint, "phase");
830
+ setSection(intent, "mustNotDo", phaseHint, "phase");
831
+ setSection(intent, "nextActions", phaseHint, "phase");
832
+ }
833
+ const fallbackSections = Object.entries(intent.provenance).filter(([, source]) => source === "compatibility").map(([section]) => section);
834
+ if (fallbackSections.length > 0) {
835
+ intent.warnings.push(
836
+ `ACTIVITY_HINT_COMPATIBILITY_FALLBACK:${activity}:${fallbackSections.join(",")}`
837
+ );
838
+ }
839
+ return intent;
840
+ }
841
+
842
+ // src/activity-context/sources.ts
843
+ import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
844
+ import { join as join3 } from "path";
845
+ function getStageName2(workflow, stageId) {
846
+ return workflow.stages.find((stage) => stage.id === stageId)?.name ?? stageId;
847
+ }
848
+ function findCurrentItem2(workflow) {
849
+ const activeStages = workflow.stages.filter(
850
+ (stage) => stage.zone === "doing" || !stage.zone && stage.order > 0 && stage.order < workflow.stages.length - 1
851
+ ).map((stage) => stage.id);
852
+ const stageSet = new Set(activeStages);
853
+ if (stageSet.size === 0) {
854
+ const middle = Math.floor(workflow.stages.length / 2);
855
+ const stage = workflow.stages[middle];
856
+ if (stage) stageSet.add(stage.id);
857
+ }
858
+ const items = workflow.items.filter((item) => stageSet.has(item.stage));
859
+ if (items.length === 0) return null;
860
+ return items.reduce(
861
+ (left, right) => new Date(left.createdAt) > new Date(right.createdAt) ? left : right
862
+ );
863
+ }
864
+ function extractOutcome(content) {
865
+ const match = content.match(/## Outcome\s+([\s\S]*?)(?=\n## |\n*$)/);
866
+ return match ? match[1].trim() : null;
867
+ }
868
+ function countSpecACs2(content) {
869
+ const boldPending = content.match(/-\s*\[ \]\s*\*\*AC[-]?\d+\*\*/g) || [];
870
+ const boldDone = content.match(/-\s*\[[xX]\]\s*\*\*AC[-]?\d+\*\*/g) || [];
871
+ if (boldPending.length > 0 || boldDone.length > 0) {
872
+ return {
873
+ pending: boldPending.length,
874
+ done: boldDone.length,
875
+ total: boldPending.length + boldDone.length
876
+ };
877
+ }
878
+ const genericPending = content.match(/^- \[ \]\s+AC[-]?\d+/gm) || [];
879
+ const genericDone = content.match(/^- \[[xX]\]\s+AC[-]?\d+/gm) || [];
880
+ return {
881
+ pending: genericPending.length,
882
+ done: genericDone.length,
883
+ total: genericPending.length + genericDone.length
884
+ };
885
+ }
886
+ function loadSpecMeta(root, specName) {
887
+ if (!specName) return null;
888
+ const specPath = join3(getLetraDir2(root), "specs", specName, "spec.md");
889
+ if (!existsSync4(specPath)) {
890
+ return {
891
+ name: specName,
892
+ path: `.letra/specs/${specName}/spec.md`,
893
+ outcome: null,
894
+ acs: { pending: 0, done: 0, total: 0 }
895
+ };
896
+ }
897
+ const content = readFileSync4(specPath, "utf-8");
898
+ return {
899
+ name: specName,
900
+ path: `.letra/specs/${specName}/spec.md`,
901
+ outcome: extractOutcome(content),
902
+ acs: countSpecACs2(content)
903
+ };
904
+ }
905
+ function loadActivityContextSources(root) {
906
+ const workflow = loadWorkflow(root);
907
+ const flowResolution = resolveActiveFlow(root);
908
+ const focus = readFocusFile(root);
909
+ const focusedItem = workflow && focus?.itemId ? workflow.items.find((item) => item.id === focus.itemId) ?? null : null;
910
+ const currentItem = focusedItem ?? (workflow ? findCurrentItem2(workflow) : null);
911
+ const currentPhase = currentItem?.currentPhase ?? null;
912
+ const activeFlowStage = currentItem ? flowResolution.flow?.stages.find((stage) => stage.id === currentItem.stage) ?? null : null;
913
+ const activePhaseDef = currentPhase && activeFlowStage?.phases?.states?.[currentPhase] ? activeFlowStage.phases.states[currentPhase] : null;
914
+ const activePhaseHarness = activePhaseDef?.harness ?? null;
915
+ const activeReviewExpectation = activePhaseHarness?.activity?.review ?? activePhaseHarness?.review ?? activeFlowStage?.activity?.review ?? null;
916
+ const activeGateExpectation = activePhaseHarness?.activity?.gate ?? activePhaseHarness?.gate ?? activeFlowStage?.activity?.gate ?? null;
917
+ const focusDiverged = !!(focus && currentItem?.spec && focus.specName !== currentItem.spec);
918
+ const specName = focus?.specName || currentItem?.spec || null;
919
+ const spec = loadSpecMeta(root, specName);
920
+ const activeAlerts = getActiveEntries(loadHealthRecord(root));
921
+ const lastActions = queryLog(root, { all: false, limit: 5 });
922
+ return {
923
+ workflow,
924
+ currentItem,
925
+ currentPhase,
926
+ activeFlowStage,
927
+ activePhaseDef,
928
+ activePhaseHarness,
929
+ activeReviewExpectation,
930
+ activeGateExpectation,
931
+ focus,
932
+ focusDiverged,
933
+ spec,
934
+ activeAlerts,
935
+ lastActions
936
+ };
937
+ }
938
+
939
+ // src/activity-context/builder.ts
940
+ function buildSignals(activity, intentSignal, focusDiverged, alertCount, highSeverityCount, hasCurrentItem, pendingAcs) {
941
+ const signals = [];
942
+ if (!hasCurrentItem) {
943
+ signals.push({
944
+ level: "warning",
945
+ code: "no-current-item",
946
+ message: "Nenhum item em andamento. Selecione um item no Kanban para come\xE7ar."
947
+ });
948
+ }
949
+ if (focusDiverged) {
950
+ signals.push({
951
+ level: "error",
952
+ code: "focus-diverged",
953
+ message: "Foco desatualizado. Atualize focus.md ou selecione o item correto."
954
+ });
955
+ }
956
+ if (alertCount > 0) {
957
+ signals.push({
958
+ level: highSeverityCount > 0 ? "error" : "warning",
959
+ code: "active-health-alerts",
960
+ message: `${alertCount} alerta(s) ativo(s). Verifique o painel de supervis\xE3o antes de continuar.`
961
+ });
962
+ }
963
+ if ((activity === "review" || activity === "gate") && pendingAcs > 0) {
964
+ signals.push({
965
+ level: "warning",
966
+ code: "pending-acceptance-criteria",
967
+ message: `${pendingAcs} AC(s) pendente(s). Complete os crit\xE9rios antes de prosseguir.`
968
+ });
969
+ }
970
+ if (intentSignal) {
971
+ signals.push({ level: "info", ...intentSignal });
972
+ }
973
+ return signals;
974
+ }
975
+ function buildRisks(activity, alertCount, highSeverityCount, pendingAcs) {
976
+ const risks = [];
977
+ if (highSeverityCount > 0) {
978
+ risks.push({
979
+ level: "high",
980
+ message: `${highSeverityCount} alerta(s) de severidade alta ainda est\xE3o ativos.`
981
+ });
982
+ }
983
+ if (pendingAcs > 0) {
984
+ risks.push({
985
+ level: activity === "review" || activity === "gate" ? "high" : "medium",
986
+ message: `${pendingAcs} AC(s) ainda pendente(s) na spec ativa.`
987
+ });
988
+ }
989
+ if (alertCount > 0 && highSeverityCount === 0) {
990
+ risks.push({
991
+ level: "low",
992
+ message: "H\xE1 alertas ativos que podem sinalizar drift ou inconsist\xEAncia operacional."
993
+ });
994
+ }
995
+ return risks;
996
+ }
997
+ function buildActivityContext(options) {
998
+ const { activity, workspaceRoot } = options;
999
+ const sources = loadActivityContextSources(workspaceRoot);
1000
+ const intent = resolveActivityIntent(activity, sources);
1001
+ const currentItem = sources.currentItem;
1002
+ const currentItemContext = currentItem ? {
1003
+ id: currentItem.id,
1004
+ description: currentItem.description,
1005
+ stage: currentItem.stage,
1006
+ stageName: sources.activeFlowStage?.name ?? (sources.workflow ? getStageName2(sources.workflow, currentItem.stage) : currentItem.stage),
1007
+ currentPhase: sources.currentPhase ?? void 0,
1008
+ spec: currentItem.spec ?? null,
1009
+ outcome: sources.spec?.outcome ?? sources.focus?.outcome ?? null,
1010
+ acs: sources.spec?.acs ?? { pending: 0, done: 0, total: 0 }
1011
+ } : null;
1012
+ const stage = currentItem ? {
1013
+ id: currentItem.stage,
1014
+ name: sources.activeFlowStage?.name ?? (sources.workflow ? getStageName2(sources.workflow, currentItem.stage) : currentItem.stage)
1015
+ } : null;
1016
+ const highSeverityCount = sources.activeAlerts.filter(
1017
+ (entry) => entry.severity === "alta"
1018
+ ).length;
1019
+ const pendingAcs = sources.spec?.acs.pending ?? 0;
1020
+ return {
1021
+ activity,
1022
+ objective: intent.objective,
1023
+ currentItem: currentItemContext,
1024
+ stage,
1025
+ mustRead: intent.mustRead,
1026
+ mustNotDo: intent.mustNotDo,
1027
+ nextActions: intent.nextActions,
1028
+ risks: buildRisks(activity, sources.activeAlerts.length, highSeverityCount, pendingAcs),
1029
+ signals: buildSignals(
1030
+ activity,
1031
+ intent.signal,
1032
+ sources.focusDiverged,
1033
+ sources.activeAlerts.length,
1034
+ highSeverityCount,
1035
+ !!currentItem,
1036
+ pendingAcs
1037
+ )
1038
+ };
1039
+ }
1040
+
1041
+ // src/flow-serve/context.ts
1042
+ function resolveRequestedActivity(value) {
1043
+ return value === "design" || value === "implement" || value === "review" || value === "diagnose" || value === "gate" ? value : "implement";
1044
+ }
1045
+ function buildRequestedActivityContext(workspaceRoot, activityParam) {
1046
+ return buildActivityContext({
1047
+ activity: resolveRequestedActivity(activityParam),
1048
+ workspaceRoot
1049
+ });
1050
+ }
1051
+ function readFocusState(workspaceDir) {
1052
+ const focusFile = join4(workspaceDir, "focus.md");
1053
+ if (!existsSync5(focusFile)) return { active: false };
1054
+ const lines = readFileSync5(focusFile, "utf-8").split(/\r?\n/);
1055
+ const itemLine = lines.find((line) => line.startsWith("**Item**: "));
1056
+ return {
1057
+ active: true,
1058
+ spec: lines[0]?.replace(/^#\s*/, "") || "",
1059
+ itemId: itemLine?.replace("**Item**: ", "") || void 0
1060
+ };
1061
+ }
1062
+ function readFocusDocument(workspaceDir) {
1063
+ const focusFile = join4(workspaceDir, "focus.md");
1064
+ return existsSync5(focusFile) ? readFileSync5(focusFile, "utf-8") : null;
1065
+ }
1066
+ function readDecisions(workspaceDir) {
1067
+ const decisionsDir = join4(workspaceDir, "decisions");
1068
+ if (!existsSync5(decisionsDir)) return [];
1069
+ return readdirSync2(decisionsDir).filter((name) => name.endsWith(".md")).sort().reverse().map((name) => ({
1070
+ name,
1071
+ content: readFileSync5(join4(decisionsDir, name), "utf-8")
1072
+ }));
1073
+ }
1074
+ function contextFileExists(workspaceDir, file) {
1075
+ return existsSync5(join4(workspaceDir, file));
1076
+ }
1077
+
1078
+ // src/flow-serve/workspace.ts
1079
+ import {
1080
+ accessSync,
1081
+ constants,
1082
+ existsSync as existsSync6,
1083
+ mkdirSync as mkdirSync2,
1084
+ rmSync,
1085
+ readFileSync as readFileSync6,
1086
+ readdirSync as readdirSync3,
1087
+ statSync,
1088
+ writeFileSync as writeFileSync2
1089
+ } from "fs";
1090
+ import { basename, join as join5, resolve as resolve2 } from "path";
1091
+ var LEGACY_BOOTSTRAP_TEMPLATES = {
1092
+ padrao: {
1093
+ name: "Padr\xE3o",
1094
+ stages: [
1095
+ { id: "backlog", name: "Backlog", zone: "todo" },
1096
+ { id: "design", name: "Design", zone: "doing" },
1097
+ { id: "code", name: "Code", zone: "doing" },
1098
+ { id: "review", name: "Review", zone: "doing" },
1099
+ { id: "done", name: "Done", zone: "done" }
1100
+ ]
1101
+ },
1102
+ kanban: {
1103
+ name: "Kanban",
1104
+ stages: [
1105
+ { id: "todo", name: "A Fazer", zone: "todo" },
1106
+ { id: "doing", name: "Fazendo", zone: "doing" },
1107
+ { id: "done", name: "Feito", zone: "done" }
1108
+ ]
1109
+ },
1110
+ agil: {
1111
+ name: "\xC1gil",
1112
+ stages: [
1113
+ { id: "product-backlog", name: "Product Backlog", zone: "todo" },
1114
+ { id: "sprint-backlog", name: "Sprint Backlog", zone: "todo" },
1115
+ { id: "in-progress", name: "In Progress", zone: "doing" },
1116
+ { id: "review", name: "Review", zone: "doing" },
1117
+ { id: "done", name: "Done", zone: "done" }
1118
+ ]
1119
+ }
1120
+ };
1121
+ var TARGET_MARKERS = [
1122
+ "package.json",
1123
+ "pyproject.toml",
1124
+ "requirements.txt",
1125
+ "go.mod",
1126
+ "Cargo.toml",
1127
+ "pom.xml",
1128
+ "build.gradle",
1129
+ "build.gradle.kts"
1130
+ ];
1131
+ function hasTargetMarker(path) {
1132
+ return TARGET_MARKERS.some((marker) => existsSync6(join5(path, marker))) || existsSync6(join5(path, ".git"));
1133
+ }
1134
+ function detectStack(path) {
1135
+ const stack = /* @__PURE__ */ new Set();
1136
+ const evidence = [];
1137
+ const packagePath = join5(path, "package.json");
1138
+ if (existsSync6(packagePath)) {
1139
+ stack.add("Node.js");
1140
+ evidence.push("package.json");
1141
+ try {
1142
+ const pkg = JSON.parse(readFileSync6(packagePath, "utf-8"));
1143
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
1144
+ if (deps.react) stack.add("React");
1145
+ if (deps.vite) stack.add("Vite");
1146
+ if (deps.typescript) stack.add("TypeScript");
1147
+ if (deps.next) stack.add("Next.js");
1148
+ } catch {
1149
+ evidence.push("package.json inv\xE1lido");
1150
+ }
1151
+ }
1152
+ if (existsSync6(join5(path, "pyproject.toml")) || existsSync6(join5(path, "requirements.txt"))) {
1153
+ stack.add("Python");
1154
+ evidence.push(
1155
+ existsSync6(join5(path, "pyproject.toml")) ? "pyproject.toml" : "requirements.txt"
1156
+ );
1157
+ }
1158
+ if (existsSync6(join5(path, "go.mod"))) {
1159
+ stack.add("Go");
1160
+ evidence.push("go.mod");
1161
+ }
1162
+ if (existsSync6(join5(path, "Cargo.toml"))) {
1163
+ stack.add("Rust");
1164
+ evidence.push("Cargo.toml");
1165
+ }
1166
+ try {
1167
+ if (readdirSync3(path).some((file) => file.endsWith(".tf"))) {
1168
+ stack.add("Terraform");
1169
+ evidence.push("arquivos .tf");
1170
+ }
1171
+ } catch {
1172
+ }
1173
+ if (existsSync6(join5(path, "Dockerfile")) || existsSync6(join5(path, "docker-compose.yml"))) {
1174
+ stack.add("Docker");
1175
+ evidence.push(existsSync6(join5(path, "Dockerfile")) ? "Dockerfile" : "docker-compose.yml");
1176
+ }
1177
+ return { stack: [...stack], evidence };
1178
+ }
1179
+ function targetId(path) {
1180
+ const normalized = path.replace(/\\/g, "/").toLowerCase();
1181
+ let hash = 2166136261;
1182
+ for (const char of normalized) {
1183
+ hash ^= char.charCodeAt(0);
1184
+ hash = Math.imul(hash, 16777619);
1185
+ }
1186
+ return `target-${(hash >>> 0).toString(36)}`;
1187
+ }
1188
+ function discoverTargetPaths(root) {
1189
+ const candidates = /* @__PURE__ */ new Set();
1190
+ if (hasTargetMarker(root)) candidates.add(root);
1191
+ try {
1192
+ for (const entry of readdirSync3(root, { withFileTypes: true })) {
1193
+ if (!entry.isDirectory() || entry.name.startsWith(".") || entry.name === "node_modules")
1194
+ continue;
1195
+ const child = join5(root, entry.name);
1196
+ if (hasTargetMarker(child)) candidates.add(child);
1197
+ if (entry.name === "packages" || entry.name === "apps" || entry.name === "services") {
1198
+ for (const nested of readdirSync3(child, { withFileTypes: true }).slice(0, 50)) {
1199
+ if (!nested.isDirectory() || nested.name.startsWith(".")) continue;
1200
+ const nestedPath = join5(child, nested.name);
1201
+ if (hasTargetMarker(nestedPath)) candidates.add(nestedPath);
1202
+ }
1203
+ }
1204
+ }
1205
+ } catch {
1206
+ }
1207
+ if (candidates.size === 0) candidates.add(root);
1208
+ return [...candidates].slice(0, 100);
1209
+ }
1210
+ function analyzeWorkspaceSetup(input) {
1211
+ const root = resolve2(input.root);
1212
+ if (!existsSync6(root) || !statSync(root).isDirectory()) {
1213
+ throw new Error("A pasta inicial n\xE3o existe ou n\xE3o \xE9 um diret\xF3rio.");
1214
+ }
1215
+ try {
1216
+ accessSync(root, constants.R_OK);
1217
+ } catch {
1218
+ throw new Error("O Letra n\xE3o possui permiss\xE3o para ler a pasta inicial.");
1219
+ }
1220
+ const tools = supportedAdapterTools();
1221
+ const locations = discoverTargetPaths(root).map((path) => {
1222
+ const detectedTools = new Set(detectExistingTools(path));
1223
+ const detected = detectStack(path);
1224
+ return {
1225
+ id: targetId(path).replace(/^target-/, "loc-"),
1226
+ label: detectProjectName(path) || basename(path),
1227
+ path: path.replace(/\\/g, "/"),
1228
+ stack: detected.stack,
1229
+ evidence: detected.evidence,
1230
+ adapters: tools.map((tool) => {
1231
+ const isDetected = detectedTools.has(tool.id);
1232
+ return {
1233
+ tool: tool.id,
1234
+ label: tool.label,
1235
+ capabilities: tool.capabilities,
1236
+ state: isDetected ? "detected" : "available",
1237
+ selected: isDetected,
1238
+ evidence: isDetected ? tool.detectionPaths.filter(
1239
+ (adapterPath) => existsSync6(join5(path, adapterPath))
1240
+ ) : []
1241
+ };
1242
+ })
1243
+ };
1244
+ });
1245
+ return {
1246
+ id: `proposal-${Date.now().toString(36)}`,
1247
+ workspace: {
1248
+ name: input.name.trim(),
1249
+ root: root.replace(/\\/g, "/"),
1250
+ harnessVersion: DEFAULT_HARNESS_VERSION
1251
+ },
1252
+ locations,
1253
+ warnings: locations.every(
1254
+ (location) => location.adapters.every((adapter) => !adapter.selected)
1255
+ ) ? ["Nenhuma ferramenta ag\xEAntica foi detectada. Selecione os adapters manualmente."] : []
1256
+ };
1257
+ }
1258
+ function buildLineDiff(before, after) {
1259
+ if (before === after) return " Sem altera\xE7\xF5es de conte\xFAdo.";
1260
+ const beforeLines = before === "" ? [] : before.replace(/\r\n/g, "\n").split("\n");
1261
+ const afterLines = after === "" ? [] : after.replace(/\r\n/g, "\n").split("\n");
1262
+ let prefix = 0;
1263
+ while (prefix < beforeLines.length && prefix < afterLines.length && beforeLines[prefix] === afterLines[prefix])
1264
+ prefix += 1;
1265
+ let suffix = 0;
1266
+ while (suffix < beforeLines.length - prefix && suffix < afterLines.length - prefix && beforeLines[beforeLines.length - 1 - suffix] === afterLines[afterLines.length - 1 - suffix])
1267
+ suffix += 1;
1268
+ const lines = [
1269
+ ...beforeLines.slice(Math.max(0, prefix - 2), prefix).map((line) => ` ${line}`),
1270
+ ...beforeLines.slice(prefix, beforeLines.length - suffix).map((line) => `- ${line}`),
1271
+ ...afterLines.slice(prefix, afterLines.length - suffix).map((line) => `+ ${line}`),
1272
+ ...suffix > 0 ? afterLines.slice(
1273
+ afterLines.length - suffix,
1274
+ Math.min(afterLines.length, afterLines.length - suffix + 2)
1275
+ ).map((line) => ` ${line}`) : []
1276
+ ];
1277
+ const limit = 240;
1278
+ return lines.length > limit ? [...lines.slice(0, limit), ` ... ${lines.length - limit} linha(s) omitida(s)`].join("\n") : lines.join("\n");
1279
+ }
1280
+ function operationFor(path, context, after) {
1281
+ if (!existsSync6(path)) {
1282
+ return {
1283
+ kind: "create",
1284
+ path: path.replace(/\\/g, "/"),
1285
+ ...context,
1286
+ reason: "Arquivo ainda n\xE3o existe.",
1287
+ after,
1288
+ diff: buildLineDiff("", after)
1289
+ };
1290
+ }
1291
+ const current = readFileSync6(path, "utf-8");
1292
+ const generated = /(?:Generated by letra|Gerado (?:por|by) letra)/i.test(current.slice(0, 500));
1293
+ const managedSection = context.artifactId === "codex-project-config";
1294
+ return {
1295
+ kind: generated || managedSection ? "update" : "conflict",
1296
+ path: path.replace(/\\/g, "/"),
1297
+ ...context,
1298
+ reason: managedSection ? "Se\xE7\xE3o MCP do Letra mesclada preservando a configura\xE7\xE3o do usu\xE1rio." : generated ? "Adapter reconhecido como gerado pelo Letra." : "Existe conte\xFAdo n\xE3o reconhecido; o Letra n\xE3o ir\xE1 sobrescrev\xEA-lo.",
1299
+ before: current,
1300
+ after,
1301
+ diff: buildLineDiff(current, after)
1302
+ };
1303
+ }
1304
+ function planWorkspaceSetup(input) {
1305
+ const workspaceRoot = resolve2(input.workspaceRoot);
1306
+ const normalizedRoot = workspaceRoot.replace(/\\/g, "/");
1307
+ const operations = [];
1308
+ const workflowPath = join5(workspaceRoot, "workflow.json");
1309
+ const workflowBefore = existsSync6(workflowPath) ? readFileSync6(workflowPath, "utf-8") : void 0;
1310
+ const workflowAfter = input.workflow ? JSON.stringify(input.workflow, null, 2) : void 0;
1311
+ operations.push({
1312
+ kind: workflowBefore ? "conflict" : "create",
1313
+ path: workflowPath.replace(/\\/g, "/"),
1314
+ reason: workflowBefore ? "A pasta j\xE1 cont\xE9m um workflow; preserve-o ou escolha outra pasta." : "Harness can\xF4nico do workspace.",
1315
+ before: workflowBefore,
1316
+ after: workflowAfter,
1317
+ diff: workflowAfter ? buildLineDiff(workflowBefore || "", workflowAfter) : void 0
1318
+ });
1319
+ for (const target of input.targets) {
1320
+ const resolvedTarget = resolve2(target.path);
1321
+ if (!existsSync6(resolvedTarget) || !statSync(resolvedTarget).isDirectory()) {
1322
+ throw new Error(`O projeto "${target.label}" n\xE3o existe ou n\xE3o \xE9 um diret\xF3rio.`);
1323
+ }
1324
+ const linkPath = join5(resolvedTarget, ".letra-link");
1325
+ const linkBefore = existsSync6(linkPath) ? readFileSync6(linkPath, "utf-8") : void 0;
1326
+ const linkAfter = `${normalizedRoot}
1327
+ `;
1328
+ const linkMatches = linkBefore?.trim().replace(/\\/g, "/") === normalizedRoot;
1329
+ operations.push({
1330
+ kind: !linkBefore ? "create" : linkMatches ? "preserve" : "conflict",
1331
+ path: linkPath.replace(/\\/g, "/"),
1332
+ targetId: target.id,
1333
+ reason: !linkBefore ? "Link rastre\xE1vel para o harness central." : linkMatches ? "O target j\xE1 aponta para este workspace." : "O target est\xE1 vinculado a outro workspace.",
1334
+ before: linkBefore,
1335
+ after: linkAfter,
1336
+ diff: buildLineDiff(linkBefore || "", linkAfter)
1337
+ });
1338
+ const renderedAdapters = renderAdapterFiles(resolvedTarget, target.adapters, {
1339
+ source: "init",
1340
+ quiet: true,
1341
+ workspaceDir: workspaceRoot,
1342
+ workflow: input.workflow ? {
1343
+ name: input.workflow.name,
1344
+ stages: input.workflow.stages,
1345
+ items: input.workflow.items
1346
+ } : void 0,
1347
+ activeStageId: input.workflow?.stages[0]?.id ?? "backlog"
1348
+ });
1349
+ for (const adapter of renderedAdapters) {
1350
+ operations.push(
1351
+ operationFor(
1352
+ join5(resolvedTarget, adapter.path),
1353
+ {
1354
+ targetId: target.id,
1355
+ tool: adapter.tool,
1356
+ artifactId: adapter.artifactId
1357
+ },
1358
+ adapter.content
1359
+ )
1360
+ );
1361
+ }
1362
+ }
1363
+ return {
1364
+ proposalId: input.proposalId,
1365
+ workspaceRoot: normalizedRoot,
1366
+ operations,
1367
+ conflictCount: operations.filter((operation) => operation.kind === "conflict").length
1368
+ };
1369
+ }
1370
+ function createWorkflowFromTemplate(root, templateId, options, harness) {
1371
+ const template = harness?.flows?.[templateId] ? {
1372
+ name: harness.flows[templateId].name,
1373
+ stages: harness.flows[templateId].stages.map(stageFromTemplateStage)
1374
+ } : LEGACY_BOOTSTRAP_TEMPLATES[templateId];
1375
+ if (!template) {
1376
+ throw new Error(
1377
+ `Template "${templateId}" not found. Available: ${Object.keys(LEGACY_BOOTSTRAP_TEMPLATES).join(", ")}`
1378
+ );
1379
+ }
1380
+ const stages = template.stages.map((stage, index) => ({
1381
+ ...stage,
1382
+ order: "order" in stage && typeof stage.order === "number" ? stage.order : index
1383
+ }));
1384
+ const existing = loadWorkflow(root);
1385
+ return {
1386
+ version: "1.0",
1387
+ name: options?.name ?? detectProjectName(root) ?? template.name,
1388
+ language: existing?.language,
1389
+ createdAt: existing?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
1390
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1391
+ stages,
1392
+ items: existing?.items ?? [],
1393
+ specLinks: existing?.specLinks ?? void 0,
1394
+ tools: options?.tools ?? existing?.tools ?? [],
1395
+ template: templateId,
1396
+ harnessVersion: existing?.harnessVersion ?? DEFAULT_HARNESS_VERSION
1397
+ };
1398
+ }
1399
+ function registerWorkspaceSetup(input) {
1400
+ const name = input.name.trim();
1401
+ const description = input.description.trim();
1402
+ const workspaceRoot = input.workspacePath ? resolve2(input.workspacePath) : resolve2(process.cwd());
1403
+ mkdirSync2(workspaceRoot, { recursive: true });
1404
+ const slug2 = name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 64);
1405
+ const registryDir = join5(getLetraDir(), "workspaces", slug2);
1406
+ mkdirSync2(registryDir, { recursive: true });
1407
+ const workspaceId = `ws_${Date.now().toString(36)}`;
1408
+ const createdAt = (/* @__PURE__ */ new Date()).toISOString();
1409
+ const workspace = {
1410
+ id: workspaceId,
1411
+ name,
1412
+ description,
1413
+ slug: slug2,
1414
+ createdAt,
1415
+ root: workspaceRoot.replace(/\\/g, "/"),
1416
+ directories: input.directories,
1417
+ tools: input.tools,
1418
+ template: input.template
1419
+ };
1420
+ const registryFile = join5(registryDir, "workspace.json");
1421
+ if (existsSync6(registryFile)) {
1422
+ throw new Error("J\xE1 existe um workspace registrado com este nome.");
1423
+ }
1424
+ writeFileSync2(registryFile, JSON.stringify(workspace, null, 2), "utf-8");
1425
+ return { workspace, workspaceRoot, registryFile };
1426
+ }
1427
+ function writeWorkspaceTargetAdapters(workspaceRoot, targets, workflow) {
1428
+ const workspaceRootNormalized = workspaceRoot.replace(/\\/g, "/");
1429
+ for (const target of targets) {
1430
+ const targetPath = resolve2(target.path);
1431
+ if (!existsSync6(targetPath)) continue;
1432
+ writeFileSync2(join5(targetPath, ".letra-link"), `${workspaceRootNormalized}
1433
+ `, "utf-8");
1434
+ generateAdapters(targetPath, target.adapters, {
1435
+ source: "init",
1436
+ quiet: true,
1437
+ workspaceDir: workspaceRoot,
1438
+ workflow: {
1439
+ name: workflow.name,
1440
+ stages: workflow.stages,
1441
+ items: workflow.items
1442
+ },
1443
+ activeStageId: workflow.stages[0]?.id ?? "backlog"
1444
+ });
1445
+ }
1446
+ }
1447
+ function writeExternalWorkspaceSetup(workspaceRoot, workflow, workspace) {
1448
+ const root = resolve2(workspaceRoot);
1449
+ ensureExternalWorkspaceLayout(root, { workflow, workspace });
1450
+ writeFileSync2(join5(root, "workflow.json"), JSON.stringify(workflow, null, 2), "utf-8");
1451
+ writeFileSync2(join5(root, "workspace.json"), JSON.stringify(workspace, null, 2), "utf-8");
1452
+ }
1453
+ function workflowLocations(targets, workspaceRoot) {
1454
+ return targets.map((target) => ({
1455
+ id: target.id,
1456
+ path: target.path.replace(/\\/g, "/"),
1457
+ label: target.label,
1458
+ adapters: [...target.adapters]
1459
+ })).filter(
1460
+ (target) => resolve2(target.path) !== resolve2(workspaceRoot) || target.adapters.length > 0
1461
+ );
1462
+ }
1463
+ function captureWorkspaceSetup(plan) {
1464
+ return plan.operations.filter((operation) => operation.kind === "create" || operation.kind === "update").map((operation) => ({
1465
+ path: operation.path,
1466
+ existed: existsSync6(operation.path),
1467
+ contentBase64: existsSync6(operation.path) ? Buffer.from(readFileSync6(operation.path)).toString("base64") : void 0
1468
+ }));
1469
+ }
1470
+ function restoreWorkspaceSetup(snapshots) {
1471
+ for (const snapshot of [...snapshots].reverse()) {
1472
+ if (snapshot.existed) {
1473
+ mkdirSync2(join5(snapshot.path, ".."), { recursive: true });
1474
+ writeFileSync2(snapshot.path, Buffer.from(snapshot.contentBase64 || "", "base64"));
1475
+ } else if (existsSync6(snapshot.path)) {
1476
+ rmSync(snapshot.path, { force: true });
1477
+ }
1478
+ }
1479
+ }
1480
+ function saveWorkspaceSetupManifest(workspaceRoot, proposalId, operations, snapshots) {
1481
+ const manifestId = `setup-${Date.now().toString(36)}`;
1482
+ const manifestDir = join5(resolve2(workspaceRoot), "operations", "setup-manifests");
1483
+ mkdirSync2(manifestDir, { recursive: true });
1484
+ writeFileSync2(
1485
+ join5(manifestDir, `${manifestId}.json`),
1486
+ JSON.stringify(
1487
+ {
1488
+ id: manifestId,
1489
+ proposalId,
1490
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1491
+ operations,
1492
+ snapshots
1493
+ },
1494
+ null,
1495
+ 2
1496
+ ),
1497
+ "utf-8"
1498
+ );
1499
+ return manifestId;
1500
+ }
1501
+ function rollbackWorkspaceSetup(workspaceRoot, manifestId) {
1502
+ if (!/^setup-[a-z0-9]+$/i.test(manifestId)) throw new Error("Manifest de rollback inv\xE1lido.");
1503
+ const root = resolve2(workspaceRoot);
1504
+ const manifestPath = existsSync6(
1505
+ join5(root, "operations", "setup-manifests", `${manifestId}.json`)
1506
+ ) ? join5(root, "operations", "setup-manifests", `${manifestId}.json`) : join5(root, ".letra", "setup-manifests", `${manifestId}.json`);
1507
+ if (!existsSync6(manifestPath)) throw new Error("Manifest de rollback n\xE3o encontrado.");
1508
+ const manifest = JSON.parse(readFileSync6(manifestPath, "utf-8"));
1509
+ restoreWorkspaceSetup(Array.isArray(manifest.snapshots) ? manifest.snapshots : []);
1510
+ writeFileSync2(
1511
+ join5(manifestPath, "..", `${manifestId}.rollback.json`),
1512
+ JSON.stringify({ manifestId, rolledBackAt: (/* @__PURE__ */ new Date()).toISOString() }, null, 2),
1513
+ "utf-8"
1514
+ );
1515
+ }
1516
+
1517
+ // src/flow-serve/system-actions.ts
1518
+ var RECURRING_SYSTEM_ACTIONS = [
1519
+ {
1520
+ id: "workflow-watch",
1521
+ label: "Workflow watcher",
1522
+ trigger: "watch",
1523
+ cadence: "sob mudan\xE7a de arquivo",
1524
+ cause: "Mudan\xE7a em `.letra/workflow.json`",
1525
+ effect: "Recarrega estado observ\xE1vel do flow e emite `workflow-updated`"
1526
+ },
1527
+ {
1528
+ id: "specs-watch",
1529
+ label: "Specs watcher",
1530
+ trigger: "watch",
1531
+ cadence: "sob mudan\xE7a de arquivo",
1532
+ cause: "Mudan\xE7a em `.letra/specs/**`",
1533
+ effect: "Atualiza a vis\xE3o derivada de specs e emite `workflow-updated`"
1534
+ },
1535
+ {
1536
+ id: "diagnostics-scan",
1537
+ label: "Diagnostics recurring scan",
1538
+ trigger: "interval",
1539
+ cadence: "a cada 30 segundos e no boot",
1540
+ cause: "Timer do servidor e scan inicial",
1541
+ effect: "Sincroniza `health-record` e emite `diagnostics-updated`"
1542
+ }
1543
+ ];
1544
+ function logSystemAction(root, actionId, options) {
1545
+ const definition = RECURRING_SYSTEM_ACTIONS.find((item) => item.id === actionId);
1546
+ const cause = options.cause ?? definition?.cause ?? null;
1547
+ const effect = options.effect ?? definition?.effect ?? null;
1548
+ const descriptionParts = [`automation:${actionId}`, options.outcome];
1549
+ if (cause) descriptionParts.push(`cause=${cause}`);
1550
+ if (effect) descriptionParts.push(`effect=${effect}`);
1551
+ if (options.error) descriptionParts.push(`error=${options.error}`);
1552
+ return logEntry(root, "system", descriptionParts.join(" | "), {
1553
+ details: {
1554
+ systemAction: true,
1555
+ actionId,
1556
+ outcome: options.outcome,
1557
+ trigger: definition?.trigger ?? null,
1558
+ cadence: definition?.cadence ?? null,
1559
+ cause,
1560
+ effect,
1561
+ error: options.error ?? null,
1562
+ ...options.details
1563
+ }
1564
+ });
1565
+ }
1566
+ function getRecurringSystemActions(root) {
1567
+ const entries = loadSessionLog(root).entries;
1568
+ return RECURRING_SYSTEM_ACTIONS.map((definition) => {
1569
+ const last = [...entries].reverse().find(
1570
+ (entry) => entry.action === "system" && entry.details?.actionId === definition.id
1571
+ );
1572
+ const lastOutcome = typeof last?.details?.outcome === "string" ? last.details.outcome : null;
1573
+ const status = lastOutcome === "failed" ? "error" : lastOutcome === "completed" || lastOutcome === "triggered" ? "success" : lastOutcome === "armed" ? "active" : "idle";
1574
+ return {
1575
+ ...definition,
1576
+ status,
1577
+ lastRunAt: last?.timestamp ?? null,
1578
+ lastOutcome: lastOutcome ?? null,
1579
+ lastDescription: last?.description ?? null
1580
+ };
1581
+ });
1582
+ }
1583
+
1584
+ // src/flow-serve/request-context.ts
1585
+ function createRequestContext(req, res, url, binding) {
1586
+ return Object.freeze({
1587
+ req,
1588
+ res,
1589
+ url,
1590
+ path: url.pathname,
1591
+ method: req.method ?? "GET",
1592
+ workspaceRoot: binding.workspaceRoot,
1593
+ workspaceDir: binding.workspaceDir,
1594
+ workflow: binding.workflow
1595
+ });
1596
+ }
1597
+
1598
+ // src/flow-serve/router.ts
1599
+ var FlowServerRouter = class {
1600
+ handlers = [];
1601
+ register(handler) {
1602
+ this.handlers.push(handler);
1603
+ }
1604
+ async dispatch(context) {
1605
+ for (const handler of this.handlers) {
1606
+ if (await handler(context)) return true;
1607
+ }
1608
+ return false;
1609
+ }
1610
+ };
1611
+
1612
+ // src/flow-serve/http.ts
1613
+ var DEFAULT_MAX_BODY_BYTES = 1024 * 1024;
1614
+ var HttpBodyError = class extends Error {
1615
+ constructor(message, status) {
1616
+ super(message);
1617
+ this.status = status;
1618
+ this.name = "HttpBodyError";
1619
+ }
1620
+ status;
1621
+ };
1622
+ async function readJson(req, maxBytes = DEFAULT_MAX_BODY_BYTES) {
1623
+ const chunks = [];
1624
+ let size = 0;
1625
+ for await (const chunk of req) {
1626
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
1627
+ size += buffer.byteLength;
1628
+ if (size > maxBytes) {
1629
+ throw new HttpBodyError("Request body exceeds the allowed size", 413);
1630
+ }
1631
+ chunks.push(buffer);
1632
+ }
1633
+ try {
1634
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
1635
+ } catch {
1636
+ throw new HttpBodyError("Malformed JSON request body", 400);
1637
+ }
1638
+ }
1639
+ function sendJson(res, status, payload) {
1640
+ res.writeHead(status, { "Content-Type": "application/json" });
1641
+ res.end(JSON.stringify(payload));
1642
+ }
1643
+ function sendError(res, status, message) {
1644
+ sendJson(res, status, { error: message });
1645
+ }
1646
+ function routeParam(path, pattern) {
1647
+ const pathSegments = path.split("/").filter(Boolean);
1648
+ const patternSegments = pattern.split("/").filter(Boolean);
1649
+ if (pathSegments.length !== patternSegments.length) return null;
1650
+ let parameter = null;
1651
+ for (let index = 0; index < patternSegments.length; index += 1) {
1652
+ const expected = patternSegments[index];
1653
+ const actual = pathSegments[index];
1654
+ if (expected.startsWith(":")) {
1655
+ parameter = decodeURIComponent(actual);
1656
+ continue;
1657
+ }
1658
+ if (expected !== actual) return null;
1659
+ }
1660
+ return parameter;
1661
+ }
1662
+
1663
+ // src/flow-serve/routes/item-routes.ts
1664
+ function resolveDecisionTarget(flow, currentStageId, target) {
1665
+ const currentIndex = flow.stages.findIndex((stage) => stage.id === currentStageId);
1666
+ if (currentIndex === -1) return null;
1667
+ if (target === "next") return flow.stages[currentIndex + 1]?.id ?? null;
1668
+ if (target === "previous") return flow.stages[currentIndex - 1]?.id ?? null;
1669
+ if (target === "first") return flow.stages[0]?.id ?? null;
1670
+ return flow.stages.some((stage) => stage.id === target) ? target : null;
1671
+ }
1672
+ function sendBodyError(error, res) {
1673
+ if (error instanceof HttpBodyError) {
1674
+ sendError(res, error.status, error.message);
1675
+ return;
1676
+ }
1677
+ sendError(res, 400, error.message);
1678
+ }
1679
+ function createItemRoutes(dependencies) {
1680
+ return async (context) => {
1681
+ const { method, path, req, res, workspaceRoot, workflow } = context;
1682
+ if (path === "/api/items/alerts" && method === "GET") {
1683
+ const record = dependencies.loadHealthRecord(workspaceRoot);
1684
+ const itemAlerts = {};
1685
+ for (const entry of record.entries) {
1686
+ if (entry.status !== "novo") continue;
1687
+ const match = entry.id.match(/_([A-Z]+-\d+)_/);
1688
+ if (!match) continue;
1689
+ const itemId2 = match[1];
1690
+ itemAlerts[itemId2] = (itemAlerts[itemId2] ?? 0) + 1;
1691
+ }
1692
+ sendJson(res, 200, { itemAlerts });
1693
+ return true;
1694
+ }
1695
+ if (path === "/api/items" && method === "POST") {
1696
+ try {
1697
+ const data = await readJson(req);
1698
+ if (!data.id || !data.description || !data.stage) {
1699
+ sendError(res, 400, "id, description, and stage required");
1700
+ return true;
1701
+ }
1702
+ if (!workflow) {
1703
+ sendError(res, 404, "No workflow");
1704
+ return true;
1705
+ }
1706
+ const item = {
1707
+ id: data.id,
1708
+ description: data.description,
1709
+ stage: data.stage,
1710
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1711
+ tasks: []
1712
+ };
1713
+ workflow.items.push(item);
1714
+ workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1715
+ dependencies.writeWorkflow(workspaceRoot, {
1716
+ workflow,
1717
+ source: "web-ui",
1718
+ primaryItemId: item.id,
1719
+ skipSitrep: true,
1720
+ quiet: true
1721
+ });
1722
+ dependencies.broadcast();
1723
+ sendJson(res, 200, item);
1724
+ } catch (error) {
1725
+ sendBodyError(error, res);
1726
+ }
1727
+ return true;
1728
+ }
1729
+ const gateDecisionItemId = routeParam(path, "/api/items/:id/gate-decisions");
1730
+ if (gateDecisionItemId !== null && method === "POST") {
1731
+ try {
1732
+ const data = await readJson(req);
1733
+ if (!workflow) {
1734
+ sendError(res, 404, "No workflow");
1735
+ return true;
1736
+ }
1737
+ if (!data.decision || !["approve", "request-changes", "reject"].includes(data.decision)) {
1738
+ sendError(res, 400, "decision must be approve, request-changes, or reject");
1739
+ return true;
1740
+ }
1741
+ const reason = data.reason?.trim();
1742
+ if (data.decision !== "approve" && !reason) {
1743
+ sendError(res, 400, "reason is required for request-changes and reject");
1744
+ return true;
1745
+ }
1746
+ const item = workflow.items.find(
1747
+ (candidate) => candidate.id === gateDecisionItemId
1748
+ );
1749
+ if (!item) {
1750
+ sendError(res, 404, "Item not found");
1751
+ return true;
1752
+ }
1753
+ const resolved = dependencies.resolveActiveFlow(workspaceRoot, workflow);
1754
+ const flow = resolved.flow;
1755
+ const currentStage = flow?.stages.find((stage) => stage.id === item.stage);
1756
+ const gate = currentStage?.gate;
1757
+ if (!flow || gate?.type !== "human" || !gate.blocking) {
1758
+ sendError(res, 422, "Item is not waiting at a blocking human gate");
1759
+ return true;
1760
+ }
1761
+ const targetRule = gate.decisions?.[data.decision];
1762
+ if (!targetRule) {
1763
+ sendError(
1764
+ res,
1765
+ 422,
1766
+ `Gate "${gate.name}" does not define the "${data.decision}" decision in the harness`
1767
+ );
1768
+ return true;
1769
+ }
1770
+ const targetStage = resolveDecisionTarget(flow, item.stage, targetRule);
1771
+ if (!targetStage) {
1772
+ sendError(
1773
+ res,
1774
+ 422,
1775
+ `Gate "${gate.name}" resolves "${data.decision}" to an invalid stage`
1776
+ );
1777
+ return true;
1778
+ }
1779
+ const sourceStage = item.stage;
1780
+ item.stage = targetStage;
1781
+ workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1782
+ await dependencies.writeWorkflow(workspaceRoot, {
1783
+ workflow,
1784
+ source: "web-ui-gate-decision",
1785
+ primaryItemId: item.id,
1786
+ skipSitrep: true,
1787
+ quiet: true
1788
+ });
1789
+ dependencies.logEntry(
1790
+ workspaceRoot,
1791
+ "decision",
1792
+ `Gate ${gate.name}: ${data.decision} (${item.id})`,
1793
+ {
1794
+ itemId: item.id,
1795
+ details: {
1796
+ kind: "gate",
1797
+ gateId: gate.id,
1798
+ decision: data.decision,
1799
+ reason: reason ?? null,
1800
+ from: sourceStage,
1801
+ to: targetStage,
1802
+ by: "human:web-ui",
1803
+ outcome: "completed"
1804
+ }
1805
+ }
1806
+ );
1807
+ if (item.spec) {
1808
+ dependencies.writeFocusFile(workspaceRoot, item.spec, item.id);
1809
+ }
1810
+ dependencies.broadcast();
1811
+ void dependencies.fireWebhooks(workspaceRoot, "gate.decided", {
1812
+ itemId: item.id,
1813
+ gateId: gate.id,
1814
+ decision: data.decision,
1815
+ reason: reason ?? null,
1816
+ sourceStage,
1817
+ targetStage
1818
+ });
1819
+ sendJson(res, 200, {
1820
+ item,
1821
+ decision: {
1822
+ gateId: gate.id,
1823
+ value: data.decision,
1824
+ reason: reason ?? null,
1825
+ sourceStage,
1826
+ targetStage
1827
+ }
1828
+ });
1829
+ } catch (error) {
1830
+ sendBodyError(error, res);
1831
+ }
1832
+ return true;
1833
+ }
1834
+ const itemId = routeParam(path, "/api/items/:id");
1835
+ if (itemId !== null && method === "GET") {
1836
+ if (!workflow) {
1837
+ sendError(res, 404, "No workflow");
1838
+ return true;
1839
+ }
1840
+ const item = workflow.items.find((candidate) => candidate.id === itemId);
1841
+ if (!item) {
1842
+ sendError(res, 404, "Item not found");
1843
+ return true;
1844
+ }
1845
+ sendJson(res, 200, item);
1846
+ return true;
1847
+ }
1848
+ if (itemId !== null && method === "PATCH") {
1849
+ try {
1850
+ const data = await readJson(req);
1851
+ if (!workflow) {
1852
+ sendError(res, 404, "No workflow");
1853
+ return true;
1854
+ }
1855
+ const item = workflow.items.find((candidate) => candidate.id === itemId);
1856
+ if (!item) {
1857
+ sendError(res, 404, "Item not found");
1858
+ return true;
1859
+ }
1860
+ const oldStage = item.stage;
1861
+ if (data.stage !== void 0 && data.stage !== oldStage) {
1862
+ const resolved = dependencies.resolveActiveFlow(workspaceRoot, workflow);
1863
+ const sourceStage = resolved.flow?.stages.find(
1864
+ (stage) => stage.id === oldStage
1865
+ );
1866
+ if (sourceStage?.gate?.type === "human" && sourceStage.gate.blocking) {
1867
+ sendError(
1868
+ res,
1869
+ 422,
1870
+ `Gate bloqueante: ${sourceStage.gate.name}. Use uma decis\xE3o humana expl\xEDcita para sair de "${sourceStage.name}".`
1871
+ );
1872
+ return true;
1873
+ }
1874
+ const targetStage = resolved.flow?.stages.find(
1875
+ (stage) => stage.id === data.stage
1876
+ );
1877
+ const gate = targetStage?.gate;
1878
+ if (gate?.type === "human" && gate.blocking) {
1879
+ sendError(
1880
+ res,
1881
+ 422,
1882
+ `Gate bloqueante: ${gate.name}. Aprova\xE7\xE3o humana necess\xE1ria para entrar em "${targetStage?.name ?? data.stage}".`
1883
+ );
1884
+ return true;
1885
+ }
1886
+ item.stage = data.stage;
1887
+ }
1888
+ if (data.description !== void 0) item.description = data.description;
1889
+ if (data.tasks !== void 0) item.tasks = data.tasks;
1890
+ workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1891
+ dependencies.writeWorkflow(workspaceRoot, {
1892
+ workflow,
1893
+ source: "web-ui",
1894
+ primaryItemId: itemId,
1895
+ skipSitrep: true,
1896
+ quiet: true
1897
+ });
1898
+ dependencies.broadcast();
1899
+ if (data.stage !== void 0 && data.stage !== oldStage) {
1900
+ if (item.spec) {
1901
+ dependencies.writeFocusFile(workspaceRoot, item.spec, item.id);
1902
+ dependencies.logEntry(
1903
+ workspaceRoot,
1904
+ "focus_sync",
1905
+ `Focus synced to ${item.spec} via item move (${item.id})`,
1906
+ { itemId: item.id, spec: item.spec }
1907
+ );
1908
+ console.log(` [focus] Synced to ${item.spec} via drag`);
1909
+ }
1910
+ void dependencies.fireWebhooks(workspaceRoot, "item.moved", {
1911
+ itemId: item.id,
1912
+ itemDescription: item.description,
1913
+ sourceStage: oldStage,
1914
+ targetStage: data.stage
1915
+ });
1916
+ }
1917
+ sendJson(res, 200, item);
1918
+ } catch (error) {
1919
+ sendBodyError(error, res);
1920
+ }
1921
+ return true;
1922
+ }
1923
+ if (itemId !== null && method === "DELETE") {
1924
+ if (!workflow) {
1925
+ sendError(res, 404, "No workflow");
1926
+ return true;
1927
+ }
1928
+ const index = workflow.items.findIndex((candidate) => candidate.id === itemId);
1929
+ if (index === -1) {
1930
+ sendError(res, 404, "Item not found");
1931
+ return true;
1932
+ }
1933
+ workflow.items.splice(index, 1);
1934
+ workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1935
+ dependencies.writeWorkflow(workspaceRoot, {
1936
+ workflow,
1937
+ source: "web-ui",
1938
+ skipSitrep: true,
1939
+ quiet: true
1940
+ });
1941
+ dependencies.broadcast();
1942
+ sendJson(res, 200, { deleted: itemId });
1943
+ return true;
1944
+ }
1945
+ const claimId = routeParam(path, "/api/items/:id/claim");
1946
+ if (claimId !== null && method === "POST") {
1947
+ if (!workflow) {
1948
+ sendError(res, 404, "No workflow");
1949
+ return true;
1950
+ }
1951
+ const item = workflow.items.find((candidate) => candidate.id === claimId);
1952
+ if (!item) {
1953
+ sendError(res, 404, "Item not found");
1954
+ return true;
1955
+ }
1956
+ const doneZones = new Set(
1957
+ workflow.stages.filter((stage) => stage.zone === "done").map((stage) => stage.id)
1958
+ );
1959
+ if (doneZones.has(item.stage)) {
1960
+ sendError(res, 400, "Cannot claim a completed item");
1961
+ return true;
1962
+ }
1963
+ item.claimedBy = "web-ui";
1964
+ item.claimedAt = (/* @__PURE__ */ new Date()).toISOString();
1965
+ workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1966
+ dependencies.writeWorkflow(workspaceRoot, {
1967
+ workflow,
1968
+ source: "web-ui",
1969
+ primaryItemId: item.id,
1970
+ skipSitrep: true,
1971
+ quiet: true
1972
+ });
1973
+ dependencies.broadcast();
1974
+ sendJson(res, 200, item);
1975
+ return true;
1976
+ }
1977
+ const releaseId = routeParam(path, "/api/items/:id/release");
1978
+ if (releaseId !== null && method === "POST") {
1979
+ if (!workflow) {
1980
+ sendError(res, 404, "No workflow");
1981
+ return true;
1982
+ }
1983
+ const item = workflow.items.find((candidate) => candidate.id === releaseId);
1984
+ if (!item) {
1985
+ sendError(res, 404, "Item not found");
1986
+ return true;
1987
+ }
1988
+ item.claimedBy = void 0;
1989
+ item.claimedAt = void 0;
1990
+ workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1991
+ dependencies.writeWorkflow(workspaceRoot, {
1992
+ workflow,
1993
+ source: "web-ui",
1994
+ skipSitrep: true,
1995
+ quiet: true
1996
+ });
1997
+ dependencies.broadcast();
1998
+ sendJson(res, 200, item);
1999
+ return true;
2000
+ }
2001
+ const focusId = routeParam(path, "/api/items/:id/focus");
2002
+ if (focusId !== null && method === "POST") {
2003
+ if (!workflow) {
2004
+ sendError(res, 404, "No workflow");
2005
+ return true;
2006
+ }
2007
+ const item = workflow.items.find((candidate) => candidate.id === focusId);
2008
+ if (!item) {
2009
+ sendError(res, 404, "Item not found");
2010
+ return true;
2011
+ }
2012
+ const specName = item.spec || focusId;
2013
+ dependencies.writeFocusFile(workspaceRoot, specName, item.id);
2014
+ dependencies.logEntry(workspaceRoot, "focus_set", `Focus set via UI: ${specName}`, {
2015
+ itemId: focusId
2016
+ });
2017
+ dependencies.broadcast();
2018
+ sendJson(res, 200, { itemId: focusId, spec: specName });
2019
+ return true;
2020
+ }
2021
+ return false;
2022
+ };
2023
+ }
2024
+
2025
+ // src/flow-serve/routes/spec-routes.ts
2026
+ function specIdFrom(path) {
2027
+ return decodeURIComponent(path.replace("/api/specs/", "").split("/")[0] ?? "");
2028
+ }
2029
+ function sendBodyError2(error, res) {
2030
+ if (error instanceof HttpBodyError) {
2031
+ sendError(res, error.status, error.message);
2032
+ return;
2033
+ }
2034
+ sendError(res, 400, error.message);
2035
+ }
2036
+ function createSpecRoutes(dependencies) {
2037
+ return async ({ method, path, req, res, workspaceRoot, workspaceDir, workflow }) => {
2038
+ if (path === "/api/specs" && method === "GET") {
2039
+ try {
2040
+ sendJson(res, 200, dependencies.loadResolvedSpecs(workspaceRoot, workflow));
2041
+ } catch {
2042
+ sendJson(res, 200, []);
2043
+ }
2044
+ return true;
2045
+ }
2046
+ if (path === "/api/specs" && method === "POST") {
2047
+ try {
2048
+ const { id, content } = await readJson(req);
2049
+ if (!id || !content) {
2050
+ sendError(res, 400, "id and content required");
2051
+ return true;
2052
+ }
2053
+ dependencies.writeSpec(workspaceDir, id, content);
2054
+ if (workflow) {
2055
+ workflow.specLinks ??= {};
2056
+ workflow.specLinks[id] = { path: `.letra/specs/${id}/spec.md` };
2057
+ workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2058
+ dependencies.writeWorkflow(workspaceRoot, {
2059
+ workflow,
2060
+ source: "web-ui",
2061
+ skipSitrep: true,
2062
+ quiet: true
2063
+ });
2064
+ dependencies.broadcast();
2065
+ }
2066
+ sendJson(res, 200, { id, content });
2067
+ } catch (error) {
2068
+ sendBodyError2(error, res);
2069
+ }
2070
+ return true;
2071
+ }
2072
+ if (!path.startsWith("/api/specs/")) return false;
2073
+ const specId = specIdFrom(path);
2074
+ if (method === "POST" && path.endsWith("/validate")) {
2075
+ sendJson(res, 200, dependencies.validateSpec(workspaceDir, specId));
2076
+ return true;
2077
+ }
2078
+ if (method === "DELETE") {
2079
+ if (!specId) {
2080
+ sendError(res, 400, "spec id required");
2081
+ return true;
2082
+ }
2083
+ dependencies.clearSpec(workspaceDir, specId);
2084
+ if (workflow?.specLinks) {
2085
+ delete workflow.specLinks[specId];
2086
+ workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2087
+ dependencies.writeWorkflow(workspaceRoot, {
2088
+ workflow,
2089
+ source: "web-ui",
2090
+ skipSitrep: true,
2091
+ quiet: true
2092
+ });
2093
+ dependencies.broadcast();
2094
+ }
2095
+ sendJson(res, 200, { deleted: specId });
2096
+ return true;
2097
+ }
2098
+ if (method === "PUT") {
2099
+ try {
2100
+ const { content } = await readJson(req);
2101
+ if (content === void 0) {
2102
+ sendError(res, 400, "content required");
2103
+ return true;
2104
+ }
2105
+ dependencies.writeSpec(workspaceDir, specId, content);
2106
+ if (workflow) {
2107
+ workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2108
+ dependencies.writeWorkflow(workspaceRoot, {
2109
+ workflow,
2110
+ source: "web-ui",
2111
+ skipSitrep: true,
2112
+ quiet: true
2113
+ });
2114
+ dependencies.broadcast();
2115
+ }
2116
+ sendJson(res, 200, { id: specId, content });
2117
+ } catch (error) {
2118
+ sendBodyError2(error, res);
2119
+ }
2120
+ return true;
2121
+ }
2122
+ return false;
2123
+ };
2124
+ }
2125
+
2126
+ // src/flow-serve/routes/diagnostics-routes.ts
2127
+ function sendBodyError3(error, res) {
2128
+ if (error instanceof HttpBodyError) {
2129
+ sendError(res, error.status, error.message);
2130
+ return;
2131
+ }
2132
+ sendError(res, 400, error.message);
2133
+ }
2134
+ function createDiagnosticsRoutes(dependencies) {
2135
+ return async ({ method, path, req, res, url, workspaceRoot }) => {
2136
+ const engine = dependencies.engineFor(workspaceRoot);
2137
+ if (path === "/api/diagnostics" && method === "GET") {
2138
+ sendJson(res, 200, engine.getLastOutput());
2139
+ return true;
2140
+ }
2141
+ if (path === "/api/diagnostics/snapshots" && method === "GET") {
2142
+ let snapshots = engine.listSnapshots();
2143
+ const total = snapshots.length;
2144
+ const limitParam = url.searchParams.get("limit");
2145
+ const offsetParam = url.searchParams.get("offset");
2146
+ if (limitParam === null && offsetParam === null) {
2147
+ sendJson(res, 200, { snapshots });
2148
+ return true;
2149
+ }
2150
+ const limit = limitParam ? Number.parseInt(limitParam, 10) : total;
2151
+ const offset = offsetParam ? Number.parseInt(offsetParam, 10) : 0;
2152
+ snapshots = snapshots.slice(offset, offset + limit);
2153
+ sendJson(res, 200, { snapshots, total, limit, offset });
2154
+ return true;
2155
+ }
2156
+ if (path === "/api/diagnostics/scan" && method === "POST") {
2157
+ try {
2158
+ const output = await dependencies.runDiagnostics(engine, workspaceRoot);
2159
+ dependencies.broadcastDiagnostics(output);
2160
+ sendJson(res, 200, output);
2161
+ } catch (error) {
2162
+ sendError(res, 500, error.message);
2163
+ }
2164
+ return true;
2165
+ }
2166
+ const undoMatch = path.match(/^\/api\/diagnostics\/undo\/(.+)$/);
2167
+ if (undoMatch && method === "POST") {
2168
+ try {
2169
+ const result = await engine.undo(decodeURIComponent(undoMatch[1]));
2170
+ if (!result.ok) sendError(res, 404, "Snapshot not found");
2171
+ else {
2172
+ dependencies.broadcast();
2173
+ sendJson(res, 200, result);
2174
+ }
2175
+ } catch (error) {
2176
+ sendError(res, 500, error.message);
2177
+ }
2178
+ return true;
2179
+ }
2180
+ const redoMatch = path.match(/^\/api\/diagnostics\/redo\/(.+)$/);
2181
+ if (redoMatch && method === "POST") {
2182
+ try {
2183
+ const result = await engine.redo(decodeURIComponent(redoMatch[1]));
2184
+ if (!result.ok) sendError(res, 404, "Snapshot not found");
2185
+ else {
2186
+ dependencies.broadcast();
2187
+ sendJson(res, 200, result);
2188
+ }
2189
+ } catch (error) {
2190
+ sendError(res, 500, error.message);
2191
+ }
2192
+ return true;
2193
+ }
2194
+ if (path === "/api/health" && method === "GET") {
2195
+ const record = dependencies.loadHealthRecord(workspaceRoot);
2196
+ sendJson(res, 200, {
2197
+ summary: dependencies.getSummary(record),
2198
+ entries: record.entries,
2199
+ active: dependencies.getActiveEntries(record)
2200
+ });
2201
+ return true;
2202
+ }
2203
+ if (path === "/api/health/alerts" && method === "GET") {
2204
+ const record = dependencies.loadHealthRecord(workspaceRoot);
2205
+ sendJson(
2206
+ res,
2207
+ 200,
2208
+ record.entries.filter((entry) => entry.status === "novo")
2209
+ );
2210
+ return true;
2211
+ }
2212
+ if (path === "/api/health/scan" && method === "POST") {
2213
+ try {
2214
+ const output = await dependencies.runDiagnostics(engine, workspaceRoot);
2215
+ dependencies.broadcastDiagnostics(output);
2216
+ sendJson(res, 200, {
2217
+ fixes: output.fixes.length,
2218
+ suggestions: output.suggestions.length
2219
+ });
2220
+ } catch (error) {
2221
+ sendError(res, 500, error.message);
2222
+ }
2223
+ return true;
2224
+ }
2225
+ if (path === "/api/health/ack" && method === "POST") {
2226
+ try {
2227
+ const { id } = await readJson(req);
2228
+ const record = dependencies.loadHealthRecord(workspaceRoot);
2229
+ if (!dependencies.ackEntry(record, id)) sendError(res, 404, "Entry not found");
2230
+ else {
2231
+ dependencies.saveHealthRecord(workspaceRoot, record);
2232
+ dependencies.broadcast();
2233
+ sendJson(res, 200, { acked: id });
2234
+ }
2235
+ } catch (error) {
2236
+ sendBodyError3(error, res);
2237
+ }
2238
+ return true;
2239
+ }
2240
+ if (path === "/api/health/dismiss" && method === "POST") {
2241
+ try {
2242
+ const { id, reason } = await readJson(req);
2243
+ const record = dependencies.loadHealthRecord(workspaceRoot);
2244
+ if (!dependencies.dismissEntry(record, id, reason)) {
2245
+ sendError(res, 404, "Entry not found");
2246
+ } else {
2247
+ dependencies.saveHealthRecord(workspaceRoot, record);
2248
+ dependencies.broadcast();
2249
+ sendJson(res, 200, { dismissed: id });
2250
+ }
2251
+ } catch (error) {
2252
+ sendBodyError3(error, res);
2253
+ }
2254
+ return true;
2255
+ }
2256
+ return false;
2257
+ };
2258
+ }
2259
+
2260
+ // src/operational-audit/normalizer.ts
2261
+ function inferKind(entry) {
2262
+ if (entry.action === "system") return "system";
2263
+ if (entry.action === "manual") return "human";
2264
+ if (entry.action === "ac_done" || entry.action === "ac_complete") return "execution";
2265
+ if (entry.action === "validate" || entry.action === "diagnose") return "execution";
2266
+ if (entry.action === "health_scan" || entry.action === "health_ack" || entry.action === "health_dismiss")
2267
+ return "system";
2268
+ return "flow";
2269
+ }
2270
+ function inferStatus(entry) {
2271
+ const action = entry.action;
2272
+ const outcome = entry.details?.outcome;
2273
+ if (outcome === "failed" || outcome === "error") return "failed";
2274
+ if (outcome === "triggered" || outcome === "started") return "started";
2275
+ if (outcome === "armed") return "started";
2276
+ if (outcome === "completed") return "succeeded";
2277
+ if (action === "ac_done" || action === "item_move" || action === "item_release")
2278
+ return "succeeded";
2279
+ if (action === "validate" || action === "diagnose" || action === "health_scan")
2280
+ return "succeeded";
2281
+ if (action === "decision" || action === "sitrep") return "succeeded";
2282
+ if (action === "focus_set" || action === "focus_sync" || action === "focus_clear")
2283
+ return "succeeded";
2284
+ if (action === "session_end") return "succeeded";
2285
+ if (action === "manual") return "succeeded";
2286
+ if (action === "health_ack" || action === "health_dismiss") return "succeeded";
2287
+ return "info";
2288
+ }
2289
+ function inferActor(entry) {
2290
+ if (entry.action === "system") return { type: "system", label: "automation" };
2291
+ if (entry.action === "manual") return { type: "human", label: "User" };
2292
+ const by = entry.details?.by;
2293
+ if (typeof by === "string") return { type: "human", label: by };
2294
+ if (entry.details?.systemAction) return { type: "system", label: "automation" };
2295
+ return { type: "system", label: "Letra" };
2296
+ }
2297
+ function inferSource(entry) {
2298
+ const trigger = entry.details?.trigger;
2299
+ if (entry.action === "system") {
2300
+ if (trigger === "watch") return { surface: "watcher" };
2301
+ if (trigger === "interval") return { surface: "harness" };
2302
+ return { surface: "harness" };
2303
+ }
2304
+ if (entry.action === "manual") return { surface: "cli" };
2305
+ return { surface: "harness" };
2306
+ }
2307
+ function inferSubject(entry) {
2308
+ if (entry.itemId) return { type: "item", id: entry.itemId };
2309
+ if (entry.acId) return { type: "ac", id: entry.acId };
2310
+ const specVal = entry.details?.spec;
2311
+ if (typeof specVal === "string") return { type: "spec", id: specVal };
2312
+ return void 0;
2313
+ }
2314
+ function buildSummary(entry) {
2315
+ const desc = entry.description;
2316
+ const actionId = entry.details?.actionId;
2317
+ const outcome = entry.details?.outcome;
2318
+ if (typeof actionId === "string" && typeof outcome === "string") {
2319
+ const label = actionId;
2320
+ return `${label}: ${outcome}`;
2321
+ }
2322
+ return desc.split("|")[0]?.trim() || desc;
2323
+ }
2324
+ function inferReason(entry) {
2325
+ const reason = entry.details?.reason;
2326
+ if (typeof reason === "string") return reason;
2327
+ const cause = entry.details?.cause;
2328
+ if (typeof cause === "string") return cause;
2329
+ return void 0;
2330
+ }
2331
+ function inferCorrelationId(entry) {
2332
+ const actionId = entry.details?.actionId;
2333
+ if (typeof actionId === "string") return actionId;
2334
+ const runId = entry.details?.runId;
2335
+ if (typeof runId === "string") return runId;
2336
+ const corrId = entry.details?.correlationId;
2337
+ if (typeof corrId === "string") return corrId;
2338
+ return void 0;
2339
+ }
2340
+ function normalizeEntry(entry) {
2341
+ return {
2342
+ id: entry.id,
2343
+ timestamp: entry.timestamp,
2344
+ kind: inferKind(entry),
2345
+ action: entry.action,
2346
+ status: inferStatus(entry),
2347
+ actor: inferActor(entry),
2348
+ source: inferSource(entry),
2349
+ subject: inferSubject(entry),
2350
+ summary: buildSummary(entry),
2351
+ reason: inferReason(entry),
2352
+ correlationId: inferCorrelationId(entry),
2353
+ details: { ...entry.details },
2354
+ legacy: { ...entry }
2355
+ };
2356
+ }
2357
+ function normalizeEntries(entries) {
2358
+ return entries.map(normalizeEntry);
2359
+ }
2360
+ function buildAuditResponse(entries, total, page, limit) {
2361
+ const items = normalizeEntries(entries);
2362
+ const kinds = {};
2363
+ const statuses = {};
2364
+ const sources = {};
2365
+ const actions = {};
2366
+ for (const item of items) {
2367
+ kinds[item.kind] = (kinds[item.kind] || 0) + 1;
2368
+ statuses[item.status] = (statuses[item.status] || 0) + 1;
2369
+ sources[item.source.surface] = (sources[item.source.surface] || 0) + 1;
2370
+ actions[item.action] = (actions[item.action] || 0) + 1;
2371
+ }
2372
+ return {
2373
+ items,
2374
+ entries,
2375
+ total,
2376
+ page,
2377
+ limit,
2378
+ facets: { kinds, statuses, sources, actions }
2379
+ };
2380
+ }
2381
+
2382
+ // src/flow-serve/routes/context-routes.ts
2383
+ function sendBodyError4(error, res) {
2384
+ if (error instanceof HttpBodyError) sendError(res, error.status, error.message);
2385
+ else sendError(res, 400, error.message);
2386
+ }
2387
+ function createContextRoutes(dependencies) {
2388
+ return async ({ method, path, req, res, url, workspaceRoot, workspaceDir }) => {
2389
+ if (path === "/api/focus") {
2390
+ if (method === "DELETE") {
2391
+ dependencies.clearFocusFile(workspaceRoot);
2392
+ dependencies.logEntry(workspaceRoot, "focus_clear", "Focus cleared via UI");
2393
+ dependencies.broadcast();
2394
+ sendJson(res, 200, { active: false });
2395
+ return true;
2396
+ }
2397
+ if (method === "POST") {
2398
+ try {
2399
+ const data = await readJson(req);
2400
+ const spec = data.spec || "unknown";
2401
+ const itemId = data.itemId || "";
2402
+ dependencies.writeFocusFile(workspaceRoot, spec, itemId);
2403
+ dependencies.logEntry(workspaceRoot, "focus_set", `Focus set via UI: ${spec}`, {
2404
+ itemId
2405
+ });
2406
+ dependencies.broadcast();
2407
+ sendJson(res, 200, { active: true, spec, itemId });
2408
+ } catch (error) {
2409
+ sendBodyError4(error, res);
2410
+ }
2411
+ return true;
2412
+ }
2413
+ const state = dependencies.readFocusState(workspaceDir);
2414
+ const content = dependencies.readFocusDocument(workspaceDir);
2415
+ sendJson(
2416
+ res,
2417
+ 200,
2418
+ state.active ? { ...state, content: content ?? "" } : { active: false }
2419
+ );
2420
+ return true;
2421
+ }
2422
+ if (path === "/api/context") {
2423
+ const file = url.searchParams.get("file") || "context.md";
2424
+ if (file === "decisions") {
2425
+ sendJson(res, 200, dependencies.readDecisions(workspaceDir));
2426
+ return true;
2427
+ }
2428
+ const content = dependencies.readAllowedContextFile(workspaceDir, file);
2429
+ if (content === null) {
2430
+ sendError(
2431
+ res,
2432
+ dependencies.contextFileExists(workspaceDir, file) ? 400 : 404,
2433
+ dependencies.contextFileExists(workspaceDir, file) ? `Invalid file: ${file}` : `File not found: ${file}`
2434
+ );
2435
+ return true;
2436
+ }
2437
+ res.writeHead(200, { "Content-Type": "text/plain" });
2438
+ res.end(content);
2439
+ return true;
2440
+ }
2441
+ if (path === "/api/log" && method === "GET") {
2442
+ const rawLimit = url.searchParams.get("limit");
2443
+ const rawPage = url.searchParams.get("page");
2444
+ const page = rawPage ? Math.max(1, Number.parseInt(rawPage, 10)) : 1;
2445
+ const limit = rawLimit ? Math.max(1, Math.min(500, Number.parseInt(rawLimit, 10))) : 50;
2446
+ const offset = (page - 1) * limit;
2447
+ const result = dependencies.queryLogWithMeta(workspaceRoot, {
2448
+ all: url.searchParams.get("all") === "true",
2449
+ itemId: url.searchParams.get("item") ?? void 0,
2450
+ action: url.searchParams.get("action") ?? void 0,
2451
+ since: url.searchParams.get("since") ?? void 0,
2452
+ q: url.searchParams.get("q") ?? void 0,
2453
+ from: url.searchParams.get("from") ?? void 0,
2454
+ to: url.searchParams.get("to") ?? void 0,
2455
+ spec: url.searchParams.get("spec") ?? void 0,
2456
+ actor: url.searchParams.get("actor") ?? void 0,
2457
+ debug: url.searchParams.get("debug") === "true",
2458
+ limit,
2459
+ offset
2460
+ });
2461
+ const response = buildAuditResponse(result.entries, result.total, page, limit);
2462
+ sendJson(res, 200, response);
2463
+ return true;
2464
+ }
2465
+ if (path === "/api/harness-viewer" && method === "GET") {
2466
+ try {
2467
+ let readFile2 = function(relativePath) {
2468
+ const fp = join14(workspaceDir, relativePath);
2469
+ if (!existsSync16(fp)) return "";
2470
+ try {
2471
+ return readFileSync12(fp, "utf-8");
2472
+ } catch {
2473
+ return "";
2474
+ }
2475
+ };
2476
+ var readFile = readFile2;
2477
+ const { existsSync: existsSync16, readFileSync: readFileSync12 } = await import("fs");
2478
+ const { join: join14 } = await import("path");
2479
+ const { readFocusFile: readFocusFile2 } = await import("./focus-sync-3D3XWCTI.js");
2480
+ const { loadSessionLog: loadSessionLog2 } = await import("./session-log-WTQ5JBEN.js");
2481
+ const { loadHealthRecord: loadHealthRecord2, getActiveEntries: getActiveEntries2 } = await import("./health-record-YDVXEVLR.js");
2482
+ const l1Files = [
2483
+ "constitution.md",
2484
+ "context.md",
2485
+ "glossary.md",
2486
+ "constraints.md"
2487
+ ];
2488
+ const l1 = l1Files.map((f) => ({
2489
+ path: `.letra/${f}`,
2490
+ content: readFile2(f)
2491
+ }));
2492
+ const focus = readFocusFile2(workspaceRoot);
2493
+ const focusContent = readFile2("focus.md");
2494
+ const specContent = focus?.specName ? readFile2(`specs/${focus.specName}/spec.md`) : "";
2495
+ const l2 = {
2496
+ focus: focus ? { ...focus, content: focusContent } : null,
2497
+ spec: specContent ? { path: `.letra/specs/${focus?.specName}/spec.md`, content: specContent } : null
2498
+ };
2499
+ const healthRecord = loadHealthRecord2(workspaceRoot);
2500
+ const alerts = getActiveEntries2(healthRecord);
2501
+ const log = loadSessionLog2(workspaceRoot);
2502
+ const l3 = {
2503
+ alerts: alerts.slice(0, 10),
2504
+ alertCount: alerts.length,
2505
+ sessionEventCount: log.entries?.length ?? 0
2506
+ };
2507
+ const l4 = {
2508
+ constraintsContent: readFile2("constraints.md"),
2509
+ glossaryContent: readFile2("glossary.md")
2510
+ };
2511
+ sendJson(res, 200, { layers: { l1, l2, l3, l4 } });
2512
+ } catch (error) {
2513
+ sendError(res, 500, error.message);
2514
+ }
2515
+ return true;
2516
+ }
2517
+ if (path === "/api/system-actions" && method === "GET") {
2518
+ sendJson(res, 200, { actions: dependencies.getRecurringSystemActions(workspaceRoot) });
2519
+ return true;
2520
+ }
2521
+ if (path === "/api/sitrep" && method === "POST") {
2522
+ await dependencies.sitrep(workspaceRoot, {
2523
+ dryRun: url.searchParams.get("dryRun") === "true"
2524
+ });
2525
+ sendJson(res, 200, { ok: true });
2526
+ return true;
2527
+ }
2528
+ if (path === "/api/pulse" && method === "GET") {
2529
+ sendJson(res, 200, await dependencies.pulse(workspaceRoot, { json: false }));
2530
+ return true;
2531
+ }
2532
+ if (path === "/api/activity-context" && method === "GET") {
2533
+ sendJson(
2534
+ res,
2535
+ 200,
2536
+ dependencies.buildActivityContext(workspaceRoot, url.searchParams.get("activity"))
2537
+ );
2538
+ return true;
2539
+ }
2540
+ return false;
2541
+ };
2542
+ }
2543
+
2544
+ // src/flow-serve/routes/workflow-routes.ts
2545
+ import { existsSync as existsSync7, readFileSync as readFileSync7, unlinkSync, writeFileSync as writeFileSync3 } from "fs";
2546
+ import { join as join6, resolve as resolve3 } from "path";
2547
+ function sendBodyError5(error, res) {
2548
+ if (error instanceof HttpBodyError) sendError(res, error.status, error.message);
2549
+ else sendError(res, 400, error.message);
2550
+ }
2551
+ function normalizedPath(path) {
2552
+ return path.replace(/\\/g, "/");
2553
+ }
2554
+ function stableLocationId(path) {
2555
+ const normalized = normalizedPath(path).toLowerCase();
2556
+ let hash = 2166136261;
2557
+ for (const char of normalized) {
2558
+ hash ^= char.charCodeAt(0);
2559
+ hash = Math.imul(hash, 16777619);
2560
+ }
2561
+ const name = normalized.split("/").filter(Boolean).pop()?.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 32) || "project";
2562
+ return `loc-${name}-${(hash >>> 0).toString(36)}`;
2563
+ }
2564
+ function labelFromPath(path, fallback = "Projeto") {
2565
+ return normalizedPath(path).split("/").filter(Boolean).pop() || fallback;
2566
+ }
2567
+ function assertProjectDirectory(path) {
2568
+ const resolved = resolve3(path);
2569
+ if (!existsSync7(resolved)) throw new Error("A pasta de projeto n\xE3o existe.");
2570
+ return resolved;
2571
+ }
2572
+ function linkPathFor(locationPath) {
2573
+ return join6(resolve3(locationPath), ".letra-link");
2574
+ }
2575
+ function readLink(locationPath) {
2576
+ const path = linkPathFor(locationPath);
2577
+ if (!existsSync7(path)) return null;
2578
+ return readFileSync7(path, "utf-8").trim();
2579
+ }
2580
+ function writeLocationLink(locationPath, dataDir) {
2581
+ const resolved = assertProjectDirectory(locationPath);
2582
+ writeFileSync3(join6(resolved, ".letra-link"), `${dataDir}
2583
+ `, "utf-8");
2584
+ }
2585
+ function removeLocationLinkIfOwned(locationPath, dataDir) {
2586
+ const path = linkPathFor(locationPath);
2587
+ const current = readLink(locationPath);
2588
+ if (!current || normalizedPath(current) !== normalizedPath(dataDir)) return false;
2589
+ unlinkSync(path);
2590
+ return true;
2591
+ }
2592
+ function createWorkflowRoutes(dependencies) {
2593
+ return async ({ method, path, req, res, url, workspaceRoot, workspaceDir, workflow }) => {
2594
+ if (path === "/api/workflow" && method === "GET") {
2595
+ sendJson(res, 200, workflow ?? { error: "No workflow found" });
2596
+ return true;
2597
+ }
2598
+ if (path === "/api/workflow/active-flow" && method === "GET") {
2599
+ sendJson(
2600
+ res,
2601
+ 200,
2602
+ dependencies.resolveActiveFlow(workspaceRoot, workflow).flow ?? null
2603
+ );
2604
+ return true;
2605
+ }
2606
+ if (path === "/api/workflow/template" && method === "POST") {
2607
+ try {
2608
+ const data = await readJson(req);
2609
+ let next;
2610
+ if (data.stages) {
2611
+ next = {
2612
+ version: "1.0",
2613
+ name: data.name ?? dependencies.detectWorkspaceName(workspaceRoot) ?? "Personalizado",
2614
+ language: workflow?.language,
2615
+ createdAt: workflow?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
2616
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
2617
+ stages: data.stages.map((stage, order) => ({ ...stage, order })),
2618
+ items: workflow?.items ?? [],
2619
+ specLinks: workflow?.specLinks,
2620
+ tools: data.tools ?? workflow?.tools ?? []
2621
+ };
2622
+ } else {
2623
+ next = dependencies.createFromTemplate(
2624
+ workspaceRoot,
2625
+ data.template,
2626
+ { name: data.name, tools: data.tools },
2627
+ dependencies.loadHarness(workspaceRoot)
2628
+ );
2629
+ if (workflow?.language) next.language = workflow.language;
2630
+ const nextStages = next.stages ?? [];
2631
+ const fallbackStage = nextStages.find((s) => s.zone === "todo")?.id ?? nextStages[0]?.id ?? "backlog";
2632
+ const stageIds = new Set(nextStages.map((s) => s.id));
2633
+ next.items = (workflow?.items ?? []).map(
2634
+ (item) => stageIds.has(item.stage) ? item : { ...item, stage: fallbackStage }
2635
+ );
2636
+ if (!next.locations || (next.locations?.length ?? 0) === 0)
2637
+ next.locations = workflow?.locations;
2638
+ if (!next.specLinks || Object.keys(next.specLinks).length === 0)
2639
+ next.specLinks = workflow?.specLinks;
2640
+ if (!next.tools || (next.tools?.length ?? 0) === 0)
2641
+ next.tools = workflow?.tools ?? [];
2642
+ }
2643
+ dependencies.writeWorkflow(workspaceRoot, {
2644
+ workflow: next,
2645
+ source: "web-ui",
2646
+ skipSitrep: true,
2647
+ quiet: true
2648
+ });
2649
+ dependencies.broadcast();
2650
+ sendJson(res, 200, next);
2651
+ } catch (error) {
2652
+ sendBodyError5(error, res);
2653
+ }
2654
+ return true;
2655
+ }
2656
+ if (path === "/api/workflow" && method === "PATCH") {
2657
+ try {
2658
+ const data = await readJson(req);
2659
+ if (!workflow) {
2660
+ sendError(res, 404, "No workflow");
2661
+ return true;
2662
+ }
2663
+ if (data.stages !== void 0) workflow.stages = data.stages;
2664
+ if (data.name !== void 0) workflow.name = data.name;
2665
+ if (data.description !== void 0) workflow.description = data.description;
2666
+ workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2667
+ dependencies.writeWorkflow(workspaceRoot, {
2668
+ workflow,
2669
+ source: "web-ui",
2670
+ skipSitrep: true,
2671
+ quiet: true
2672
+ });
2673
+ dependencies.broadcast();
2674
+ sendJson(res, 200, workflow);
2675
+ } catch (error) {
2676
+ sendBodyError5(error, res);
2677
+ }
2678
+ return true;
2679
+ }
2680
+ if (path === "/api/workflow/adapters" && method === "GET") {
2681
+ try {
2682
+ const { ADAPTER_REGISTRY: ADAPTER_REGISTRY2 } = await import("./registry-6VPIA3EG.js");
2683
+ const { existsSync: existsSync16 } = await import("fs");
2684
+ const { join: join14 } = await import("path");
2685
+ const activeTools = workflow?.tools ?? [];
2686
+ const adapters = Object.values(ADAPTER_REGISTRY2).map((adapter) => ({
2687
+ id: adapter.id,
2688
+ displayName: adapter.displayName,
2689
+ capabilities: adapter.capabilities,
2690
+ detectionPaths: adapter.detectionPaths,
2691
+ active: activeTools.includes(adapter.id),
2692
+ detected: adapter.detectionPaths.some(
2693
+ (p) => existsSync16(join14(workspaceRoot, p))
2694
+ )
2695
+ }));
2696
+ sendJson(res, 200, adapters);
2697
+ } catch (error) {
2698
+ sendBodyError5(error, res);
2699
+ }
2700
+ return true;
2701
+ }
2702
+ if (path === "/api/workflow/adapters" && method === "PATCH") {
2703
+ try {
2704
+ const data = await readJson(req);
2705
+ if (!workflow) {
2706
+ sendError(res, 404, "No workflow");
2707
+ return true;
2708
+ }
2709
+ workflow.tools = data.tools;
2710
+ workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2711
+ dependencies.writeWorkflow(workspaceRoot, {
2712
+ workflow,
2713
+ source: "web-ui",
2714
+ skipSitrep: true,
2715
+ quiet: true
2716
+ });
2717
+ dependencies.broadcast();
2718
+ sendJson(res, 200, { tools: workflow.tools });
2719
+ } catch (error) {
2720
+ sendBodyError5(error, res);
2721
+ }
2722
+ return true;
2723
+ }
2724
+ if (path === "/api/workflow/locations" && method === "POST") {
2725
+ try {
2726
+ const data = await readJson(req);
2727
+ if (!workflow) {
2728
+ sendError(res, 404, "No workflow");
2729
+ return true;
2730
+ }
2731
+ if (!workflow.locations) workflow.locations = [];
2732
+ const inputs = Array.isArray(data.locations) && data.locations.length > 0 ? data.locations : data.path ? [
2733
+ {
2734
+ id: data.id,
2735
+ path: data.path,
2736
+ label: data.label,
2737
+ adapters: data.adapters
2738
+ }
2739
+ ] : [];
2740
+ if (inputs.length === 0) throw new Error("Informe ao menos uma pasta de projeto.");
2741
+ const added = inputs.map((input, index) => {
2742
+ const projectPath = normalizedPath(assertProjectDirectory(input.path));
2743
+ const location = {
2744
+ id: input.id || stableLocationId(projectPath),
2745
+ path: projectPath,
2746
+ label: input.label || labelFromPath(projectPath, `Projeto ${index + 1}`),
2747
+ adapters: Array.isArray(input.adapters) ? [...new Set(input.adapters)] : []
2748
+ };
2749
+ const existing = workflow.locations?.find(
2750
+ (candidate) => candidate.id === location.id || normalizedPath(candidate.path) === location.path
2751
+ );
2752
+ if (existing) {
2753
+ existing.path = location.path;
2754
+ existing.label = location.label;
2755
+ existing.adapters = location.adapters;
2756
+ writeLocationLink(existing.path, workspaceDir);
2757
+ return existing;
2758
+ }
2759
+ workflow.locations?.push(location);
2760
+ writeLocationLink(location.path, workspaceDir);
2761
+ return location;
2762
+ });
2763
+ workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2764
+ dependencies.writeWorkflow(workspaceRoot, {
2765
+ workflow,
2766
+ source: "web-ui",
2767
+ skipSitrep: true,
2768
+ quiet: true
2769
+ });
2770
+ dependencies.broadcast();
2771
+ sendJson(res, 200, added.length === 1 ? added[0] : { locations: added });
2772
+ } catch (error) {
2773
+ sendBodyError5(error, res);
2774
+ }
2775
+ return true;
2776
+ }
2777
+ if (path.startsWith("/api/workflow/locations/") && method === "PATCH") {
2778
+ try {
2779
+ const locationId = path.split("/").pop();
2780
+ const data = await readJson(req);
2781
+ if (!workflow) {
2782
+ sendError(res, 404, "No workflow");
2783
+ return true;
2784
+ }
2785
+ if (!workflow.locations) workflow.locations = [];
2786
+ const location = workflow.locations.find((l) => l.id === locationId);
2787
+ if (!location) {
2788
+ sendError(res, 404, "Location not found");
2789
+ return true;
2790
+ }
2791
+ if (data.label !== void 0) location.label = data.label;
2792
+ if (data.path !== void 0) {
2793
+ location.path = normalizedPath(assertProjectDirectory(data.path));
2794
+ writeLocationLink(location.path, workspaceDir);
2795
+ }
2796
+ workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2797
+ dependencies.writeWorkflow(workspaceRoot, {
2798
+ workflow,
2799
+ source: "web-ui",
2800
+ skipSitrep: true,
2801
+ quiet: true
2802
+ });
2803
+ dependencies.broadcast();
2804
+ sendJson(res, 200, location);
2805
+ } catch (error) {
2806
+ sendBodyError5(error, res);
2807
+ }
2808
+ return true;
2809
+ }
2810
+ if (path.startsWith("/api/workflow/locations/") && method === "DELETE") {
2811
+ try {
2812
+ const locationId = path.split("/").pop();
2813
+ if (!workflow) {
2814
+ sendError(res, 404, "No workflow");
2815
+ return true;
2816
+ }
2817
+ if (!workflow.locations) workflow.locations = [];
2818
+ const index = workflow.locations.findIndex((l) => l.id === locationId);
2819
+ if (index === -1) {
2820
+ sendError(res, 404, "Location not found");
2821
+ return true;
2822
+ }
2823
+ const [removed] = workflow.locations.splice(index, 1);
2824
+ const linkRemoved = removed ? removeLocationLinkIfOwned(removed.path, workspaceDir) : false;
2825
+ workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2826
+ dependencies.writeWorkflow(workspaceRoot, {
2827
+ workflow,
2828
+ source: "web-ui",
2829
+ skipSitrep: true,
2830
+ quiet: true
2831
+ });
2832
+ dependencies.broadcast();
2833
+ sendJson(res, 200, { ok: true, linkRemoved });
2834
+ } catch (error) {
2835
+ sendBodyError5(error, res);
2836
+ }
2837
+ return true;
2838
+ }
2839
+ if (path.startsWith("/api/workflow/locations/") && path.endsWith("/repair-link") && method === "POST") {
2840
+ try {
2841
+ const locationId = path.split("/").at(-2);
2842
+ if (!workflow) {
2843
+ sendError(res, 404, "No workflow");
2844
+ return true;
2845
+ }
2846
+ const location = workflow.locations?.find((l) => l.id === locationId);
2847
+ if (!location) {
2848
+ sendError(res, 404, "Location not found");
2849
+ return true;
2850
+ }
2851
+ writeLocationLink(location.path, workspaceDir);
2852
+ sendJson(res, 200, {
2853
+ ok: true,
2854
+ location,
2855
+ linkPath: normalizedPath(linkPathFor(location.path)),
2856
+ dataDir: normalizedPath(workspaceDir)
2857
+ });
2858
+ } catch (error) {
2859
+ sendBodyError5(error, res);
2860
+ }
2861
+ return true;
2862
+ }
2863
+ if (path === "/api/move") {
2864
+ const itemId = url.searchParams.get("item");
2865
+ const stage = url.searchParams.get("stage");
2866
+ const item = itemId ? workflow?.items.find((candidate) => candidate.id === itemId) : null;
2867
+ if (item && stage && workflow) {
2868
+ item.stage = stage;
2869
+ workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2870
+ dependencies.writeWorkflow(workspaceRoot, {
2871
+ workflow,
2872
+ source: "web-ui",
2873
+ primaryItemId: item.id,
2874
+ skipSitrep: true,
2875
+ quiet: true
2876
+ });
2877
+ dependencies.broadcast();
2878
+ }
2879
+ res.writeHead(302, { Location: "/" });
2880
+ res.end();
2881
+ return true;
2882
+ }
2883
+ return false;
2884
+ };
2885
+ }
2886
+
2887
+ // src/flow-serve/routes/workspace-routes.ts
2888
+ import { readdirSync as readdirSync5, existsSync as existsSync9, readFileSync as readFileSync8 } from "fs";
2889
+ import { join as join8, resolve as resolve5 } from "path";
2890
+ import { homedir } from "os";
2891
+
2892
+ // src/commands/migrate.ts
2893
+ import { existsSync as existsSync8, cpSync, rmSync as rmSync2, mkdirSync as mkdirSync3, writeFileSync as writeFileSync4, readdirSync as readdirSync4 } from "fs";
2894
+ import { join as join7, isAbsolute, resolve as resolve4 } from "path";
2895
+ import { Command as Command2 } from "commander";
2896
+ import chalk2 from "chalk";
2897
+ var EXTERNAL_ROOT = getWorkspacesDir();
2898
+ function workspaceName(root) {
2899
+ const wf = loadWorkflow(root);
2900
+ return wf?.name || slugifyWorkspaceName(root);
2901
+ }
2902
+ function copyDirectoryContents(source, target) {
2903
+ mkdirSync3(target, { recursive: true });
2904
+ for (const entry of readdirSync4(source)) {
2905
+ cpSync(join7(source, entry), join7(target, entry), { recursive: true, force: true });
2906
+ }
2907
+ }
2908
+ async function migrateWorkspace(rootPath, options) {
2909
+ const cwd = rootPath ? resolve4(process.cwd(), rootPath) : process.cwd();
2910
+ const resolution = resolveWorkspaceRoot(cwd);
2911
+ const source = resolution.workspaceDir;
2912
+ const rootForLink = resolution.workspaceRoot;
2913
+ if (!existsSync8(source)) {
2914
+ return {
2915
+ ok: false,
2916
+ from: source,
2917
+ to: "",
2918
+ cleaned: false,
2919
+ message: `Source data directory not found at ${source}`
2920
+ };
2921
+ }
2922
+ if (resolution.type === "linked") {
2923
+ return {
2924
+ ok: false,
2925
+ from: source,
2926
+ to: source,
2927
+ cleaned: false,
2928
+ message: "Workspace is already externalized (linked). Nothing to migrate."
2929
+ };
2930
+ }
2931
+ const name = workspaceName(rootForLink);
2932
+ const slug2 = slugifyWorkspaceName(name);
2933
+ const target = options?.to ? isAbsolute(options.to) ? options.to : resolve4(cwd, options.to) : join7(EXTERNAL_ROOT, slug2);
2934
+ if (existsSync8(target) && existsSync8(join7(target, "workflow.json"))) {
2935
+ return {
2936
+ ok: false,
2937
+ from: source,
2938
+ to: target,
2939
+ cleaned: false,
2940
+ message: `Target already contains a workflow.json (${target}). Move it first or pass --to <path>.`
2941
+ };
2942
+ }
2943
+ if (options?.dryRun) {
2944
+ return {
2945
+ ok: true,
2946
+ from: source,
2947
+ to: target,
2948
+ cleaned: false,
2949
+ message: `[dry-run] Would copy ${source} -> ${target} and write ${LINK_FILE} at ${rootForLink}`
2950
+ };
2951
+ }
2952
+ mkdirSync3(target, { recursive: true });
2953
+ copyDirectoryContents(source, target);
2954
+ ensureExternalWorkspaceLayout(target);
2955
+ const migrationId = `migration-${Date.now().toString(36)}`;
2956
+ const evidenceDir = join7(target, "operations", "migrations");
2957
+ mkdirSync3(evidenceDir, { recursive: true });
2958
+ const rollbackDir = join7(target, "operations", "rollbacks", migrationId);
2959
+ const rollbackSnapshotDir = join7(rollbackDir, "legacy-letra");
2960
+ copyDirectoryContents(source, rollbackSnapshotDir);
2961
+ writeFileSync4(
2962
+ join7(rollbackDir, "rollback.json"),
2963
+ JSON.stringify(
2964
+ {
2965
+ id: migrationId,
2966
+ source,
2967
+ target,
2968
+ linkPath: join7(rootForLink, LINK_FILE),
2969
+ snapshotPath: rollbackSnapshotDir,
2970
+ restore: "Copy snapshotPath back to source and remove .letra-link from linkPath."
2971
+ },
2972
+ null,
2973
+ 2
2974
+ ),
2975
+ "utf-8"
2976
+ );
2977
+ writeFileSync4(join7(rootForLink, LINK_FILE), `${target}
2978
+ `, "utf-8");
2979
+ clearWorkspaceCache();
2980
+ let cleaned = false;
2981
+ if (options?.clean) {
2982
+ rmSync2(source, { recursive: true, force: true });
2983
+ cleaned = true;
2984
+ }
2985
+ writeFileSync4(
2986
+ join7(evidenceDir, `${migrationId}.json`),
2987
+ JSON.stringify(
2988
+ {
2989
+ id: migrationId,
2990
+ migratedAt: (/* @__PURE__ */ new Date()).toISOString(),
2991
+ from: source,
2992
+ to: target,
2993
+ linkPath: join7(rootForLink, LINK_FILE),
2994
+ cleaned,
2995
+ rollbackSnapshotPath: rollbackSnapshotDir,
2996
+ rollbackManifestPath: join7(rollbackDir, "rollback.json"),
2997
+ rollback: cleaned ? "Restore by copying rollbackSnapshotPath back to the original path and removing .letra-link." : "Restore by removing .letra-link; the original .letra directory was preserved."
2998
+ },
2999
+ null,
3000
+ 2
3001
+ ),
3002
+ "utf-8"
3003
+ );
3004
+ return {
3005
+ ok: true,
3006
+ from: source,
3007
+ to: target,
3008
+ cleaned,
3009
+ message: `Migrated data to ${target} (${cleaned ? "source removed" : "source kept"}).`
3010
+ };
3011
+ }
3012
+ function migrateCommand() {
3013
+ const cmd = new Command2("migrate").description(
3014
+ "Externalize a workspace's .letra directory to ~/.letra/workspaces/{slug}/ and leave a link"
3015
+ ).argument("[root]", "workspace root (defaults to cwd)").option("--to <path>", "target data directory (overrides default)").option("--clean", "remove the original .letra directory after migrating").option("--dry-run", "print what would happen without writing").action(
3016
+ async (root, opts) => {
3017
+ const result = await migrateWorkspace(root ?? ".", opts);
3018
+ if (!result.ok) {
3019
+ console.log(chalk2.red(`\u2717 ${result.message}`));
3020
+ process.exitCode = 1;
3021
+ } else {
3022
+ console.log(chalk2.green(`\u2713 ${result.message}`));
3023
+ console.log(` from: ${result.from}`);
3024
+ console.log(` to: ${result.to}`);
3025
+ }
3026
+ }
3027
+ );
3028
+ return cmd;
3029
+ }
3030
+
3031
+ // src/flow-serve/routes/workspace-routes.ts
3032
+ function sendBodyError6(error, res) {
3033
+ if (error instanceof HttpBodyError) sendError(res, error.status, error.message);
3034
+ else sendError(res, 400, error.message);
3035
+ }
3036
+ function resolveUserPath(path, fallback = process.cwd()) {
3037
+ const input = path.trim();
3038
+ if (!input) return resolve5(fallback);
3039
+ if (input === "~") return homedir();
3040
+ if (input.startsWith("~/") || input.startsWith("~\\")) {
3041
+ return resolve5(homedir(), input.slice(2));
3042
+ }
3043
+ return resolve5(input);
3044
+ }
3045
+ function templates(harness) {
3046
+ if (!harness) return [];
3047
+ return Object.values(harness.flows).map((flow) => {
3048
+ const gateIds = new Set(
3049
+ flow.stages.map((stage) => stage.gate).filter((gate) => !!gate).map((gate) => gate.replace(/^.*[\\/]/, "").replace(/\.ya?ml$/, ""))
3050
+ );
3051
+ const gates = [...gateIds].flatMap((id) => harness.gates[id] ? [harness.gates[id]] : []);
3052
+ const roleIds = new Set(flow.stages.flatMap((stage) => stage.agents ?? []));
3053
+ const roles = [...roleIds].flatMap((id) => harness.roles[id] ? [harness.roles[id]] : []);
3054
+ const policyRefs = new Set(
3055
+ gates.flatMap(
3056
+ (gate) => gate.policyRef ? [gate.policyRef.replace(/^.*[\\/]/, "").replace(/\.json$/, "")] : []
3057
+ )
3058
+ );
3059
+ const policies = [...policyRefs].flatMap(
3060
+ (id) => harness.policies?.[id] ? [harness.policies[id]] : []
3061
+ );
3062
+ return { ...flow, gates, roles, policies };
3063
+ });
3064
+ }
3065
+ function createWorkspaceRoutes(dependencies) {
3066
+ return async ({ method, path, req, res, url, workspaceRoot, workspaceDir }) => {
3067
+ if (path === "/api/workspaces" && method === "GET") {
3068
+ try {
3069
+ const registered = dependencies.listWorkspaces();
3070
+ const active = workspaceRoot;
3071
+ const hasActive = typeof active === "string" && active.length > 0 && existsSync9(join8(getLetraDir2(active), "workflow.json"));
3072
+ const workspaces = hasActive ? registered.some((w) => String(w.root ?? "") === active) ? registered : [
3073
+ {
3074
+ id: "ws-active",
3075
+ name: active.split(/[/\\]/).pop() ?? "workspace",
3076
+ root: active,
3077
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
3078
+ },
3079
+ ...registered
3080
+ ] : registered;
3081
+ sendJson(
3082
+ res,
3083
+ 200,
3084
+ workspaces.map((workspace) => {
3085
+ const legacy = workspace;
3086
+ const root = String(legacy.root || "");
3087
+ const dataDir = root ? getLetraDir2(root) : null;
3088
+ const wfPath = dataDir ? join8(dataDir, "workflow.json") : null;
3089
+ let wf = null;
3090
+ if (wfPath && existsSync9(wfPath)) {
3091
+ try {
3092
+ wf = JSON.parse(readFileSync8(wfPath, "utf-8"));
3093
+ } catch {
3094
+ }
3095
+ }
3096
+ const wfLocations = wf && Array.isArray(wf.locations) ? wf.locations : [];
3097
+ return {
3098
+ ...workspace,
3099
+ description: String(legacy.description || wf?.description || ""),
3100
+ slug: legacy.slug || String(workspace.name ?? "").toLowerCase().replace(/[^a-z0-9]+/g, "-"),
3101
+ root,
3102
+ dataDir,
3103
+ directories: legacy.directories || wfLocations.map((l) => String(l?.path ?? "")).filter(Boolean),
3104
+ tools: legacy.tools || (wf && Array.isArray(wf.tools) ? wf.tools : []),
3105
+ template: legacy.template || String(wf?.template || "padrao")
3106
+ };
3107
+ })
3108
+ );
3109
+ } catch {
3110
+ sendJson(res, 200, []);
3111
+ }
3112
+ return true;
3113
+ }
3114
+ if (path === "/api/workspace/switch" && method === "POST") {
3115
+ try {
3116
+ const data = await readJson(req);
3117
+ const root = data.root || data.workspaceRoot || data.projectRoot;
3118
+ if (root) dependencies.switchWorkspace(resolve5(root));
3119
+ const activeRoot = dependencies.activeWorkspaceRoot();
3120
+ const activeResolution = resolveWorkspaceRoot(activeRoot);
3121
+ sendJson(res, 200, {
3122
+ ok: true,
3123
+ workspaceRoot: activeRoot,
3124
+ dataDir: activeResolution.workspaceDir,
3125
+ locationPath: activeResolution.locationPath,
3126
+ projectRoot: activeRoot
3127
+ });
3128
+ } catch (error) {
3129
+ sendBodyError6(error, res);
3130
+ }
3131
+ return true;
3132
+ }
3133
+ if (path === "/api/workspace/directory/switch" && method === "POST") {
3134
+ try {
3135
+ const data = await readJson(req);
3136
+ dependencies.switchDirectory(data.directory || null);
3137
+ sendJson(res, 200, { ok: true, activeDirectory: dependencies.activeDirectory() });
3138
+ } catch (error) {
3139
+ sendBodyError6(error, res);
3140
+ }
3141
+ return true;
3142
+ }
3143
+ if (path === "/api/workspace/setup/analyze" && method === "POST") {
3144
+ try {
3145
+ const data = await readJson(req);
3146
+ sendJson(
3147
+ res,
3148
+ 200,
3149
+ dependencies.analyzeSetup({
3150
+ name: String(data.name || "").trim(),
3151
+ root: String(data.root || "").trim()
3152
+ })
3153
+ );
3154
+ } catch (error) {
3155
+ sendBodyError6(error, res);
3156
+ }
3157
+ return true;
3158
+ }
3159
+ if (path === "/api/workspace/setup/plan" && method === "POST") {
3160
+ try {
3161
+ const data = await readJson(req);
3162
+ const locations = Array.isArray(data.locations) ? data.locations : [];
3163
+ const tools = [...new Set(locations.flatMap((location) => location.adapters))];
3164
+ const root = resolveUserPath(
3165
+ String(data.dataDir || data.workspaceRoot || workspaceDir || "")
3166
+ );
3167
+ const workflow = dependencies.createFromTemplate(
3168
+ root,
3169
+ String(data.template || "padrao"),
3170
+ { name: String(data.name || "Workspace"), tools },
3171
+ dependencies.loadHarness(workspaceRoot)
3172
+ );
3173
+ workflow.locations = workflowLocations(locations, root);
3174
+ sendJson(
3175
+ res,
3176
+ 200,
3177
+ dependencies.planSetup({
3178
+ proposalId: String(data.proposalId || ""),
3179
+ workspaceRoot: root,
3180
+ targets: locations,
3181
+ workflow
3182
+ })
3183
+ );
3184
+ } catch (error) {
3185
+ sendBodyError6(error, res);
3186
+ }
3187
+ return true;
3188
+ }
3189
+ if (path === "/api/workspace/setup/rollback" && method === "POST") {
3190
+ try {
3191
+ const data = await readJson(req);
3192
+ dependencies.rollbackSetup(
3193
+ String(data.workspaceRoot || ""),
3194
+ String(data.manifestId || "")
3195
+ );
3196
+ sendJson(res, 200, { ok: true });
3197
+ } catch (error) {
3198
+ sendBodyError6(error, res);
3199
+ }
3200
+ return true;
3201
+ }
3202
+ if (path === "/api/workflow/setup" && method === "POST") {
3203
+ try {
3204
+ const data = await readJson(req);
3205
+ const name = String(data.name || "Workspace").trim();
3206
+ const description = String(data.description || "").trim();
3207
+ const workspacePath = String(data.dataDir || data.workspacePath || "").trim();
3208
+ const directories = Array.isArray(data.directories) ? data.directories : [];
3209
+ const tools = Array.isArray(data.tools) ? data.tools : [];
3210
+ const locations = Array.isArray(data.locations) ? data.locations : directories.map((directory, index) => ({
3211
+ id: `loc-${index + 1}`,
3212
+ label: directory.replace(/\\/g, "/").split("/").pop() || `Projeto ${index + 1}`,
3213
+ path: directory,
3214
+ adapters: tools
3215
+ }));
3216
+ const template = String(data.template || "padrao");
3217
+ const resolvedWorkspacePath = resolveUserPath(workspacePath);
3218
+ const workflow = dependencies.createFromTemplate(
3219
+ resolvedWorkspacePath,
3220
+ template,
3221
+ { name, tools },
3222
+ dependencies.loadHarness(workspaceRoot)
3223
+ );
3224
+ workflow.locations = workflowLocations(locations, resolvedWorkspacePath);
3225
+ const plan = dependencies.planSetup({
3226
+ proposalId: String(data.proposalId || "legacy-setup"),
3227
+ workspaceRoot: resolvedWorkspacePath,
3228
+ targets: locations,
3229
+ workflow
3230
+ });
3231
+ if (plan.conflictCount > 0) {
3232
+ throw new Error(
3233
+ "O plano cont\xE9m conflitos. Revise e preserve os arquivos antes de criar o workspace."
3234
+ );
3235
+ }
3236
+ const snapshots = dependencies.captureSetup(plan);
3237
+ try {
3238
+ const setup = dependencies.registerSetup({
3239
+ name,
3240
+ description,
3241
+ workspacePath: resolvedWorkspacePath,
3242
+ directories,
3243
+ tools,
3244
+ template
3245
+ });
3246
+ snapshots.push({ path: setup.registryFile, existed: false });
3247
+ dependencies.writeExternalSetup(
3248
+ resolvedWorkspacePath,
3249
+ workflow,
3250
+ setup.workspace
3251
+ );
3252
+ dependencies.writeTargetAdapters(resolvedWorkspacePath, locations, workflow);
3253
+ const rollbackId = dependencies.saveSetupManifest(
3254
+ resolvedWorkspacePath,
3255
+ plan.proposalId,
3256
+ plan.operations,
3257
+ snapshots
3258
+ );
3259
+ sendJson(res, 200, { workspace: setup.workspace, workflow, rollbackId });
3260
+ } catch (error) {
3261
+ dependencies.restoreSetup(snapshots);
3262
+ throw error;
3263
+ }
3264
+ } catch (error) {
3265
+ sendBodyError6(error, res);
3266
+ }
3267
+ return true;
3268
+ }
3269
+ if (path === "/api/harness/templates" && method === "GET") {
3270
+ sendJson(res, 200, templates(dependencies.loadHarness(workspaceRoot)));
3271
+ return true;
3272
+ }
3273
+ if (path === "/api/harness/roles" && method === "GET") {
3274
+ const harness = dependencies.loadHarness(workspaceRoot);
3275
+ const roles = harness ? Object.values(harness.roles).map((r) => ({
3276
+ id: r.id,
3277
+ label: r.label,
3278
+ description: r.description || "",
3279
+ allowedStages: r.allowedStages || [],
3280
+ capabilities: r.capabilities || []
3281
+ })) : [];
3282
+ sendJson(res, 200, roles);
3283
+ return true;
3284
+ }
3285
+ if (path === "/api/fs/dirs" && method === "GET") {
3286
+ const dirPath = url.searchParams.get("path") || process.cwd();
3287
+ try {
3288
+ const dirs = readdirSync5(dirPath, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => ({
3289
+ name: entry.name,
3290
+ path: join8(dirPath, entry.name).replace(/\\\\/g, "/")
3291
+ })).sort((a, b) => a.name.localeCompare(b.name));
3292
+ sendJson(res, 200, { path: dirPath, dirs });
3293
+ } catch {
3294
+ sendJson(res, 200, { path: dirPath, dirs: [], error: "Could not read directory" });
3295
+ }
3296
+ return true;
3297
+ }
3298
+ if (path === "/api/workflow/migrate-harness" && method === "POST") {
3299
+ try {
3300
+ const data = await readJson(req);
3301
+ const root = resolveUserPath(
3302
+ String(
3303
+ data.dataDir || data.workspaceRoot || dependencies.activeWorkspaceRoot()
3304
+ )
3305
+ );
3306
+ const result = await migrateWorkspace(root, {
3307
+ clean: !!data.clean,
3308
+ dryRun: !!data.dryRun
3309
+ });
3310
+ sendJson(res, result.ok ? 200 : 409, result);
3311
+ } catch (error) {
3312
+ sendBodyError6(error, res);
3313
+ }
3314
+ return true;
3315
+ }
3316
+ return false;
3317
+ };
3318
+ }
3319
+
3320
+ // src/flow-serve/routes/adapter-routes.ts
3321
+ import { existsSync as existsSync11, statSync as statSync2 } from "fs";
3322
+ import { join as join10 } from "path";
3323
+
3324
+ // src/commands/sync.ts
3325
+ import { existsSync as existsSync10 } from "fs";
3326
+ import { resolve as resolve6, join as join9 } from "path";
3327
+ import { Command as Command3 } from "commander";
3328
+ import chalk3 from "chalk";
3329
+ async function validateFocus(focusSpec, items, stages) {
3330
+ const warnings = [];
3331
+ const doneIds = new Set(stages.filter((s) => s.id === "done").map((s) => s.id));
3332
+ const matchingItems = items.filter((i) => i.spec === focusSpec);
3333
+ if (matchingItems.length === 0) {
3334
+ warnings.push(`Focus spec "${focusSpec}" does not match any item's spec in workflow`);
3335
+ } else {
3336
+ for (const item of matchingItems) {
3337
+ if (doneIds.has(item.stage)) {
3338
+ warnings.push(
3339
+ `Focus spec "${focusSpec}" matches ${item.id} which is in "done" stage`
3340
+ );
3341
+ }
3342
+ }
3343
+ }
3344
+ return warnings;
3345
+ }
3346
+ async function syncNow(rootPath, options) {
3347
+ const workflowFile = join9(getLetraDir2(rootPath), "workflow.json");
3348
+ if (!existsSync10(workflowFile)) {
3349
+ return {
3350
+ ok: false,
3351
+ filesUpdated: [],
3352
+ warnings: [],
3353
+ error: "No workflow found at .letra/workflow.json"
3354
+ };
3355
+ }
3356
+ const workflow = loadWorkflow(rootPath);
3357
+ if (!workflow) {
3358
+ return { ok: false, filesUpdated: [], warnings: [], error: "Failed to load workflow" };
3359
+ }
3360
+ const warnings = [];
3361
+ const focus = readFocusFile(rootPath);
3362
+ if (focus?.specName) {
3363
+ const focusWarnings = await validateFocus(focus.specName, workflow.items, workflow.stages);
3364
+ warnings.push(...focusWarnings);
3365
+ }
3366
+ if (options?.dryRun) {
3367
+ const filesUpdated = [
3368
+ ".letra/workflow.json",
3369
+ ...(workflow.tools || []).map((t) => t),
3370
+ ".letra/context.md"
3371
+ ];
3372
+ return { ok: true, filesUpdated, warnings, error: void 0 };
3373
+ }
3374
+ const result = await writeWorkflow(rootPath, {
3375
+ workflow,
3376
+ source: "flow-edit",
3377
+ skipSitrep: options?.skipSitrep ?? false
3378
+ });
3379
+ return { ...result, warnings };
3380
+ }
3381
+ function sync_default() {
3382
+ const cmd = new Command3("sync").description("Sync workflow state to all adapters");
3383
+ cmd.option("--dry-run", "Show what would be done without writing").option("--fix", "Apply reconciliation (default behavior)").action(async (opts) => {
3384
+ const root = resolve6(process.cwd());
3385
+ const isDryRun = !!opts.dryRun;
3386
+ const result = await syncNow(root, { dryRun: isDryRun });
3387
+ if (!result.ok) {
3388
+ console.log(chalk3.red(`\u2717 Sync failed: ${result.error ?? "unknown error"}`));
3389
+ process.exit(1);
3390
+ }
3391
+ if (result.warnings.length > 0) {
3392
+ for (const w of result.warnings) {
3393
+ console.log(chalk3.yellow(` \u26A0 ${w}`));
3394
+ }
3395
+ }
3396
+ if (isDryRun) {
3397
+ console.log(chalk3.bold("\n\u{1F4CB} Simula\xE7\xE3o \u2014 dry-run\n"));
3398
+ console.log(chalk3.gray(" Seriam regenerados:"));
3399
+ for (const f of result.filesUpdated) {
3400
+ console.log(` ${chalk3.gray("\u2192")} ${f}`);
3401
+ }
3402
+ return;
3403
+ }
3404
+ console.log(chalk3.green("\u2713 Workflow synced"));
3405
+ for (const f of result.filesUpdated) {
3406
+ console.log(` ${chalk3.gray("\u2192")} ${f}`);
3407
+ }
3408
+ });
3409
+ return cmd;
3410
+ }
3411
+
3412
+ // src/flow-serve/routes/adapter-routes.ts
3413
+ function getAdapterStatus(workspaceRoot) {
3414
+ return Object.values(ADAPTER_REGISTRY).map((adapter) => {
3415
+ const paths = adapter.detectionPaths.map((p) => join10(workspaceRoot, p));
3416
+ const artifacts = paths.map((fullPath) => {
3417
+ let exists = false;
3418
+ let modifiedAt = null;
3419
+ try {
3420
+ exists = existsSync11(fullPath);
3421
+ if (exists) {
3422
+ modifiedAt = statSync2(fullPath).mtime.toISOString();
3423
+ }
3424
+ } catch {
3425
+ }
3426
+ return {
3427
+ path: adapter.detectionPaths[paths.indexOf(fullPath)],
3428
+ exists,
3429
+ modifiedAt
3430
+ };
3431
+ });
3432
+ const detected = artifacts.some((a) => a.exists);
3433
+ const wf = join10(getLetraDir2(workspaceRoot), "workflow.json");
3434
+ const wfMtime = existsSync11(wf) ? statSync2(wf).mtime.getTime() : 0;
3435
+ const newestArtifact = artifacts.filter((a) => a.exists && a.modifiedAt).sort(
3436
+ (a, b) => new Date(b.modifiedAt).getTime() - new Date(a.modifiedAt).getTime()
3437
+ )[0];
3438
+ const synced = newestArtifact ? new Date(newestArtifact.modifiedAt).getTime() >= wfMtime : false;
3439
+ const syncedAt = newestArtifact?.modifiedAt ?? null;
3440
+ return {
3441
+ id: adapter.id,
3442
+ label: adapter.displayName,
3443
+ detected,
3444
+ artifacts,
3445
+ synced,
3446
+ syncedAt
3447
+ };
3448
+ });
3449
+ }
3450
+ function createAdapterRoutes(dependencies) {
3451
+ return async ({ method, path, req, res, workspaceRoot }) => {
3452
+ if (path === "/api/adapters") {
3453
+ if (method === "GET") {
3454
+ const statuses = getAdapterStatus(workspaceRoot);
3455
+ sendJson(res, 200, { adapters: statuses });
3456
+ return true;
3457
+ }
3458
+ if (method === "POST") {
3459
+ try {
3460
+ const result = await syncNow(workspaceRoot);
3461
+ if (result.ok) {
3462
+ dependencies.logEntry(workspaceRoot, "sync", "Adapters synced via UI");
3463
+ dependencies.broadcast();
3464
+ sendJson(res, 200, {
3465
+ ok: true,
3466
+ filesUpdated: result.filesUpdated,
3467
+ adapters: getAdapterStatus(workspaceRoot)
3468
+ });
3469
+ } else {
3470
+ sendError(res, 500, result.error ?? "Sync failed");
3471
+ }
3472
+ } catch (error) {
3473
+ sendError(res, 500, error.message);
3474
+ }
3475
+ return true;
3476
+ }
3477
+ }
3478
+ return false;
3479
+ };
3480
+ }
3481
+
3482
+ // src/flow-serve/routes/handoff-routes.ts
3483
+ function createHandoffRoutes(dependencies) {
3484
+ return async (context) => {
3485
+ if (context.method !== "GET") return false;
3486
+ if (context.path === "/api/handoff/pending") {
3487
+ const url = new URL(
3488
+ context.req.url || "/",
3489
+ `http://${context.req.headers.host || "localhost"}`
3490
+ );
3491
+ const agentId = url.searchParams.get("agent") || void 0;
3492
+ const handoffs = dependencies.getPendingHandoffs(agentId);
3493
+ sendJson(context.res, 200, {
3494
+ handoffs,
3495
+ count: handoffs.length
3496
+ });
3497
+ return true;
3498
+ }
3499
+ return false;
3500
+ };
3501
+ }
3502
+
3503
+ // src/flow-serve/client-assets.ts
3504
+ import { existsSync as existsSync12, readFileSync as readFileSync10 } from "fs";
3505
+ import { dirname, extname, join as join11 } from "path";
3506
+ import { fileURLToPath } from "url";
3507
+ var ClientAssets = class {
3508
+ constructor(root) {
3509
+ this.root = root;
3510
+ }
3511
+ root;
3512
+ clientDir = null;
3513
+ serve(path, req, res) {
3514
+ if (!this.clientDir) {
3515
+ const moduleDir = dirname(fileURLToPath(import.meta.url));
3516
+ const candidates = [
3517
+ join11(moduleDir, "client"),
3518
+ join11(this.root, "packages", "client", "dist"),
3519
+ join11(moduleDir, "..", "..", "..", "client", "dist")
3520
+ ];
3521
+ this.clientDir = candidates.find((directory) => existsSync12(join11(directory, "index.html"))) ?? null;
3522
+ }
3523
+ if (!this.clientDir) {
3524
+ this.proxyToVite(req, res);
3525
+ return;
3526
+ }
3527
+ let filePath = join11(this.clientDir, path === "/" ? "index.html" : path);
3528
+ if (!existsSync12(filePath)) filePath = join11(this.clientDir, "index.html");
3529
+ const mime = {
3530
+ ".html": "text/html; charset=utf-8",
3531
+ ".js": "application/javascript; charset=utf-8",
3532
+ ".css": "text/css; charset=utf-8",
3533
+ ".svg": "image/svg+xml",
3534
+ ".png": "image/png",
3535
+ ".ico": "image/x-icon",
3536
+ ".json": "application/json"
3537
+ };
3538
+ res.writeHead(200, {
3539
+ "Content-Type": mime[extname(filePath)] ?? "application/octet-stream"
3540
+ });
3541
+ res.end(readFileSync10(filePath));
3542
+ }
3543
+ proxyToVite(req, res) {
3544
+ fetch(`http://localhost:5173${req.url}`).then((proxyRes) => {
3545
+ res.writeHead(proxyRes.status, Object.fromEntries(proxyRes.headers));
3546
+ return proxyRes.body?.pipeTo(
3547
+ new WritableStream({
3548
+ write: (chunk) => {
3549
+ res.write(chunk);
3550
+ },
3551
+ close: () => {
3552
+ res.end();
3553
+ }
3554
+ })
3555
+ );
3556
+ }).catch(() => {
3557
+ res.writeHead(502, { "Content-Type": "text/plain" });
3558
+ res.end("Vite dev server not running on http://localhost:5173");
3559
+ });
3560
+ }
3561
+ };
3562
+
3563
+ // src/flow-serve/automation-runtime.ts
3564
+ import { existsSync as existsSync13, watch } from "fs";
3565
+ import { join as join12 } from "path";
3566
+ var AutomationRuntime = class {
3567
+ constructor(dependencies) {
3568
+ this.dependencies = dependencies;
3569
+ }
3570
+ dependencies;
3571
+ workflowWatcher;
3572
+ specsWatcher;
3573
+ workflowDebounceTimer;
3574
+ specsDebounceTimer;
3575
+ diagnosticsTimer;
3576
+ binding;
3577
+ start(binding) {
3578
+ this.rebind(binding);
3579
+ }
3580
+ rebind(binding) {
3581
+ this.closeResources();
3582
+ this.binding = binding;
3583
+ this.armWatchers(binding);
3584
+ binding.engine.ensureDirs();
3585
+ this.safeLogAction(binding.workspaceRoot, "diagnostics-scan", "armed");
3586
+ this.scan("startup");
3587
+ this.diagnosticsTimer = setInterval(
3588
+ () => this.scan("interval"),
3589
+ this.dependencies.intervalMs ?? 3e4
3590
+ );
3591
+ }
3592
+ stop() {
3593
+ this.closeResources();
3594
+ this.binding = void 0;
3595
+ }
3596
+ armWatchers(binding) {
3597
+ const workflowPath = join12(binding.workspaceDir, "workflow.json");
3598
+ const pathExists = this.dependencies.pathExists ?? existsSync13;
3599
+ const watchPath = this.dependencies.watchPath ?? ((path, options, listener) => watch(path, options, listener));
3600
+ if (pathExists(workflowPath)) {
3601
+ try {
3602
+ this.safeLogAction(binding.workspaceRoot, "workflow-watch", "armed", {
3603
+ details: { path: workflowPath }
3604
+ });
3605
+ this.workflowWatcher = watchPath(workflowPath, {}, () => {
3606
+ if (this.workflowDebounceTimer) clearTimeout(this.workflowDebounceTimer);
3607
+ this.workflowDebounceTimer = setTimeout(() => {
3608
+ this.workflowDebounceTimer = void 0;
3609
+ this.publishWorkflowChange(binding, "workflow-watch", workflowPath);
3610
+ }, this.dependencies.debounceMs ?? 100);
3611
+ });
3612
+ } catch {
3613
+ }
3614
+ }
3615
+ const specsPath = join12(binding.workspaceDir, "specs");
3616
+ if (pathExists(specsPath)) {
3617
+ try {
3618
+ this.safeLogAction(binding.workspaceRoot, "specs-watch", "armed", {
3619
+ details: { path: specsPath }
3620
+ });
3621
+ this.specsWatcher = watchPath(specsPath, { recursive: true }, () => {
3622
+ if (this.specsDebounceTimer) clearTimeout(this.specsDebounceTimer);
3623
+ this.specsDebounceTimer = setTimeout(() => {
3624
+ this.specsDebounceTimer = void 0;
3625
+ this.publishWorkflowChange(binding, "specs-watch", specsPath);
3626
+ }, this.dependencies.debounceMs ?? 100);
3627
+ });
3628
+ } catch {
3629
+ }
3630
+ }
3631
+ }
3632
+ publishWorkflowChange(binding, actionId, path) {
3633
+ if (this.binding !== binding) return;
3634
+ this.safeLogAction(binding.workspaceRoot, actionId, "triggered", {
3635
+ details: { path }
3636
+ });
3637
+ this.dependencies.broadcastWorkflow();
3638
+ this.safeLogAction(binding.workspaceRoot, actionId, "completed", {
3639
+ details: { path }
3640
+ });
3641
+ }
3642
+ safeLogAction(root, actionId, outcome, options) {
3643
+ try {
3644
+ this.dependencies.logAction(root, actionId, outcome, options);
3645
+ } catch (error) {
3646
+ const reportError = this.dependencies.reportError ?? ((message, cause) => console.warn(message, cause));
3647
+ reportError(
3648
+ `Flow automation "${actionId}" could not persist outcome "${outcome}".`,
3649
+ error
3650
+ );
3651
+ }
3652
+ }
3653
+ scan(reason) {
3654
+ const binding = this.binding;
3655
+ if (!binding) return;
3656
+ this.safeLogAction(binding.workspaceRoot, "diagnostics-scan", "triggered", {
3657
+ details: { reason }
3658
+ });
3659
+ void this.dependencies.runDiagnostics(binding.engine, binding.workspaceRoot).then((output) => {
3660
+ if (this.binding !== binding) return;
3661
+ this.dependencies.broadcastDiagnostics(output);
3662
+ this.safeLogAction(binding.workspaceRoot, "diagnostics-scan", "completed", {
3663
+ details: {
3664
+ reason,
3665
+ fixes: output.fixes.length,
3666
+ suggestions: output.suggestions.length,
3667
+ errors: output.errors.length
3668
+ }
3669
+ });
3670
+ }).catch((error) => {
3671
+ this.safeLogAction(binding.workspaceRoot, "diagnostics-scan", "failed", {
3672
+ details: { reason },
3673
+ error: error instanceof Error ? error.message : String(error)
3674
+ });
3675
+ });
3676
+ }
3677
+ closeResources() {
3678
+ this.workflowWatcher?.close();
3679
+ this.specsWatcher?.close();
3680
+ if (this.workflowDebounceTimer) clearTimeout(this.workflowDebounceTimer);
3681
+ if (this.specsDebounceTimer) clearTimeout(this.specsDebounceTimer);
3682
+ if (this.diagnosticsTimer) clearInterval(this.diagnosticsTimer);
3683
+ this.workflowWatcher = void 0;
3684
+ this.specsWatcher = void 0;
3685
+ this.workflowDebounceTimer = void 0;
3686
+ this.specsDebounceTimer = void 0;
3687
+ this.diagnosticsTimer = void 0;
3688
+ }
3689
+ };
3690
+
3691
+ // src/orchestrator/orchestrator.ts
3692
+ import {
3693
+ existsSync as existsSync14,
3694
+ mkdirSync as mkdirSync4,
3695
+ readFileSync as readFileSync11,
3696
+ writeFileSync as writeFileSync5,
3697
+ unlinkSync as unlinkSync2,
3698
+ readdirSync as readdirSync6
3699
+ } from "fs";
3700
+ import { join as join13 } from "path";
3701
+ var DEFAULT_HEARTBEAT_TIMEOUT = 6e4;
3702
+ var DEFAULT_MAX_EXECUTION_TIME = 18e5;
3703
+ var RECLAIM_INTERVAL = 6e4;
3704
+ var Orchestrator = class {
3705
+ root;
3706
+ gateChecker;
3707
+ manifest;
3708
+ executors = /* @__PURE__ */ new Map();
3709
+ heartbeats = /* @__PURE__ */ new Map();
3710
+ stageExecutorPreferences = /* @__PURE__ */ new Map();
3711
+ onHandoffEvent;
3712
+ reclaimTimer = null;
3713
+ constructor(config) {
3714
+ this.root = config.root;
3715
+ this.manifest = loadHarness(resolveHarnessRoot(config.root, DEFAULT_HARNESS_VERSION));
3716
+ this.gateChecker = new GateChecker(config.root, this.manifest ?? void 0);
3717
+ this.onHandoffEvent = config.onHandoffEvent;
3718
+ }
3719
+ registerExecutor(executor) {
3720
+ this.executors.set(executor.id, executor);
3721
+ this.heartbeats.set(executor.id, {
3722
+ executorId: executor.id,
3723
+ lastHeartbeat: (/* @__PURE__ */ new Date()).toISOString(),
3724
+ isOnline: true
3725
+ });
3726
+ }
3727
+ registerFromManifest() {
3728
+ if (!this.manifest?.executors) return;
3729
+ for (const entry of this.manifest.executors.executors) {
3730
+ this.registerExecutor({
3731
+ id: entry.id,
3732
+ label: entry.label,
3733
+ capabilities: entry.capabilities,
3734
+ notification: entry.notification,
3735
+ heartbeat: entry.heartbeat,
3736
+ maxExecutionTime: entry.maxExecutionTime,
3737
+ priority: entry.priority
3738
+ });
3739
+ }
3740
+ for (const [stageId, prefs] of Object.entries(
3741
+ this.manifest.executors.stageExecutorPreferences
3742
+ )) {
3743
+ this.stageExecutorPreferences.set(stageId, prefs);
3744
+ }
3745
+ }
3746
+ getManifest() {
3747
+ return this.manifest;
3748
+ }
3749
+ detectPendingHandoff(agentId) {
3750
+ const workflow = loadWorkflow(this.root);
3751
+ if (!workflow) return null;
3752
+ for (const item of workflow.items) {
3753
+ if (item.handoff && item.handoff.to === agentId) {
3754
+ if (new Date(item.handoff.expiresAt) < /* @__PURE__ */ new Date()) {
3755
+ continue;
3756
+ }
3757
+ return {
3758
+ item,
3759
+ handoff: {
3760
+ itemId: item.id,
3761
+ from: item.handoff.from,
3762
+ to: item.handoff.to,
3763
+ summary: item.handoff.summary,
3764
+ evidence: item.handoff.evidence,
3765
+ timestamp: item.handoff.timestamp,
3766
+ expiresAt: item.handoff.expiresAt,
3767
+ executorId: item.handoff.executorId
3768
+ }
3769
+ };
3770
+ }
3771
+ }
3772
+ return null;
3773
+ }
3774
+ emitHandoff(payload) {
3775
+ const workflow = loadWorkflow(this.root);
3776
+ if (!workflow) {
3777
+ return { success: false, reason: "No workflow found" };
3778
+ }
3779
+ const item = workflow.items.find((i) => i.id === payload.itemId);
3780
+ if (!item) {
3781
+ return { success: false, reason: `Item ${payload.itemId} not found` };
3782
+ }
3783
+ const stage = workflow.stages.find((s) => s.id === item.stage);
3784
+ if (!stage) {
3785
+ return { success: false, reason: `Stage ${item.stage} not found` };
3786
+ }
3787
+ const currentStage = workflow.stages.find((s) => s.id === item.stage);
3788
+ if (currentStage?.gate) {
3789
+ const gateResult = this.gateChecker.checkHandoffAllowed(currentStage.gate, item);
3790
+ if (!gateResult.allowed) {
3791
+ return { success: false, reason: gateResult.reason };
3792
+ }
3793
+ }
3794
+ item.handoff = {
3795
+ from: payload.from,
3796
+ to: payload.to,
3797
+ summary: payload.summary,
3798
+ evidence: payload.evidence,
3799
+ timestamp: payload.timestamp,
3800
+ expiresAt: payload.expiresAt,
3801
+ executorId: payload.executorId
3802
+ };
3803
+ workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
3804
+ writeWorkflow(this.root, {
3805
+ workflow,
3806
+ source: "orchestrator",
3807
+ primaryItemId: item.id,
3808
+ skipSitrep: true
3809
+ });
3810
+ this.writeHandoffFile(item);
3811
+ logEntry(this.root, "handoff_emitted", `Handoff emitted to ${payload.to}`, {
3812
+ itemId: payload.itemId,
3813
+ from: payload.from,
3814
+ to: payload.to,
3815
+ summary: payload.summary,
3816
+ evidence: payload.evidence
3817
+ });
3818
+ if (this.onHandoffEvent) {
3819
+ this.onHandoffEvent({
3820
+ itemId: payload.itemId,
3821
+ from: payload.from,
3822
+ to: payload.to,
3823
+ summary: payload.summary,
3824
+ evidence: payload.evidence,
3825
+ executorId: payload.executorId,
3826
+ timestamp: payload.timestamp,
3827
+ expiresAt: payload.expiresAt,
3828
+ action: "emitted"
3829
+ });
3830
+ }
3831
+ return { success: true };
3832
+ }
3833
+ autoClaim(itemId, executorId, agentId) {
3834
+ const workflow = loadWorkflow(this.root);
3835
+ if (!workflow) {
3836
+ return { success: false, reason: "No workflow found" };
3837
+ }
3838
+ const item = workflow.items.find((i) => i.id === itemId);
3839
+ if (!item) {
3840
+ return { success: false, reason: `Item ${itemId} not found` };
3841
+ }
3842
+ const lock = this.readFileLock(itemId);
3843
+ if (lock && lock.executor !== executorId) {
3844
+ const lockOwnerConfig = this.executors.get(lock.executor);
3845
+ const lockMaxExecTime = lockOwnerConfig?.maxExecutionTime ? lockOwnerConfig.maxExecutionTime * 1e3 : DEFAULT_MAX_EXECUTION_TIME;
3846
+ const lockAge = Date.now() - lock.claimedAt;
3847
+ if (lockAge < lockMaxExecTime) {
3848
+ return { success: false, reason: `Item already claimed by ${lock.executor}` };
3849
+ }
3850
+ }
3851
+ if (item.handoff && item.handoff.to !== agentId) {
3852
+ return {
3853
+ success: false,
3854
+ reason: `Item handoff is for ${item.handoff.to}, not ${agentId}`
3855
+ };
3856
+ }
3857
+ this.writeFileLock(itemId, { executor: executorId, claimedAt: Date.now() });
3858
+ item.claimedBy = executorId;
3859
+ item.claimedAt = (/* @__PURE__ */ new Date()).toISOString();
3860
+ const handoffData = item.handoff && item.handoff.to === agentId ? { ...item.handoff } : null;
3861
+ if (item.handoff && item.handoff.to === agentId) {
3862
+ item.handoff = void 0;
3863
+ this.removeHandoffFile(itemId);
3864
+ }
3865
+ workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
3866
+ writeWorkflow(this.root, {
3867
+ workflow,
3868
+ source: "orchestrator",
3869
+ primaryItemId: itemId,
3870
+ skipSitrep: true
3871
+ });
3872
+ logEntry(this.root, "item_claim", `Claimed by ${executorId}`, {
3873
+ itemId,
3874
+ executorId,
3875
+ agentId
3876
+ });
3877
+ if (this.onHandoffEvent && handoffData) {
3878
+ this.onHandoffEvent({
3879
+ itemId,
3880
+ from: handoffData.from,
3881
+ to: handoffData.to,
3882
+ summary: handoffData.summary,
3883
+ evidence: handoffData.evidence || [],
3884
+ executorId: handoffData.executorId,
3885
+ timestamp: handoffData.timestamp,
3886
+ expiresAt: handoffData.expiresAt,
3887
+ action: "claimed"
3888
+ });
3889
+ }
3890
+ return { success: true };
3891
+ }
3892
+ buildContext(itemId, agentId) {
3893
+ const workflow = loadWorkflow(this.root);
3894
+ if (!workflow) return null;
3895
+ const item = workflow.items.find((i) => i.id === itemId);
3896
+ if (!item) return null;
3897
+ const snapshot = resolveAgentDirection(this.root);
3898
+ let specContent = null;
3899
+ if (item.spec) {
3900
+ const specPath = join13(this.root, ".letra", "specs", item.spec, "spec.md");
3901
+ if (existsSync14(specPath)) {
3902
+ specContent = readFileSync11(specPath, "utf-8");
3903
+ }
3904
+ }
3905
+ let promptTemplate = null;
3906
+ if (this.manifest) {
3907
+ const stage = workflow.stages.find((s) => s.id === item.stage);
3908
+ if (stage) {
3909
+ for (const flowId of Object.keys(this.manifest.flows)) {
3910
+ const flow = this.manifest.flows[flowId];
3911
+ const flowStage = flow.stages.find((s) => s.id === stage.id);
3912
+ if (flowStage) {
3913
+ for (const roleId of flowStage.agents) {
3914
+ const role = this.manifest.roles[roleId];
3915
+ if (role?.promptTemplate) {
3916
+ promptTemplate = role.promptTemplate;
3917
+ break;
3918
+ }
3919
+ }
3920
+ break;
3921
+ }
3922
+ }
3923
+ }
3924
+ }
3925
+ return {
3926
+ itemId: item.id,
3927
+ item,
3928
+ agent: agentId,
3929
+ stage: item.stage,
3930
+ spec: specContent,
3931
+ snapshot,
3932
+ promptTemplate,
3933
+ commands: snapshot?.commands?.map((c) => c.command) || [],
3934
+ prohibitions: snapshot?.prohibitions || []
3935
+ };
3936
+ }
3937
+ heartbeat(executorId) {
3938
+ this.heartbeats.set(executorId, {
3939
+ executorId,
3940
+ lastHeartbeat: (/* @__PURE__ */ new Date()).toISOString(),
3941
+ isOnline: true
3942
+ });
3943
+ }
3944
+ reclaimStaleItems() {
3945
+ const workflow = loadWorkflow(this.root);
3946
+ if (!workflow) return [];
3947
+ const reclaimed = [];
3948
+ const now = Date.now();
3949
+ const lockFiles = this.listLockFiles();
3950
+ for (const [itemId, lock] of lockFiles) {
3951
+ const executorConfig = this.executors.get(lock.executor);
3952
+ const maxExecTime = executorConfig?.maxExecutionTime ? executorConfig.maxExecutionTime * 1e3 : DEFAULT_MAX_EXECUTION_TIME;
3953
+ const age = now - lock.claimedAt;
3954
+ if (age > maxExecTime) {
3955
+ const item = workflow.items.find((i) => i.id === itemId);
3956
+ if (item) {
3957
+ item.claimedBy = void 0;
3958
+ item.claimedAt = void 0;
3959
+ reclaimed.push(itemId);
3960
+ logEntry(this.root, "item_reclaim", `Item reclaimed (timeout ${age}ms)`, {
3961
+ itemId,
3962
+ executorId: lock.executor
3963
+ });
3964
+ }
3965
+ this.deleteFileLock(itemId);
3966
+ }
3967
+ }
3968
+ for (const [executorId, heartbeat] of this.heartbeats) {
3969
+ const executor = this.executors.get(executorId);
3970
+ if (executor?.heartbeat) {
3971
+ const lastBeat = new Date(heartbeat.lastHeartbeat).getTime();
3972
+ const beatAge = now - lastBeat;
3973
+ if (beatAge > DEFAULT_HEARTBEAT_TIMEOUT) {
3974
+ this.heartbeats.set(executorId, {
3975
+ ...heartbeat,
3976
+ isOnline: false
3977
+ });
3978
+ }
3979
+ }
3980
+ }
3981
+ if (reclaimed.length > 0) {
3982
+ workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
3983
+ writeWorkflow(this.root, {
3984
+ workflow,
3985
+ source: "orchestrator-reclaim",
3986
+ skipSitrep: true
3987
+ });
3988
+ }
3989
+ return reclaimed;
3990
+ }
3991
+ startReclaimTimer() {
3992
+ if (this.reclaimTimer) return;
3993
+ this.reclaimTimer = setInterval(() => {
3994
+ this.reclaimStaleItems();
3995
+ }, RECLAIM_INTERVAL);
3996
+ }
3997
+ stopReclaimTimer() {
3998
+ if (this.reclaimTimer) {
3999
+ clearInterval(this.reclaimTimer);
4000
+ this.reclaimTimer = null;
4001
+ }
4002
+ }
4003
+ getExecutorStatus(executorId) {
4004
+ return this.heartbeats.get(executorId);
4005
+ }
4006
+ getAllExecutorStatuses() {
4007
+ return Array.from(this.heartbeats.values());
4008
+ }
4009
+ getLocksDir() {
4010
+ return join13(this.root, ".letra", "locks");
4011
+ }
4012
+ readFileLock(itemId) {
4013
+ const lockPath = join13(this.getLocksDir(), `${itemId}.lock`);
4014
+ if (!existsSync14(lockPath)) return null;
4015
+ try {
4016
+ const data = JSON.parse(readFileSync11(lockPath, "utf-8"));
4017
+ return { executor: data.executor, claimedAt: data.claimedAt };
4018
+ } catch {
4019
+ return null;
4020
+ }
4021
+ }
4022
+ writeFileLock(itemId, lock) {
4023
+ const dir = this.getLocksDir();
4024
+ mkdirSync4(dir, { recursive: true });
4025
+ const lockPath = join13(dir, `${itemId}.lock`);
4026
+ writeFileSync5(lockPath, JSON.stringify(lock, null, 2));
4027
+ }
4028
+ deleteFileLock(itemId) {
4029
+ const lockPath = join13(this.getLocksDir(), `${itemId}.lock`);
4030
+ if (existsSync14(lockPath)) {
4031
+ unlinkSync2(lockPath);
4032
+ }
4033
+ }
4034
+ listLockFiles() {
4035
+ const dir = this.getLocksDir();
4036
+ if (!existsSync14(dir)) return /* @__PURE__ */ new Map();
4037
+ const files = readdirSync6(dir).filter((f) => f.endsWith(".lock"));
4038
+ const locks = /* @__PURE__ */ new Map();
4039
+ for (const file of files) {
4040
+ const itemId = file.replace(".lock", "");
4041
+ const lock = this.readFileLock(itemId);
4042
+ if (lock) locks.set(itemId, lock);
4043
+ }
4044
+ return locks;
4045
+ }
4046
+ getHandoffsDir() {
4047
+ return join13(this.root, ".letra", "handoffs");
4048
+ }
4049
+ writeHandoffFile(item) {
4050
+ if (!item.handoff) return;
4051
+ const dir = this.getHandoffsDir();
4052
+ mkdirSync4(dir, { recursive: true });
4053
+ const filePath = join13(dir, `${item.id}.json`);
4054
+ writeFileSync5(
4055
+ filePath,
4056
+ JSON.stringify(
4057
+ {
4058
+ itemId: item.id,
4059
+ from: item.handoff.from,
4060
+ to: item.handoff.to,
4061
+ summary: item.handoff.summary,
4062
+ evidence: item.handoff.evidence,
4063
+ timestamp: item.handoff.timestamp,
4064
+ expiresAt: item.handoff.expiresAt,
4065
+ executorId: item.handoff.executorId
4066
+ },
4067
+ null,
4068
+ 2
4069
+ )
4070
+ );
4071
+ }
4072
+ removeHandoffFile(itemId) {
4073
+ const filePath = join13(this.getHandoffsDir(), `${itemId}.json`);
4074
+ if (existsSync14(filePath)) {
4075
+ unlinkSync2(filePath);
4076
+ }
4077
+ }
4078
+ retryHandoff(itemId) {
4079
+ const workflow = loadWorkflow(this.root);
4080
+ if (!workflow) {
4081
+ return { success: false, reason: "No workflow found" };
4082
+ }
4083
+ const item = workflow.items.find((i) => i.id === itemId);
4084
+ if (!item) {
4085
+ return { success: false, reason: `Item ${itemId} not found` };
4086
+ }
4087
+ if (!item.handoff) {
4088
+ return { success: false, reason: `Item ${itemId} has no pending handoff` };
4089
+ }
4090
+ if (new Date(item.handoff.expiresAt) >= /* @__PURE__ */ new Date()) {
4091
+ return { success: false, reason: `Handoff for ${itemId} has not expired yet` };
4092
+ }
4093
+ const previousTo = item.handoff.to;
4094
+ const previousFrom = item.handoff.from;
4095
+ const summary = item.handoff.summary;
4096
+ const evidence = item.handoff.evidence;
4097
+ const manifest = this.manifest ?? loadHarness(resolveHarnessRoot(this.root, DEFAULT_HARNESS_VERSION));
4098
+ if (!manifest?.executors) {
4099
+ return { success: false, reason: "No executor registry available for retry" };
4100
+ }
4101
+ const registry = manifest.executors;
4102
+ const currentExecutor = item.handoff.executorId;
4103
+ const candidates = registry.executors.filter((e) => e.id !== currentExecutor).sort((a, b) => a.priority - b.priority);
4104
+ const nextExecutor = candidates.find((e) => {
4105
+ const hb = this.heartbeats.get(e.id);
4106
+ return !hb || hb.isOnline;
4107
+ });
4108
+ if (!nextExecutor) {
4109
+ return { success: false, reason: "No other executor available for retry" };
4110
+ }
4111
+ const ttlMinutes = 30;
4112
+ const now = /* @__PURE__ */ new Date();
4113
+ const expiresAt = new Date(now.getTime() + ttlMinutes * 60 * 1e3);
4114
+ item.handoff = {
4115
+ from: previousFrom,
4116
+ to: previousTo,
4117
+ summary,
4118
+ evidence,
4119
+ timestamp: now.toISOString(),
4120
+ expiresAt: expiresAt.toISOString(),
4121
+ executorId: nextExecutor.id
4122
+ };
4123
+ workflow.updatedAt = now.toISOString();
4124
+ writeWorkflow(this.root, {
4125
+ workflow,
4126
+ source: "orchestrator-retry",
4127
+ primaryItemId: itemId,
4128
+ skipSitrep: true
4129
+ });
4130
+ this.writeHandoffFile(item);
4131
+ logEntry(
4132
+ this.root,
4133
+ "handoff_emitted",
4134
+ `Handoff re-emitted to ${previousTo} (retry via ${nextExecutor.id})`,
4135
+ {
4136
+ itemId,
4137
+ from: previousFrom,
4138
+ to: previousTo,
4139
+ executorId: nextExecutor.id,
4140
+ retry: true
4141
+ }
4142
+ );
4143
+ if (this.onHandoffEvent) {
4144
+ this.onHandoffEvent({
4145
+ itemId,
4146
+ from: previousFrom,
4147
+ to: previousTo,
4148
+ summary,
4149
+ evidence,
4150
+ executorId: nextExecutor.id,
4151
+ timestamp: now.toISOString(),
4152
+ expiresAt: expiresAt.toISOString(),
4153
+ action: "retry"
4154
+ });
4155
+ }
4156
+ return { success: true, reEmittedTo: nextExecutor.id };
4157
+ }
4158
+ getPendingHandoffFiles() {
4159
+ const dir = this.getHandoffsDir();
4160
+ if (!existsSync14(dir)) return [];
4161
+ const { readdirSync: readdirSync7 } = __require("fs");
4162
+ const files = readdirSync7(dir).filter((f) => f.endsWith(".json"));
4163
+ const now = /* @__PURE__ */ new Date();
4164
+ return files.flatMap((file) => {
4165
+ try {
4166
+ const data = JSON.parse(readFileSync11(join13(dir, file), "utf-8"));
4167
+ if (new Date(data.expiresAt) < now) return [];
4168
+ return [{ itemId: data.itemId, to: data.to, expiresAt: data.expiresAt }];
4169
+ } catch {
4170
+ return [];
4171
+ }
4172
+ });
4173
+ }
4174
+ };
4175
+
4176
+ // src/commands/flow-serve.ts
4177
+ var DEFAULT_PORT = 3e3;
4178
+ function resolveHarnessWithShared(root) {
4179
+ const local = resolveHarnessRoot(root, DEFAULT_HARNESS_VERSION);
4180
+ if (existsSync15(local)) return local;
4181
+ return ensureSharedHarness(DEFAULT_HARNESS_VERSION);
4182
+ }
4183
+ var FlowServer = class {
4184
+ server;
4185
+ events = new FlowServerEvents();
4186
+ router = new FlowServerRouter();
4187
+ clientAssets;
4188
+ automationRuntime;
4189
+ orchestrator;
4190
+ port;
4191
+ loadWorkflow;
4192
+ engine;
4193
+ resolution;
4194
+ activeWorkspaceRoot;
4195
+ activeDirectory = null;
4196
+ constructor(root, port = DEFAULT_PORT) {
4197
+ this.clientAssets = new ClientAssets(root);
4198
+ this.port = port;
4199
+ this.resolution = resolveWorkspaceRoot(root);
4200
+ this.activeWorkspaceRoot = this.resolution.workspaceRoot;
4201
+ this.loadWorkflow = (overrideRoot) => loadWorkflow(overrideRoot ?? this.activeWorkspaceRoot);
4202
+ this.engine = new DiagnosticEngine(this.activeWorkspaceRoot);
4203
+ this.automationRuntime = new AutomationRuntime({
4204
+ runDiagnostics: runDiagnosticsAndSyncHealth,
4205
+ broadcastWorkflow: () => this.broadcast(),
4206
+ broadcastDiagnostics: (output) => this.broadcastDiagnostics(output),
4207
+ logAction: (workspaceRoot, actionId, outcome, options) => {
4208
+ logSystemAction(workspaceRoot, actionId, {
4209
+ outcome,
4210
+ error: options?.error,
4211
+ details: options?.details
4212
+ });
4213
+ this.events.broadcastSystemActionUpdated({ actionId, outcome });
4214
+ }
4215
+ });
4216
+ this.orchestrator = new Orchestrator({
4217
+ root: this.activeWorkspaceRoot,
4218
+ onHandoffEvent: (payload) => this.events.broadcastHandoff(payload)
4219
+ });
4220
+ this.orchestrator.registerFromManifest();
4221
+ this.router.register((context) => {
4222
+ if (context.path !== "/events") return false;
4223
+ this.events.handleSse(context.req, context.res);
4224
+ return true;
4225
+ });
4226
+ this.router.register(
4227
+ createItemRoutes({
4228
+ writeWorkflow,
4229
+ loadHealthRecord,
4230
+ writeFocusFile: writeFocusWithRecommendations,
4231
+ logEntry,
4232
+ resolveActiveFlow: resolveActiveFlowFor,
4233
+ broadcast: () => this.broadcast(),
4234
+ fireWebhooks: (workspaceRoot, event, payload) => this.fireWebhooks(workspaceRoot, event, payload)
4235
+ })
4236
+ );
4237
+ this.router.register(
4238
+ createSpecRoutes({
4239
+ loadResolvedSpecs,
4240
+ writeSpec,
4241
+ clearSpec,
4242
+ validateSpec,
4243
+ writeWorkflow,
4244
+ broadcast: () => this.broadcast()
4245
+ })
4246
+ );
4247
+ this.router.register(
4248
+ createDiagnosticsRoutes({
4249
+ engineFor: (workspaceRoot) => workspaceRoot === this.activeWorkspaceRoot ? this.engine : new DiagnosticEngine(workspaceRoot),
4250
+ runDiagnostics: runDiagnosticsAndSyncHealth,
4251
+ loadHealthRecord,
4252
+ saveHealthRecord,
4253
+ ackEntry,
4254
+ dismissEntry,
4255
+ getSummary,
4256
+ getActiveEntries,
4257
+ broadcast: () => this.broadcast(),
4258
+ broadcastDiagnostics: (output) => this.broadcastDiagnostics(output)
4259
+ })
4260
+ );
4261
+ this.router.register(
4262
+ createContextRoutes({
4263
+ clearFocusFile,
4264
+ writeFocusFile: writeFocusWithRecommendations,
4265
+ logEntry,
4266
+ queryLog,
4267
+ queryLogWithMeta,
4268
+ readFocusState,
4269
+ readFocusDocument,
4270
+ readDecisions,
4271
+ readAllowedContextFile,
4272
+ contextFileExists,
4273
+ getRecurringSystemActions,
4274
+ sitrep,
4275
+ pulse,
4276
+ buildActivityContext: buildRequestedActivityContext,
4277
+ broadcast: () => this.broadcast()
4278
+ })
4279
+ );
4280
+ this.router.register(
4281
+ createWorkflowRoutes({
4282
+ writeWorkflow,
4283
+ resolveActiveFlow: resolveActiveFlowFor,
4284
+ detectWorkspaceName: detectProjectName,
4285
+ loadHarness: (workspaceRoot) => loadHarness(resolveHarnessWithShared(workspaceRoot)),
4286
+ createFromTemplate: createWorkflowFromTemplate,
4287
+ broadcast: () => this.broadcast()
4288
+ })
4289
+ );
4290
+ this.router.register(
4291
+ createWorkspaceRoutes({
4292
+ listWorkspaces,
4293
+ switchWorkspace: (root2) => this.switchWorkspace(root2),
4294
+ switchDirectory: (directory) => this.switchDirectory(directory),
4295
+ activeWorkspaceRoot: () => this.activeWorkspaceRoot,
4296
+ activeDirectory: () => this.activeDirectory,
4297
+ registerSetup: registerWorkspaceSetup,
4298
+ createFromTemplate: createWorkflowFromTemplate,
4299
+ writeWorkflow,
4300
+ writeExternalSetup: writeExternalWorkspaceSetup,
4301
+ writeTargetAdapters: writeWorkspaceTargetAdapters,
4302
+ analyzeSetup: analyzeWorkspaceSetup,
4303
+ planSetup: planWorkspaceSetup,
4304
+ captureSetup: captureWorkspaceSetup,
4305
+ restoreSetup: restoreWorkspaceSetup,
4306
+ saveSetupManifest: saveWorkspaceSetupManifest,
4307
+ rollbackSetup: rollbackWorkspaceSetup,
4308
+ loadHarness: (root2) => loadHarness(resolveHarnessWithShared(root2))
4309
+ })
4310
+ );
4311
+ this.router.register(
4312
+ createAdapterRoutes({
4313
+ logEntry,
4314
+ broadcast: () => this.broadcast()
4315
+ })
4316
+ );
4317
+ this.router.register(
4318
+ createHandoffRoutes({
4319
+ getPendingHandoffs: (agentId) => {
4320
+ const workflow = this.loadWorkflow();
4321
+ if (!workflow) return [];
4322
+ const now = /* @__PURE__ */ new Date();
4323
+ return workflow.items.filter((item) => {
4324
+ if (!item.handoff) return false;
4325
+ if (new Date(item.handoff.expiresAt) < now) return false;
4326
+ if (agentId && item.handoff.to !== agentId) return false;
4327
+ return true;
4328
+ }).map((item) => ({
4329
+ itemId: item.id,
4330
+ from: item.handoff?.from ?? "",
4331
+ to: item.handoff?.to ?? "",
4332
+ summary: item.handoff?.summary ?? "",
4333
+ evidence: item.handoff?.evidence || [],
4334
+ executorId: item.handoff?.executorId,
4335
+ timestamp: item.handoff?.timestamp ?? "",
4336
+ expiresAt: item.handoff?.expiresAt ?? ""
4337
+ }));
4338
+ }
4339
+ })
4340
+ );
4341
+ }
4342
+ switchWorkspace(workspaceRoot) {
4343
+ this.activeWorkspaceRoot = workspaceRoot;
4344
+ this.activeDirectory = null;
4345
+ this.resolution = resolveWorkspaceRoot(workspaceRoot);
4346
+ this.loadWorkflow = (overrideRoot) => loadWorkflow(overrideRoot ?? this.activeWorkspaceRoot);
4347
+ this.engine = new DiagnosticEngine(this.activeWorkspaceRoot);
4348
+ this.automationRuntime.rebind(this.automationBinding());
4349
+ this.orchestrator = new Orchestrator({
4350
+ root: this.activeWorkspaceRoot,
4351
+ onHandoffEvent: (payload) => this.events.broadcastHandoff(payload)
4352
+ });
4353
+ this.orchestrator.registerFromManifest();
4354
+ this.orchestrator.startReclaimTimer();
4355
+ this.broadcast();
4356
+ }
4357
+ switchDirectory(directory) {
4358
+ this.activeDirectory = directory;
4359
+ this.loadWorkflow = (overrideRoot) => loadWorkflow(overrideRoot ?? this.activeDirectory ?? this.activeWorkspaceRoot);
4360
+ this.broadcast();
4361
+ }
4362
+ workspaceRootFor(url) {
4363
+ const ws = url.searchParams.get("workspace");
4364
+ if (ws) return resolve7(ws);
4365
+ return this.activeDirectory ?? this.activeWorkspaceRoot;
4366
+ }
4367
+ automationBinding() {
4368
+ return {
4369
+ workspaceRoot: this.activeWorkspaceRoot,
4370
+ workspaceDir: this.resolution.workspaceDir,
4371
+ engine: this.engine
4372
+ };
4373
+ }
4374
+ handleRequest = async (req, res) => {
4375
+ const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
4376
+ const path = url.pathname;
4377
+ const requestRoot = this.workspaceRootFor(url);
4378
+ const requestResolution = resolveWorkspaceRoot(requestRoot);
4379
+ const context = createRequestContext(req, res, url, {
4380
+ workspaceRoot: requestRoot,
4381
+ workspaceDir: requestResolution.workspaceDir,
4382
+ workflow: this.loadWorkflow(requestRoot)
4383
+ });
4384
+ if (await this.router.dispatch(context)) return;
4385
+ this.clientAssets.serve(path, req, res);
4386
+ };
4387
+ broadcast() {
4388
+ this.events.broadcastWorkflowUpdated();
4389
+ }
4390
+ broadcastDiagnostics(output) {
4391
+ this.events.broadcastDiagnosticsUpdated({
4392
+ fixes: output.fixes.length,
4393
+ suggestions: output.suggestions.length,
4394
+ errors: output.errors.length
4395
+ });
4396
+ }
4397
+ async fireWebhooks(workspaceRoot, event, payload) {
4398
+ const wf = this.loadWorkflow(workspaceRoot);
4399
+ if (!wf?.webhooks || wf.webhooks.length === 0) return;
4400
+ const matching = wf.webhooks.filter((wh) => wh.events.includes(event));
4401
+ if (matching.length === 0) return;
4402
+ const body = JSON.stringify({
4403
+ event,
4404
+ workflow: wf.name,
4405
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
4406
+ ...payload
4407
+ });
4408
+ for (const wh of matching) {
4409
+ try {
4410
+ const res = await fetch(wh.url, {
4411
+ method: "POST",
4412
+ headers: { "Content-Type": "application/json" },
4413
+ body
4414
+ });
4415
+ wh.lastStatus = res.ok ? "ok" : "error";
4416
+ } catch {
4417
+ wh.lastStatus = "error";
4418
+ }
4419
+ wh.lastSentAt = (/* @__PURE__ */ new Date()).toISOString();
4420
+ }
4421
+ writeWorkflow(workspaceRoot, {
4422
+ workflow: wf,
4423
+ source: "web-ui",
4424
+ skipAdapters: true,
4425
+ skipSitrep: true,
4426
+ skipLog: true,
4427
+ quiet: true
4428
+ });
4429
+ }
4430
+ start() {
4431
+ return new Promise((resolve8, reject) => {
4432
+ this.server = createServer(this.handleRequest);
4433
+ this.server.listen(this.port, () => {
4434
+ this.automationRuntime.start(this.automationBinding());
4435
+ this.orchestrator.startReclaimTimer();
4436
+ resolve8();
4437
+ });
4438
+ this.server.on("error", reject);
4439
+ });
4440
+ }
4441
+ stop() {
4442
+ this.automationRuntime.stop();
4443
+ this.orchestrator.stopReclaimTimer();
4444
+ if (this.server) this.server.close();
4445
+ this.events.close();
4446
+ }
4447
+ getPort() {
4448
+ return this.port;
4449
+ }
4450
+ };
4451
+ async function flowServeAction(targetPath, options) {
4452
+ const root = resolve7(process.cwd(), targetPath ?? ".");
4453
+ const port = options?.port ?? DEFAULT_PORT;
4454
+ const wf = loadWorkflow(root);
4455
+ if (!wf) {
4456
+ console.log("No workflow found. Run 'letra flow init --quick' first");
4457
+ return;
4458
+ }
4459
+ const server = new FlowServer(root, port);
4460
+ try {
4461
+ await server.start();
4462
+ console.log(`
4463
+ Flow Board \u2192 http://localhost:${port}
4464
+ `);
4465
+ console.log(" Press Ctrl+C to stop\n");
4466
+ if (options?.open) {
4467
+ const { execSync: execSync2 } = await import("child_process");
4468
+ const cmd = process.platform === "win32" ? "start" : process.platform === "darwin" ? "open" : "xdg-open";
4469
+ try {
4470
+ execSync2(`${cmd} http://localhost:${port}`, { stdio: "ignore" });
4471
+ } catch {
4472
+ }
4473
+ }
4474
+ await new Promise((resolve8) => {
4475
+ process.on("SIGINT", () => {
4476
+ server.stop();
4477
+ resolve8();
4478
+ });
4479
+ });
4480
+ } catch (err) {
4481
+ console.error(`Failed to start server on port ${port}:`, err.message);
4482
+ process.exit(1);
4483
+ }
4484
+ }
4485
+
4486
+ export {
4487
+ pulse_default,
4488
+ validateSpecStructure,
4489
+ buildActivityContext,
4490
+ migrateCommand,
4491
+ sync_default,
4492
+ FlowServer,
4493
+ flowServeAction
4494
+ };