@letra-ai/cli 0.6.2 → 0.7.0

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 (52) hide show
  1. package/dist/chunk-2GRNAFBQ.js +5305 -0
  2. package/dist/{chunk-MJ2QXNH6.js → chunk-42RST74I.js} +1 -1
  3. package/dist/chunk-HC24XMPZ.js +269 -0
  4. package/dist/chunk-LUPN3TRC.js +554 -0
  5. package/dist/{chunk-URUC6ZZP.js → chunk-MUCIMQAU.js} +1735 -861
  6. package/dist/chunk-POGWTSEA.js +125 -0
  7. package/dist/chunk-TNF7XTFG.js +6178 -0
  8. package/dist/{chunk-BKAUN5QH.js → chunk-UMC5PDL2.js} +227 -33
  9. package/dist/{chunk-6HSUVCTR.js → chunk-YAQ2TKSK.js} +82 -30
  10. package/dist/client/assets/index-C-6kWNFi.js +232 -0
  11. package/dist/client/assets/index-QV-zN0V8.css +1 -0
  12. package/dist/client/index.html +2 -2
  13. package/dist/fallback-CXCCKHBA.js +56 -0
  14. package/dist/flow-serve-LFILD3EV.js +19 -0
  15. package/dist/{generate-UPFERQMD.js → generate-3R7POT7L.js} +4 -5
  16. package/dist/harness/default/v0.1.0/gates/all-acs-passing.yaml +1 -0
  17. package/dist/harness/default/v0.1.0/gates/has-spec-file.yaml +1 -0
  18. package/dist/harness/default/v0.1.1/gates/all-acs-passing.yaml +1 -0
  19. package/dist/harness/default/v0.1.1/gates/has-spec-file.yaml +1 -0
  20. package/dist/harness/default/v0.1.2/gates/all-acs-passing.yaml +1 -0
  21. package/dist/harness/default/v0.1.2/gates/has-spec-file.yaml +1 -0
  22. package/dist/harness/default/v0.1.3/gates/all-acs-passing.yaml +1 -0
  23. package/dist/harness/default/v0.1.3/gates/has-spec-file.yaml +1 -0
  24. package/dist/harness/default/v0.2.0/executors/registry.yaml +17 -0
  25. package/dist/harness/default/v0.2.0/flows/flow-main.yaml +81 -3
  26. package/dist/harness/default/v0.2.0/gates/code-reviewed.yaml +1 -0
  27. package/dist/harness/default/v0.2.0/gates/human-approved.yaml +1 -0
  28. package/dist/harness/default/v0.2.0/gates/security-clear.yaml +1 -0
  29. package/dist/{health-record-YDVXEVLR.js → health-record-JO2ZTIMR.js} +2 -2
  30. package/dist/index.js +2284 -1168
  31. package/dist/{push-VJRSQGUD.js → push-2ZCQSOHF.js} +37 -49
  32. package/dist/server-WUYVNSH7.js +677 -0
  33. package/dist/service-SVEAXQBX.js +28 -0
  34. package/dist/service-TOBY3OHO.js +22 -0
  35. package/dist/service-USTAY5E3.js +62 -0
  36. package/dist/{session-log-WTQ5JBEN.js → session-log-X2Q4XKQN.js} +6 -2
  37. package/dist/specs-CQRB7LPA.js +21 -0
  38. package/dist/sync-LIVPQXEW.js +21 -0
  39. package/package.json +1 -1
  40. package/dist/chunk-DMOLJWWW.js +0 -3321
  41. package/dist/chunk-EDD55PWL.js +0 -119
  42. package/dist/chunk-H64RC3YS.js +0 -254
  43. package/dist/chunk-L6YKDTAQ.js +0 -275
  44. package/dist/chunk-OIHMDOIN.js +0 -1326
  45. package/dist/client/assets/index-EyRsq1SH.css +0 -1
  46. package/dist/client/assets/index-WfKR7Xp6.js +0 -232
  47. package/dist/fallback-MQLGS4KL.js +0 -46
  48. package/dist/flow-serve-G5MSSB3G.js +0 -18
  49. package/dist/focus-sync-3D3XWCTI.js +0 -17
  50. package/dist/server-P6GKRWDX.js +0 -423
  51. package/dist/service-2JN2KI4D.js +0 -29
  52. package/dist/sitrep-OKNZJICV.js +0 -16
package/dist/index.js CHANGED
@@ -1,46 +1,63 @@
1
1
  #!/usr/bin/env node
2
- import {
3
- activityOperation,
4
- validate
5
- } from "./chunk-OIHMDOIN.js";
6
2
  import {
7
3
  buildActivityContext,
8
4
  flowServeAction,
9
5
  migrateCommand,
10
6
  pulse_default,
11
- sync_default,
7
+ sitrep_default
8
+ } from "./chunk-MUCIMQAU.js";
9
+ import {
12
10
  validateSpecStructure
13
- } from "./chunk-URUC6ZZP.js";
11
+ } from "./chunk-POGWTSEA.js";
12
+ import {
13
+ sync_default
14
+ } from "./chunk-HC24XMPZ.js";
14
15
  import {
15
16
  GateChecker,
17
+ activityOperation,
18
+ completeAcOperation,
19
+ createItemOperation,
20
+ directionForOperation,
21
+ directionForRunAwareOperation,
22
+ migrateRunWorkflowOperation,
23
+ requestHandoffOperation,
24
+ requestPassageOperation,
25
+ rollbackHandoffOperation,
26
+ runSecurityReviewOperation,
27
+ validate,
16
28
  writeFocusWithRecommendations
17
- } from "./chunk-H64RC3YS.js";
18
- import {
19
- sitrep_default
20
- } from "./chunk-L6YKDTAQ.js";
29
+ } from "./chunk-TNF7XTFG.js";
21
30
  import {
22
31
  DEFAULT_HARNESS_VERSION,
23
32
  DiagnosticEngine,
33
+ clearFocusFile,
34
+ createWorkflowDefinition,
35
+ createWorkflowDraft,
24
36
  flowInitAction,
25
37
  generateAdapters,
38
+ getActiveWorkflowVersion,
39
+ getWorkflowDraft,
40
+ inspectWorkspaceIntegrity,
41
+ listWorkflowDefinitions,
42
+ listWorkflowDraftRevisions,
43
+ listWorkflowVersions,
26
44
  loadHarness,
27
45
  loadWorkflow,
46
+ publishWorkflowDraft,
28
47
  resolveActiveFlow,
48
+ resolveAgentDirection,
49
+ resolveDirection,
29
50
  resolveHarnessRoot,
51
+ resolveLocalIdentity,
52
+ rollbackWorkflowVersion,
30
53
  saveWorkflow,
54
+ signLocalOperation,
55
+ validateWorkflowContent,
31
56
  writeWorkflow
32
- } from "./chunk-DMOLJWWW.js";
33
- import {
34
- logEntry,
35
- pruneSessionLog,
36
- queryLog
37
- } from "./chunk-BKAUN5QH.js";
57
+ } from "./chunk-2GRNAFBQ.js";
38
58
  import {
39
59
  supportedAdapterTools
40
60
  } from "./chunk-JMIC5NKB.js";
41
- import {
42
- clearFocusFile
43
- } from "./chunk-EDD55PWL.js";
44
61
  import {
45
62
  ackEntry,
46
63
  dismissEntry,
@@ -49,7 +66,15 @@ import {
49
66
  loadHealthRecord,
50
67
  mergeScanResults,
51
68
  saveHealthRecord
52
- } from "./chunk-MJ2QXNH6.js";
69
+ } from "./chunk-42RST74I.js";
70
+ import {
71
+ writeSpecCatalog
72
+ } from "./chunk-LUPN3TRC.js";
73
+ import {
74
+ logEntry,
75
+ pruneSessionLog,
76
+ queryLog
77
+ } from "./chunk-UMC5PDL2.js";
53
78
  import {
54
79
  LINK_FILE,
55
80
  clearWorkspaceCache,
@@ -60,14 +85,14 @@ import {
60
85
  initWorkspace,
61
86
  listWorkspaces,
62
87
  loadWorkspaceInfo
63
- } from "./chunk-6HSUVCTR.js";
88
+ } from "./chunk-YAQ2TKSK.js";
64
89
  import "./chunk-PDX44BCA.js";
65
90
 
66
91
  // src/index.ts
67
- import { readFileSync as readFileSync13 } from "fs";
68
- import { join as join16, resolve as resolve30 } from "path";
92
+ import { readFileSync as readFileSync16 } from "fs";
93
+ import { join as join18, resolve as resolve34 } from "path";
69
94
  import { fileURLToPath as fileURLToPath2 } from "url";
70
- import { Command as Command12 } from "commander";
95
+ import { Command as Command16 } from "commander";
71
96
 
72
97
  // src/commands/decision.ts
73
98
  import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "fs";
@@ -142,41 +167,20 @@ What are the trade-offs? What does this enable or prevent?
142
167
 
143
168
  // src/commands/flow.ts
144
169
  import { Command as Command2 } from "commander";
145
- import chalk16 from "chalk";
170
+ import chalk17 from "chalk";
171
+ import { resolve as resolve17 } from "path";
146
172
 
147
173
  // src/commands/flow-backlog.ts
148
- import { existsSync as existsSync2 } from "fs";
149
- import { resolve as resolve2, join as join2 } from "path";
174
+ import { resolve as resolve2 } from "path";
150
175
  import chalk2 from "chalk";
151
- function now() {
152
- return (/* @__PURE__ */ new Date()).toISOString();
153
- }
154
- function nextItemId(workflow) {
155
- let max = 0;
156
- for (const item of workflow.items) {
157
- const match = item.id.match(/^ITEM-(\d+)$/);
158
- if (match) {
159
- const num = Number.parseInt(match[1], 10);
160
- if (num > max) max = num;
161
- }
162
- }
163
- return `ITEM-${max + 1}`;
164
- }
165
176
  function workflowExists(root) {
166
177
  return loadWorkflow(root);
167
178
  }
168
- function backlogAdd(root, description, spec) {
179
+ async function backlogAdd(root, description, spec, requestedId) {
169
180
  if (!description) {
170
181
  console.log(chalk2.red("Description is required"));
171
182
  process.exit(1);
172
183
  }
173
- if (spec) {
174
- const specsDir = join2(getLetraDir(root), "specs", spec);
175
- if (!existsSync2(specsDir)) {
176
- console.log(chalk2.red(`Spec "${spec}" not found at .letra/specs/${spec}/`));
177
- return;
178
- }
179
- }
180
184
  const workflow = workflowExists(root);
181
185
  if (!workflow) {
182
186
  console.log(chalk2.red("No workflow found. Run 'letra flow init --quick' first"));
@@ -186,31 +190,21 @@ function backlogAdd(root, description, spec) {
186
190
  console.log(chalk2.red("Workflow has no stages defined"));
187
191
  process.exit(1);
188
192
  }
189
- const firstStage = workflow.stages[0].id;
190
- const item = {
191
- id: nextItemId(workflow),
193
+ const direction = resolveDirection(root);
194
+ const operation = await createItemOperation(root, {
195
+ id: requestedId,
192
196
  description,
193
- stage: firstStage,
194
- createdAt: now(),
195
- spec: spec || void 0
196
- };
197
- if (spec) {
198
- if (!workflow.specLinks) workflow.specLinks = {};
199
- if (!workflow.specLinks[spec]) {
200
- workflow.specLinks[spec] = { path: `.letra/specs/${spec}/spec.md` };
201
- }
202
- }
203
- workflow.items.push(item);
204
- workflow.updatedAt = now();
205
- writeWorkflow(root, {
206
- workflow,
207
- source: "flow-backlog",
208
- primaryItemId: item.id,
209
- skipSitrep: true
197
+ spec,
198
+ expectedRevision: direction.revision,
199
+ reason: "Cria\xE7\xE3o de item pelo backlog da CLI.",
200
+ actor: resolveLocalIdentity(root).id
210
201
  });
211
- console.log(
212
- ` ${chalk2.green("\u2713")} Item ${chalk2.cyan(item.id)} added to ${chalk2.cyan(workflow.stages[0].name)}`
213
- );
202
+ if (operation.outcome !== "accepted") {
203
+ console.log(chalk2.red(` ${operation.reasonCode}: ${operation.reason}`));
204
+ return;
205
+ }
206
+ const created = operation.createdItem;
207
+ console.log(` ${chalk2.green("\u2713")} Item ${chalk2.cyan(created?.id ?? requestedId ?? "criado")} added to ${chalk2.cyan(workflow.stages[0].name)}`);
214
208
  }
215
209
  function backlogList(root) {
216
210
  const workflow = workflowExists(root);
@@ -241,9 +235,9 @@ function backlogList(root) {
241
235
  }
242
236
  console.log("");
243
237
  }
244
- function backlogActionAdd(targetPath, description, spec) {
238
+ function backlogActionAdd(targetPath, description, spec, requestedId) {
245
239
  const root = resolve2(process.cwd(), targetPath || ".");
246
- backlogAdd(root, description, spec);
240
+ return backlogAdd(root, description, spec, requestedId);
247
241
  }
248
242
  function backlogActionList(targetPath) {
249
243
  const root = resolve2(process.cwd(), targetPath || ".");
@@ -251,8 +245,8 @@ function backlogActionList(targetPath) {
251
245
  }
252
246
 
253
247
  // src/commands/flow-board.ts
254
- import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
255
- import { join as join3, resolve as resolve3 } from "path";
248
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
249
+ import { join as join2, resolve as resolve3 } from "path";
256
250
  import chalk3 from "chalk";
257
251
  function resolveBoardStages(workflow, resolvedStages) {
258
252
  const stages = resolvedStages?.length ? resolvedStages.map((stage) => ({ ...stage })) : workflow.stages.map((stage) => ({ ...stage }));
@@ -291,10 +285,10 @@ function flowBoard(root) {
291
285
  `);
292
286
  }
293
287
  const boardStages = resolveBoardStages(workflow, resolveActiveFlow(root).flow?.stages);
294
- const healthPath = join3(getLetraDir(root), "health-record.json");
288
+ const healthPath = join2(getLetraDir(root), "health-record.json");
295
289
  const itemAlerts = /* @__PURE__ */ new Map();
296
290
  try {
297
- if (existsSync3(healthPath)) {
291
+ if (existsSync2(healthPath)) {
298
292
  const health = JSON.parse(readFileSync2(healthPath, "utf-8"));
299
293
  const entries = health.entries || [];
300
294
  for (const entry of entries) {
@@ -331,8 +325,8 @@ function flowBoard(root) {
331
325
  if (item.spec) {
332
326
  const specLink2 = workflow.specLinks?.[item.spec];
333
327
  if (specLink2) {
334
- const specPath = join3(root, specLink2.path);
335
- specInfo = existsSync3(specPath) ? chalk3.cyan(`\u{1F4CE}${item.spec}`) : chalk3.red("\u26A0spec?");
328
+ const specPath = join2(getLetraDir(root), specLink2.path.replace(/^\.letra[\\/]/, ""));
329
+ specInfo = existsSync2(specPath) ? chalk3.cyan(`\u{1F4CE}${item.spec}`) : chalk3.red("\u26A0spec?");
336
330
  } else {
337
331
  specInfo = chalk3.red("\u26A0reg?");
338
332
  }
@@ -354,10 +348,10 @@ function flowBoardAction(targetPath) {
354
348
  }
355
349
 
356
350
  // src/commands/flow-edit-diff.ts
357
- import { existsSync as existsSync4, readFileSync as readFileSync3, readdirSync as readdirSync2, writeFileSync as writeFileSync2 } from "fs";
358
- import { join as join4, resolve as resolve4 } from "path";
351
+ import { existsSync as existsSync3, readFileSync as readFileSync3, readdirSync as readdirSync2, writeFileSync as writeFileSync2 } from "fs";
352
+ import { join as join3, resolve as resolve4 } from "path";
359
353
  import chalk4 from "chalk";
360
- function now2() {
354
+ function now() {
361
355
  return (/* @__PURE__ */ new Date()).toISOString();
362
356
  }
363
357
  function normalizeVersion(v) {
@@ -372,8 +366,8 @@ function incrementVersion(v) {
372
366
  return parts.join(".");
373
367
  }
374
368
  function loadBackup(root, version) {
375
- const path = join4(getLetraDir(root), `workflow.v${version}.json`);
376
- if (!existsSync4(path)) return null;
369
+ const path = join3(getLetraDir(root), `workflow.v${version}.json`);
370
+ if (!existsSync3(path)) return null;
377
371
  try {
378
372
  return JSON.parse(readFileSync3(path, "utf-8"));
379
373
  } catch {
@@ -389,7 +383,7 @@ function loadVersion(root, version) {
389
383
  }
390
384
  function getLatestBackupVersion(root) {
391
385
  const dir = getLetraDir(root);
392
- if (!existsSync4(dir)) return null;
386
+ if (!existsSync3(dir)) return null;
393
387
  const files = readdirSync2(dir).filter((f) => f.startsWith("workflow.v") && f.endsWith(".json"));
394
388
  if (files.length === 0) return null;
395
389
  const versions = files.map((f) => f.replace("workflow.v", "").replace(".json", ""));
@@ -404,9 +398,9 @@ function getLatestBackupVersion(root) {
404
398
  return versions[versions.length - 1];
405
399
  }
406
400
  function backupFilePath(root, version) {
407
- return join4(getLetraDir(root), `workflow.v${version}.json`);
401
+ return join3(getLetraDir(root), `workflow.v${version}.json`);
408
402
  }
409
- function flowEdit(root, options) {
403
+ async function flowEdit(root, options) {
410
404
  const workflow = loadWorkflow(root);
411
405
  if (!workflow) {
412
406
  console.log(chalk4.yellow("No workflow found. Run 'letra flow init --quick' first"));
@@ -414,7 +408,7 @@ function flowEdit(root, options) {
414
408
  }
415
409
  const currentVersion = normalizeVersion(workflow.version);
416
410
  const backupPath = backupFilePath(root, currentVersion);
417
- if (!existsSync4(backupPath)) {
411
+ if (!existsSync3(backupPath)) {
418
412
  writeFileSync2(backupPath, JSON.stringify(workflow, null, 2));
419
413
  }
420
414
  if (options.name !== void 0) {
@@ -424,8 +418,8 @@ function flowEdit(root, options) {
424
418
  workflow.description = options.desc;
425
419
  }
426
420
  workflow.version = incrementVersion(workflow.version);
427
- workflow.updatedAt = now2();
428
- writeWorkflow(root, { workflow, source: "flow-edit", skipSitrep: true });
421
+ workflow.updatedAt = now();
422
+ await writeWorkflow(root, { workflow, source: "flow-edit", skipSitrep: true });
429
423
  console.log(` ${chalk4.green("\u2713")} Workflow updated to v${workflow.version}`);
430
424
  if (options.name !== void 0) {
431
425
  console.log(` Name: ${chalk4.cyan(options.name)}`);
@@ -546,9 +540,9 @@ function flowDiff(root, v1, v2) {
546
540
  for (const line of lines) console.log(line);
547
541
  }
548
542
  }
549
- function flowEditAction(targetPath, options) {
543
+ async function flowEditAction(targetPath, options) {
550
544
  const root = resolve4(process.cwd(), targetPath || ".");
551
- flowEdit(root, options);
545
+ await flowEdit(root, options);
552
546
  }
553
547
  function flowDiffAction(targetPath, v1, v2) {
554
548
  const root = resolve4(process.cwd(), targetPath || ".");
@@ -556,8 +550,8 @@ function flowDiffAction(targetPath, v1, v2) {
556
550
  }
557
551
 
558
552
  // src/commands/flow-export-import.ts
559
- import { existsSync as existsSync5, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "fs";
560
- import { join as join5, resolve as resolve5 } from "path";
553
+ import { existsSync as existsSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "fs";
554
+ import { join as join4, resolve as resolve5 } from "path";
561
555
  import chalk5 from "chalk";
562
556
  function flowExport(root, options) {
563
557
  const workflow = loadWorkflow(root);
@@ -572,11 +566,11 @@ function flowExportAction(targetPath, options) {
572
566
  const root = resolve5(process.cwd(), targetPath || ".");
573
567
  flowExport(root, options);
574
568
  }
575
- function now3() {
569
+ function now2() {
576
570
  return (/* @__PURE__ */ new Date()).toISOString();
577
571
  }
578
572
  function flowImport(root, filePath) {
579
- if (!existsSync5(filePath)) {
573
+ if (!existsSync4(filePath)) {
580
574
  console.log(chalk5.red(`File not found: ${filePath}`));
581
575
  process.exit(1);
582
576
  }
@@ -600,31 +594,34 @@ function flowImport(root, filePath) {
600
594
  const imported = parsed;
601
595
  const existingWorkflow = loadWorkflow(root);
602
596
  if (existingWorkflow) {
603
- const backup = join5(getLetraDir(root), `workflow.v${existingWorkflow.version}.json`);
604
- if (!existsSync5(backup)) {
597
+ const backup = join4(getLetraDir(root), `workflow.v${existingWorkflow.version}.json`);
598
+ if (!existsSync4(backup)) {
605
599
  writeFileSync3(backup, JSON.stringify(existingWorkflow, null, 2));
606
600
  console.log(
607
601
  chalk5.gray(`Backup saved: .letra/workflow.v${existingWorkflow.version}.json`)
608
602
  );
609
603
  }
610
604
  }
611
- imported.createdAt = now3();
612
- imported.updatedAt = now3();
613
- writeWorkflow(root, { workflow: imported, source: "flow-import", skipSitrep: true });
614
- console.log(chalk5.green(`Workflow imported: ${imported.name} (${imported.version})`));
605
+ imported.createdAt = now2();
606
+ imported.updatedAt = now2();
607
+ return writeWorkflow(root, { workflow: imported, source: "flow-import", skipSitrep: true }).then(
608
+ () => {
609
+ console.log(chalk5.green(`Workflow imported: ${imported.name} (${imported.version})`));
610
+ }
611
+ );
615
612
  }
616
- function flowImportAction(targetPath, filePath) {
613
+ async function flowImportAction(targetPath, filePath) {
617
614
  const root = resolve5(process.cwd(), targetPath || ".");
618
- flowImport(root, filePath);
615
+ await flowImport(root, filePath);
619
616
  }
620
617
 
621
618
  // src/commands/flow-import-issues.ts
622
619
  import { resolve as resolve6 } from "path";
623
620
  import chalk6 from "chalk";
624
- function now4() {
621
+ function now3() {
625
622
  return (/* @__PURE__ */ new Date()).toISOString();
626
623
  }
627
- function nextItemId2(workflow) {
624
+ function nextItemId(workflow) {
628
625
  let max = 0;
629
626
  for (const item of workflow.items) {
630
627
  const match = item.id.match(/^ITEM-(\d+)$/);
@@ -701,17 +698,17 @@ async function backlogImportGitHub(root, repo, options) {
701
698
  const labels = issue.labels?.map((l) => l.name).join(", ") || "";
702
699
  const description = labels ? `[${issue.number}] ${issue.title} (${labels})` : `[${issue.number}] ${issue.title}`;
703
700
  const item = {
704
- id: nextItemId2(workflow),
701
+ id: nextItemId(workflow),
705
702
  description,
706
703
  stage: firstStage,
707
- createdAt: now4(),
704
+ createdAt: now3(),
708
705
  source: "github",
709
706
  sourceUrl: issue.html_url
710
707
  };
711
708
  workflow.items.push(item);
712
709
  imported++;
713
710
  }
714
- workflow.updatedAt = now4();
711
+ workflow.updatedAt = now3();
715
712
  writeWorkflow(root, { workflow, source: "flow-import", skipSitrep: true, quiet: true });
716
713
  console.log(
717
714
  ` ${chalk6.green("\u2713")} Imported ${chalk6.cyan(String(imported))} issue${imported !== 1 ? "s" : ""} from ${chalk6.cyan(repo)}`
@@ -785,17 +782,17 @@ async function backlogImportLinear(root, team, options) {
785
782
  for (const issue of issues) {
786
783
  const description = `${issue.identifier} ${issue.title}`;
787
784
  const item = {
788
- id: nextItemId2(workflow),
785
+ id: nextItemId(workflow),
789
786
  description,
790
787
  stage: firstStage,
791
- createdAt: now4(),
788
+ createdAt: now3(),
792
789
  source: "linear",
793
790
  sourceUrl: issue.url
794
791
  };
795
792
  workflow.items.push(item);
796
793
  imported++;
797
794
  }
798
- workflow.updatedAt = now4();
795
+ workflow.updatedAt = now3();
799
796
  writeWorkflow(root, { workflow, source: "flow-import", skipSitrep: true, quiet: true });
800
797
  console.log(
801
798
  ` ${chalk6.green("\u2713")} Imported ${chalk6.cyan(String(imported))} issue${imported !== 1 ? "s" : ""} from Linear team ${chalk6.cyan(team)}`
@@ -817,568 +814,111 @@ async function backlogImportLinearAction(targetPath, team, options) {
817
814
  }
818
815
 
819
816
  // src/commands/flow-move.ts
820
- import { existsSync as existsSync7, readFileSync as readFileSync6 } from "fs";
821
- import { join as join7, resolve as resolve7 } from "path";
817
+ import { resolve as resolve7 } from "path";
822
818
  import chalk7 from "chalk";
823
-
824
- // src/phases/runner.ts
825
- import { execSync } from "child_process";
826
- import { existsSync as existsSync6, mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync4 } from "fs";
827
- import { join as join6 } from "path";
828
- var PhaseActionRunner = class {
829
- execPhase(root, item, phaseDef) {
830
- if (!phaseDef.actions || phaseDef.actions.length === 0) {
831
- return { ok: true, actions: [] };
819
+ function resolveStage(workflow, input) {
820
+ const lower = input.toLowerCase();
821
+ return workflow.stages.find((stage) => stage.id === lower || stage.name.toLowerCase() === lower)?.id ?? null;
822
+ }
823
+ async function flowMove(root, itemId, targetStageInput, options) {
824
+ const workflow = loadWorkflow(root);
825
+ if (!workflow) {
826
+ console.log(chalk7.red("No workflow found. Run 'letra flow init --quick' first"));
827
+ return false;
828
+ }
829
+ const item = workflow.items.find((candidate) => candidate.id === itemId || candidate.id.toLowerCase() === itemId.toLowerCase() || candidate.description.toLowerCase() === itemId.toLowerCase());
830
+ if (!item) {
831
+ console.log(chalk7.red(`Item "${itemId}" not found`));
832
+ return false;
833
+ }
834
+ if (options?.auto) {
835
+ const current = workflow.stages.find((stage) => stage.id === item.stage);
836
+ if (!current) {
837
+ console.log(chalk7.red(`Stage "${item.stage}" not found in workflow`));
838
+ return false;
832
839
  }
833
- const checker = new GateChecker(root);
834
- const results = [];
835
- for (const action of phaseDef.actions) {
836
- try {
837
- switch (action.type) {
838
- case "command": {
839
- const output = execSync(action.cmd, {
840
- cwd: root,
841
- timeout: 3e4,
842
- stdio: "pipe"
843
- });
844
- const label = `command: ${action.cmd}`;
845
- results.push(label);
846
- logEntry(root, "system", `action:${label}`, {
847
- itemId: item.id,
848
- details: { phase: phaseDef.id }
849
- });
850
- break;
851
- }
852
- case "agent-prompt": {
853
- const promptDir = getLetraDir(root);
854
- if (!existsSync6(promptDir)) mkdirSync2(promptDir, { recursive: true });
855
- const content = [
856
- `# Phase Prompt: ${phaseDef.label}`,
857
- "",
858
- action.prompt,
859
- "",
860
- "---",
861
- `Item: ${item.id}`,
862
- `Phase: ${phaseDef.id}`
863
- ].join("\n");
864
- writeFileSync4(join6(getLetraDir(root), "phase-prompt.md"), content, "utf-8");
865
- const label = `agent-prompt: ${action.prompt}`;
866
- results.push(label);
867
- logEntry(root, "system", `action:${label}`, {
868
- itemId: item.id,
869
- details: { phase: phaseDef.id }
870
- });
871
- break;
872
- }
873
- case "generate-report": {
874
- const reportDir = join6(getLetraDir(root), "reports");
875
- if (!existsSync6(reportDir)) mkdirSync2(reportDir, { recursive: true });
876
- const reportContent = [
877
- `# Report: ${item.id} - ${phaseDef.label}`,
878
- `Generated: ${(/* @__PURE__ */ new Date()).toISOString()}`,
879
- `Template: ${action.template}`
880
- ].join("\n");
881
- const reportPath = join6(reportDir, `${item.id}-${phaseDef.id}.md`);
882
- writeFileSync4(reportPath, reportContent, "utf-8");
883
- const label = `generate-report: ${action.template}`;
884
- results.push(label);
885
- logEntry(root, "system", `action:${label}`, {
886
- itemId: item.id,
887
- details: { phase: phaseDef.id }
888
- });
889
- break;
890
- }
891
- case "notify-human": {
892
- logEntry(root, "system", `action:notify-human: ${action.message}`, {
893
- itemId: item.id,
894
- details: { phase: phaseDef.id }
895
- });
896
- const notifyPath = join6(getLetraDir(root), "human-notify.md");
897
- writeFileSync4(
898
- notifyPath,
899
- `# Human Notification
900
-
901
- ${action.message}
902
-
903
- Item: ${item.id}
904
- Phase: ${phaseDef.id}`,
905
- "utf-8"
906
- );
907
- const label = `notify-human: ${action.message}`;
908
- results.push(label);
909
- break;
910
- }
911
- case "wait-human": {
912
- const gateId = action.gate ?? "";
913
- const gateResult = checker.check(gateId, item);
914
- if (!gateResult.allowed) {
915
- logEntry(
916
- root,
917
- "system",
918
- `action:wait-human gate "${gateId}" blocking`,
919
- {
920
- itemId: item.id,
921
- details: { gate: gateId, phase: phaseDef.id }
922
- }
923
- );
924
- return {
925
- ok: false,
926
- error: gateResult.reason?.includes("humana") ? `Gate "${gateId}" not approved` : gateResult.reason ?? `Gate "${gateId}" not approved`,
927
- actions: results
928
- };
929
- }
930
- const label = `wait-human: ${gateId} (approved)`;
931
- results.push(label);
932
- break;
933
- }
934
- }
935
- } catch (e) {
936
- const msg = `Action "${action.type}" failed: ${e.message}`;
937
- logEntry(root, "system", `action:error ${msg}`, {
938
- itemId: item.id,
939
- details: { phase: phaseDef.id }
940
- });
941
- return { ok: false, error: msg, actions: results };
942
- }
840
+ const next = workflow.stages.filter((stage) => stage.order > current.order).sort((a, b) => a.order - b.order)[0];
841
+ if (!next) {
842
+ console.log(chalk7.yellow(`Item ${itemId} is already at the last stage (${current.name})`));
843
+ return false;
943
844
  }
944
- return { ok: true, actions: results };
845
+ targetStageInput = next.id;
945
846
  }
946
- };
947
-
948
- // src/phases/engine.ts
949
- function getStagePhases(workflow, stageId) {
950
- const stage = workflow.stages.find((s) => s.id === stageId);
951
- if (!stage) return null;
952
- return stage.phases ?? null;
953
- }
954
- function getPhaseDef(phases, phaseId) {
955
- return phases.states[phaseId] ?? null;
956
- }
957
- function enterStage(workflow, item) {
958
- const phases = getStagePhases(workflow, item.stage);
959
- if (!phases) {
960
- item.currentPhase = void 0;
961
- return { ok: true, phase: void 0 };
847
+ const targetStageId = resolveStage(workflow, targetStageInput);
848
+ if (!targetStageId) {
849
+ console.log(chalk7.red(`Stage "${targetStageInput}" not found`));
850
+ return false;
962
851
  }
963
- const initial = phases.initialState;
964
- if (!phases.states[initial]) {
965
- return {
966
- ok: false,
967
- error: `Initial phase "${initial}" not defined in stage "${item.stage}"`
968
- };
852
+ if (item.stage === targetStageId) {
853
+ console.log(chalk7.yellow(`Item ${itemId} is already in stage "${targetStageId}"`));
854
+ return true;
969
855
  }
970
- item.currentPhase = initial;
971
- return {
972
- ok: true,
973
- phase: initial,
974
- triggeredActions: ["enterStage"],
975
- triggeredAutoTransition: false
976
- };
977
- }
978
- var _runner = new PhaseActionRunner();
979
- function transitionPhase(root, workflow, item, targetPhaseId) {
980
- const phases = getStagePhases(workflow, item.stage);
981
- if (!phases) {
982
- return { ok: false, error: `Stage "${item.stage}" has no phases defined` };
856
+ const fromStage = workflow.stages.find((stage) => stage.id === item.stage)?.name ?? item.stage;
857
+ const toStage = workflow.stages.find((stage) => stage.id === targetStageId)?.name ?? targetStageId;
858
+ if (!item.claimExecutorId) {
859
+ console.log(chalk7.red(`Cannot move ${itemId}: item n\xE3o possui claim ativa; adquira uma claim antes da passagem.`));
860
+ return false;
983
861
  }
984
- const currentDef = item.currentPhase ? getPhaseDef(phases, item.currentPhase) : null;
985
- const transition = currentDef?.transitions?.find((t) => t.target === targetPhaseId);
986
- if (targetPhaseId === "__EXIT__") {
987
- if (!transition) {
988
- const allowed = (currentDef?.transitions ?? []).map((t) => t.target).join(", ");
989
- return {
990
- ok: false,
991
- error: `Transition from "${item.currentPhase}" to "__EXIT__" not allowed. Allowed: ${allowed || "none"}`
992
- };
993
- }
994
- item.currentPhase = void 0;
995
- return { ok: true, phase: void 0, triggeredActions: [], triggeredAutoTransition: false };
862
+ const activeFlow = resolveActiveFlow(root, { itemId: item.id, workflowVersionId: item.workflowVersionId }).flow;
863
+ const destination = activeFlow?.stages.find((stage) => stage.id === targetStageId);
864
+ const recipients = destination?.roleIds?.length ? destination.roleIds : destination?.agents ?? [];
865
+ if (!recipients.length) {
866
+ console.log(chalk7.red(`Cannot move ${itemId}: est\xE1gio ${targetStageId} sem papel/destinat\xE1rio configurado.`));
867
+ return false;
996
868
  }
997
- if (!phases.states[targetPhaseId]) {
998
- return { ok: false, error: `Phase "${targetPhaseId}" not found in stage "${item.stage}"` };
869
+ if (recipients.length > 1) {
870
+ console.log(chalk7.red(`Cannot move ${itemId}: m\xFAltiplos destinat\xE1rios configurados (${recipients.join(", ")}); escolha expl\xEDcita ainda n\xE3o est\xE1 dispon\xEDvel neste comando.`));
871
+ return false;
999
872
  }
1000
- if (currentDef && !transition) {
1001
- const allowed = (currentDef.transitions ?? []).map((t) => t.target).join(", ");
1002
- return {
1003
- ok: false,
1004
- error: `Transition from "${item.currentPhase}" to "${targetPhaseId}" not allowed. Allowed: ${allowed || "none"}`
1005
- };
1006
- }
1007
- item.currentPhase = targetPhaseId;
1008
- const targetDef = getPhaseDef(phases, targetPhaseId);
1009
- let actions = [];
1010
- if (root && targetDef) {
1011
- const result = _runner.execPhase(root, item, targetDef);
1012
- actions = result.actions;
1013
- if (!result.ok) {
1014
- return {
1015
- ok: false,
1016
- error: result.error,
1017
- phase: item.currentPhase,
1018
- triggeredActions: actions
1019
- };
1020
- }
1021
- } else {
1022
- actions = (targetDef?.actions ?? []).map((a) => {
1023
- if (a.type === "agent-prompt") return `agent-prompt: ${a.prompt}`;
1024
- if (a.type === "command") return `command: ${a.cmd}`;
1025
- if (a.type === "generate-report") return `generate-report: ${a.template}`;
1026
- if (a.type === "notify-human") return `notify-human: ${a.message}`;
1027
- if (a.type === "wait-human") return `wait-human: ${a.gate}`;
1028
- return "unknown action";
1029
- });
1030
- }
1031
- let triggeredAutoTransition = false;
1032
- if (transition?.auto) {
1033
- const nextAuto = targetDef?.transitions?.find((t) => t.auto);
1034
- if (nextAuto && phases.states[nextAuto.target]) {
1035
- item.currentPhase = nextAuto.target;
1036
- triggeredAutoTransition = true;
1037
- }
1038
- }
1039
- return {
1040
- ok: true,
1041
- phase: item.currentPhase,
1042
- triggeredActions: actions,
1043
- triggeredAutoTransition
1044
- };
1045
- }
1046
-
1047
- // src/phases/autopilot.ts
1048
- var MAX_AUTO_TRANSITIONS = 10;
1049
- var runner = new PhaseActionRunner();
1050
- function getAutoTarget(workflow, item) {
1051
- const phases = getStagePhases(workflow, item.stage);
1052
- if (!phases || !item.currentPhase) return null;
1053
- const def = getPhaseDef(phases, item.currentPhase);
1054
- if (!def) return null;
1055
- const autoTrans = (def.transitions ?? []).find((t) => t.auto);
1056
- return autoTrans?.target ?? null;
1057
- }
1058
- var PhaseAutoPilot = class {
1059
- transitionsApplied = 0;
1060
- async run(root, workflow, item) {
1061
- this.transitionsApplied = 0;
1062
- if (!item.currentPhase) {
1063
- logEntry(root, "system", `autopilot:${item.id} no current phase \u2014 nothing to do`, {
1064
- itemId: item.id
1065
- });
1066
- return { ok: true, finalPhase: void 0, transitionsApplied: 0 };
1067
- }
1068
- logEntry(
1069
- root,
1070
- "system",
1071
- `autopilot:starting for ${item.id} from phase "${item.currentPhase}"`,
1072
- { itemId: item.id }
1073
- );
1074
- while (this.transitionsApplied < MAX_AUTO_TRANSITIONS) {
1075
- const autoTarget = getAutoTarget(workflow, item);
1076
- if (!autoTarget) {
1077
- logEntry(
1078
- root,
1079
- "system",
1080
- `autopilot:${item.id} stopped at phase "${item.currentPhase}" \u2014 no auto-transition`,
1081
- {
1082
- itemId: item.id
1083
- }
1084
- );
1085
- return {
1086
- ok: true,
1087
- finalPhase: item.currentPhase,
1088
- transitionsApplied: this.transitionsApplied
1089
- };
1090
- }
1091
- const phases = getStagePhases(workflow, item.stage);
1092
- const phaseDef = item.currentPhase && phases ? getPhaseDef(phases, item.currentPhase) : null;
1093
- if (phaseDef) {
1094
- const actionResult = runner.execPhase(root, item, phaseDef);
1095
- if (!actionResult.ok) {
1096
- logEntry(
1097
- root,
1098
- "system",
1099
- `autopilot:${item.id} stopped \u2014 action failed: ${actionResult.error}`,
1100
- {
1101
- itemId: item.id
1102
- }
1103
- );
1104
- return {
1105
- ok: false,
1106
- error: actionResult.error,
1107
- finalPhase: item.currentPhase,
1108
- transitionsApplied: this.transitionsApplied
1109
- };
1110
- }
1111
- }
1112
- const prevPhase = item.currentPhase;
1113
- const result = transitionPhase(root, workflow, item, autoTarget);
1114
- if (!result.ok) {
1115
- logEntry(
1116
- root,
1117
- "system",
1118
- `autopilot:${item.id} transition failed \u2014 ${result.error}`,
1119
- { itemId: item.id }
1120
- );
1121
- return {
1122
- ok: false,
1123
- error: result.error,
1124
- finalPhase: prevPhase,
1125
- transitionsApplied: this.transitionsApplied
1126
- };
1127
- }
1128
- this.transitionsApplied++;
1129
- logEntry(
1130
- root,
1131
- "system",
1132
- `autopilot:${item.id} ${prevPhase} \u2192 ${item.currentPhase || "__EXIT__"}`,
1133
- {
1134
- itemId: item.id
1135
- }
1136
- );
1137
- if (!item.currentPhase) {
1138
- logEntry(root, "system", `autopilot:${item.id} exited phase system`, {
1139
- itemId: item.id
1140
- });
1141
- return {
1142
- ok: true,
1143
- finalPhase: void 0,
1144
- transitionsApplied: this.transitionsApplied
1145
- };
1146
- }
1147
- }
1148
- const msg = "Auto-loop limit exceeded";
1149
- logEntry(root, "system", `autopilot:${item.id} ${msg}`, { itemId: item.id });
1150
- return {
1151
- ok: false,
1152
- error: msg,
1153
- finalPhase: item.currentPhase,
1154
- transitionsApplied: this.transitionsApplied
1155
- };
1156
- }
1157
- };
1158
- async function autopilotRun(root, workflow, item) {
1159
- const pilot = new PhaseAutoPilot();
1160
- return pilot.run(root, workflow, item);
1161
- }
1162
- function canAutopilot(workflow, item) {
1163
- if (!item.currentPhase) return false;
1164
- const phases = getStagePhases(workflow, item.stage);
1165
- if (!phases) return false;
1166
- const def = getPhaseDef(phases, item.currentPhase);
1167
- if (!def) return false;
1168
- return (def.transitions ?? []).some((t) => t.auto);
1169
- }
1170
-
1171
- // src/commands/flow-move.ts
1172
- function now5() {
1173
- return (/* @__PURE__ */ new Date()).toISOString();
1174
- }
1175
- function resolveStage(workflow, input) {
1176
- const lower = input.toLowerCase();
1177
- for (const stage of workflow.stages) {
1178
- if (stage.id === lower) return stage.id;
1179
- if (stage.name.toLowerCase() === lower) return stage.id;
1180
- }
1181
- return null;
1182
- }
1183
- async function flowMove(root, itemId, targetStageInput, options) {
1184
- const workflow = loadWorkflow(root);
1185
- if (!workflow) {
1186
- console.log(chalk7.red("No workflow found. Run 'letra flow init --quick' first"));
1187
- process.exit(1);
1188
- }
1189
- const item = workflow.items.find((i) => i.id === itemId) || workflow.items.find((i) => i.id.toLowerCase() === itemId.toLowerCase()) || workflow.items.find((i) => i.description.toLowerCase() === itemId.toLowerCase());
1190
- if (!item) {
1191
- console.log(chalk7.red(`Item "${itemId}" not found`));
1192
- process.exit(1);
1193
- }
1194
- if (options?.auto) {
1195
- const currentStage = workflow.stages.find((s) => s.id === item.stage);
1196
- if (!currentStage) {
1197
- console.log(chalk7.red(`Stage "${item.stage}" not found in workflow`));
1198
- process.exit(1);
1199
- return;
1200
- }
1201
- const nextStage = workflow.stages.filter((s) => s.order > currentStage.order).sort((a, b) => a.order - b.order)[0];
1202
- if (!nextStage) {
1203
- console.log(
1204
- chalk7.yellow(`Item ${itemId} is already at the last stage (${currentStage.name})`)
1205
- );
1206
- return;
1207
- }
1208
- targetStageInput = nextStage.id;
1209
- if (!options?.force && item.spec) {
1210
- const specFile = join7(getLetraDir(root), "specs", item.spec, "spec.md");
1211
- if (existsSync7(specFile)) {
1212
- const content = readFileSync6(specFile, "utf-8");
1213
- const pendingACs = content.match(/^- \[ \]/gm) || [];
1214
- if (pendingACs.length > 0) {
1215
- console.log(
1216
- chalk7.yellow(
1217
- `\u26A0 Item ${itemId} has ${pendingACs.length} pending AC(s) in "${item.spec}"`
1218
- )
1219
- );
1220
- console.log(
1221
- chalk7.yellow(" Use --force to move anyway, or complete ACs first.")
1222
- );
1223
- return;
1224
- }
1225
- const doneACs = content.match(/^- \[[xX]\]/gm) || [];
1226
- if (doneACs.length > 0) {
1227
- const acLogEntries = queryLog(root, { itemId, action: "ac_done", limit: 999 });
1228
- if (acLogEntries.length < doneACs.length) {
1229
- console.log(
1230
- chalk7.yellow(
1231
- `\u26A0 ${doneACs.length - acLogEntries.length} AC(s) marked [x] without "ac done" log entry.`
1232
- )
1233
- );
1234
- console.log(
1235
- chalk7.yellow(" Run letra ac done <ID> for each completed AC.")
1236
- );
1237
- }
1238
- }
1239
- }
1240
- }
1241
- }
1242
- if (!options?.auto && !options?.force && item.spec) {
1243
- const specFile = join7(getLetraDir(root), "specs", item.spec, "spec.md");
1244
- if (existsSync7(specFile)) {
1245
- const content = readFileSync6(specFile, "utf-8");
1246
- const pendingACs = content.match(/^- \[ \]/gm) || [];
1247
- if (pendingACs.length > 0) {
1248
- console.log(
1249
- chalk7.yellow(
1250
- `\u26A0 Item ${itemId} has ${pendingACs.length} pending AC(s) in "${item.spec}"`
1251
- )
1252
- );
1253
- console.log(chalk7.yellow(" Use --force to move anyway, or complete ACs first."));
1254
- return;
1255
- }
1256
- const doneACs = content.match(/^- \[[xX]\]/gm) || [];
1257
- if (doneACs.length > 0) {
1258
- const acLogEntries = queryLog(root, { itemId, action: "ac_done", limit: 999 });
1259
- if (acLogEntries.length < doneACs.length) {
1260
- console.log(
1261
- chalk7.yellow(
1262
- `\u26A0 ${doneACs.length - acLogEntries.length} AC(s) marked [x] without "ac done" log entry.`
1263
- )
1264
- );
1265
- console.log(chalk7.yellow(" Run letra ac done <ID> for each completed AC."));
1266
- }
1267
- }
1268
- }
1269
- }
1270
- {
1271
- const resolved = resolveActiveFlow(root);
1272
- const targetDef = resolved.flow?.stages.find((stage) => stage.id === targetStageInput);
1273
- const gate = targetDef?.gate;
1274
- if (gate?.blocking) {
1275
- if (gate.type === "human") {
1276
- if (options?.force) {
1277
- console.log(chalk7.yellow(` Gate "${gate.name}" bypassado via --force`));
1278
- } else {
1279
- const resolvedTarget = resolveStage(workflow, targetStageInput) || targetStageInput;
1280
- console.log(chalk7.red(`Gate bloqueante: ${gate.name}`));
1281
- console.log(
1282
- chalk7.yellow(
1283
- ` Aprova\xE7\xE3o humana necess\xE1ria para entrar em "${resolvedTarget}".`
1284
- )
1285
- );
1286
- return;
1287
- }
1288
- } else {
1289
- const checker = new GateChecker(root);
1290
- const result2 = checker.check(gate.id, item);
1291
- if (!result2.allowed) {
1292
- const resolvedTarget = resolveStage(workflow, targetStageInput) || targetStageInput;
1293
- console.log(chalk7.red(`Gate bloqueante: ${gate.name}`));
1294
- console.log(chalk7.yellow(` ${result2.reason}`));
1295
- console.log(
1296
- chalk7.yellow(
1297
- ` Aprova\xE7\xE3o humana necess\xE1ria para entrar em "${resolvedTarget}".`
1298
- )
1299
- );
1300
- return;
1301
- }
1302
- }
1303
- }
1304
- }
1305
- const targetStageId = resolveStage(workflow, targetStageInput);
1306
- if (!targetStageId) {
1307
- const valid = workflow.stages.map((s) => `${s.id} (${s.name})`).join(", ");
1308
- console.log(chalk7.red(`Stage "${targetStageInput}" not found. Valid stages: ${valid}`));
1309
- process.exit(1);
1310
- }
1311
- if (item.stage === targetStageId) {
1312
- console.log(chalk7.yellow(`Item ${itemId} is already in stage "${targetStageId}"`));
1313
- return;
1314
- }
1315
- const fromStage = workflow.stages.find((s) => s.id === item.stage)?.name || item.stage;
1316
- const toStage = workflow.stages.find((s) => s.id === targetStageId)?.name || targetStageId;
1317
- item.stage = targetStageId;
1318
- const phaseResult = enterStage(workflow, item);
1319
- if (phaseResult.phase) {
1320
- logEntry(root, "system", `phase_entry: ${item.id} \u2192 ${phaseResult.phase}`);
1321
- }
1322
- workflow.updatedAt = now5();
1323
- if (phaseResult.ok && item.currentPhase && canAutopilot(workflow, item)) {
1324
- console.log(
1325
- ` ${chalk7.cyan("\u23E9")} Auto-pilot dispon\xEDvel para ${item.id} (fase inicial tem auto-transition)`
1326
- );
1327
- const pilotResult = await autopilotRun(root, workflow, item);
1328
- if (pilotResult.ok) {
1329
- console.log(
1330
- ` ${chalk7.green("\u2713")} Auto-pilot: ${pilotResult.transitionsApplied} transi\xE7\xE3o(\xF5es) \u2014 parou em "${pilotResult.finalPhase || "__EXIT__"}"`
1331
- );
1332
- } else {
1333
- console.log(
1334
- ` ${chalk7.yellow("\u23F8")} Auto-pilot: ${pilotResult.error} \u2014 parou em "${pilotResult.finalPhase}"`
1335
- );
1336
- }
1337
- }
1338
- const targetStageIsDone = workflow.stages.find((s) => s.id === targetStageId)?.zone === "done";
1339
- if (targetStageIsDone && item.claimedBy) {
1340
- if (item.claimedBy === "opencode") {
1341
- console.log(
1342
- ` ${chalk7.gray("Release autom\xE1tico:")} ${itemId} n\xE3o est\xE1 mais sob responsabilidade do agente`
1343
- );
1344
- }
1345
- item.claimedBy = void 0;
1346
- item.claimedAt = void 0;
1347
- }
1348
- const result = await writeWorkflow(root, {
1349
- workflow,
1350
- source: "flow-move",
1351
- primaryItemId: itemId,
1352
- skipSitrep: true
1353
- });
1354
- if (item.spec) {
1355
- writeFocusWithRecommendations(root, item.spec, item.id);
1356
- }
1357
- logEntry(root, "item_move", `Item ${itemId} movido: ${fromStage} \u2192 ${toStage}`, {
1358
- itemId,
1359
- details: { from: item.stage, to: targetStageId }
1360
- });
1361
- console.log(
1362
- ` ${chalk7.green("\u2713")} Item ${chalk7.cyan(itemId)} moved: ${chalk7.yellow(fromStage)} \u2192 ${chalk7.green(toStage)}`
1363
- );
1364
- if (result.ok && result.filesUpdated.length > 0) {
1365
- console.log(` ${chalk7.gray("Updated:")} ${result.filesUpdated.join(", ")}`);
873
+ const operation = await requestPassageOperation(root, {
874
+ itemId,
875
+ targetStageId,
876
+ runId: options?.run,
877
+ to: recipients[0],
878
+ executorId: item.claimExecutorId,
879
+ summary: `Passagem solicitada pela CLI: ${fromStage} \u2192 ${toStage}.`,
880
+ evidence: [],
881
+ actor: options?.actor?.trim() || resolveLocalIdentity(root).id,
882
+ // The revision requestPassageOperation compares (run-aware, bound to
883
+ // the claim's executor); resolveAgentDirection diverges once a Run exists.
884
+ expectedRevision: directionForRunAwareOperation(root, {
885
+ itemId: item.id,
886
+ runId: options?.run,
887
+ executorId: item.claimExecutorId
888
+ }).revision,
889
+ reason: options?.reason?.trim() || `Transi\xE7\xE3o solicitada pela CLI: ${fromStage} \u2192 ${toStage}.`
890
+ });
891
+ if (operation.outcome === "approval-required") {
892
+ console.log(chalk7.yellow(`Passagem de ${itemId} aguarda aprova\xE7\xE3o humana [${operation.reasonCode}]: ${operation.reason}`));
893
+ return true;
894
+ }
895
+ if (operation.outcome !== "accepted") {
896
+ console.log(chalk7.red(`Cannot move ${itemId} [${operation.reasonCode}]: ${operation.reason}${operation.recoveryActions?.length ? `
897
+ Recupera\xE7\xE3o: ${operation.recoveryActions.join("; ")}` : ""}`));
898
+ if (operation.nextCommand)
899
+ console.log(`${operation.humanRequired ? "Pr\xF3ximo passo \xE9 humano; para diagn\xF3stico" : "Pr\xF3ximo comando"}: ${operation.nextCommand}`);
900
+ return false;
1366
901
  }
902
+ console.log(` ${chalk7.green("\u2713")} Item ${chalk7.cyan(itemId)} moved: ${chalk7.yellow(fromStage)} \u2192 ${chalk7.green(toStage)}`);
903
+ return true;
1367
904
  }
1368
905
  function normalizeItemId(input) {
1369
906
  if (/^ITEM-\d+$/i.test(input)) return input.toUpperCase();
1370
907
  if (/^\d+$/.test(input)) return `ITEM-${input}`;
1371
908
  console.log(chalk7.red(`Invalid item ID: "${input}". Use a number (e.g. 34) or ITEM-N format.`));
1372
- process.exit(1);
909
+ return input;
1373
910
  }
1374
911
  function flowMoveAction(targetPath, itemId, options) {
1375
912
  const root = resolve7(process.cwd(), targetPath || ".");
1376
- const normalized = normalizeItemId(itemId);
1377
- if (options.auto) {
1378
- flowMove(root, normalized, options.to || "", { auto: true, force: options.force });
1379
- } else {
1380
- flowMove(root, normalized, options.to || "", { force: options.force });
1381
- }
913
+ return flowMove(root, normalizeItemId(itemId), options.to || "", options).then(
914
+ (moved) => {
915
+ if (!moved) process.exitCode = 1;
916
+ },
917
+ (error) => {
918
+ console.log(chalk7.red(`Cannot move ${itemId}: ${error instanceof Error ? error.message : String(error)}`));
919
+ process.exitCode = 1;
920
+ }
921
+ );
1382
922
  }
1383
923
 
1384
924
  // src/commands/flow-claim.ts
@@ -1388,10 +928,10 @@ import chalk8 from "chalk";
1388
928
  function askYesNo(query) {
1389
929
  if (!process.stdin.isTTY) return Promise.resolve(true);
1390
930
  const rl = createInterface({ input: process.stdin, output: process.stdout });
1391
- return new Promise((resolve31) => {
931
+ return new Promise((resolve35) => {
1392
932
  rl.question(`${chalk8.yellow(query)} (y/N) `, (answer) => {
1393
933
  rl.close();
1394
- resolve31(answer.trim().toLowerCase() === "y");
934
+ resolve35(answer.trim().toLowerCase() === "y");
1395
935
  });
1396
936
  });
1397
937
  }
@@ -1519,21 +1059,19 @@ async function handoffItem(root, itemId, options) {
1519
1059
  process.exit(1);
1520
1060
  }
1521
1061
  const previousFrom = item.handoff.from;
1522
- item.claimedBy = previousFrom;
1523
- item.claimedAt = (/* @__PURE__ */ new Date()).toISOString();
1524
- item.handoff = void 0;
1525
- workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1526
- writeWorkflow(root, {
1527
- workflow,
1528
- source: "flow-handoff-rollback",
1529
- primaryItemId: item.id,
1530
- skipSitrep: true
1531
- });
1532
- logEntry(root, "handoff_rollback", `Handoff rolled back to ${previousFrom}`, {
1533
- itemId: item.id,
1534
- to: previousFrom,
1535
- reason: options.summary
1062
+ const actor = resolveLocalIdentity(root).id;
1063
+ const operation2 = await rollbackHandoffOperation(root, {
1064
+ itemId,
1065
+ actor,
1066
+ // The item's direction, as the operation compares it; the item-less
1067
+ // workspace direction has a different revision.
1068
+ expectedRevision: directionForOperation(root, { itemId }).revision,
1069
+ reason: options.summary ?? "Rollback solicitado pela CLI."
1536
1070
  });
1071
+ if (operation2.outcome !== "accepted") {
1072
+ console.log(chalk9.red(`Cannot rollback: ${operation2.reason}`));
1073
+ process.exit(1);
1074
+ }
1537
1075
  console.log(` ${chalk9.green("\u2713")} ${itemId} handoff rolled back to ${previousFrom}`);
1538
1076
  return;
1539
1077
  }
@@ -1545,15 +1083,6 @@ async function handoffItem(root, itemId, options) {
1545
1083
  console.log(chalk9.red("Summary is required (--summary)"));
1546
1084
  process.exit(1);
1547
1085
  }
1548
- const currentStage = workflow.stages.find((s) => s.id === item.stage);
1549
- if (currentStage?.gate) {
1550
- const gateChecker = new GateChecker(root);
1551
- const gateResult = gateChecker.checkHandoffAllowed(currentStage.gate, item);
1552
- if (!gateResult.allowed) {
1553
- console.log(chalk9.red(`Cannot handoff: ${gateResult.reason}`));
1554
- process.exit(1);
1555
- }
1556
- }
1557
1086
  let ttlMinutes = DEFAULT_HANDOFF_TTL_MINUTES;
1558
1087
  try {
1559
1088
  const manifest = loadHarness(resolveHarnessRoot(root, DEFAULT_HARNESS_VERSION));
@@ -1565,34 +1094,32 @@ async function handoffItem(root, itemId, options) {
1565
1094
  }
1566
1095
  } catch {
1567
1096
  }
1568
- const now6 = /* @__PURE__ */ new Date();
1569
- const expiresAt = new Date(now6.getTime() + ttlMinutes * 60 * 1e3);
1570
- item.handoff = {
1571
- from: item.claimedBy || "unknown",
1097
+ const now4 = /* @__PURE__ */ new Date();
1098
+ const expiresAt = new Date(now4.getTime() + ttlMinutes * 60 * 1e3);
1099
+ const from = item.claimedBy;
1100
+ if (!from) {
1101
+ console.log(chalk9.red("Cannot handoff: item has no active claim"));
1102
+ process.exit(1);
1103
+ }
1104
+ const executorId = options.executor ?? item.claimExecutorId ?? "cli";
1105
+ const operation = await requestHandoffOperation(root, {
1106
+ itemId,
1572
1107
  to: options.to,
1108
+ actor: from,
1109
+ executorId,
1573
1110
  summary: options.summary,
1574
1111
  evidence: options.evidence || [],
1575
- timestamp: now6.toISOString(),
1576
- expiresAt: expiresAt.toISOString(),
1577
- executorId: options.executor
1578
- };
1579
- workflow.updatedAt = now6.toISOString();
1580
- writeWorkflow(root, {
1581
- workflow,
1582
- source: "flow-handoff",
1583
- primaryItemId: item.id,
1584
- skipSitrep: true
1585
- });
1586
- logEntry(root, "handoff", `Handoff from ${item.handoff.from} to ${options.to}`, {
1587
- itemId: item.id,
1588
- from: item.handoff.from,
1589
- to: options.to,
1590
- summary: options.summary,
1591
- evidence: options.evidence,
1592
- executorId: options.executor,
1593
- expiresAt: expiresAt.toISOString()
1112
+ ttlMinutes,
1113
+ // Handoff is a canonical passage: it compares the run-aware direction
1114
+ // of this item, not the item-less workspace direction.
1115
+ expectedRevision: directionForRunAwareOperation(root, { itemId, executorId }).revision,
1116
+ reason: options.summary
1594
1117
  });
1595
- console.log(` ${chalk9.green("\u2713")} ${itemId} handoff: ${item.handoff.from} \u2192 ${options.to}`);
1118
+ if (operation.outcome !== "accepted") {
1119
+ console.log(chalk9.red(`Cannot handoff: ${operation.reason}`));
1120
+ process.exit(1);
1121
+ }
1122
+ console.log(` ${chalk9.green("\u2713")} ${itemId} handoff: ${from} \u2192 ${options.to}`);
1596
1123
  console.log(` ${chalk9.dim(`Expires at: ${expiresAt.toISOString()}`)}`);
1597
1124
  }
1598
1125
  async function handoffAction(targetPath, itemId, options) {
@@ -1601,8 +1128,8 @@ async function handoffAction(targetPath, itemId, options) {
1601
1128
  }
1602
1129
 
1603
1130
  // src/commands/flow-ac.ts
1604
- import { existsSync as existsSync8, readFileSync as readFileSync7, writeFileSync as writeFileSync5 } from "fs";
1605
- import { join as join8, resolve as resolve10 } from "path";
1131
+ import { existsSync as existsSync5, readFileSync as readFileSync5, writeFileSync as writeFileSync4 } from "fs";
1132
+ import { join as join5, resolve as resolve10 } from "path";
1606
1133
  import chalk10 from "chalk";
1607
1134
  function findACLine(lines, n) {
1608
1135
  let count = 0;
@@ -1630,13 +1157,13 @@ function markAC(root, itemId, acNum) {
1630
1157
  console.log(chalk10.red(`Item ${itemId} has no linked spec`));
1631
1158
  process.exit(1);
1632
1159
  }
1633
- const specDir = join8(getLetraDir(root), "specs", item.spec);
1634
- const specFile = join8(specDir, "spec.md");
1635
- if (!existsSync8(specFile)) {
1160
+ const specDir = join5(getLetraDir(root), "specs", item.spec);
1161
+ const specFile = join5(specDir, "spec.md");
1162
+ if (!existsSync5(specFile)) {
1636
1163
  console.log(chalk10.red(`Spec file not found: ${specFile}`));
1637
1164
  process.exit(1);
1638
1165
  }
1639
- const content = readFileSync7(specFile, "utf-8");
1166
+ const content = readFileSync5(specFile, "utf-8");
1640
1167
  const lines = content.split("\n");
1641
1168
  const lineIdx = findACLine(lines, acNum);
1642
1169
  if (lineIdx === null) {
@@ -1649,7 +1176,7 @@ function markAC(root, itemId, acNum) {
1649
1176
  }
1650
1177
  const orig = lines[lineIdx];
1651
1178
  lines[lineIdx] = orig.replace(/^- \[ \]/, "- [x]");
1652
- writeFileSync5(specFile, lines.join("\n"), "utf-8");
1179
+ writeFileSync4(specFile, lines.join("\n"), "utf-8");
1653
1180
  if (workflow.specLinks?.[item.spec]) {
1654
1181
  writeWorkflow(root, {
1655
1182
  workflow,
@@ -1679,7 +1206,7 @@ function flowAcAction(targetPath, itemId, acNumber) {
1679
1206
  }
1680
1207
 
1681
1208
  // src/commands/flow-visualize.ts
1682
- import { writeFileSync as writeFileSync6 } from "fs";
1209
+ import { writeFileSync as writeFileSync5 } from "fs";
1683
1210
  import { resolve as resolve11 } from "path";
1684
1211
  import chalk11 from "chalk";
1685
1212
  var MERMAID_LIVE = "https://mermaid.live/edit#";
@@ -1705,71 +1232,275 @@ function generateMermaid(workflow) {
1705
1232
  for (let i = 1; i < sorted.length - 1; i++) {
1706
1233
  lines.push(` ${sorted[i].id} --> ${sorted[i + 1].id}["${labelFor(sorted[i + 1])}"]`);
1707
1234
  }
1708
- return lines.join("\n");
1235
+ return lines.join("\n");
1236
+ }
1237
+ function buildHtml(mermaid) {
1238
+ return `<!DOCTYPE html>
1239
+ <html lang="en">
1240
+ <head>
1241
+ <meta charset="UTF-8">
1242
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1243
+ <title>Workflow Diagram</title>
1244
+ <script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script>
1245
+ <style>
1246
+ body { font-family: system-ui, sans-serif; max-width: 960px; margin: 2rem auto; padding: 0 1rem; }
1247
+ .mermaid { text-align: center; }
1248
+ </style>
1249
+ </head>
1250
+ <body>
1251
+ <pre class="mermaid">
1252
+ ${mermaid}
1253
+ </pre>
1254
+ <script>mermaid.initialize({ startOnLoad: true });</script>
1255
+ </body>
1256
+ </html>`;
1257
+ }
1258
+ function flowVisualize(root, options) {
1259
+ const workflow = loadWorkflow(root);
1260
+ if (!workflow) {
1261
+ console.log(chalk11.yellow("No workflow found. Run 'letra flow init --quick' first"));
1262
+ return;
1263
+ }
1264
+ const mermaid = generateMermaid(workflow);
1265
+ if (options?.output) {
1266
+ const outputPath = resolve11(root, options.output);
1267
+ const ext = options.output.toLowerCase().split(".").pop();
1268
+ let content;
1269
+ let label;
1270
+ if (ext === "html") {
1271
+ content = buildHtml(mermaid);
1272
+ label = "HTML page";
1273
+ } else if (ext === "md") {
1274
+ content = `\`\`\`mermaid
1275
+ ${mermaid}
1276
+ \`\`\`
1277
+ `;
1278
+ label = "Markdown file";
1279
+ } else {
1280
+ content = `${mermaid}
1281
+ `;
1282
+ label = "Diagram file";
1283
+ }
1284
+ writeFileSync5(outputPath, content);
1285
+ console.log(`${label} saved to ${options.output}`);
1286
+ } else {
1287
+ console.log(mermaid);
1288
+ console.log(chalk11.dim(`
1289
+ Copy to ${MERMAID_LIVE} to render`));
1290
+ }
1291
+ }
1292
+ function flowVisualizeAction(targetPath, options) {
1293
+ const root = resolve11(process.cwd(), targetPath || ".");
1294
+ flowVisualize(root, options);
1295
+ }
1296
+
1297
+ // src/commands/flow-phases.ts
1298
+ import { resolve as resolve12 } from "path";
1299
+ import chalk12 from "chalk";
1300
+
1301
+ // src/phases/runner.ts
1302
+ import { execSync } from "child_process";
1303
+ import { existsSync as existsSync6, mkdirSync as mkdirSync2, readFileSync as readFileSync6, writeFileSync as writeFileSync6 } from "fs";
1304
+ import { join as join6 } from "path";
1305
+ var PhaseActionRunner = class {
1306
+ execPhase(root, item, phaseDef) {
1307
+ if (!phaseDef.actions || phaseDef.actions.length === 0) {
1308
+ return { ok: true, actions: [] };
1309
+ }
1310
+ const checker = new GateChecker(root);
1311
+ const results = [];
1312
+ for (const action of phaseDef.actions) {
1313
+ try {
1314
+ switch (action.type) {
1315
+ case "command": {
1316
+ const output = execSync(action.cmd, {
1317
+ cwd: root,
1318
+ timeout: 3e4,
1319
+ stdio: "pipe"
1320
+ });
1321
+ const label = `command: ${action.cmd}`;
1322
+ results.push(label);
1323
+ logEntry(root, "system", `action:${label}`, {
1324
+ itemId: item.id,
1325
+ details: { phase: phaseDef.id }
1326
+ });
1327
+ break;
1328
+ }
1329
+ case "agent-prompt": {
1330
+ const promptDir = getLetraDir(root);
1331
+ if (!existsSync6(promptDir)) mkdirSync2(promptDir, { recursive: true });
1332
+ const content = [
1333
+ `# Phase Prompt: ${phaseDef.label}`,
1334
+ "",
1335
+ action.prompt,
1336
+ "",
1337
+ "---",
1338
+ `Item: ${item.id}`,
1339
+ `Phase: ${phaseDef.id}`
1340
+ ].join("\n");
1341
+ writeFileSync6(join6(getLetraDir(root), "phase-prompt.md"), content, "utf-8");
1342
+ const label = `agent-prompt: ${action.prompt}`;
1343
+ results.push(label);
1344
+ logEntry(root, "system", `action:${label}`, {
1345
+ itemId: item.id,
1346
+ details: { phase: phaseDef.id }
1347
+ });
1348
+ break;
1349
+ }
1350
+ case "generate-report": {
1351
+ const reportDir = join6(getLetraDir(root), "reports");
1352
+ if (!existsSync6(reportDir)) mkdirSync2(reportDir, { recursive: true });
1353
+ const reportContent = [
1354
+ `# Report: ${item.id} - ${phaseDef.label}`,
1355
+ `Generated: ${(/* @__PURE__ */ new Date()).toISOString()}`,
1356
+ `Template: ${action.template}`
1357
+ ].join("\n");
1358
+ const reportPath = join6(reportDir, `${item.id}-${phaseDef.id}.md`);
1359
+ writeFileSync6(reportPath, reportContent, "utf-8");
1360
+ const label = `generate-report: ${action.template}`;
1361
+ results.push(label);
1362
+ logEntry(root, "system", `action:${label}`, {
1363
+ itemId: item.id,
1364
+ details: { phase: phaseDef.id }
1365
+ });
1366
+ break;
1367
+ }
1368
+ case "notify-human": {
1369
+ logEntry(root, "system", `action:notify-human: ${action.message}`, {
1370
+ itemId: item.id,
1371
+ details: { phase: phaseDef.id }
1372
+ });
1373
+ const notifyPath = join6(getLetraDir(root), "human-notify.md");
1374
+ writeFileSync6(
1375
+ notifyPath,
1376
+ `# Human Notification
1377
+
1378
+ ${action.message}
1379
+
1380
+ Item: ${item.id}
1381
+ Phase: ${phaseDef.id}`,
1382
+ "utf-8"
1383
+ );
1384
+ const label = `notify-human: ${action.message}`;
1385
+ results.push(label);
1386
+ break;
1387
+ }
1388
+ case "wait-human": {
1389
+ const gateId = action.gate ?? "";
1390
+ const gateResult = checker.check(gateId, item);
1391
+ if (!gateResult.allowed) {
1392
+ logEntry(
1393
+ root,
1394
+ "system",
1395
+ `action:wait-human gate "${gateId}" blocking`,
1396
+ {
1397
+ itemId: item.id,
1398
+ details: { gate: gateId, phase: phaseDef.id }
1399
+ }
1400
+ );
1401
+ return {
1402
+ ok: false,
1403
+ error: gateResult.reason?.includes("humana") ? `Gate "${gateId}" not approved` : gateResult.reason ?? `Gate "${gateId}" not approved`,
1404
+ actions: results
1405
+ };
1406
+ }
1407
+ const label = `wait-human: ${gateId} (approved)`;
1408
+ results.push(label);
1409
+ break;
1410
+ }
1411
+ }
1412
+ } catch (e) {
1413
+ const msg = `Action "${action.type}" failed: ${e.message}`;
1414
+ logEntry(root, "system", `action:error ${msg}`, {
1415
+ itemId: item.id,
1416
+ details: { phase: phaseDef.id }
1417
+ });
1418
+ return { ok: false, error: msg, actions: results };
1419
+ }
1420
+ }
1421
+ return { ok: true, actions: results };
1422
+ }
1423
+ };
1424
+
1425
+ // src/phases/engine.ts
1426
+ function getStagePhases(workflow, stageId) {
1427
+ const stage = workflow.stages.find((s) => s.id === stageId);
1428
+ if (!stage) return null;
1429
+ return stage.phases ?? null;
1709
1430
  }
1710
- function buildHtml(mermaid) {
1711
- return `<!DOCTYPE html>
1712
- <html lang="en">
1713
- <head>
1714
- <meta charset="UTF-8">
1715
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
1716
- <title>Workflow Diagram</title>
1717
- <script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script>
1718
- <style>
1719
- body { font-family: system-ui, sans-serif; max-width: 960px; margin: 2rem auto; padding: 0 1rem; }
1720
- .mermaid { text-align: center; }
1721
- </style>
1722
- </head>
1723
- <body>
1724
- <pre class="mermaid">
1725
- ${mermaid}
1726
- </pre>
1727
- <script>mermaid.initialize({ startOnLoad: true });</script>
1728
- </body>
1729
- </html>`;
1431
+ function getPhaseDef(phases, phaseId) {
1432
+ return phases.states[phaseId] ?? null;
1730
1433
  }
1731
- function flowVisualize(root, options) {
1732
- const workflow = loadWorkflow(root);
1733
- if (!workflow) {
1734
- console.log(chalk11.yellow("No workflow found. Run 'letra flow init --quick' first"));
1735
- return;
1434
+ var _runner = new PhaseActionRunner();
1435
+ function transitionPhase(root, workflow, item, targetPhaseId) {
1436
+ const phases = getStagePhases(workflow, item.stage);
1437
+ if (!phases) {
1438
+ return { ok: false, error: `Stage "${item.stage}" has no phases defined` };
1736
1439
  }
1737
- const mermaid = generateMermaid(workflow);
1738
- if (options?.output) {
1739
- const outputPath = resolve11(root, options.output);
1740
- const ext = options.output.toLowerCase().split(".").pop();
1741
- let content;
1742
- let label;
1743
- if (ext === "html") {
1744
- content = buildHtml(mermaid);
1745
- label = "HTML page";
1746
- } else if (ext === "md") {
1747
- content = `\`\`\`mermaid
1748
- ${mermaid}
1749
- \`\`\`
1750
- `;
1751
- label = "Markdown file";
1752
- } else {
1753
- content = `${mermaid}
1754
- `;
1755
- label = "Diagram file";
1440
+ const currentDef = item.currentPhase ? getPhaseDef(phases, item.currentPhase) : null;
1441
+ const transition = currentDef?.transitions?.find((t) => t.target === targetPhaseId);
1442
+ if (targetPhaseId === "__EXIT__") {
1443
+ if (!transition) {
1444
+ const allowed = (currentDef?.transitions ?? []).map((t) => t.target).join(", ");
1445
+ return {
1446
+ ok: false,
1447
+ error: `Transition from "${item.currentPhase}" to "__EXIT__" not allowed. Allowed: ${allowed || "none"}`
1448
+ };
1449
+ }
1450
+ item.currentPhase = void 0;
1451
+ return { ok: true, phase: void 0, triggeredActions: [], triggeredAutoTransition: false };
1452
+ }
1453
+ if (!phases.states[targetPhaseId]) {
1454
+ return { ok: false, error: `Phase "${targetPhaseId}" not found in stage "${item.stage}"` };
1455
+ }
1456
+ if (currentDef && !transition) {
1457
+ const allowed = (currentDef.transitions ?? []).map((t) => t.target).join(", ");
1458
+ return {
1459
+ ok: false,
1460
+ error: `Transition from "${item.currentPhase}" to "${targetPhaseId}" not allowed. Allowed: ${allowed || "none"}`
1461
+ };
1462
+ }
1463
+ item.currentPhase = targetPhaseId;
1464
+ const targetDef = getPhaseDef(phases, targetPhaseId);
1465
+ let actions = [];
1466
+ if (root && targetDef) {
1467
+ const result = _runner.execPhase(root, item, targetDef);
1468
+ actions = result.actions;
1469
+ if (!result.ok) {
1470
+ return {
1471
+ ok: false,
1472
+ error: result.error,
1473
+ phase: item.currentPhase,
1474
+ triggeredActions: actions
1475
+ };
1756
1476
  }
1757
- writeFileSync6(outputPath, content);
1758
- console.log(`${label} saved to ${options.output}`);
1759
1477
  } else {
1760
- console.log(mermaid);
1761
- console.log(chalk11.dim(`
1762
- Copy to ${MERMAID_LIVE} to render`));
1478
+ actions = (targetDef?.actions ?? []).map((a) => {
1479
+ if (a.type === "agent-prompt") return `agent-prompt: ${a.prompt}`;
1480
+ if (a.type === "command") return `command: ${a.cmd}`;
1481
+ if (a.type === "generate-report") return `generate-report: ${a.template}`;
1482
+ if (a.type === "notify-human") return `notify-human: ${a.message}`;
1483
+ if (a.type === "wait-human") return `wait-human: ${a.gate}`;
1484
+ return "unknown action";
1485
+ });
1763
1486
  }
1764
- }
1765
- function flowVisualizeAction(targetPath, options) {
1766
- const root = resolve11(process.cwd(), targetPath || ".");
1767
- flowVisualize(root, options);
1487
+ let triggeredAutoTransition = false;
1488
+ if (transition?.auto) {
1489
+ const nextAuto = targetDef?.transitions?.find((t) => t.auto);
1490
+ if (nextAuto && phases.states[nextAuto.target]) {
1491
+ item.currentPhase = nextAuto.target;
1492
+ triggeredAutoTransition = true;
1493
+ }
1494
+ }
1495
+ return {
1496
+ ok: true,
1497
+ phase: item.currentPhase,
1498
+ triggeredActions: actions,
1499
+ triggeredAutoTransition
1500
+ };
1768
1501
  }
1769
1502
 
1770
1503
  // src/commands/flow-phases.ts
1771
- import { resolve as resolve12 } from "path";
1772
- import chalk12 from "chalk";
1773
1504
  function flowPhasesAction(itemId) {
1774
1505
  const root = resolve12(process.cwd());
1775
1506
  const workflow = loadWorkflow(root);
@@ -1805,39 +1536,157 @@ function flowPhasesAction(itemId) {
1805
1536
  console.log(` ${chalk12.dim(`\u2192 ${targets}`)}`);
1806
1537
  }
1807
1538
  }
1808
- console.log("");
1809
- }
1810
- function flowPhaseTransitionAction(itemId, targetPhase) {
1811
- const root = resolve12(process.cwd());
1812
- const workflow = loadWorkflow(root);
1813
- if (!workflow) {
1814
- console.log(chalk12.red("No workflow found"));
1815
- return;
1816
- }
1817
- const item = workflow.items.find((i) => i.id === itemId);
1818
- if (!item) {
1819
- console.log(chalk12.red(`Item "${itemId}" not found`));
1820
- return;
1821
- }
1822
- const result = transitionPhase(root, workflow, item, targetPhase);
1823
- if (!result.ok) {
1824
- console.log(chalk12.red(result.error));
1825
- return;
1826
- }
1827
- saveWorkflow(root, workflow);
1828
- logEntry(root, "system", `phase_transition: ${item.id} \u2192 ${targetPhase}`);
1829
- console.log(` ${chalk12.green("\u2713")} Phase transition: ${chalk12.cyan(item.currentPhase || "")}`);
1830
- if (result.triggeredActions && result.triggeredActions.length > 0) {
1831
- console.log(` ${chalk12.gray("Actions:")} ${result.triggeredActions.join(", ")}`);
1832
- }
1833
- if (result.triggeredAutoTransition) {
1834
- console.log(` ${chalk12.yellow("\u21BB Auto-transition triggered")}`);
1835
- }
1539
+ console.log("");
1540
+ }
1541
+ function flowPhaseTransitionAction(itemId, targetPhase) {
1542
+ const root = resolve12(process.cwd());
1543
+ const workflow = loadWorkflow(root);
1544
+ if (!workflow) {
1545
+ console.log(chalk12.red("No workflow found"));
1546
+ return;
1547
+ }
1548
+ const item = workflow.items.find((i) => i.id === itemId);
1549
+ if (!item) {
1550
+ console.log(chalk12.red(`Item "${itemId}" not found`));
1551
+ return;
1552
+ }
1553
+ const result = transitionPhase(root, workflow, item, targetPhase);
1554
+ if (!result.ok) {
1555
+ console.log(chalk12.red(result.error));
1556
+ return;
1557
+ }
1558
+ saveWorkflow(root, workflow);
1559
+ logEntry(root, "system", `phase_transition: ${item.id} \u2192 ${targetPhase}`);
1560
+ console.log(` ${chalk12.green("\u2713")} Phase transition: ${chalk12.cyan(item.currentPhase || "")}`);
1561
+ if (result.triggeredActions && result.triggeredActions.length > 0) {
1562
+ console.log(` ${chalk12.gray("Actions:")} ${result.triggeredActions.join(", ")}`);
1563
+ }
1564
+ if (result.triggeredAutoTransition) {
1565
+ console.log(` ${chalk12.yellow("\u21BB Auto-transition triggered")}`);
1566
+ }
1567
+ }
1568
+
1569
+ // src/commands/flow-autopilot.ts
1570
+ import { resolve as resolve13 } from "path";
1571
+ import chalk13 from "chalk";
1572
+
1573
+ // src/phases/autopilot.ts
1574
+ var MAX_AUTO_TRANSITIONS = 10;
1575
+ var runner = new PhaseActionRunner();
1576
+ function getAutoTarget(workflow, item) {
1577
+ const phases = getStagePhases(workflow, item.stage);
1578
+ if (!phases || !item.currentPhase) return null;
1579
+ const def = getPhaseDef(phases, item.currentPhase);
1580
+ if (!def) return null;
1581
+ const autoTrans = (def.transitions ?? []).find((t) => t.auto);
1582
+ return autoTrans?.target ?? null;
1583
+ }
1584
+ var PhaseAutoPilot = class {
1585
+ transitionsApplied = 0;
1586
+ async run(root, workflow, item) {
1587
+ this.transitionsApplied = 0;
1588
+ if (!item.currentPhase) {
1589
+ logEntry(root, "system", `autopilot:${item.id} no current phase \u2014 nothing to do`, {
1590
+ itemId: item.id
1591
+ });
1592
+ return { ok: true, finalPhase: void 0, transitionsApplied: 0 };
1593
+ }
1594
+ logEntry(
1595
+ root,
1596
+ "system",
1597
+ `autopilot:starting for ${item.id} from phase "${item.currentPhase}"`,
1598
+ { itemId: item.id }
1599
+ );
1600
+ while (this.transitionsApplied < MAX_AUTO_TRANSITIONS) {
1601
+ const autoTarget = getAutoTarget(workflow, item);
1602
+ if (!autoTarget) {
1603
+ logEntry(
1604
+ root,
1605
+ "system",
1606
+ `autopilot:${item.id} stopped at phase "${item.currentPhase}" \u2014 no auto-transition`,
1607
+ {
1608
+ itemId: item.id
1609
+ }
1610
+ );
1611
+ return {
1612
+ ok: true,
1613
+ finalPhase: item.currentPhase,
1614
+ transitionsApplied: this.transitionsApplied
1615
+ };
1616
+ }
1617
+ const phases = getStagePhases(workflow, item.stage);
1618
+ const phaseDef = item.currentPhase && phases ? getPhaseDef(phases, item.currentPhase) : null;
1619
+ if (phaseDef) {
1620
+ const actionResult = runner.execPhase(root, item, phaseDef);
1621
+ if (!actionResult.ok) {
1622
+ logEntry(
1623
+ root,
1624
+ "system",
1625
+ `autopilot:${item.id} stopped \u2014 action failed: ${actionResult.error}`,
1626
+ {
1627
+ itemId: item.id
1628
+ }
1629
+ );
1630
+ return {
1631
+ ok: false,
1632
+ error: actionResult.error,
1633
+ finalPhase: item.currentPhase,
1634
+ transitionsApplied: this.transitionsApplied
1635
+ };
1636
+ }
1637
+ }
1638
+ const prevPhase = item.currentPhase;
1639
+ const result = transitionPhase(root, workflow, item, autoTarget);
1640
+ if (!result.ok) {
1641
+ logEntry(
1642
+ root,
1643
+ "system",
1644
+ `autopilot:${item.id} transition failed \u2014 ${result.error}`,
1645
+ { itemId: item.id }
1646
+ );
1647
+ return {
1648
+ ok: false,
1649
+ error: result.error,
1650
+ finalPhase: prevPhase,
1651
+ transitionsApplied: this.transitionsApplied
1652
+ };
1653
+ }
1654
+ this.transitionsApplied++;
1655
+ logEntry(
1656
+ root,
1657
+ "system",
1658
+ `autopilot:${item.id} ${prevPhase} \u2192 ${item.currentPhase || "__EXIT__"}`,
1659
+ {
1660
+ itemId: item.id
1661
+ }
1662
+ );
1663
+ if (!item.currentPhase) {
1664
+ logEntry(root, "system", `autopilot:${item.id} exited phase system`, {
1665
+ itemId: item.id
1666
+ });
1667
+ return {
1668
+ ok: true,
1669
+ finalPhase: void 0,
1670
+ transitionsApplied: this.transitionsApplied
1671
+ };
1672
+ }
1673
+ }
1674
+ const msg = "Auto-loop limit exceeded";
1675
+ logEntry(root, "system", `autopilot:${item.id} ${msg}`, { itemId: item.id });
1676
+ return {
1677
+ ok: false,
1678
+ error: msg,
1679
+ finalPhase: item.currentPhase,
1680
+ transitionsApplied: this.transitionsApplied
1681
+ };
1682
+ }
1683
+ };
1684
+ async function autopilotRun(root, workflow, item) {
1685
+ const pilot = new PhaseAutoPilot();
1686
+ return pilot.run(root, workflow, item);
1836
1687
  }
1837
1688
 
1838
1689
  // src/commands/flow-autopilot.ts
1839
- import { resolve as resolve13 } from "path";
1840
- import chalk13 from "chalk";
1841
1690
  async function flowAutopilotAction(itemId) {
1842
1691
  const root = resolve13(process.cwd());
1843
1692
  const workflow = loadWorkflow(root);
@@ -1992,6 +1841,202 @@ async function flowBindAction(targetPath, options) {
1992
1841
  await flowBind(root, options);
1993
1842
  }
1994
1843
 
1844
+ // src/commands/flow-workflow.ts
1845
+ import chalk16 from "chalk";
1846
+ import { join as join7 } from "path";
1847
+ import { readFileSync as readFileSync7, writeFileSync as writeFileSync7 } from "fs";
1848
+ function section(title) {
1849
+ console.log(`
1850
+ ${chalk16.bold(title)}`);
1851
+ console.log("\u2500".repeat(40));
1852
+ }
1853
+ function workflowListCommands(root) {
1854
+ const definitions = listWorkflowDefinitions(root);
1855
+ if (definitions.length === 0) {
1856
+ console.log(chalk16.yellow("Nenhuma defini\xE7\xE3o de workflow encontrada."));
1857
+ return;
1858
+ }
1859
+ section("Workflow Definitions");
1860
+ for (const def of definitions) {
1861
+ const active = def.activeVersionId ? chalk16.green("\u25CF ativo") : chalk16.gray("\u25CB sem publica\xE7\xE3o");
1862
+ console.log(` ${chalk16.cyan(def.id)} ${chalk16.bold(def.name)} (${def.nextVersionNumber} vers\xF5es) ${active}`);
1863
+ }
1864
+ }
1865
+ function workflowShowCommand(root, workflowId) {
1866
+ const definitions = listWorkflowDefinitions(root);
1867
+ const def = definitions.find((d) => d.id === workflowId);
1868
+ if (!def) {
1869
+ console.log(chalk16.red(`Defini\xE7\xE3o "${workflowId}" n\xE3o encontrada.`));
1870
+ return;
1871
+ }
1872
+ const versions = listWorkflowVersions(root, workflowId);
1873
+ const active = getActiveWorkflowVersion(root, workflowId);
1874
+ section(`Workflow: ${def.name}`);
1875
+ console.log(` ID: ${def.id}`);
1876
+ console.log(` Next version: ${def.nextVersionNumber}`);
1877
+ console.log(` Total versions: ${versions.length}`);
1878
+ console.log(` Active version: ${active ? active.number : "none"}`);
1879
+ console.log(` Created: ${def.createdAt}`);
1880
+ console.log(` Updated: ${def.updatedAt}`);
1881
+ }
1882
+ function workflowDraftCommand(root, workflowId, actor, basedOnVersionNumber) {
1883
+ try {
1884
+ const draft = createWorkflowDraft(root, workflowId, actor, basedOnVersionNumber);
1885
+ section("Draft created");
1886
+ console.log(` Workflow: ${workflowId}`);
1887
+ console.log(` Revision: ${draft.revision}`);
1888
+ console.log(` Number: ${draft.number ?? "(draft)"}`);
1889
+ } catch (error) {
1890
+ console.log(chalk16.red(`Erro: ${error.message}`));
1891
+ }
1892
+ }
1893
+ function workflowValidateCommand(root, workflowId) {
1894
+ const draft = getWorkflowDraft(root, workflowId);
1895
+ const result = validateWorkflowContent(draft.content);
1896
+ if (result.valid) {
1897
+ console.log(chalk16.green("\u2713 Workflow v\xE1lido"));
1898
+ } else {
1899
+ section("Validation errors");
1900
+ for (const err of result.errors) {
1901
+ console.log(` ${chalk16.red("\u2717")} ${err.message} ${chalk16.gray(`(${err.code})`)}`);
1902
+ }
1903
+ }
1904
+ }
1905
+ function workflowPublishCommand(root, workflowId, actor, expectedRevision, reason) {
1906
+ try {
1907
+ const published = publishWorkflowDraft(root, workflowId, { expectedRevision, actor, reason });
1908
+ section("Workflow published");
1909
+ console.log(` Version: ${published.number}`);
1910
+ console.log(` ID: ${published.id}`);
1911
+ console.log(` Actor: ${published.publishedBy}`);
1912
+ console.log(` Hash: ${published.contentHash}`);
1913
+ } catch (error) {
1914
+ console.log(chalk16.red(`Erro: ${error.message}`));
1915
+ }
1916
+ }
1917
+ function workflowRollbackCommand(root, workflowId, actor, versionNumber, reason) {
1918
+ try {
1919
+ const proof = signLocalOperation(root, actor, "workflow.rollback", { workflowId, versionNumber, reason });
1920
+ const restored = rollbackWorkflowVersion(root, workflowId, { versionNumber, actor, reason, proof });
1921
+ section("Workflow rolled back");
1922
+ console.log(` New version: ${restored.number}`);
1923
+ console.log(` Restored from: ${restored.restoredFromVersionId}`);
1924
+ console.log(` Actor: ${actor}`);
1925
+ } catch (error) {
1926
+ console.log(chalk16.red(`Erro: ${error.message}`));
1927
+ }
1928
+ }
1929
+ function workflowVersionsCommand(root, workflowId) {
1930
+ const versions = listWorkflowVersions(root, workflowId);
1931
+ if (versions.length === 0) {
1932
+ console.log(chalk16.yellow("Nenhuma vers\xE3o publicada."));
1933
+ return;
1934
+ }
1935
+ section(`Versions of ${workflowId}`);
1936
+ for (const v of versions) {
1937
+ const status2 = v.status === "published" ? chalk16.green("\u25CF") : chalk16.gray("\u25CB");
1938
+ console.log(
1939
+ ` ${status2} v${v.number} ${chalk16.gray(v.publishedAt ?? "")} ${v.publishedBy ?? ""} ${v.changeSummary ?? ""}`
1940
+ );
1941
+ }
1942
+ }
1943
+ function workflowDraftRevisionsCommand(root, workflowId) {
1944
+ const revisions = listWorkflowDraftRevisions(root, workflowId);
1945
+ if (revisions.length === 0) {
1946
+ console.log(chalk16.yellow("Nenhuma revis\xE3o de rascunho."));
1947
+ return;
1948
+ }
1949
+ section(`Draft revisions of ${workflowId}`);
1950
+ for (const r of revisions) {
1951
+ console.log(` r${r.revision} ${r.changeSummary ?? "(sem resumo)"}`);
1952
+ }
1953
+ }
1954
+ function workflowTemplateCommand(root, workflowId, actor, template, options) {
1955
+ try {
1956
+ const name = options.name ?? template;
1957
+ let content;
1958
+ if (options.stages) {
1959
+ content = {
1960
+ name,
1961
+ stages: options.stages.map((id, index) => ({ id, name: id, order: index })),
1962
+ ...options.tools && { tools: options.tools }
1963
+ };
1964
+ } else {
1965
+ if (!template.trim()) throw new Error("Informe o template com --template <nome>.");
1966
+ const available = Object.keys(loadHarness(resolveHarnessRoot(root))?.flows ?? {});
1967
+ if (!available.includes(template)) {
1968
+ const known = available.length > 0 ? available.join(", ") : "nenhum (harness indispon\xEDvel)";
1969
+ throw new Error(`Template "${template}" n\xE3o existe no harness. Dispon\xEDveis: ${known}.`);
1970
+ }
1971
+ content = {
1972
+ name,
1973
+ template,
1974
+ ...options.tools && { tools: options.tools }
1975
+ };
1976
+ }
1977
+ const result = createWorkflowDefinition(root, { name, actor, content });
1978
+ console.log(chalk16.green(`\u2713 Workflow criado: ${result.definition.id}`));
1979
+ console.log(` Draft: ${result.draft.revision}`);
1980
+ if (!options.stages) {
1981
+ console.log(
1982
+ ` Pr\xF3ximo passo: no board, abra Configura\xE7\xF5es \u2192 Fluxo, use "Usar est\xE1gios como ponto de partida", valide e publique.`
1983
+ );
1984
+ }
1985
+ } catch (error) {
1986
+ console.log(chalk16.red(`Erro: ${error.message}`));
1987
+ process.exitCode = 1;
1988
+ }
1989
+ }
1990
+ function workflowAdaptersCommand(root, workflowId, options) {
1991
+ try {
1992
+ const workflowPath = join7(root, ".letra", "workflow.json");
1993
+ const workflow = JSON.parse(readFileSync7(workflowPath, "utf8"));
1994
+ if (options.list || !options.tools) {
1995
+ console.log(chalk16.bold(`Adapters ativos: ${workflow.tools?.join(", ") ?? "nenhum"}`));
1996
+ return;
1997
+ }
1998
+ workflow.tools = options.tools.split(",").map((t) => t.trim());
1999
+ workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2000
+ writeFileSync7(workflowPath, JSON.stringify(workflow, null, 2));
2001
+ console.log(chalk16.green(`\u2713 Adapters atualizados: ${workflow.tools.join(", ")}`));
2002
+ } catch (error) {
2003
+ console.log(chalk16.red(`Erro: ${error.message}`));
2004
+ }
2005
+ }
2006
+ function workflowLocationsCommand(root, workflowId, options) {
2007
+ try {
2008
+ const workflowPath = join7(root, ".letra", "workflow.json");
2009
+ const workflow = JSON.parse(readFileSync7(workflowPath, "utf8"));
2010
+ if (options.list || !options.add && !options.remove) {
2011
+ const locations = workflow.locations ?? [];
2012
+ if (locations.length === 0) {
2013
+ console.log(chalk16.yellow("Nenhuma location configurada."));
2014
+ return;
2015
+ }
2016
+ console.log(chalk16.bold(`Locations (${locations.length}):`));
2017
+ for (const loc of locations) {
2018
+ console.log(` ${loc.id ?? loc.path} \u2014 ${loc.label ?? loc.path}`);
2019
+ }
2020
+ return;
2021
+ }
2022
+ if (!workflow.locations) workflow.locations = [];
2023
+ if (options.add) {
2024
+ workflow.locations.push({ id: `${workflow.locations.length + 1}`, path: options.add, label: options.add });
2025
+ workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2026
+ writeFileSync7(workflowPath, JSON.stringify(workflow, null, 2));
2027
+ console.log(chalk16.green(`\u2713 Location adicionada: ${options.add}`));
2028
+ }
2029
+ if (options.remove) {
2030
+ workflow.locations = workflow.locations.filter((l) => l.id !== options.remove && l.path !== options.remove);
2031
+ workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2032
+ writeFileSync7(workflowPath, JSON.stringify(workflow, null, 2));
2033
+ console.log(chalk16.green(`\u2713 Location removida: ${options.remove}`));
2034
+ }
2035
+ } catch (error) {
2036
+ console.log(chalk16.red(`Erro: ${error.message}`));
2037
+ }
2038
+ }
2039
+
1995
2040
  // src/commands/flow.ts
1996
2041
  function flowCommand() {
1997
2042
  const cmd = new Command2("flow");
@@ -2002,8 +2047,8 @@ function flowCommand() {
2002
2047
  flowInitAction(void 0, { quick: true, template: options.template || "flow-main" });
2003
2048
  });
2004
2049
  const backlog = cmd.command("backlog").description("Manage backlog items");
2005
- backlog.command("add <description>").option("--spec <name>", "Spec name to link").description("Add item to the first stage").action((description, options) => {
2006
- backlogActionAdd(void 0, description, options.spec);
2050
+ backlog.command("add <description>").option("--spec <name>", "Spec name to link").option("--id <item-id>", "Use a specific ITEM-N identifier instead of the next sequential ID").description("Add item to the first stage").action(async (description, options) => {
2051
+ await backlogActionAdd(void 0, description, options.spec, options.id);
2007
2052
  });
2008
2053
  backlog.command("list").description("List all items with stage and age").action(() => {
2009
2054
  backlogActionList(void 0);
@@ -2015,12 +2060,12 @@ function flowCommand() {
2015
2060
  importCmd.command("linear <team>").option("--limit <number>", "Max issues to import", "50").description("Import issues from a Linear team").action((team, options) => {
2016
2061
  backlogImportLinearAction(void 0, team, options);
2017
2062
  });
2018
- cmd.command("move <item-id>").option("--to <stage>", "Target stage id or name").option("--auto", "Automatically discover next stage by order").option("--force", "Skip pre-move validation (pending ACs, etc)").description("Move item to another stage and regenerate adapters").action((itemId, options) => {
2063
+ cmd.command("move <item-id>").option("--to <stage>", "Target stage id or name").option("--auto", "Automatically discover next stage by order").option("--force", "Deprecated; does not bypass workflow passage rules").option("--actor <actor>", "Auditable human identity required with --force").option("--reason <reason>", "Auditable reason required with --force").option("--run <run-id>", "Select the active Run for this item").description("Move item to another stage and regenerate adapters").action((itemId, options) => {
2019
2064
  if (!options.to && !options.auto) {
2020
- console.log(chalk16.red("Either --to or --auto is required"));
2065
+ console.log(chalk17.red("Either --to or --auto is required"));
2021
2066
  process.exit(1);
2022
2067
  }
2023
- flowMoveAction(void 0, itemId, options);
2068
+ return flowMoveAction(void 0, itemId, options);
2024
2069
  });
2025
2070
  cmd.command("board").description("Show board with all stages and items").action(() => {
2026
2071
  flowBoardAction(void 0);
@@ -2028,8 +2073,8 @@ function flowCommand() {
2028
2073
  cmd.command("export").option("--minified", "Output JSON without indentation").description("Export workflow to stdout").action((options) => {
2029
2074
  flowExportAction(void 0, options);
2030
2075
  });
2031
- cmd.command("import <file>").description("Import workflow from a JSON file").action((file) => {
2032
- flowImportAction(void 0, file);
2076
+ cmd.command("import <file>").description("Import workflow from a JSON file").action(async (file) => {
2077
+ await flowImportAction(void 0, file);
2033
2078
  });
2034
2079
  cmd.command("serve").option("--port <number>", "Port to listen on", "3000").option("--open", "Open browser automatically").option("--autopilot", "Enable deterministic semiautonomous dispatcher (human gates still block)").description("Start local web server with live board").action((options) => {
2035
2080
  flowServeAction(void 0, {
@@ -2055,8 +2100,8 @@ function flowCommand() {
2055
2100
  cmd.command("ac <item-id> <ac-number>").description("Mark an acceptance criterion as completed in the spec file").action((itemId, acNumber) => {
2056
2101
  flowAcAction(void 0, itemId, acNumber);
2057
2102
  });
2058
- cmd.command("edit").option("--name <name>", "New workflow name").option("--desc <desc>", "New workflow description").description("Edit workflow metadata").action((options) => {
2059
- flowEditAction(void 0, options);
2103
+ cmd.command("edit").option("--name <name>", "New workflow name").option("--desc <desc>", "New workflow description").description("Edit workflow metadata").action(async (options) => {
2104
+ await flowEditAction(void 0, options);
2060
2105
  });
2061
2106
  cmd.command("bind").requiredOption("--template <id>", "Flow template id from the harness").requiredOption(
2062
2107
  "--harness-version <version>",
@@ -2080,25 +2125,65 @@ function flowCommand() {
2080
2125
  cmd.command("phase-run <item-id>").description("Execute actions of the current phase for an item").action((itemId) => {
2081
2126
  flowPhaseRunAction(itemId);
2082
2127
  });
2128
+ const workflow = cmd.command("workflow").description("Manage versioned workflow definitions");
2129
+ workflow.command("list").description("List all workflow definitions").action(() => {
2130
+ workflowListCommands(resolve17(process.cwd()));
2131
+ });
2132
+ workflow.command("show <id>").description("Show workflow definition details").action((id) => {
2133
+ workflowShowCommand(resolve17(process.cwd()), id);
2134
+ });
2135
+ workflow.command("draft <id>").option("--actor <actor>", "Identity actor", void 0).option("--based-on <version>", "Base version number", void 0).description("Create a draft for editing").action((id, options) => {
2136
+ const actor = options.actor ?? resolveLocalIdentity(resolve17(process.cwd())).id;
2137
+ workflowDraftCommand(resolve17(process.cwd()), id, actor, options.basedOn ? Number(options.basedOn) : void 0);
2138
+ });
2139
+ workflow.command("validate <id>").description("Validate current draft").action((id) => {
2140
+ workflowValidateCommand(resolve17(process.cwd()), id);
2141
+ });
2142
+ workflow.command("publish <id>").option("--actor <actor>", "Identity actor", void 0).requiredOption("--revision <revision>", "Expected revision number").requiredOption("--reason <reason>", "Publication reason").description("Publish current draft as new version").action((id, options) => {
2143
+ const actor = options.actor ?? resolveLocalIdentity(resolve17(process.cwd())).id;
2144
+ workflowPublishCommand(resolve17(process.cwd()), id, actor, Number(options.revision), options.reason);
2145
+ });
2146
+ workflow.command("rollback <id>").option("--actor <actor>", "Identity actor", void 0).requiredOption("--version <version>", "Version number to restore").requiredOption("--reason <reason>", "Rollback reason").description("Rollback to a previous version (publishes new derived version)").action((id, options) => {
2147
+ const actor = options.actor ?? resolveLocalIdentity(resolve17(process.cwd())).id;
2148
+ workflowRollbackCommand(resolve17(process.cwd()), id, actor, Number(options.version), options.reason);
2149
+ });
2150
+ workflow.command("versions <id>").description("List all published versions").action((id) => {
2151
+ workflowVersionsCommand(resolve17(process.cwd()), id);
2152
+ });
2153
+ workflow.command("history <id>").description("List draft revision history").action((id) => {
2154
+ workflowDraftRevisionsCommand(resolve17(process.cwd()), id);
2155
+ });
2156
+ workflow.command("template <id>").option("--template <name>", "Template name").option("--name <name>", "Workflow name").option("--actor <actor>", "Identity actor", void 0).description("Create workflow from template").action((id, options) => {
2157
+ const actor = options.actor ?? resolveLocalIdentity(resolve17(process.cwd())).id;
2158
+ workflowTemplateCommand(resolve17(process.cwd()), id, actor, options.template ?? "", options);
2159
+ });
2160
+ workflow.command("adapters <id>").option("--tools <tools>", "Comma-separated tools").option("--list", "List active adapters").option("--actor <actor>", "Identity actor", void 0).description("Manage workflow adapters").action((id, options) => {
2161
+ const actor = options.actor ?? resolveLocalIdentity(resolve17(process.cwd())).id;
2162
+ workflowAdaptersCommand(resolve17(process.cwd()), id, { tools: options.tools, list: options.list });
2163
+ });
2164
+ workflow.command("locations <id>").option("--add <path>", "Add location").option("--remove <id>", "Remove location").option("--list", "List locations").option("--actor <actor>", "Identity actor", void 0).description("Manage workflow locations").action((id, options) => {
2165
+ const actor = options.actor ?? resolveLocalIdentity(resolve17(process.cwd())).id;
2166
+ workflowLocationsCommand(resolve17(process.cwd()), id, { add: options.add, remove: options.remove, list: options.list });
2167
+ });
2083
2168
  return cmd;
2084
2169
  }
2085
2170
 
2086
2171
  // src/commands/focus.ts
2087
- import { existsSync as existsSync9, readFileSync as readFileSync8 } from "fs";
2088
- import { join as join9, resolve as resolve16 } from "path";
2089
- import chalk17 from "chalk";
2172
+ import { existsSync as existsSync7, readFileSync as readFileSync8 } from "fs";
2173
+ import { join as join8, resolve as resolve18 } from "path";
2174
+ import chalk18 from "chalk";
2090
2175
  import { Command as Command3 } from "commander";
2091
2176
  function focus_default() {
2092
2177
  return new Command3("focus").argument("[spec]", "Spec name to focus on").option("--claim", "Also claim the item (set claimedBy)").option("--clear", "Remove focus file").action(async (spec, options) => {
2093
- const root = resolve16(process.cwd());
2094
- const focusFile = join9(getLetraDir(root), "focus.md");
2178
+ const root = resolve18(process.cwd());
2179
+ const focusFile = join8(getLetraDir(root), "focus.md");
2095
2180
  if (options.clear) {
2096
- if (existsSync9(focusFile)) {
2181
+ if (existsSync7(focusFile)) {
2097
2182
  clearFocusFile(root);
2098
2183
  logEntry(root, "focus_set", "Foco removido");
2099
- console.log(chalk17.green("Focus removed."));
2184
+ console.log(chalk18.green("Focus removed."));
2100
2185
  } else {
2101
- console.log(chalk17.yellow("No focus to remove."));
2186
+ console.log(chalk18.yellow("No focus to remove."));
2102
2187
  }
2103
2188
  const workflow = loadWorkflow(root);
2104
2189
  if (workflow) {
@@ -2117,7 +2202,7 @@ function focus_default() {
2117
2202
  }
2118
2203
  }
2119
2204
  if (releasedCount > 0) {
2120
- console.log(chalk17.gray(` Released ${releasedCount} item(s).`));
2205
+ console.log(chalk18.gray(` Released ${releasedCount} item(s).`));
2121
2206
  }
2122
2207
  await writeWorkflow(root, {
2123
2208
  workflow,
@@ -2129,10 +2214,10 @@ function focus_default() {
2129
2214
  return;
2130
2215
  }
2131
2216
  if (spec) {
2132
- const specDir = join9(getLetraDir(root), "specs", spec);
2133
- const specFile = join9(specDir, "spec.md");
2134
- if (!existsSync9(specFile)) {
2135
- console.log(chalk17.red(`Spec "${spec}" not found`));
2217
+ const specDir = join8(getLetraDir(root), "specs", spec);
2218
+ const specFile = join8(specDir, "spec.md");
2219
+ if (!existsSync7(specFile)) {
2220
+ console.log(chalk18.red(`Spec "${spec}" not found`));
2136
2221
  process.exit(1);
2137
2222
  }
2138
2223
  const workflow = loadWorkflow(root);
@@ -2165,7 +2250,7 @@ function focus_default() {
2165
2250
  }
2166
2251
  itemWithSpec.claimedBy = "opencode";
2167
2252
  itemWithSpec.claimedAt = (/* @__PURE__ */ new Date()).toISOString();
2168
- console.log(chalk17.gray(` Claimed ${itemId}.`));
2253
+ console.log(chalk18.gray(` Claimed ${itemId}.`));
2169
2254
  logEntry(root, "item_claim", `Auto-claim: ${itemId}`, {
2170
2255
  itemId,
2171
2256
  by: "opencode"
@@ -2174,7 +2259,7 @@ function focus_default() {
2174
2259
  }
2175
2260
  writeFocusWithRecommendations(root, spec, itemId);
2176
2261
  logEntry(root, "focus_set", `Foco definido: ${spec}`, { itemId });
2177
- console.log(chalk17.green(`Focus set to "${spec}".`));
2262
+ console.log(chalk18.green(`Focus set to "${spec}".`));
2178
2263
  if (workflow) {
2179
2264
  await writeWorkflow(root, {
2180
2265
  workflow,
@@ -2186,7 +2271,7 @@ function focus_default() {
2186
2271
  }
2187
2272
  return;
2188
2273
  }
2189
- if (existsSync9(focusFile)) {
2274
+ if (existsSync7(focusFile)) {
2190
2275
  console.log(readFileSync8(focusFile, "utf-8"));
2191
2276
  } else {
2192
2277
  console.log("Nenhum foco definido.");
@@ -2195,15 +2280,15 @@ function focus_default() {
2195
2280
  }
2196
2281
 
2197
2282
  // src/commands/health.ts
2198
- import { resolve as resolve17 } from "path";
2199
- import chalk18 from "chalk";
2283
+ import { resolve as resolve19 } from "path";
2284
+ import chalk19 from "chalk";
2200
2285
  import { Command as Command4 } from "commander";
2201
2286
  function health_default() {
2202
2287
  const cmd = new Command4("health").description(
2203
2288
  "Manage health record \u2014 persistent diagnostic state"
2204
2289
  );
2205
2290
  cmd.option("--json", "Output in JSON format").option("--all", "Show all entries including resolved and dismissed").action((options) => {
2206
- const root = resolve17(process.cwd());
2291
+ const root = resolve19(process.cwd());
2207
2292
  const record = loadHealthRecord(root);
2208
2293
  const summary = getSummary(record);
2209
2294
  if (options.json) {
@@ -2211,14 +2296,14 @@ function health_default() {
2211
2296
  return;
2212
2297
  }
2213
2298
  console.log(`
2214
- ${chalk18.bold("\u{1F4CB} Prontu\xE1rio de Sa\xFAde")}
2299
+ ${chalk19.bold("\u{1F4CB} Prontu\xE1rio de Sa\xFAde")}
2215
2300
  `);
2216
2301
  console.log(
2217
- ` ${chalk18.red(`${summary.novo} novo(s)${summary.alta > 0 ? ` (${summary.alta} cr\xEDtico(s))` : ""}`)}`
2302
+ ` ${chalk19.red(`${summary.novo} novo(s)${summary.alta > 0 ? ` (${summary.alta} cr\xEDtico(s))` : ""}`)}`
2218
2303
  );
2219
- console.log(` ${chalk18.yellow(`${summary.ciente} em acompanhamento`)}`);
2220
- console.log(` ${chalk18.gray(`${summary.resolvido} resolvido(s)`)}`);
2221
- console.log(` ${chalk18.gray(`${summary.descartado} descartado(s)`)}`);
2304
+ console.log(` ${chalk19.yellow(`${summary.ciente} em acompanhamento`)}`);
2305
+ console.log(` ${chalk19.gray(`${summary.resolvido} resolvido(s)`)}`);
2306
+ console.log(` ${chalk19.gray(`${summary.descartado} descartado(s)`)}`);
2222
2307
  console.log();
2223
2308
  if (summary.novo === 0 && summary.ciente === 0) {
2224
2309
  console.log(" Nenhum alerta ativo. Tudo ok.");
@@ -2226,17 +2311,17 @@ ${chalk18.bold("\u{1F4CB} Prontu\xE1rio de Sa\xFAde")}
2226
2311
  const entries = options.all ? record.entries : getActiveEntries(record);
2227
2312
  if (entries.length > 0) {
2228
2313
  for (const entry of entries) {
2229
- const color = entry.severity === "alta" ? chalk18.red : entry.severity === "media" ? chalk18.yellow : chalk18.blue;
2314
+ const color = entry.severity === "alta" ? chalk19.red : entry.severity === "media" ? chalk19.yellow : chalk19.blue;
2230
2315
  console.log(` ${color(entry.id)} \u2014 ${entry.title}`);
2231
2316
  console.log(
2232
- ` ${chalk18.gray(`${entry.status} | ${entry.severity} | ${entry.source} | ${new Date(entry.detectedAt).toLocaleString()}`)}`
2317
+ ` ${chalk19.gray(`${entry.status} | ${entry.severity} | ${entry.source} | ${new Date(entry.detectedAt).toLocaleString()}`)}`
2233
2318
  );
2234
2319
  }
2235
2320
  console.log();
2236
2321
  }
2237
2322
  });
2238
2323
  cmd.command("scan").description("Run diagnostics and merge into health record").action(async () => {
2239
- const root = resolve17(process.cwd());
2324
+ const root = resolve19(process.cwd());
2240
2325
  const engine = new DiagnosticEngine(root);
2241
2326
  engine.ensureDirs();
2242
2327
  const output = await engine.runAll();
@@ -2273,7 +2358,7 @@ ${chalk18.bold("\u{1F4CB} Prontu\xE1rio de Sa\xFAde")}
2273
2358
  }
2274
2359
  }
2275
2360
  console.log(
2276
- chalk18.green(
2361
+ chalk19.green(
2277
2362
  `
2278
2363
  \u2705 Scan conclu\xEDdo. ${output.fixes.length} auto-corre\xE7\xE3o(\xF5es), ${output.suggestions.length} sugest\xE3o(\xF5es) registradas.
2279
2364
  `
@@ -2281,7 +2366,7 @@ ${chalk18.bold("\u{1F4CB} Prontu\xE1rio de Sa\xFAde")}
2281
2366
  );
2282
2367
  });
2283
2368
  cmd.command("ack <id>").description("Acknowledge a health entry").action((id) => {
2284
- const root = resolve17(process.cwd());
2369
+ const root = resolve19(process.cwd());
2285
2370
  const record = loadHealthRecord(root);
2286
2371
  if (ackEntry(record, id)) {
2287
2372
  saveHealthRecord(root, record);
@@ -2299,14 +2384,14 @@ ${chalk18.bold("\u{1F4CB} Prontu\xE1rio de Sa\xFAde")}
2299
2384
  }
2300
2385
  }
2301
2386
  logEntry(root, "health_ack", `Alerta ${id} reconhecido`);
2302
- console.log(chalk18.green(`Entrada ${id} reconhecida.`));
2387
+ console.log(chalk19.green(`Entrada ${id} reconhecida.`));
2303
2388
  } else {
2304
- console.log(chalk18.red(`Entrada ${id} n\xE3o encontrada.`));
2389
+ console.log(chalk19.red(`Entrada ${id} n\xE3o encontrada.`));
2305
2390
  process.exit(1);
2306
2391
  }
2307
2392
  });
2308
2393
  cmd.command("dismiss <id>").description("Dismiss a health entry").option("--reason <reason>", "Dismiss reason").action((id, options) => {
2309
- const root = resolve17(process.cwd());
2394
+ const root = resolve19(process.cwd());
2310
2395
  const record = loadHealthRecord(root);
2311
2396
  if (dismissEntry(record, id, options.reason)) {
2312
2397
  saveHealthRecord(root, record);
@@ -2331,9 +2416,9 @@ ${chalk18.bold("\u{1F4CB} Prontu\xE1rio de Sa\xFAde")}
2331
2416
  details: { reason: options.reason }
2332
2417
  }
2333
2418
  );
2334
- console.log(chalk18.green(`Entrada ${id} descartada.`));
2419
+ console.log(chalk19.green(`Entrada ${id} descartada.`));
2335
2420
  } else {
2336
- console.log(chalk18.red(`Entrada ${id} n\xE3o encontrada.`));
2421
+ console.log(chalk19.red(`Entrada ${id} n\xE3o encontrada.`));
2337
2422
  process.exit(1);
2338
2423
  }
2339
2424
  });
@@ -2341,14 +2426,14 @@ ${chalk18.bold("\u{1F4CB} Prontu\xE1rio de Sa\xFAde")}
2341
2426
  }
2342
2427
 
2343
2428
  // src/commands/log.ts
2344
- import { resolve as resolve18 } from "path";
2345
- import chalk19 from "chalk";
2429
+ import { resolve as resolve20 } from "path";
2430
+ import chalk20 from "chalk";
2346
2431
  import { Command as Command5 } from "commander";
2347
2432
  function log_default() {
2348
2433
  const cmd = new Command5("log").description("Session log \u2014 continuity between agent sessions");
2349
2434
  cmd.option("--all", "Show all entries").option("--json", "Output in JSON format").option("--item <id>", "Filter by item ID").option("--action <action>", "Filter by action type").option("--filter <type>", "Filter by type (alias for --action, e.g. handoff)").option("--since <date>", "Filter by date (ISO or YYYY-MM-DD)").option("--debug", "Include debug/system entries").action(
2350
2435
  (options) => {
2351
- const root = resolve18(process.cwd());
2436
+ const root = resolve20(process.cwd());
2352
2437
  const action = options.action ?? options.filter;
2353
2438
  const entries = queryLog(root, {
2354
2439
  all: options.all,
@@ -2367,34 +2452,34 @@ function log_default() {
2367
2452
  }
2368
2453
  console.log(
2369
2454
  `
2370
- ${chalk19.bold("\u{1F4D3} Di\xE1rio de Bordo")}${options.all ? " (todos)" : " (\xFAltimos 10)"}
2455
+ ${chalk20.bold("\u{1F4D3} Di\xE1rio de Bordo")}${options.all ? " (todos)" : " (\xFAltimos 10)"}
2371
2456
  `
2372
2457
  );
2373
2458
  for (const entry of entries) {
2374
- const actionColor = actionColors[entry.action] ?? chalk19.white;
2375
- const level = entry.level === "debug" ? chalk19.gray(" debug") : "";
2459
+ const actionColor = actionColors[entry.action] ?? chalk20.white;
2460
+ const level = entry.level === "debug" ? chalk20.gray(" debug") : "";
2376
2461
  console.log(
2377
- ` ${chalk19.gray(entry.id)} ${actionColor(entry.action)}${level} ${chalk19.gray(new Date(entry.timestamp).toLocaleString())}`
2462
+ ` ${chalk20.gray(entry.id)} ${actionColor(entry.action)}${level} ${chalk20.gray(new Date(entry.timestamp).toLocaleString())}`
2378
2463
  );
2379
2464
  console.log(` ${entry.description}`);
2380
2465
  if (entry.itemId)
2381
2466
  console.log(
2382
- ` ${chalk19.cyan(`item: ${entry.itemId}${entry.acId ? ` | ac: ${entry.acId}` : ""}`)}`
2467
+ ` ${chalk20.cyan(`item: ${entry.itemId}${entry.acId ? ` | ac: ${entry.acId}` : ""}`)}`
2383
2468
  );
2384
2469
  console.log();
2385
2470
  }
2386
2471
  }
2387
2472
  );
2388
2473
  cmd.command("add <description>").option("--item <id>", "Associated item ID").option("--ac <id>", "Associated AC ID").description("Add a manual log entry").action((description, options) => {
2389
- const root = resolve18(process.cwd());
2474
+ const root = resolve20(process.cwd());
2390
2475
  logEntry(root, "manual", description, {
2391
2476
  itemId: options.item,
2392
2477
  acId: options.ac
2393
2478
  });
2394
- console.log(chalk19.green("Registro adicionado ao di\xE1rio de bordo."));
2479
+ console.log(chalk20.green("Registro adicionado ao di\xE1rio de bordo."));
2395
2480
  });
2396
2481
  cmd.command("ac <acId>").option("--item <id>", "Associated item ID").description("Register an AC as completed").action((acId, options) => {
2397
- const root = resolve18(process.cwd());
2482
+ const root = resolve20(process.cwd());
2398
2483
  logEntry(
2399
2484
  root,
2400
2485
  "ac_done",
@@ -2404,61 +2489,58 @@ ${chalk19.bold("\u{1F4D3} Di\xE1rio de Bordo")}${options.all ? " (todos)" : " (\
2404
2489
  acId
2405
2490
  }
2406
2491
  );
2407
- console.log(chalk19.green(`AC ${acId} registrado como conclu\xEDdo.`));
2492
+ console.log(chalk20.green(`AC ${acId} registrado como conclu\xEDdo.`));
2408
2493
  });
2409
2494
  cmd.command("session-end").description("Mark end of session").option("--item <id>", "Current item at end of session").action((options) => {
2410
- const root = resolve18(process.cwd());
2495
+ const root = resolve20(process.cwd());
2411
2496
  logEntry(root, "session_end", "Sess\xE3o encerrada", { itemId: options.item });
2412
- console.log(chalk19.green("Fim de sess\xE3o registrado."));
2497
+ console.log(chalk20.green("Fim de sess\xE3o registrado."));
2413
2498
  });
2414
2499
  cmd.command("prune").requiredOption("--keep <days>", "Number of days to keep").description("Remove rotated JSONL logs older than the retention window").action((options) => {
2415
- const root = resolve18(process.cwd());
2500
+ const root = resolve20(process.cwd());
2416
2501
  const removed = pruneSessionLog(root, Number.parseInt(options.keep, 10));
2417
2502
  console.log(
2418
- chalk19.green(`Retencao aplicada: ${removed.length} arquivo(s) removido(s).`)
2503
+ chalk20.green(`Retencao aplicada: ${removed.length} arquivo(s) removido(s).`)
2419
2504
  );
2420
2505
  });
2421
2506
  return cmd;
2422
2507
  }
2423
2508
  var actionColors = {
2424
- validate: (s) => chalk19.blue(s),
2425
- diagnose: (s) => chalk19.blue(s),
2426
- health_scan: (s) => chalk19.magenta(s),
2427
- health_ack: (s) => chalk19.magenta(s),
2428
- health_dismiss: (s) => chalk19.magenta(s),
2429
- ac_complete: (s) => chalk19.green(s),
2430
- ac_done: (s) => chalk19.green(s),
2431
- item_move: (s) => chalk19.cyan(s),
2432
- decision: (s) => chalk19.yellow(s),
2433
- sitrep: (s) => chalk19.blue(s),
2434
- focus_set: (s) => chalk19.cyan(s),
2435
- manual: (s) => chalk19.white(s),
2436
- session_end: (s) => chalk19.red(s),
2437
- handoff: (s) => chalk19.yellowBright(s),
2438
- handoff_emitted: (s) => chalk19.yellowBright(s),
2439
- handoff_rollback: (s) => chalk19.redBright(s),
2440
- item_claim: (s) => chalk19.greenBright(s),
2441
- item_reclaim: (s) => chalk19.red(s)
2509
+ validate: (s) => chalk20.blue(s),
2510
+ diagnose: (s) => chalk20.blue(s),
2511
+ health_scan: (s) => chalk20.magenta(s),
2512
+ health_ack: (s) => chalk20.magenta(s),
2513
+ health_dismiss: (s) => chalk20.magenta(s),
2514
+ ac_complete: (s) => chalk20.green(s),
2515
+ ac_done: (s) => chalk20.green(s),
2516
+ item_move: (s) => chalk20.cyan(s),
2517
+ decision: (s) => chalk20.yellow(s),
2518
+ sitrep: (s) => chalk20.blue(s),
2519
+ focus_set: (s) => chalk20.cyan(s),
2520
+ manual: (s) => chalk20.white(s),
2521
+ session_end: (s) => chalk20.red(s),
2522
+ handoff: (s) => chalk20.yellowBright(s),
2523
+ handoff_emitted: (s) => chalk20.yellowBright(s),
2524
+ handoff_rollback: (s) => chalk20.redBright(s),
2525
+ item_claim: (s) => chalk20.greenBright(s),
2526
+ item_reclaim: (s) => chalk20.red(s)
2442
2527
  };
2443
2528
 
2444
2529
  // src/commands/ac.ts
2445
- import { existsSync as existsSync10, readFileSync as readFileSync9, writeFileSync as writeFileSync7 } from "fs";
2446
- import { join as join10, resolve as resolve19 } from "path";
2447
- import chalk20 from "chalk";
2530
+ import { existsSync as existsSync8, readFileSync as readFileSync9, writeFileSync as writeFileSync8 } from "fs";
2531
+ import { join as join9, resolve as resolve21 } from "path";
2532
+ import chalk21 from "chalk";
2448
2533
  import { Command as Command6 } from "commander";
2449
- function findAcByPattern(lines, acId) {
2450
- const normalized = acId.trim();
2451
- for (let i = 0; i < lines.length; i++) {
2452
- const line = lines[i].trim();
2453
- if (!/^- \[ \]/.test(line)) continue;
2454
- const text = line.replace(/^- \[ \]/, "").trim();
2455
- if (text.toLowerCase().includes(normalized.toLowerCase())) return i;
2456
- }
2457
- return null;
2534
+ function explicitItemDirection(root, itemId) {
2535
+ if (!itemId) throw new Error("Item alvo expl\xEDcito obrigat\xF3rio (--item ITEM-ID) quando n\xE3o h\xE1 Run selecionada.");
2536
+ return resolveAgentDirection(root, itemId);
2537
+ }
2538
+ function collectEvidence(value, previous) {
2539
+ return [...previous, value];
2458
2540
  }
2459
2541
  function listPendingACs(lines) {
2460
2542
  const result = [];
2461
- const explicit = /^- \[ \] \*\*(AC[\d.]+)\*\*: (.+)$/;
2543
+ const explicit = /^- \[ \] \*\*(AC(?:-gap-)?[\d.]+)(?:\s*[—-][^*]*)?\*\*:?\s*(.*)$/i;
2462
2544
  const plain = /^- \[ \] (.+)$/;
2463
2545
  for (let i = 0; i < lines.length; i++) {
2464
2546
  const line = lines[i].trim();
@@ -2470,114 +2552,98 @@ function listPendingACs(lines) {
2470
2552
  match = line.match(plain);
2471
2553
  if (match) {
2472
2554
  const text = match[1];
2473
- const id = `AC-${i + 1}`;
2474
- result.push({ lineIdx: i, id, text });
2555
+ const identified = text.match(/^\*\*(AC(?:-gap-)?[\d.]+)(?:\s*[—-][^*]*)?\*\*:?\s*(.*)$/i) ?? text.match(/^(AC(?:-gap-)?[\d.]+)\s*:?\s*(.*)$/i);
2556
+ if (identified) result.push({ lineIdx: i, id: identified[1], text: identified[2] });
2475
2557
  }
2476
2558
  }
2477
2559
  return result;
2478
2560
  }
2479
- function markAcById(root, acId, specName) {
2480
- const workflow = loadWorkflow(root);
2481
- let spec = specName;
2482
- if (!spec && workflow) {
2483
- const primaryItem = workflow.items.find((i) => i.id === workflow.primaryItemId);
2484
- spec = primaryItem?.spec;
2485
- }
2486
- if (!spec) {
2487
- throw new Error(
2488
- "Spec name required. Use --spec <name> or ensure an active item has a linked spec."
2489
- );
2490
- }
2491
- const specFile = join10(getLetraDir(root), "specs", spec, "spec.md");
2492
- if (!existsSync10(specFile)) {
2493
- throw new Error(`Spec file not found: ${specFile}`);
2494
- }
2495
- const content = readFileSync9(specFile, "utf-8");
2496
- const lines = content.split("\n");
2497
- const lineIdx = findAcByPattern(lines, acId);
2498
- if (lineIdx === null) {
2499
- const pendings = listPendingACs(lines);
2500
- const msg = `AC "${acId}" n\xE3o encontrado ou j\xE1 marcado como conclu\xEDdo.`;
2501
- if (pendings.length > 0) {
2502
- const pendingStr = pendings.map((ac) => `${ac.id}: ${ac.text}`).join(", ");
2503
- throw new Error(`${msg} Pendentes: ${pendingStr}`);
2504
- }
2505
- throw new Error(msg);
2506
- }
2507
- lines[lineIdx] = lines[lineIdx].replace(/^- \[ \]/, "- [x]");
2508
- writeFileSync7(specFile, lines.join("\n"), "utf-8");
2509
- const itemId = workflow?.items.find((i) => i.spec === spec)?.id;
2510
- logEntry(root, "ac_done", `AC ${acId} marcado como conclu\xEDdo em ${spec}`, {
2511
- itemId,
2512
- acId,
2513
- details: { spec }
2514
- });
2515
- console.log(
2516
- ` ${chalk20.green("\u2713")} AC ${chalk20.cyan(acId)} marcado como conclu\xEDdo em ${chalk20.cyan(spec)}`
2517
- );
2518
- try {
2519
- validate(root, { format: "text" });
2520
- } catch {
2521
- }
2522
- if (workflow?.tools && workflow.tools.length > 0) {
2523
- generateAdapters(root, workflow.tools, { source: "flow-ac", quiet: true });
2524
- }
2525
- }
2526
- function listPendingAction(root, specName) {
2561
+ function listPendingAction(root, specName, itemId) {
2527
2562
  const workflow = loadWorkflow(root);
2528
2563
  let spec = specName;
2529
2564
  if (!spec && workflow) {
2530
- const primaryItem = workflow.items.find((i) => i.id === workflow.primaryItemId);
2531
- spec = primaryItem?.spec;
2565
+ spec = explicitItemDirection(root, itemId).item?.spec ?? void 0;
2532
2566
  }
2533
2567
  if (!spec) {
2534
2568
  console.log(
2535
- chalk20.yellow(
2569
+ chalk21.yellow(
2536
2570
  "Nenhum spec ativo. Use --spec <name> ou tenha um item ativo com spec vinculada."
2537
2571
  )
2538
2572
  );
2539
2573
  return;
2540
2574
  }
2541
- const specFile = join10(getLetraDir(root), "specs", spec, "spec.md");
2542
- if (!existsSync10(specFile)) {
2543
- console.log(chalk20.red(`Spec file not found: ${specFile}`));
2575
+ const specFile = join9(getLetraDir(root), "specs", spec, "spec.md");
2576
+ if (!existsSync8(specFile)) {
2577
+ console.log(chalk21.red(`Spec file not found: ${specFile}`));
2544
2578
  return;
2545
2579
  }
2546
2580
  const content = readFileSync9(specFile, "utf-8");
2547
2581
  const lines = content.split("\n");
2548
2582
  const pendings = listPendingACs(lines);
2549
2583
  if (pendings.length === 0) {
2550
- console.log(chalk20.green(`\u2705 Todos os ACs em "${spec}" est\xE3o conclu\xEDdos!`));
2584
+ console.log(chalk21.green(`\u2705 Todos os ACs em "${spec}" est\xE3o conclu\xEDdos!`));
2551
2585
  } else {
2552
- console.log(chalk20.yellow(`
2553
- ACs pendentes em "${chalk20.cyan(spec)}":`));
2586
+ console.log(chalk21.yellow(`
2587
+ ACs pendentes em "${chalk21.cyan(spec)}":`));
2554
2588
  for (const ac of pendings) {
2555
- console.log(` ${chalk20.red("\u2717")} ${chalk20.cyan(ac.id)}: ${ac.text}`);
2589
+ console.log(` ${chalk21.red("\u2717")} ${chalk21.cyan(ac.id)}: ${ac.text}`);
2556
2590
  }
2557
- console.log(chalk20.dim("\nPara marcar um AC: letra ac done <AC-ID>"));
2591
+ console.log(chalk21.dim("\nPara marcar um AC: letra ac done <AC-ID> --item <ITEM-ID>"));
2558
2592
  }
2559
2593
  }
2560
2594
  function acCommand() {
2561
2595
  const cmd = new Command6("ac").description(
2562
2596
  "Gerenciar Acceptance Criteria \u2014 marcar como conclu\xEDdo e listar pendentes"
2563
2597
  );
2564
- cmd.command("done <ac-id>").option("--spec <name>", "Nome do spec (padr\xE3o: spec do item ativo)").description("Marcar um AC como conclu\xEDdo no spec.md").action((acId, options) => {
2565
- const root = resolve19(process.cwd());
2566
- markAcById(root, acId, options.spec);
2598
+ cmd.command("done <ac-id>").requiredOption("--item <item-id>", "Item alvo expl\xEDcito (ex.: ITEM-98)").option("--spec <name>", "Nome do spec (padr\xE3o: spec do item informado)").requiredOption("--expected-revision <revision>", "Revision retornada por letra direction").requiredOption("--reason <reason>", "Motivo da conclus\xE3o").requiredOption("--evidence <evidence>", "Evid\xEAncia verific\xE1vel; pode ser repetido", collectEvidence, []).requiredOption("--executor <executor-id>", "Executor que produziu a evid\xEAncia").option("--actor <actor>", "Identidade do actor que possui o claim", "agent:codex").option("--idempotency-key <key>", "Chave idempotente da opera\xE7\xE3o").description("Concluir um AC pela opera\xE7\xE3o can\xF4nica do harness").action((acId, options) => {
2599
+ const root = resolve21(process.cwd());
2600
+ const result = completeAcOperation(root, {
2601
+ acId,
2602
+ itemId: options.item,
2603
+ expectedRevision: options.expectedRevision,
2604
+ reason: options.reason,
2605
+ evidence: options.evidence,
2606
+ executorId: options.executor,
2607
+ actor: options.actor,
2608
+ idempotencyKey: options.idempotencyKey
2609
+ });
2610
+ if (result.outcome !== "accepted") throw new Error(`${result.reasonCode}: ${result.reason}`);
2611
+ console.log(JSON.stringify(result, null, 2));
2567
2612
  });
2568
- cmd.command("list").option("--spec <name>", "Nome do spec (padr\xE3o: spec do item ativo)").description("Listar ACs pendentes de um spec").action((options) => {
2569
- const root = resolve19(process.cwd());
2570
- listPendingAction(root, options.spec);
2613
+ cmd.command("list").option("--spec <name>", "Nome do spec (padr\xE3o: spec do item ativo)").option("--item <item-id>", "Item alvo quando n\xE3o h\xE1 Run selecionada").option("--json", "Sa\xEDda em JSON").description("Listar ACs pendentes de um spec").action((options) => {
2614
+ const root = resolve21(process.cwd());
2615
+ if (options.json) {
2616
+ const workflow = loadWorkflow(root);
2617
+ let spec = options.spec;
2618
+ if (!spec && workflow) {
2619
+ spec = explicitItemDirection(root, options.item).item?.spec ?? void 0;
2620
+ }
2621
+ if (!spec) {
2622
+ console.log(JSON.stringify({ error: "Nenhum spec ativo." }, null, 2));
2623
+ return;
2624
+ }
2625
+ const specFile = join9(getLetraDir(root), "specs", spec, "spec.md");
2626
+ if (!existsSync8(specFile)) {
2627
+ console.log(JSON.stringify({ error: `Spec file not found: ${specFile}` }, null, 2));
2628
+ return;
2629
+ }
2630
+ const content = readFileSync9(specFile, "utf-8");
2631
+ const lines = content.split("\n");
2632
+ const pendings = listPendingACs(lines);
2633
+ console.log(JSON.stringify({ spec, pending: pendings }, null, 2));
2634
+ return;
2635
+ }
2636
+ listPendingAction(root, options.spec, options.item);
2571
2637
  });
2572
2638
  cmd.action(() => {
2573
- const root = resolve19(process.cwd());
2639
+ const root = resolve21(process.cwd());
2574
2640
  listPendingAction(root);
2575
2641
  });
2576
2642
  return cmd;
2577
2643
  }
2578
2644
 
2579
2645
  // src/commands/activity-context.ts
2580
- import { resolve as resolve20 } from "path";
2646
+ import { resolve as resolve22 } from "path";
2581
2647
  import { Command as Command7 } from "commander";
2582
2648
  function renderText(context) {
2583
2649
  const lines = [];
@@ -2635,11 +2701,11 @@ function activityContextCommand() {
2635
2701
  "--activity <kind>",
2636
2702
  "Activity kind: design, implement, review, diagnose, gate",
2637
2703
  "implement"
2638
- ).option("--format <type>", "Output format: text or json", "text").action((options) => {
2704
+ ).option("--format <type>", "Output format: text or json", "text").option("--run <id>", "Execution Run ID").option("--executor <id>", "Executor identity").option("--item <id>", "Explicit item ID for read-only context").action((options) => {
2639
2705
  const activity = options.activity || "implement";
2640
2706
  const format = options.format || "text";
2641
- const root = resolve20(process.cwd());
2642
- const context = buildActivityContext({ activity, workspaceRoot: root });
2707
+ const root = resolve22(process.cwd());
2708
+ const context = buildActivityContext({ activity, workspaceRoot: root, runId: options.run, executorId: options.executor, itemId: options.item });
2643
2709
  if (format === "json") {
2644
2710
  console.log(JSON.stringify(context, null, 2));
2645
2711
  return;
@@ -2649,101 +2715,216 @@ function activityContextCommand() {
2649
2715
  }
2650
2716
 
2651
2717
  // src/commands/direction.ts
2652
- import { resolve as resolve21 } from "path";
2718
+ import { resolve as resolve23 } from "path";
2653
2719
  import { Command as Command8 } from "commander";
2720
+ function directionScope(direction, itemId) {
2721
+ if (direction.assignment?.status === "assigned") return "run";
2722
+ if (itemId || direction.item) return "item";
2723
+ return "workspace";
2724
+ }
2725
+ var WORKSPACE_SCOPE_WARNING = {
2726
+ code: "DIRECTION_SCOPE_WORKSPACE",
2727
+ message: "Esta \xE9 a dire\xE7\xE3o do workspace. Opera\xE7\xF5es de item comparam a dire\xE7\xE3o do item ou da Run: use letra direction --item <ITEM-ID> --json (ou --run <RUN-ID>)."
2728
+ };
2729
+ function withDirectionScope(direction, itemId) {
2730
+ const scope = directionScope(direction, itemId);
2731
+ return {
2732
+ ...direction,
2733
+ scope,
2734
+ warnings: scope === "workspace" ? [...direction.warnings, WORKSPACE_SCOPE_WARNING] : direction.warnings
2735
+ };
2736
+ }
2654
2737
  function directionCommand() {
2655
- return new Command8("direction").description("Read the current harness direction through the degraded CLI fallback").option("--json", "Output the complete structured snapshot").action(async (options) => {
2656
- const { resolveFallbackDirection } = await import("./fallback-MQLGS4KL.js");
2657
- const direction = resolveFallbackDirection(resolve21(process.cwd()));
2738
+ return new Command8("direction").description("Read the current harness direction through the degraded CLI fallback").option("--json", "Output the complete structured snapshot").option("--run <run-id>", "Select a canonical execution Run").option("--item <item-id>", "Select an explicitly authorized item when no Run is selected").option("--executor <executor-id>", "Bind Run selection to an executor identity").action(async (options) => {
2739
+ const { resolveFallbackDirection } = await import("./fallback-CXCCKHBA.js");
2740
+ const direction = withDirectionScope(
2741
+ resolveFallbackDirection(resolve23(process.cwd()), { runId: options.run, itemId: options.item, executorId: options.executor }),
2742
+ options.item
2743
+ );
2658
2744
  if (options.json) {
2659
2745
  process.stdout.write(`${JSON.stringify(direction, null, 2)}
2660
2746
  `);
2661
2747
  return;
2662
2748
  }
2663
2749
  console.log(`Mode: ${direction.mode}`);
2750
+ console.log(`Scope: ${direction.scope}`);
2664
2751
  console.log(`Revision: ${direction.revision}`);
2665
2752
  console.log(`Item: ${direction.item?.id ?? "none"}`);
2753
+ if (direction.scope === "workspace") console.log(WORKSPACE_SCOPE_WARNING.message);
2666
2754
  console.log("Use --json for the complete direction contract.");
2667
2755
  });
2668
2756
  }
2669
2757
 
2670
2758
  // src/commands/mcp.ts
2671
- import { resolve as resolve22 } from "path";
2759
+ import { resolve as resolve24 } from "path";
2760
+ import { execSync as execSync2 } from "child_process";
2672
2761
  import { Command as Command9 } from "commander";
2673
2762
  function mcpCommand() {
2674
2763
  const command = new Command9("mcp").description("Expose Letra harness capabilities through MCP");
2675
2764
  command.command("serve").option("--stdio", "Use the local stdio transport").description("Start the local read-only Letra MCP server").action(async () => {
2676
- const { startLetraMcpServer } = await import("./server-P6GKRWDX.js");
2677
- await startLetraMcpServer(resolve22(process.cwd()));
2765
+ const { startLetraMcpServer } = await import("./server-WUYVNSH7.js");
2766
+ await startLetraMcpServer(resolve24(process.cwd()));
2767
+ });
2768
+ command.command("restart").description("Restart the local MCP server (kills running process, opencode will restart it)").action(() => {
2769
+ try {
2770
+ const cmd = `powershell -Command "Get-CimInstance Win32_Process -Filter \\"Name='node.exe'\\" | Where-Object { $_.CommandLine -like '*mcp*serve*' } | Select-Object -ExpandProperty ProcessId"`;
2771
+ const output = execSync2(cmd, { encoding: "utf-8" }).trim();
2772
+ const pids = output.split("\n").filter((p) => p.trim());
2773
+ if (pids.length === 0) {
2774
+ console.log("No MCP server processes found.");
2775
+ return;
2776
+ }
2777
+ console.log(`Found ${pids.length} MCP server process(es): ${pids.join(", ")}`);
2778
+ for (const pid of pids) {
2779
+ try {
2780
+ execSync2(`taskkill /PID ${pid.trim()} /F`, { encoding: "utf-8" });
2781
+ console.log(`Killed process ${pid.trim()}`);
2782
+ } catch {
2783
+ console.log(`Process ${pid.trim()} already terminated`);
2784
+ }
2785
+ }
2786
+ console.log("MCP server killed. Opencode will restart it automatically.");
2787
+ } catch (error) {
2788
+ console.log("No MCP server processes found or error occurred.");
2789
+ }
2678
2790
  });
2679
2791
  return command;
2680
2792
  }
2681
2793
 
2682
2794
  // src/commands/operation.ts
2683
- import { resolve as resolve23 } from "path";
2795
+ import { resolve as resolve25 } from "path";
2684
2796
  import { Command as Command10, Option } from "commander";
2685
- function collectEvidence(value, previous) {
2797
+ function collectEvidence2(value, previous) {
2686
2798
  return [...previous, value];
2687
2799
  }
2688
2800
  function printJson(value) {
2689
2801
  process.stdout.write(`${JSON.stringify(value, null, 2)}
2690
2802
  `);
2803
+ if (isRejected(value)) process.exitCode = 1;
2804
+ }
2805
+ function isRejected(value) {
2806
+ return typeof value === "object" && value !== null && value.outcome === "rejected";
2691
2807
  }
2692
2808
  function operationCommand() {
2693
2809
  const command = new Command10("operation").description(
2694
2810
  "Execute controlled harness operations with structured JSON results"
2695
2811
  );
2696
- command.command("event <item-id>").requiredOption("--status <status>", "started, heartbeat, succeeded ou failed").requiredOption("--executor <executor-id>", "Executor externo").requiredOption("--expected-revision <revision>", "Direction revision returned by Letra").requiredOption("--reason <reason>", "Reason for the operation").option("--actor <actor>", "Identidade do actor", "agent:codex").option("--message <message>", "Mensagem do evento").option("--recovery <recovery>", "retry, release, handoff ou human").option("--error-code <code>", "C\xF3digo da falha").action(async (itemId, options) => {
2697
- const { recordExecutionEvent } = await import("./service-2JN2KI4D.js");
2698
- printJson(await recordExecutionEvent(resolve23(process.cwd()), { itemId, status: options.status, executorId: options.executor, expectedRevision: options.expectedRevision, reason: options.reason, actor: options.actor, message: options.message, recovery: options.recovery, errorCode: options.errorCode }));
2812
+ command.command("run-migrate-workflow <run-id>").requiredOption("--to-version <version-id>", "Published workflow version ID").requiredOption("--to-stage <stage-id>", "Destination stage ID").requiredOption("--run-revision <revision>", "Expected Run revision", (value) => Number(value)).requiredOption("--expected-revision <revision>", "Direction revision").requiredOption("--reason <reason>", "Audited migration reason").action((runId, options) => {
2813
+ const root = resolve25(process.cwd());
2814
+ const actor = resolveLocalIdentity(root).id;
2815
+ const details = { runId, toWorkflowVersionId: options.toVersion, toStageId: options.toStage, expectedRunRevision: options.runRevision, expectedDirectionRevision: options.expectedRevision, reason: options.reason };
2816
+ const proof = signLocalOperation(root, actor, "run.workflow.migrate", details);
2817
+ printJson(migrateRunWorkflowOperation(root, { ...details, expectedRevision: options.expectedRevision, actor, proof }));
2699
2818
  });
2700
- command.command("claim <item-id>").requiredOption("--executor <executor-id>", "Executor externo").requiredOption("--capability <capability>", "Capability usada").requiredOption("--expected-revision <revision>", "Direction revision returned by Letra").requiredOption("--reason <reason>", "Reason for the operation").option("--actor <actor>", "Identidade do actor", "agent:codex").option("--ttl <minutes>", "TTL do claim em minutos", (value) => Number(value), 30).action(async (itemId, options) => {
2701
- const { claimOperation } = await import("./service-2JN2KI4D.js");
2702
- printJson(await claimOperation(resolve23(process.cwd()), { itemId, executorId: options.executor, capability: options.capability, expectedRevision: options.expectedRevision, reason: options.reason, actor: options.actor, ttlMinutes: options.ttl }));
2819
+ command.command("reclaim-expired-claims").option("--item <item-id>", "Recover only this explicitly selected item").requiredOption("--expected-revision <revision>", "Direction revision returned by Letra").requiredOption("--reason <reason>", "Audited recovery reason").option("--actor <actor>", "System recovery actor", "system:cli-recovery").option("--idempotency-key <key>", "Idempotency key").action(async (options) => {
2820
+ const { reclaimExpiredClaimsOperation } = await import("./service-USTAY5E3.js");
2821
+ printJson(await reclaimExpiredClaimsOperation(resolve25(process.cwd()), {
2822
+ itemId: options.item,
2823
+ expectedRevision: options.expectedRevision,
2824
+ reason: options.reason,
2825
+ actor: options.actor,
2826
+ idempotencyKey: options.idempotencyKey
2827
+ }));
2828
+ });
2829
+ command.command("event <item-id>").requiredOption("--status <status>", "started, heartbeat, succeeded ou failed").requiredOption("--executor <executor-id>", "Executor externo").requiredOption("--expected-revision <revision>", "Direction revision returned by Letra").requiredOption("--reason <reason>", "Reason for the operation").option("--actor <actor>", "Identidade do actor", "agent:codex").option("--message <message>", "Mensagem do evento").option("--recovery <recovery>", "retry, release, handoff ou human").option("--error-code <code>", "C\xF3digo da falha").option("--idempotency-key <key>", "Chave idempotente da opera\xE7\xE3o").action(async (itemId, options) => {
2830
+ const { recordExecutionEvent } = await import("./service-USTAY5E3.js");
2831
+ printJson(await recordExecutionEvent(resolve25(process.cwd()), { itemId, status: options.status, executorId: options.executor, expectedRevision: options.expectedRevision, reason: options.reason, actor: options.actor, message: options.message, recovery: options.recovery, errorCode: options.errorCode, idempotencyKey: options.idempotencyKey }));
2832
+ });
2833
+ command.command("claim <item-id>").requiredOption("--executor <executor-id>", "Executor externo").requiredOption("--capability <capability>", "Capability usada").requiredOption("--expected-revision <revision>", "Direction revision returned by Letra").requiredOption("--reason <reason>", "Reason for the operation").option("--actor <actor>", "Identidade do actor", "agent:codex").option("--ttl <minutes>", "TTL do claim em minutos", (value) => Number(value), 30).option("--idempotency-key <key>", "Chave idempotente da opera\xE7\xE3o").action(async (itemId, options) => {
2834
+ const { claimOperation } = await import("./service-USTAY5E3.js");
2835
+ printJson(await claimOperation(resolve25(process.cwd()), { itemId, executorId: options.executor, capability: options.capability, expectedRevision: options.expectedRevision, reason: options.reason, actor: options.actor, ttlMinutes: options.ttl, idempotencyKey: options.idempotencyKey }));
2836
+ });
2837
+ command.command("link-item-spec <item-id>").requiredOption("--spec <spec-id>", "Existing spec ID under workspace data directory").requiredOption("--run <run-id>", "Selected Run ID").requiredOption("--executor <executor-id>", "Executor that owns the selected Run").requiredOption("--expected-revision <revision>", "Direction revision returned by Letra").requiredOption("--reason <reason>", "Reason for linking the spec").option("--actor <actor>", "Stage actor", "agent:codex").option("--idempotency-key <key>", "Idempotency key").action(async (itemId, options) => {
2838
+ const { linkItemSpecOperation } = await import("./service-USTAY5E3.js");
2839
+ printJson(await linkItemSpecOperation(resolve25(process.cwd()), {
2840
+ itemId,
2841
+ specId: options.spec,
2842
+ runId: options.run,
2843
+ executorId: options.executor,
2844
+ expectedRevision: options.expectedRevision,
2845
+ reason: options.reason,
2846
+ actor: options.actor,
2847
+ idempotencyKey: options.idempotencyKey
2848
+ }));
2849
+ });
2850
+ command.command("activate-work <item-id>").requiredOption("--expected-revision <revision>", "Direction revision returned by Letra").requiredOption("--reason <reason>", "Human prioritization reason").option("--actor <actor>", "Identidade humana", void 0).action(async (itemId, options) => {
2851
+ const actor = options.actor ?? resolveLocalIdentity(resolve25(process.cwd())).id;
2852
+ const { activateWorkOperation } = await import("./service-USTAY5E3.js");
2853
+ printJson(await activateWorkOperation(resolve25(process.cwd()), { itemId, expectedRevision: options.expectedRevision, reason: options.reason, actor }));
2703
2854
  });
2704
- command.command("validate").requiredOption("--expected-revision <revision>", "Direction revision returned by Letra").requiredOption("--reason <reason>", "Reason for the operation").action(async (options) => {
2705
- const { runValidationOperation } = await import("./service-2JN2KI4D.js");
2706
- printJson(await runValidationOperation(resolve23(process.cwd()), options));
2855
+ command.command("validate").requiredOption("--expected-revision <revision>", "Direction revision returned by Letra").requiredOption("--reason <reason>", "Reason for the operation").option("--item <item-id>", "Item alvo quando n\xE3o h\xE1 Run selecionada").option("--run <run-id>", "Seleciona o Run cuja dire\xE7\xE3o foi consultada").action(async (options) => {
2856
+ const { runValidationOperation } = await import("./service-USTAY5E3.js");
2857
+ printJson(await runValidationOperation(resolve25(process.cwd()), { ...options, itemId: options.item, runId: options.run }));
2707
2858
  });
2708
- command.command("activity [item-id]").action((itemId) => printJson(activityOperation(resolve23(process.cwd()), itemId)));
2709
- command.command("evidence <item-id>").requiredOption("--executor <executor-id>", "Executor externo").requiredOption("--expected-revision <revision>", "Direction revision").requiredOption("--reason <reason>", "Reason").requiredOption("--kind <kind>", "diff, file, command, test ou artifact").requiredOption("--value <value>", "Valor/path").requiredOption("--source <source>", "Origem observada").option("--actor <actor>", "Actor", "agent:codex").action(async (itemId, options) => {
2710
- const { submitEvidenceOperation } = await import("./service-2JN2KI4D.js");
2711
- printJson(await submitEvidenceOperation(resolve23(process.cwd()), { itemId, executorId: options.executor, expectedRevision: options.expectedRevision, reason: options.reason, actor: options.actor, evidence: [{ kind: options.kind, value: options.value, source: options.source }] }));
2859
+ command.command("activity [item-id]").action((itemId) => printJson(activityOperation(resolve25(process.cwd()), itemId)));
2860
+ command.command("gate-decision <item-id>").addOption(new Option("--decision <decision>", "approve, request-changes ou reject").choices(["approve", "request-changes", "reject"]).makeOptionMandatory()).requiredOption("--expected-revision <revision>", "Direction revision returned by Letra").requiredOption("--reason <reason>", "Audited human decision reason").action(async (itemId, options) => {
2861
+ const root = resolve25(process.cwd());
2862
+ const actor = resolveLocalIdentity(root).id;
2863
+ const details = { itemId, decision: options.decision, expectedRevision: options.expectedRevision, reason: options.reason };
2864
+ const proof = signLocalOperation(root, actor, "gate.decision", details);
2865
+ const { decideGateOperation } = await import("./service-USTAY5E3.js");
2866
+ printJson(await decideGateOperation(root, { ...details, actor, proof }));
2712
2867
  });
2713
- command.command("handoff <item-id>").requiredOption("--to <actor>", "Destino").requiredOption("--executor <executor-id>", "Executor").requiredOption("--summary <summary>", "Resumo").requiredOption("--expected-revision <revision>", "Direction revision").requiredOption("--reason <reason>", "Reason").option("--actor <actor>", "Actor", "agent:codex").action(async (itemId, options) => {
2714
- const { requestHandoffOperation } = await import("./service-2JN2KI4D.js");
2715
- printJson(await requestHandoffOperation(resolve23(process.cwd()), { itemId, to: options.to, executorId: options.executor, summary: options.summary, evidence: [], expectedRevision: options.expectedRevision, reason: options.reason, actor: options.actor }));
2868
+ command.command("evidence <item-id>").requiredOption("--executor <executor-id>", "Executor externo").requiredOption("--expected-revision <revision>", "Direction revision").requiredOption("--reason <reason>", "Reason").requiredOption("--kind <kind>", "diff, file, command, test ou artifact").requiredOption("--value <value>", "Valor/path").requiredOption("--source <source>", "Origem observada").option("--actor <actor>", "Actor", "agent:codex").option("--idempotency-key <key>", "Chave idempotente da opera\xE7\xE3o").action(async (itemId, options) => {
2869
+ const { submitEvidenceOperation } = await import("./service-USTAY5E3.js");
2870
+ printJson(await submitEvidenceOperation(resolve25(process.cwd()), { itemId, executorId: options.executor, expectedRevision: options.expectedRevision, reason: options.reason, actor: options.actor, evidence: [{ kind: options.kind, value: options.value, source: options.source }], idempotencyKey: options.idempotencyKey }));
2716
2871
  });
2717
- command.command("complete-ac <ac-id>").requiredOption("--expected-revision <revision>", "Direction revision returned by Letra").requiredOption("--reason <reason>", "Reason for completing the criterion").addOption(
2718
- new Option("--evidence <evidence>", "Regression evidence").argParser(collectEvidence).default([])
2872
+ command.command("handoff <item-id>").requiredOption("--to <actor>", "Destino").requiredOption("--executor <executor-id>", "Executor").requiredOption("--summary <summary>", "Resumo").requiredOption("--expected-revision <revision>", "Direction revision").requiredOption("--reason <reason>", "Reason").addOption(
2873
+ new Option("--evidence <evidence>", "Evid\xEAncia verific\xE1vel do handoff").argParser(collectEvidence2).default([])
2874
+ ).option("--actor <actor>", "Actor", "agent:codex").option("--idempotency-key <key>", "Chave idempotente da opera\xE7\xE3o").action(async (itemId, options) => {
2875
+ const { requestHandoffOperation: requestHandoffOperation2 } = await import("./service-USTAY5E3.js");
2876
+ printJson(await requestHandoffOperation2(resolve25(process.cwd()), { itemId, to: options.to, executorId: options.executor, summary: options.summary, evidence: options.evidence, expectedRevision: options.expectedRevision, reason: options.reason, actor: options.actor, idempotencyKey: options.idempotencyKey }));
2877
+ });
2878
+ command.command("complete-ac <ac-id>").requiredOption("--item <item-id>", "Explicit target item ID").requiredOption("--expected-revision <revision>", "Direction revision returned by Letra").requiredOption("--reason <reason>", "Reason for completing the criterion").option("--executor <executor-id>", "Executor que produziu a evid\xEAncia").option("--run <run-id>", "Run cuja dire\xE7\xE3o foi consultada").option("--actor <actor>", "Identidade do actor", "agent:codex").option("--idempotency-key <key>", "Chave idempotente da opera\xE7\xE3o").addOption(
2879
+ new Option("--evidence <evidence>", "Regression evidence").argParser(collectEvidence2).default([])
2719
2880
  ).action(
2720
2881
  async (acId, options) => {
2721
- const { completeAcOperation } = await import("./service-2JN2KI4D.js");
2722
- printJson(completeAcOperation(resolve23(process.cwd()), { acId, ...options }));
2882
+ const { completeAcOperation: completeAcOperation2 } = await import("./service-USTAY5E3.js");
2883
+ printJson(completeAcOperation2(resolve25(process.cwd()), { acId, itemId: options.item, executorId: options.executor, runId: options.run, ...options }));
2723
2884
  }
2724
2885
  );
2725
- command.command("request-transition <item-id>").requiredOption("--to <stage-id>", "Target stage ID").requiredOption("--expected-revision <revision>", "Direction revision returned by Letra").requiredOption("--reason <reason>", "Reason for requesting the transition").action(
2886
+ command.command("request-transition <item-id>").requiredOption("--to <stage-id>", "Target stage ID").requiredOption("--expected-revision <revision>", "Direction revision returned by Letra").requiredOption("--reason <reason>", "Reason for requesting the transition").option("--actor <actor>", "Identidade do actor", "agent:codex").option("--idempotency-key <key>", "Chave idempotente da opera\xE7\xE3o").action(
2726
2887
  async (itemId, options) => {
2727
- const { requestTransitionOperation } = await import("./service-2JN2KI4D.js");
2888
+ const { requestTransitionOperation } = await import("./service-USTAY5E3.js");
2728
2889
  printJson(
2729
- await requestTransitionOperation(resolve23(process.cwd()), {
2890
+ await requestTransitionOperation(resolve25(process.cwd()), {
2730
2891
  itemId,
2731
2892
  targetStageId: options.to,
2732
2893
  expectedRevision: options.expectedRevision,
2733
- reason: options.reason
2894
+ reason: options.reason,
2895
+ actor: options.actor,
2896
+ idempotencyKey: options.idempotencyKey
2734
2897
  })
2735
2898
  );
2736
2899
  }
2737
2900
  );
2901
+ command.command("passage <item-id>").requiredOption("--stage <stage-id>", "Configured destination stage").requiredOption("--to <actor>", "Configured destination role").requiredOption("--executor <executor-id>", "Source executor").requiredOption("--summary <summary>", "Handoff summary").requiredOption("--expected-revision <revision>", "Direction revision").requiredOption("--reason <reason>", "Reason").option("--run <run-id>", "Run cuja dire\xE7\xE3o foi consultada").addOption(new Option("--evidence <evidence>", "Verifiable evidence").argParser(collectEvidence2).default([])).option("--actor <actor>", "Source role", "agent:codex").option("--idempotency-key <key>", "Idempotency key").action(async (itemId, options) => {
2902
+ const { requestPassageOperation: requestPassageOperation2 } = await import("./service-USTAY5E3.js");
2903
+ printJson(await requestPassageOperation2(resolve25(process.cwd()), { itemId, targetStageId: options.stage, to: options.to, executorId: options.executor, runId: options.run, summary: options.summary, evidence: options.evidence, expectedRevision: options.expectedRevision, reason: options.reason, actor: options.actor, idempotencyKey: options.idempotencyKey }));
2904
+ });
2905
+ command.command("release <item-id>").requiredOption("--expected-revision <revision>", "Direction revision").requiredOption("--reason <reason>", "Reason for releasing the claim").option("--actor <actor>", "Actor", "agent:codex").option("--idempotency-key <key>", "Chave idempotente da opera\xE7\xE3o").action(async (itemId, options) => {
2906
+ const { releaseClaimOperation } = await import("./service-USTAY5E3.js");
2907
+ printJson(await releaseClaimOperation(resolve25(process.cwd()), { itemId, expectedRevision: options.expectedRevision, reason: options.reason, actor: options.actor, idempotencyKey: options.idempotencyKey }));
2908
+ });
2909
+ command.command("request-rework <item-id>").requiredOption("--expected-revision <revision>", "Direction revision").requiredOption("--reason <reason>", "Motivo objetivo do retrabalho").addOption(new Option("--ac <description>", "Crit\xE9rio novo a ser implementado").argParser(collectEvidence2).default([]).makeOptionMandatory()).option("--actor <actor>", "Reviewer que solicita o retrabalho", "reviewer").action(async (itemId, options) => {
2910
+ const { requestReworkOperation } = await import("./service-USTAY5E3.js");
2911
+ printJson(await requestReworkOperation(resolve25(process.cwd()), {
2912
+ itemId,
2913
+ expectedRevision: options.expectedRevision,
2914
+ reason: options.reason,
2915
+ actor: options.actor,
2916
+ acceptanceCriteria: options.ac.map((description) => ({ description }))
2917
+ }));
2918
+ });
2738
2919
  return command;
2739
2920
  }
2740
2921
 
2741
2922
  // src/commands/init.ts
2742
- import { existsSync as existsSync12, mkdirSync as mkdirSync3, writeFileSync as writeFileSync8 } from "fs";
2743
- import { basename, join as join11, resolve as resolve24 } from "path";
2923
+ import { existsSync as existsSync10, mkdirSync as mkdirSync3, writeFileSync as writeFileSync9 } from "fs";
2924
+ import { basename, join as join10, resolve as resolve26 } from "path";
2744
2925
  import { createInterface as createInterface2 } from "readline";
2745
2926
  import { fileURLToPath } from "url";
2746
- import chalk21 from "chalk";
2927
+ import chalk22 from "chalk";
2747
2928
  import ora from "ora";
2748
2929
 
2749
2930
  // src/adapters/language-registry.ts
@@ -2785,18 +2966,18 @@ var __dirname = fileURLToPath(new URL(".", import.meta.url));
2785
2966
  function ask(query, options) {
2786
2967
  if (!process.stdin.isTTY) return Promise.resolve(options[0]);
2787
2968
  const rl = createInterface2({ input: process.stdin, output: process.stdout });
2788
- return new Promise((resolve31) => {
2789
- const formatted = `${chalk21.cyan(query)} ${options.map((o) => chalk21.gray(`(${o})`)).join(" ")}
2969
+ return new Promise((resolve35) => {
2970
+ const formatted = `${chalk22.cyan(query)} ${options.map((o) => chalk22.gray(`(${o})`)).join(" ")}
2790
2971
  > `;
2791
2972
  rl.question(formatted, (answer) => {
2792
2973
  rl.close();
2793
2974
  const trimmed = answer.trim().toLowerCase();
2794
2975
  if (trimmed && options.some((o) => o.toLowerCase().startsWith(trimmed))) {
2795
- resolve31(options.find((o) => o.toLowerCase().startsWith(trimmed)) ?? options[0]);
2976
+ resolve35(options.find((o) => o.toLowerCase().startsWith(trimmed)) ?? options[0]);
2796
2977
  } else if (trimmed && options.includes(trimmed)) {
2797
- resolve31(trimmed);
2978
+ resolve35(trimmed);
2798
2979
  } else {
2799
- resolve31(options[0]);
2980
+ resolve35(options[0]);
2800
2981
  }
2801
2982
  });
2802
2983
  });
@@ -2849,13 +3030,13 @@ function stableLocationId(path) {
2849
3030
  return `loc-${name}-${(hash >>> 0).toString(36)}`;
2850
3031
  }
2851
3032
  function externalWorkspaceWorkflow(workspaceName, projectRoot, harnessVersion) {
2852
- const now6 = (/* @__PURE__ */ new Date()).toISOString();
3033
+ const now4 = (/* @__PURE__ */ new Date()).toISOString();
2853
3034
  const locationPath = normalizedPath(projectRoot);
2854
3035
  return {
2855
3036
  version: "1.0",
2856
3037
  name: workspaceName,
2857
- createdAt: now6,
2858
- updatedAt: now6,
3038
+ createdAt: now4,
3039
+ updatedAt: now4,
2859
3040
  stages: [
2860
3041
  { id: "backlog", name: "Backlog", order: 0, zone: "todo" },
2861
3042
  { id: "design", name: "Design", order: 1, zone: "doing" },
@@ -2878,7 +3059,7 @@ function externalWorkspaceWorkflow(workspaceName, projectRoot, harnessVersion) {
2878
3059
  };
2879
3060
  }
2880
3061
  async function init(targetPath, options) {
2881
- const root = resolve24(process.cwd(), targetPath || ".");
3062
+ const root = resolve26(process.cwd(), targetPath || ".");
2882
3063
  if (options?.workspace) {
2883
3064
  const spinner2 = ora("Creating workspace...").start();
2884
3065
  try {
@@ -2890,38 +3071,43 @@ async function init(targetPath, options) {
2890
3071
  root,
2891
3072
  info.harnessVersion
2892
3073
  );
2893
- writeFileSync8(
2894
- join11(workspaceDir, "workflow.json"),
3074
+ writeFileSync9(
3075
+ join10(workspaceDir, "workflow.json"),
2895
3076
  JSON.stringify(workflow, null, 2),
2896
3077
  "utf-8"
2897
3078
  );
2898
- writeFileSync8(join11(root, LINK_FILE), `${workspaceDir}
3079
+ writeFileSync9(join10(root, LINK_FILE), `${workspaceDir}
2899
3080
  `, "utf-8");
2900
3081
  clearWorkspaceCache();
2901
- spinner2.succeed(chalk21.green(`Workspace "${options.workspace}" created`));
2902
- console.log(` ${chalk21.gray("Data dir:")} ${workspaceDir}`);
2903
- console.log(` ${chalk21.gray("Project:")} ${root}`);
2904
- console.log(` ${chalk21.gray("Link:")} ${join11(root, LINK_FILE)}`);
2905
- console.log(` ${chalk21.gray("Harness:")} ${info.harnessVersion}`);
3082
+ const { regenerateWorkspaceAdapters } = await import("./sync-LIVPQXEW.js");
3083
+ const regenerated = regenerateWorkspaceAdapters(root);
3084
+ for (const path of regenerated.conflicts) {
3085
+ console.log(chalk22.yellow(` Arquivo de autoria humana preservado: ${path}`));
3086
+ }
3087
+ spinner2.succeed(chalk22.green(`Workspace "${options.workspace}" created`));
3088
+ console.log(` ${chalk22.gray("Data dir:")} ${workspaceDir}`);
3089
+ console.log(` ${chalk22.gray("Project:")} ${root}`);
3090
+ console.log(` ${chalk22.gray("Link:")} ${join10(root, LINK_FILE)}`);
3091
+ console.log(` ${chalk22.gray("Harness:")} ${info.harnessVersion}`);
2906
3092
  console.log("");
2907
3093
  console.log(" Next steps:");
2908
- console.log(` ${chalk21.cyan("letra status")} View workspace info`);
2909
- console.log(` ${chalk21.cyan("letra flow backlog")} Manage backlog items`);
3094
+ console.log(` ${chalk22.cyan("letra status")} View workspace info`);
3095
+ console.log(` ${chalk22.cyan("letra flow backlog")} Manage backlog items`);
2910
3096
  return;
2911
3097
  } catch (error) {
2912
- spinner2.fail(chalk21.red("Failed to create workspace"));
2913
- if (error instanceof Error) console.error(chalk21.red(` ${error.message}`));
3098
+ spinner2.fail(chalk22.red("Failed to create workspace"));
3099
+ if (error instanceof Error) console.error(chalk22.red(` ${error.message}`));
2914
3100
  process.exit(1);
2915
3101
  }
2916
3102
  }
2917
3103
  const letraDir = getLetraDir(root);
2918
- if (existsSync12(letraDir)) {
3104
+ if (existsSync10(letraDir)) {
2919
3105
  if (options?.serve) {
2920
- console.log(chalk21.cyan(".letra/ already exists \u2014 starting UI..."));
3106
+ console.log(chalk22.cyan(".letra/ already exists \u2014 starting UI..."));
2921
3107
  await flowServeAction(targetPath, { open: true });
2922
3108
  return;
2923
3109
  }
2924
- console.log(chalk21.yellow(".letra/ already exists"));
3110
+ console.log(chalk22.yellow(".letra/ already exists"));
2925
3111
  return;
2926
3112
  }
2927
3113
  const spinner = ora("Initializing Letra...").start();
@@ -2949,9 +3135,9 @@ async function init(targetPath, options) {
2949
3135
  tool = answer.toLowerCase();
2950
3136
  spinner.start();
2951
3137
  }
2952
- mkdirSync3(join11(letraDir, "decisions"), { recursive: true });
2953
- mkdirSync3(join11(letraDir, "specs", "_template"), { recursive: true });
2954
- mkdirSync3(join11(letraDir, "adapters"), { recursive: true });
3138
+ mkdirSync3(join10(letraDir, "decisions"), { recursive: true });
3139
+ mkdirSync3(join10(letraDir, "specs", "_template"), { recursive: true });
3140
+ mkdirSync3(join10(letraDir, "adapters"), { recursive: true });
2955
3141
  const lang = detectLanguage(root);
2956
3142
  const langDisplay = lang ?? "general";
2957
3143
  const stackLine = lang ? `- **Stack**: ${lang}` : "- Sem stack espec\xEDfica (projeto general)";
@@ -2959,25 +3145,56 @@ async function init(targetPath, options) {
2959
3145
  const templateFiles = {
2960
3146
  "context.md": `# Context
2961
3147
 
2962
- > Updated: 2026-06-16
2963
- > Owner: time
3148
+ Este arquivo \xE9 mem\xF3ria humana curada: inten\xE7\xE3o, dom\xEDnio, dire\xE7\xE3o de produto, restri\xE7\xF5es reais e decis\xF5es dur\xE1veis.
3149
+ Estado vivo, item ativo, AC atual, claim, handoff e pr\xF3xima a\xE7\xE3o v\xEAm de \`get_direction\` ou \`letra direction --json\`.
2964
3150
 
2965
3151
  ## Intent
2966
3152
 
2967
- Este projeto segue Specification-Driven Development (SDD).
2968
- Capturamos dire\xE7\xE3o, inten\xE7\xE3o e contexto para enriquecer prompts de agentes de IA.
3153
+ Por que este projeto existe e qual mudan\xE7a humana ele quer produzir.
3154
+
3155
+ ## Product Thesis
3156
+
3157
+ Qual aposta de produto guia as decis\xF5es.
3158
+
3159
+ ## Audience
2969
3160
 
2970
- ## Dom\xEDnio
3161
+ Quem usa este projeto e em quais situa\xE7\xF5es.
3162
+
3163
+ ## Domain
2971
3164
 
2972
3165
  - ${stackLine}
2973
3166
  - Ferramenta: .letra/ memory format
2974
3167
  - P\xFAblico: equipe de desenvolvimento
2975
3168
 
2976
- ## Restri\xE7\xF5es Reais
3169
+ ## Core Concepts
3170
+
3171
+ Termos essenciais que um agente precisa entender antes de interpretar specs.
3172
+
3173
+ ## Product Principles
3174
+
3175
+ Princ\xEDpios dur\xE1veis que ajudam a escolher entre solu\xE7\xF5es tecnicamente v\xE1lidas.
3176
+
3177
+ ## Non-Goals
3178
+
3179
+ O que explicitamente n\xE3o faz parte da dire\xE7\xE3o do projeto.
3180
+
3181
+ ## Important Tradeoffs
3182
+
3183
+ Tradeoffs aceitos pelo time.
3184
+
3185
+ ## Durable Decisions
3186
+
3187
+ Decis\xF5es humanas que continuam v\xE1lidas entre sess\xF5es.
3188
+
3189
+ ## Constraints
2977
3190
 
2978
3191
  - Specs devem ser thin (m\xE1x 1 p\xE1gina por feature)
2979
3192
  - Sem lock-in de IDE
2980
3193
  - Drift detection deve funcionar para qualquer dom\xEDnio (n\xE3o s\xF3 c\xF3digo)
3194
+
3195
+ ## Open Questions
3196
+
3197
+ Perguntas humanas ainda abertas.
2981
3198
  `,
2982
3199
  "constitution.md": `# Constitution
2983
3200
 
@@ -3026,9 +3243,9 @@ ${codeRules}
3026
3243
  `
3027
3244
  };
3028
3245
  for (const [file, content] of Object.entries(templateFiles)) {
3029
- writeFileSync8(join11(letraDir, file), content, "utf-8");
3246
+ writeFileSync9(join10(letraDir, file), content, "utf-8");
3030
3247
  }
3031
- const specTemplate = join11(letraDir, "specs", "_template.md");
3248
+ const specTemplate = join10(letraDir, "specs", "_template.md");
3032
3249
  const specContent = `# Spec Template
3033
3250
 
3034
3251
  > Updated: YYYY-MM-DD
@@ -3048,16 +3265,16 @@ O que explicitamente N\xC3O est\xE1 neste escopo.
3048
3265
  ## Context
3049
3266
  Por que estamos construindo isso.
3050
3267
  `;
3051
- writeFileSync8(specTemplate, specContent);
3052
- const configPath = join11(letraDir, "config.json");
3053
- writeFileSync8(configPath, adaptConfig(projectType));
3054
- console.log(` ${chalk21.gray("Created")} .letra/config.json`);
3268
+ writeFileSync9(specTemplate, specContent);
3269
+ const configPath = join10(letraDir, "config.json");
3270
+ writeFileSync9(configPath, adaptConfig(projectType));
3271
+ console.log(` ${chalk22.gray("Created")} .letra/config.json`);
3055
3272
  const tools = TOOL_MAP[tool] || TOOL_MAP.todos;
3056
3273
  generateAdapters(root, tools, { source: "init" });
3057
3274
  if ((tool === "todos" || tool === "vscode") && lang === "Node.js") {
3058
- const vscodeDir = join11(root, ".vscode");
3059
- if (!existsSync12(vscodeDir)) mkdirSync3(vscodeDir, { recursive: true });
3060
- const vscodeSettingsPath = join11(vscodeDir, "settings.json");
3275
+ const vscodeDir = join10(root, ".vscode");
3276
+ if (!existsSync10(vscodeDir)) mkdirSync3(vscodeDir, { recursive: true });
3277
+ const vscodeSettingsPath = join10(vscodeDir, "settings.json");
3061
3278
  const vscodeSettingsContent = `{
3062
3279
  "editor.formatOnSave": true,
3063
3280
  "editor.defaultFormatter": "esbenp.prettier-vscode",
@@ -3067,19 +3284,19 @@ Por que estamos construindo isso.
3067
3284
  "files.autoSave": "onFocusChange"
3068
3285
  }
3069
3286
  `;
3070
- writeFileSync8(vscodeSettingsPath, vscodeSettingsContent);
3071
- console.log(` ${chalk21.gray("Created")} .vscode/settings.json`);
3287
+ writeFileSync9(vscodeSettingsPath, vscodeSettingsContent);
3288
+ console.log(` ${chalk22.gray("Created")} .vscode/settings.json`);
3072
3289
  }
3073
- spinner.succeed(chalk21.green(".letra/ initialized successfully"));
3290
+ spinner.succeed(chalk22.green(".letra/ initialized successfully"));
3074
3291
  console.log("");
3075
3292
  console.log(" Next steps:");
3076
- console.log(` ${chalk21.cyan("letra spec new <name>")} Create your first spec`);
3077
- console.log(` ${chalk21.cyan("letra lint")} Validate specs`);
3078
- console.log(` ${chalk21.cyan("letra init --serve")} Open web UI to configure workflow`);
3293
+ console.log(` ${chalk22.cyan("letra spec new <name>")} Create your first spec`);
3294
+ console.log(` ${chalk22.cyan("letra lint")} Validate specs`);
3295
+ console.log(` ${chalk22.cyan("letra init --serve")} Open web UI to configure workflow`);
3079
3296
  if (lang) {
3080
3297
  const workflow = {
3081
3298
  version: "1.0",
3082
- name: resolve24(root).split(/[\\/]/).pop() || "meu-projeto",
3299
+ name: resolve26(root).split(/[\\/]/).pop() || "meu-projeto",
3083
3300
  language: lang,
3084
3301
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
3085
3302
  updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -3097,41 +3314,27 @@ Por que estamos construindo isso.
3097
3314
  }
3098
3315
  if (options?.serve) {
3099
3316
  console.log(`
3100
- ${chalk21.cyan("Opening web UI...")}
3317
+ ${chalk22.cyan("Opening web UI...")}
3101
3318
  `);
3102
3319
  await flowServeAction(targetPath, { open: true });
3103
3320
  return;
3104
3321
  }
3105
3322
  } catch (error) {
3106
- spinner.fail(chalk21.red("Failed to initialize Letra"));
3323
+ spinner.fail(chalk22.red("Failed to initialize Letra"));
3107
3324
  process.exit(1);
3108
3325
  }
3109
3326
  }
3110
3327
 
3111
3328
  // src/commands/lint.ts
3112
- import { existsSync as existsSync13, readdirSync as readdirSync5 } from "fs";
3113
- import { join as join12, resolve as resolve25, dirname } from "path";
3114
- import chalk22 from "chalk";
3329
+ import { existsSync as existsSync11, readdirSync as readdirSync5 } from "fs";
3330
+ import { join as join11, resolve as resolve27 } from "path";
3331
+ import chalk23 from "chalk";
3115
3332
  async function lint(targetPath) {
3116
- const root = resolve25(process.cwd(), targetPath || ".");
3117
- let specsDir = join12(getLetraDir(root), "specs");
3118
- if (!existsSync13(specsDir)) {
3119
- let found = false;
3120
- let search = root;
3121
- const fsRoot = resolve25("/").replace(/\\/g, "/");
3122
- while (search && search !== fsRoot && search !== dirname(search)) {
3123
- const candidate = join12(search, ".letra", "specs");
3124
- if (existsSync13(candidate)) {
3125
- specsDir = candidate;
3126
- found = true;
3127
- break;
3128
- }
3129
- search = dirname(search);
3130
- }
3131
- if (!found) {
3132
- console.log(chalk22.red("Error: .letra/specs/ not found. Run 'letra init' first."));
3133
- process.exit(1);
3134
- }
3333
+ const root = resolve27(process.cwd(), targetPath || ".");
3334
+ const specsDir = join11(getLetraDir(root), "specs");
3335
+ if (!existsSync11(specsDir)) {
3336
+ console.log(chalk23.red("Error: workspace specs/ not found. Run 'letra init' first."));
3337
+ process.exit(1);
3135
3338
  }
3136
3339
  let totalErrors = 0;
3137
3340
  let totalWarnings = 0;
@@ -3139,7 +3342,7 @@ async function lint(targetPath) {
3139
3342
  const entries = readdirSync5(specsDir, { withFileTypes: true });
3140
3343
  for (const entry of entries) {
3141
3344
  if (!entry.isDirectory() || entry.name.startsWith("_")) continue;
3142
- const specFile = join12(specsDir, entry.name, "spec.md");
3345
+ const specFile = join11(specsDir, entry.name, "spec.md");
3143
3346
  const { errors, warnings } = validateSpecStructure(specFile);
3144
3347
  if (errors.length > 0 || warnings.length > 0) {
3145
3348
  results.push({ file: entry.name, errors, warnings });
@@ -3148,22 +3351,22 @@ async function lint(targetPath) {
3148
3351
  }
3149
3352
  }
3150
3353
  if (results.length === 0) {
3151
- console.log(chalk22.green("All specs are valid"));
3354
+ console.log(chalk23.green("All specs are valid"));
3152
3355
  process.exit(0);
3153
3356
  }
3154
3357
  console.log("");
3155
3358
  for (const result of results) {
3156
- console.log(chalk22.bold(`
3359
+ console.log(chalk23.bold(`
3157
3360
  Spec: ${result.file}`));
3158
3361
  for (const error of result.errors) {
3159
- console.log(chalk22.red(` \u2717 ${error}`));
3362
+ console.log(chalk23.red(` \u2717 ${error}`));
3160
3363
  }
3161
3364
  for (const warning of result.warnings) {
3162
- console.log(chalk22.yellow(` \u26A0 ${warning}`));
3365
+ console.log(chalk23.yellow(` \u26A0 ${warning}`));
3163
3366
  }
3164
3367
  }
3165
3368
  console.log(
3166
- chalk22.gray(
3369
+ chalk23.gray(
3167
3370
  `
3168
3371
  ${results.length} spec(s) with issues: ${totalErrors} error(s), ${totalWarnings} warning(s)`
3169
3372
  )
@@ -3172,9 +3375,9 @@ ${results.length} spec(s) with issues: ${totalErrors} error(s), ${totalWarnings}
3172
3375
  }
3173
3376
 
3174
3377
  // src/commands/spec.ts
3175
- import { existsSync as existsSync14, mkdirSync as mkdirSync4, readFileSync as readFileSync10, readdirSync as readdirSync6, writeFileSync as writeFileSync9 } from "fs";
3176
- import { join as join13, resolve as resolve26 } from "path";
3177
- import chalk23 from "chalk";
3378
+ import { existsSync as existsSync12, mkdirSync as mkdirSync4, readFileSync as readFileSync10, readdirSync as readdirSync6, writeFileSync as writeFileSync10 } from "fs";
3379
+ import { join as join12, resolve as resolve28 } from "path";
3380
+ import chalk24 from "chalk";
3178
3381
  import ora2 from "ora";
3179
3382
  var builtInTemplates = {
3180
3383
  "web-api": {
@@ -3387,8 +3590,8 @@ Template para eventos corporativos, comunit\xE1rios ou t\xE9cnicos. Adaptado par
3387
3590
  };
3388
3591
  function listTemplates(root) {
3389
3592
  const names = Object.keys(builtInTemplates);
3390
- const customDir = join13(getLetraDir(root), "templates");
3391
- if (existsSync14(customDir)) {
3593
+ const customDir = join12(getLetraDir(root), "templates");
3594
+ if (existsSync12(customDir)) {
3392
3595
  for (const file of readdirSync6(customDir)) {
3393
3596
  if (file.endsWith(".md")) {
3394
3597
  const name = file.replace(/\.md$/, "");
@@ -3401,11 +3604,11 @@ function listTemplates(root) {
3401
3604
  function findTemplate(root, type) {
3402
3605
  const lower = type.toLowerCase();
3403
3606
  if (builtInTemplates[lower]) return builtInTemplates[lower];
3404
- const customFile = join13(getLetraDir(root), "templates", `${type}.md`);
3405
- const customAcceptance = join13(getLetraDir(root), "templates", `${type}-acceptance.md`);
3406
- if (existsSync14(customFile)) {
3607
+ const customFile = join12(getLetraDir(root), "templates", `${type}.md`);
3608
+ const customAcceptance = join12(getLetraDir(root), "templates", `${type}-acceptance.md`);
3609
+ if (existsSync12(customFile)) {
3407
3610
  const spec = readFileSync10(customFile, "utf-8");
3408
- const acceptance = existsSync14(customAcceptance) ? readFileSync10(customAcceptance, "utf-8") : `# Acceptance Criteria \u2014 ${type}
3611
+ const acceptance = existsSync12(customAcceptance) ? readFileSync10(customAcceptance, "utf-8") : `# Acceptance Criteria \u2014 ${type}
3409
3612
 
3410
3613
  - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
3411
3614
  `;
@@ -3417,47 +3620,47 @@ function applyPlaceholders(content, name, date) {
3417
3620
  return content.replace(/\{\{name\}\}/g, name).replace(/\{\{date\}\}/g, date);
3418
3621
  }
3419
3622
  function specLink(itemId, specName) {
3420
- const root = resolve26(process.cwd());
3623
+ const root = resolve28(process.cwd());
3421
3624
  const workflow = loadWorkflow(root);
3422
3625
  if (!workflow) {
3423
- console.log(chalk23.red("No workflow found"));
3626
+ console.log(chalk24.red("No workflow found"));
3424
3627
  process.exit(1);
3425
3628
  }
3426
3629
  const item = workflow.items.find((i) => i.id === itemId);
3427
3630
  if (!item) {
3428
- console.log(chalk23.red(`Item ${itemId} not found`));
3631
+ console.log(chalk24.red(`Item ${itemId} not found`));
3429
3632
  process.exit(1);
3430
3633
  }
3431
- const specDir = join13(getLetraDir(root), "specs", specName);
3432
- if (!existsSync14(specDir)) {
3433
- console.log(chalk23.red(`Spec "${specName}" not found at .letra/specs/${specName}/`));
3634
+ const specDir = join12(getLetraDir(root), "specs", specName);
3635
+ if (!existsSync12(specDir)) {
3636
+ console.log(chalk24.red(`Spec "${specName}" not found at ${join12(getLetraDir(root), "specs", specName)}/`));
3434
3637
  return;
3435
3638
  }
3436
3639
  item.spec = specName;
3437
3640
  if (!workflow.specLinks) workflow.specLinks = {};
3438
- workflow.specLinks[specName] = { path: `.letra/specs/${specName}/spec.md` };
3641
+ workflow.specLinks[specName] = { path: `specs/${specName}/spec.md` };
3439
3642
  workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
3440
3643
  writeWorkflow(root, { workflow, source: "flow-edit", skipSitrep: true });
3441
3644
  logEntry(root, "manual", `spec linked: ${itemId} \u2192 ${specName}`, { itemId });
3442
- console.log(` ${chalk23.green("\u2713")} ${itemId} \u2192 ${chalk23.cyan(specName)}`);
3645
+ console.log(` ${chalk24.green("\u2713")} ${itemId} \u2192 ${chalk24.cyan(specName)}`);
3443
3646
  }
3444
3647
  async function specNew(name, options) {
3445
- const root = resolve26(process.cwd());
3648
+ const root = resolve28(process.cwd());
3446
3649
  const letraDir = getLetraDir(root);
3447
- const specDir = join13(letraDir, "specs", name);
3448
- if (!existsSync14(letraDir)) {
3449
- console.log(chalk23.red(".letra/ not found. Run 'letra init' first."));
3650
+ const specDir = join12(letraDir, "specs", name);
3651
+ if (!existsSync12(letraDir)) {
3652
+ console.log(chalk24.red(".letra/ not found. Run 'letra init' first."));
3450
3653
  process.exit(1);
3451
3654
  }
3452
- if (existsSync14(specDir)) {
3453
- console.log(chalk23.yellow(`Spec "${name}" already exists`));
3655
+ if (existsSync12(specDir)) {
3656
+ console.log(chalk24.yellow(`Spec "${name}" already exists`));
3454
3657
  return;
3455
3658
  }
3456
3659
  const templateType = options?.template || "_default";
3457
3660
  const template = templateType === "_default" ? null : findTemplate(root, templateType);
3458
3661
  if (options?.template && !template) {
3459
3662
  const available = listTemplates(root).join(", ");
3460
- console.log(chalk23.red(`Template "${options.template}" not found. Available: ${available}`));
3663
+ console.log(chalk24.red(`Template "${options.template}" not found. Available: ${available}`));
3461
3664
  process.exit(1);
3462
3665
  }
3463
3666
  const spinner = ora2(`Creating spec "${name}"...`).start();
@@ -3467,8 +3670,8 @@ async function specNew(name, options) {
3467
3670
  if (template) {
3468
3671
  const specContent = applyPlaceholders(template.spec, name, today2);
3469
3672
  const acceptanceContent = applyPlaceholders(template.acceptance, name, today2);
3470
- writeFileSync9(join13(specDir, "spec.md"), specContent);
3471
- writeFileSync9(join13(specDir, "acceptance.md"), acceptanceContent);
3673
+ writeFileSync10(join12(specDir, "spec.md"), specContent);
3674
+ writeFileSync10(join12(specDir, "acceptance.md"), acceptanceContent);
3472
3675
  } else {
3473
3676
  const specContent = `# Spec: ${name}
3474
3677
 
@@ -3493,20 +3696,30 @@ Por que estamos construindo isso. Trade-offs considerados.
3493
3696
 
3494
3697
  - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
3495
3698
  `;
3496
- writeFileSync9(join13(specDir, "spec.md"), specContent);
3497
- writeFileSync9(join13(specDir, "acceptance.md"), acceptanceContent);
3699
+ writeFileSync10(join12(specDir, "spec.md"), specContent);
3700
+ writeFileSync10(join12(specDir, "acceptance.md"), acceptanceContent);
3498
3701
  }
3499
- spinner.succeed(chalk23.green(`Spec "${name}" created at .letra/specs/${name}/`));
3702
+ spinner.succeed(chalk24.green(`Spec "${name}" created at ${join12(letraDir, "specs", name)}/`));
3500
3703
  } catch (error) {
3501
- spinner.fail(chalk23.red("Failed to create spec"));
3704
+ spinner.fail(chalk24.red("Failed to create spec"));
3502
3705
  process.exit(1);
3503
3706
  }
3504
3707
  }
3708
+ function specCatalog(targetPath, options) {
3709
+ const root = resolve28(process.cwd(), targetPath || ".");
3710
+ const workflow = loadWorkflow(root);
3711
+ const catalog = writeSpecCatalog(root, workflow);
3712
+ if (options?.json) {
3713
+ console.log(JSON.stringify(catalog, null, 2));
3714
+ return;
3715
+ }
3716
+ console.log(` ${chalk24.green("\u2713")} Matriz can\xF4nica gerada: ${chalk24.cyan(catalog.specs.length.toString())} specs e ${chalk24.cyan(catalog.items.length.toString())} itens`);
3717
+ }
3505
3718
 
3506
3719
  // src/commands/diagnose.ts
3507
- import { resolve as resolve27 } from "path";
3720
+ import { resolve as resolve29 } from "path";
3508
3721
  async function diagnose(targetPath) {
3509
- const root = resolve27(process.cwd(), targetPath ?? ".");
3722
+ const root = resolve29(process.cwd(), targetPath ?? ".");
3510
3723
  const engine = new DiagnosticEngine(root);
3511
3724
  engine.ensureDirs();
3512
3725
  console.log("\n\u{1F50D} Auto-diagn\xF3stico do Letra\n");
@@ -3578,46 +3791,46 @@ async function diagnose(targetPath) {
3578
3791
  }
3579
3792
 
3580
3793
  // src/commands/status.ts
3581
- import { existsSync as existsSync15 } from "fs";
3582
- import { resolve as resolve28 } from "path";
3794
+ import { existsSync as existsSync13 } from "fs";
3795
+ import { resolve as resolve30 } from "path";
3583
3796
  import { pathToFileURL } from "url";
3584
- import chalk24 from "chalk";
3797
+ import chalk25 from "chalk";
3585
3798
  async function status(cwd) {
3586
- const root = resolve28(process.cwd(), cwd || ".");
3799
+ const root = resolve30(process.cwd(), cwd || ".");
3587
3800
  const manifest = detectManifest(root);
3588
3801
  if (manifest) {
3589
3802
  const { manifest: m } = manifest;
3590
- console.log(chalk24.bold("\n\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\u2557"));
3591
- console.log(chalk24.bold("\u2551 Status do Workspace \u2551"));
3592
- console.log(chalk24.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\u255D\n"));
3593
- console.log(` ${chalk24.bold("Workspace:")} ${m.workspaceId}`);
3594
- console.log(` ${chalk24.bold("Projeto:")} ${m.projectId}`);
3595
- console.log(` ${chalk24.bold("Template:")} ${m.templateId}`);
3596
- console.log(` ${chalk24.bold("Harness:")} ${m.harnessVersion}`);
3597
- console.log(` ${chalk24.bold("Gates:")} ${m.gates.join(", ")}`);
3598
- console.log(` ${chalk24.bold("Repos:")} ${m.repositories.length}`);
3599
- console.log(` ${chalk24.bold("Manifest:")} ${pathToFileURL(manifest.path).href}`);
3803
+ console.log(chalk25.bold("\n\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\u2557"));
3804
+ console.log(chalk25.bold("\u2551 Status do Workspace \u2551"));
3805
+ console.log(chalk25.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\u255D\n"));
3806
+ console.log(` ${chalk25.bold("Workspace:")} ${m.workspaceId}`);
3807
+ console.log(` ${chalk25.bold("Projeto:")} ${m.projectId}`);
3808
+ console.log(` ${chalk25.bold("Template:")} ${m.templateId}`);
3809
+ console.log(` ${chalk25.bold("Harness:")} ${m.harnessVersion}`);
3810
+ console.log(` ${chalk25.bold("Gates:")} ${m.gates.join(", ")}`);
3811
+ console.log(` ${chalk25.bold("Repos:")} ${m.repositories.length}`);
3812
+ console.log(` ${chalk25.bold("Manifest:")} ${pathToFileURL(manifest.path).href}`);
3600
3813
  const wsPath = getWorkspacePath(m.workspaceId);
3601
- if (existsSync15(wsPath)) {
3814
+ if (existsSync13(wsPath)) {
3602
3815
  const info = loadWorkspaceInfo(m.workspaceId);
3603
3816
  if (info) {
3604
3817
  console.log(
3605
3818
  `
3606
- ${chalk24.gray(`Workspace criado: ${new Date(info.createdAt).toLocaleDateString()}`)}`
3819
+ ${chalk25.gray(`Workspace criado: ${new Date(info.createdAt).toLocaleDateString()}`)}`
3607
3820
  );
3608
3821
  }
3609
3822
  }
3610
3823
  } else {
3611
- console.log(chalk24.bold("\n\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\u2557"));
3612
- console.log(chalk24.bold("\u2551 Workspaces Dispon\xEDveis \u2551"));
3613
- console.log(chalk24.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\u255D\n"));
3824
+ console.log(chalk25.bold("\n\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\u2557"));
3825
+ console.log(chalk25.bold("\u2551 Workspaces Dispon\xEDveis \u2551"));
3826
+ console.log(chalk25.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\u255D\n"));
3614
3827
  const workspaces = listWorkspaces();
3615
3828
  if (workspaces.length === 0) {
3616
3829
  console.log(" Nenhum workspace encontrado.");
3617
- console.log(` Crie um com: ${chalk24.cyan("letra init --workspace <nome>")}`);
3830
+ console.log(` Crie um com: ${chalk25.cyan("letra init --workspace <nome>")}`);
3618
3831
  } else {
3619
3832
  for (const ws of workspaces) {
3620
- console.log(` ${chalk24.green("\u25CF")} ${chalk24.bold(ws.name)}`);
3833
+ console.log(` ${chalk25.green("\u25CF")} ${chalk25.bold(ws.name)}`);
3621
3834
  console.log(` ID: ${ws.id}`);
3622
3835
  console.log(` Template: ${ws.templateId}`);
3623
3836
  console.log(` Criado: ${new Date(ws.createdAt).toLocaleDateString()}`);
@@ -3632,30 +3845,37 @@ async function status(cwd) {
3632
3845
  }
3633
3846
 
3634
3847
  // src/commands/gate.ts
3635
- import { existsSync as existsSync16, readFileSync as readFileSync11, writeFileSync as writeFileSync10 } from "fs";
3636
- import { join as join14 } from "path";
3848
+ import { existsSync as existsSync14, readFileSync as readFileSync11, writeFileSync as writeFileSync11 } from "fs";
3849
+ import { join as join13 } from "path";
3637
3850
  import { Command as Command11 } from "commander";
3638
- import chalk25 from "chalk";
3639
- var GATE_DIR = join14(".letra", "harness", "gates");
3851
+ import chalk26 from "chalk";
3852
+ var GATE_DIR = join13(".letra", "harness", "gates");
3640
3853
  function gateCommand() {
3641
3854
  const cmd = new Command11("gate");
3642
3855
  cmd.description("Gerenciar gates do harness");
3643
3856
  cmd.command("approve <id>").description("Marca um gate como approved").action((id) => {
3644
3857
  const root = process.cwd();
3858
+ const dataDir = getLetraDir(root);
3645
3859
  const candidates = [
3646
- join14(root, GATE_DIR, `${id}.yaml`),
3647
- join14(root, GATE_DIR, `${id}.yml`)
3860
+ join13(dataDir, "harness", "gates", `${id}.yaml`),
3861
+ join13(dataDir, "harness", "gates", `${id}.yml`),
3862
+ join13(dataDir, "harness", DEFAULT_HARNESS_VERSION, "gates", `${id}.yaml`),
3863
+ join13(dataDir, "harness", DEFAULT_HARNESS_VERSION, "gates", `${id}.yml`),
3864
+ join13(resolveHarnessRoot(root, DEFAULT_HARNESS_VERSION), "gates", `${id}.yaml`),
3865
+ join13(resolveHarnessRoot(root, DEFAULT_HARNESS_VERSION), "gates", `${id}.yml`),
3866
+ join13(root, GATE_DIR, `${id}.yaml`),
3867
+ join13(root, GATE_DIR, `${id}.yml`)
3648
3868
  ];
3649
- const file = candidates.find((c) => existsSync16(c));
3869
+ const file = candidates.find((c) => existsSync14(c));
3650
3870
  if (!file) {
3651
- console.error(`${chalk25.red("Gate n\xE3o encontrado:")} ${id}`);
3871
+ console.error(`${chalk26.red("Gate n\xE3o encontrado:")} ${id}`);
3652
3872
  console.error(`Procurado em: ${candidates.join(", ")}`);
3653
3873
  process.exitCode = 1;
3654
3874
  return;
3655
3875
  }
3656
3876
  let raw = readFileSync11(file, "utf-8");
3657
3877
  if (raw.includes("status: approved")) {
3658
- console.log(chalk25.yellow(`Gate "${id}" j\xE1 estava approved.`));
3878
+ console.log(chalk26.yellow(`Gate "${id}" j\xE1 estava approved.`));
3659
3879
  return;
3660
3880
  }
3661
3881
  if (raw.includes("status:")) {
@@ -3665,18 +3885,18 @@ function gateCommand() {
3665
3885
  status: approved
3666
3886
  `;
3667
3887
  }
3668
- writeFileSync10(file, raw, "utf-8");
3888
+ writeFileSync11(file, raw, "utf-8");
3669
3889
  logEntry(root, "system", `gate approve ${id}`, { details: { gateId: id } });
3670
- console.log(chalk25.green(`Gate "${id}" aprovado.`));
3671
- console.log(chalk25.dim(`Arquivo: ${file}`));
3890
+ console.log(chalk26.green(`Gate "${id}" aprovado.`));
3891
+ console.log(chalk26.dim(`Arquivo: ${file}`));
3672
3892
  });
3673
3893
  return cmd;
3674
3894
  }
3675
3895
 
3676
3896
  // src/commands/check-ds.ts
3677
- import { existsSync as existsSync17, readdirSync as readdirSync7, readFileSync as readFileSync12 } from "fs";
3678
- import { join as join15, resolve as resolve29 } from "path";
3679
- import chalk26 from "chalk";
3897
+ import { existsSync as existsSync15, readdirSync as readdirSync7, readFileSync as readFileSync12 } from "fs";
3898
+ import { join as join14, resolve as resolve31 } from "path";
3899
+ import chalk27 from "chalk";
3680
3900
  var FORBIDDEN = [
3681
3901
  /\bvar\(\s*--muted\s*\)/,
3682
3902
  /\bvar\(\s*--foreground\s*\)/,
@@ -3699,7 +3919,7 @@ function collectFiles(dir) {
3699
3919
  const entries = readdirSync7(dir, { withFileTypes: true });
3700
3920
  const files = [];
3701
3921
  for (const entry of entries) {
3702
- const full = join15(dir, entry.name);
3922
+ const full = join14(dir, entry.name);
3703
3923
  if (entry.isDirectory() && entry.name !== "node_modules" && entry.name !== "dist" && !entry.name.startsWith(".")) {
3704
3924
  files.push(...collectFiles(full));
3705
3925
  } else if (entry.isFile() && entry.name.endsWith(".tsx")) {
@@ -3718,10 +3938,10 @@ function checkFile(path) {
3718
3938
  return issues;
3719
3939
  }
3720
3940
  async function checkDs(targetPath) {
3721
- const root = resolve29(process.cwd(), targetPath || ".");
3722
- const clientDir = join15(root, "packages", "client", "src");
3723
- if (!existsSync17(clientDir)) {
3724
- console.log(chalk26.red("Error: packages/client/src not found."));
3941
+ const root = resolve31(process.cwd(), targetPath || ".");
3942
+ const clientDir = join14(root, "packages", "client", "src");
3943
+ if (!existsSync15(clientDir)) {
3944
+ console.log(chalk27.red("Error: packages/client/src not found."));
3725
3945
  process.exit(1);
3726
3946
  }
3727
3947
  const files = collectFiles(clientDir);
@@ -3735,44 +3955,934 @@ async function checkDs(targetPath) {
3735
3955
  }
3736
3956
  }
3737
3957
  if (results.length === 0) {
3738
- console.log(chalk26.green("DS conformance: OK"));
3958
+ console.log(chalk27.green("DS conformance: OK"));
3739
3959
  process.exit(0);
3740
3960
  }
3741
- console.log(chalk26.red(`DS conformance: ${totalIssues} issue(s) found
3961
+ console.log(chalk27.red(`DS conformance: ${totalIssues} issue(s) found
3742
3962
  `));
3743
3963
  for (const result of results) {
3744
- console.log(chalk26.bold(`
3964
+ console.log(chalk27.bold(`
3745
3965
  File: ${result.file}`));
3746
3966
  for (const issue of result.issues) {
3747
- console.log(chalk26.red(` \u2717 ${issue}`));
3967
+ console.log(chalk27.red(` \u2717 ${issue}`));
3748
3968
  }
3749
3969
  }
3750
3970
  process.exit(1);
3751
3971
  }
3752
3972
 
3973
+ // src/commands/doctor.ts
3974
+ import { resolve as resolve32 } from "path";
3975
+ import { Command as Command12 } from "commander";
3976
+ function doctor(root = process.cwd()) {
3977
+ return inspectWorkspaceIntegrity(resolve32(root));
3978
+ }
3979
+ function doctorCommand() {
3980
+ return new Command12("doctor").description("Verifica a integridade sem\xE2ntica do workspace can\xF4nico").option("--check", "Executa a verifica\xE7\xE3o (opcional por compatibilidade)").option("--json", "Imprime o relat\xF3rio estruturado").action((options) => {
3981
+ const report = doctor();
3982
+ if (options.json) {
3983
+ process.stdout.write(`${JSON.stringify(report, null, 2)}
3984
+ `);
3985
+ if (!report.ok) process.exitCode = 2;
3986
+ return;
3987
+ }
3988
+ console.log(`${report.ok ? "\u2713" : "\u2717"} ${report.code}`);
3989
+ console.log(` workspaceDir: ${report.resolution.workspaceDir}`);
3990
+ console.log(` workspaceRoot: ${report.resolution.workspaceRoot}`);
3991
+ console.log(` mode: ${report.resolution.mode}`);
3992
+ for (const drift of report.drifts) {
3993
+ console.log(` ${drift.code}: ${drift.paths.join(" \u2194 ")}`);
3994
+ console.log(` recovery: ${drift.recovery}`);
3995
+ }
3996
+ if (!report.ok) process.exitCode = 2;
3997
+ });
3998
+ }
3999
+
4000
+ // src/commands/spec-lint.ts
4001
+ import { readFileSync as readFileSync14 } from "fs";
4002
+ import { join as join16 } from "path";
4003
+ import { Command as Command13 } from "commander";
4004
+
4005
+ // src/spec-frontmatter/validate.ts
4006
+ import { existsSync as existsSync16, readdirSync as readdirSync8, readFileSync as readFileSync13 } from "fs";
4007
+ import { join as join15 } from "path";
4008
+
4009
+ // src/spec-frontmatter/parser.ts
4010
+ var SPEC_FRONTMATTER_REQUIRED_FIELDS_V1 = [
4011
+ "item",
4012
+ "updated",
4013
+ "status"
4014
+ ];
4015
+ function parseSpecFrontmatter(specText) {
4016
+ const lines = specText.split("\n");
4017
+ const result = {
4018
+ data: null,
4019
+ warnings: [],
4020
+ errors: []
4021
+ };
4022
+ if (lines.length < 3 || lines[0].trim() !== "---") {
4023
+ result.warnings.push({
4024
+ message: "spec.md n\xE3o possui frontmatter YAML \u2014 modo legado com heur\xEDstica transit\xF3ria"
4025
+ });
4026
+ const legacy = extractLegacyMetadata(specText);
4027
+ result.legacy = true;
4028
+ result.data = legacy.data;
4029
+ for (const w of legacy.warnings) {
4030
+ result.warnings.push({ message: w });
4031
+ }
4032
+ for (const e of legacy.errors) {
4033
+ result.errors.push({ code: "LEGACY_HEURISTIC", message: e });
4034
+ }
4035
+ return result;
4036
+ }
4037
+ let endIndex = -1;
4038
+ for (let i = 1; i < lines.length; i++) {
4039
+ if (lines[i].trim() === "---") {
4040
+ endIndex = i;
4041
+ break;
4042
+ }
4043
+ }
4044
+ if (endIndex === -1) {
4045
+ result.errors.push({
4046
+ code: "UNCLOSED_FRONTMATTER",
4047
+ message: "frontmatter YAML n\xE3o foi fechado com ---"
4048
+ });
4049
+ return result;
4050
+ }
4051
+ for (let i = endIndex + 1; i < lines.length; i++) {
4052
+ if (lines[i].trim() === "---") {
4053
+ result.warnings.push({
4054
+ message: "frontmatter YAML duplicado encontrado ap\xF3s o fechamento"
4055
+ });
4056
+ break;
4057
+ }
4058
+ }
4059
+ const yamlBlock = lines.slice(1, endIndex).join("\n");
4060
+ try {
4061
+ const parsed = parseYamlFrontmatter(yamlBlock);
4062
+ for (const field of SPEC_FRONTMATTER_REQUIRED_FIELDS_V1) {
4063
+ if (!(field in parsed)) {
4064
+ result.errors.push({
4065
+ code: "MISSING_REQUIRED_FIELD",
4066
+ message: `campo obrigat\xF3rio '${field}' ausente no frontmatter`,
4067
+ field
4068
+ });
4069
+ }
4070
+ }
4071
+ result.data = normalizeSpecFrontmatter(parsed);
4072
+ } catch (e) {
4073
+ result.errors.push({
4074
+ code: "YAML_PARSE_ERROR",
4075
+ message: `YAML inv\xE1lido no frontmatter: ${e instanceof Error ? e.message : String(e)}`
4076
+ });
4077
+ return result;
4078
+ }
4079
+ if (!result.data) return result;
4080
+ for (const field of SPEC_FRONTMATTER_REQUIRED_FIELDS_V1) {
4081
+ if (!(field in result.data)) {
4082
+ result.errors.push({
4083
+ code: "MISSING_REQUIRED_FIELD",
4084
+ message: `campo obrigat\xF3rio '${field}' ausente no frontmatter`,
4085
+ field
4086
+ });
4087
+ }
4088
+ }
4089
+ if ("item" in result.data && typeof result.data.item !== "string") {
4090
+ result.errors.push({
4091
+ code: "INVALID_FIELD_TYPE",
4092
+ message: `campo 'item' deve ser string, recebeu ${typeof result.data.item}`
4093
+ });
4094
+ }
4095
+ if ("updated" in result.data && typeof result.data.updated !== "string") {
4096
+ result.errors.push({
4097
+ code: "INVALID_FIELD_TYPE",
4098
+ message: `campo 'updated' deve ser string (data ISO), recebeu ${typeof result.data.updated}`
4099
+ });
4100
+ }
4101
+ if ("status" in result.data && typeof result.data.status !== "string") {
4102
+ result.errors.push({
4103
+ code: "INVALID_FIELD_TYPE",
4104
+ message: `campo 'status' deve ser string, recebeu ${typeof result.data.status}`
4105
+ });
4106
+ }
4107
+ return result;
4108
+ }
4109
+ function parseYamlFrontmatter(yaml) {
4110
+ const openBrackets = (yaml.match(/[[{]/g) ?? []).length;
4111
+ const closeBrackets = (yaml.match(/[\]}]/g) ?? []).length;
4112
+ if (openBrackets !== closeBrackets) {
4113
+ throw new Error("YAML malformado: estruturas inline n\xE3o balanceadas");
4114
+ }
4115
+ const result = {};
4116
+ const lines = yaml.split("\n");
4117
+ let i = 0;
4118
+ while (i < lines.length) {
4119
+ const line = lines[i];
4120
+ const trimmed = line.trim();
4121
+ if (trimmed === "" || trimmed.startsWith("#")) {
4122
+ i++;
4123
+ continue;
4124
+ }
4125
+ const topLevelMatch = trimmed.match(/^([a-zA-Z_][a-zA-Z0-9_-]*)\s*:\s*(.*)$/);
4126
+ if (topLevelMatch) {
4127
+ const key = topLevelMatch[1];
4128
+ let value = topLevelMatch[2];
4129
+ if (value === "|") {
4130
+ value = parseBlockScalar(lines, i + 1);
4131
+ i = advancePastBlock(lines, i + 1);
4132
+ result[key] = value;
4133
+ continue;
4134
+ } else if (value === ">") {
4135
+ value = parseFoldedScalar(lines, i + 1);
4136
+ i = advancePastBlock(lines, i + 1);
4137
+ result[key] = value;
4138
+ continue;
4139
+ } else if (value === "" && /^- /.test(lines[i + 1]?.trim() || "")) {
4140
+ value = parseList(lines, i + 1);
4141
+ i = advancePastList(lines, i + 1);
4142
+ result[key] = value;
4143
+ continue;
4144
+ } else if (value === "" || value.trim() === "[]" || value.trim() === "{}") {
4145
+ value = value === "" ? "" : value.trim();
4146
+ } else if (value.trim().startsWith("[") || value.trim().startsWith("{")) {
4147
+ value = parseInlineStructure(value.trim());
4148
+ } else if (/^- /.test(lines[i + 1]?.trim() || "")) {
4149
+ value = parseList(lines, i + 1);
4150
+ i = advancePastList(lines, i + 1);
4151
+ result[key] = value;
4152
+ continue;
4153
+ } else if (/^\s/.test(lines[i + 1]?.trim() || "")) {
4154
+ value = parseNestedObject(lines, i + 1);
4155
+ i = advancePastNested(lines, i + 1);
4156
+ result[key] = value;
4157
+ continue;
4158
+ } else if (value === "null" || value === "~") {
4159
+ value = null;
4160
+ } else if (value === "true") {
4161
+ value = true;
4162
+ } else if (value === "false") {
4163
+ value = false;
4164
+ } else if (!isNaN(Number(value)) && value.trim() !== "") {
4165
+ value = Number(value);
4166
+ } else if (value.startsWith('"') && value.endsWith('"')) {
4167
+ value = value.slice(1, -1);
4168
+ } else if (value.startsWith("'") && value.endsWith("'")) {
4169
+ value = value.slice(1, -1);
4170
+ }
4171
+ result[key] = value;
4172
+ i++;
4173
+ continue;
4174
+ }
4175
+ const nestedMatch = trimmed.match(/^([a-zA-Z_][a-zA-Z0-9_-]*)\s*:\s*(.*)$/);
4176
+ if (nestedMatch && i > 0) {
4177
+ i++;
4178
+ continue;
4179
+ }
4180
+ i++;
4181
+ }
4182
+ return result;
4183
+ }
4184
+ function parseBlockScalar(lines, start) {
4185
+ const chunks = [];
4186
+ let i = start;
4187
+ while (i < lines.length && lines[i].trim() !== "---" && !isTopLevelKey(lines[i])) {
4188
+ if (lines[i].trim() !== "") {
4189
+ chunks.push(lines[i]);
4190
+ }
4191
+ i++;
4192
+ }
4193
+ return chunks.join("\n").trim();
4194
+ }
4195
+ function parseFoldedScalar(lines, start) {
4196
+ return parseBlockScalar(lines, start);
4197
+ }
4198
+ function parseList(lines, start) {
4199
+ const list = [];
4200
+ let i = start;
4201
+ while (i < lines.length && lines[i].trimStart().startsWith("- ")) {
4202
+ const item = lines[i].trimStart().slice(2).trim();
4203
+ let value = item;
4204
+ if (item === "|") {
4205
+ value = parseBlockScalar(lines, i + 1);
4206
+ i = advancePastBlock(lines, i + 1);
4207
+ } else if (item.startsWith("[") || item.startsWith("{")) {
4208
+ value = parseInlineStructure(item);
4209
+ } else if (item === "true") value = true;
4210
+ else if (item === "false") value = false;
4211
+ else if (item === "null" || item === "~") value = null;
4212
+ else if (!isNaN(Number(item))) value = Number(item);
4213
+ list.push(value);
4214
+ i++;
4215
+ }
4216
+ return list;
4217
+ }
4218
+ function parseNestedObject(lines, start) {
4219
+ const obj = {};
4220
+ let i = start;
4221
+ while (i < lines.length && lines[i].startsWith(" ")) {
4222
+ const trimmed = lines[i].trim();
4223
+ if (trimmed === "" || trimmed.startsWith("#")) {
4224
+ i++;
4225
+ continue;
4226
+ }
4227
+ const match = trimmed.match(/^([a-zA-Z_][a-zA-Z0-9_-]*)\s*:\s*(.*)$/);
4228
+ if (match) {
4229
+ const key = match[1];
4230
+ let value = match[2];
4231
+ if (value === "|") {
4232
+ value = parseBlockScalar(lines, i + 1);
4233
+ i = advancePastBlock(lines, i + 1);
4234
+ } else if (value === ">") {
4235
+ value = parseFoldedScalar(lines, i + 1);
4236
+ i = advancePastBlock(lines, i + 1);
4237
+ } else if (value === "" && lines[i + 1]?.startsWith(" ")) {
4238
+ value = parseNestedObject(lines, i + 1);
4239
+ i = advancePastNested(lines, i + 1);
4240
+ } else if (/^- /.test(lines[i + 1]?.trim() || "")) {
4241
+ value = parseList(lines, i + 1);
4242
+ i = advancePastList(lines, i + 1);
4243
+ } else if (value === "true") value = true;
4244
+ else if (value === "false") value = false;
4245
+ else if (value === "null" || value === "~") value = null;
4246
+ else if (!isNaN(Number(value))) value = Number(value);
4247
+ obj[key] = value;
4248
+ }
4249
+ i++;
4250
+ }
4251
+ return obj;
4252
+ }
4253
+ function parseInlineStructure(value) {
4254
+ if (value.startsWith("[") && value.endsWith("]")) {
4255
+ const inner = value.slice(1, -1);
4256
+ if (inner.trim() === "") return [];
4257
+ return inner.split(",").map((s) => {
4258
+ const v = s.trim();
4259
+ if (v === "true") return true;
4260
+ if (v === "false") return false;
4261
+ if (v === "null" || v === "~") return null;
4262
+ if (!isNaN(Number(v))) return Number(v);
4263
+ if (v.startsWith('"') && v.endsWith('"') || v.startsWith("'") && v.endsWith("'")) {
4264
+ return v.slice(1, -1);
4265
+ }
4266
+ return v;
4267
+ });
4268
+ }
4269
+ if (value.startsWith("{") && value.endsWith("}")) {
4270
+ return value;
4271
+ }
4272
+ return value;
4273
+ }
4274
+ function advancePastBlock(lines, start) {
4275
+ let i = start;
4276
+ while (i < lines.length && lines[i].trim() !== "---" && (lines[i].startsWith(" ") || lines[i].trim() === "")) {
4277
+ i++;
4278
+ }
4279
+ return i;
4280
+ }
4281
+ function advancePastList(lines, start) {
4282
+ let i = start;
4283
+ while (i < lines.length && lines[i].trimStart().startsWith("- ")) {
4284
+ i++;
4285
+ }
4286
+ return i;
4287
+ }
4288
+ function advancePastNested(lines, start) {
4289
+ let i = start;
4290
+ while (i < lines.length && lines[i].startsWith(" ")) {
4291
+ i++;
4292
+ }
4293
+ return i;
4294
+ }
4295
+ function isTopLevelKey(line) {
4296
+ return /^[a-zA-Z_][a-zA-Z0-9_-]*\s*:/.test(line.trimStart());
4297
+ }
4298
+ function extractLegacyMetadata(specText) {
4299
+ const result = {
4300
+ data: {},
4301
+ warnings: [],
4302
+ errors: []
4303
+ };
4304
+ const itemMatch = specText.match(/>\s*Item:\s*(ITEM-\d+)/i);
4305
+ if (itemMatch) {
4306
+ result.data.item = itemMatch[1];
4307
+ } else {
4308
+ result.errors.push("n\xE3o foi poss\xEDvel inferir item do header do spec");
4309
+ }
4310
+ const updatedMatch = specText.match(/>\s*Updated:\s*(.+?)(?:\n|$)/i);
4311
+ if (updatedMatch) {
4312
+ let updated = updatedMatch[1].trim();
4313
+ if (/^\d{4}-\d{2}-\d{2}$/.test(updated)) {
4314
+ } else if (/^\d{2}\/\d{2}\/\d{4}$/.test(updated)) {
4315
+ const [dd, mm, yyyy] = updated.split("/");
4316
+ updated = `${yyyy}-${mm}-${dd}`;
4317
+ } else {
4318
+ const parsed = new Date(updated);
4319
+ if (!isNaN(parsed.getTime())) {
4320
+ updated = parsed.toISOString().slice(0, 10);
4321
+ }
4322
+ }
4323
+ result.data.updated = updated;
4324
+ } else {
4325
+ result.errors.push("n\xE3o foi poss\xEDvel inferir updated do header do spec");
4326
+ }
4327
+ const statusMatch = specText.match(/>\s*Status:\s*(.+?)(?:\n|$)/i);
4328
+ if (statusMatch) {
4329
+ result.data.status = statusMatch[1].trim();
4330
+ } else {
4331
+ result.errors.push("n\xE3o foi poss\xEDvel inferir status do header do spec");
4332
+ }
4333
+ result.data.spec = "legacy";
4334
+ result.warnings.push("spec sem frontmatter \u2014 metadados inferidos por heur\xEDstica");
4335
+ return result;
4336
+ }
4337
+ function normalizeSpecFrontmatter(parsed) {
4338
+ function parseInlineList(value) {
4339
+ if (Array.isArray(value)) return value;
4340
+ if (typeof value !== "string") return void 0;
4341
+ const trimmed = value.trim();
4342
+ if (trimmed === "") return [];
4343
+ if (!trimmed.startsWith("[") || !trimmed.endsWith("]")) return void 0;
4344
+ const inner = trimmed.slice(1, -1).trim();
4345
+ if (inner === "") return [];
4346
+ return inner.split(",").map((s) => s.trim()).filter(Boolean);
4347
+ }
4348
+ const result = {
4349
+ ...parsed,
4350
+ item: typeof parsed.item === "string" ? parsed.item : parsed.item ?? "",
4351
+ updated: typeof parsed.updated === "string" ? parsed.updated : parsed.updated ?? "",
4352
+ status: typeof parsed.status === "string" ? parsed.status : parsed.status ?? "",
4353
+ schemaVersion: typeof parsed.schemaVersion === "number" ? String(parsed.schemaVersion) : typeof parsed.schemaVersion === "string" ? parsed.schemaVersion : "1",
4354
+ spec: typeof parsed.spec === "string" ? parsed.spec : void 0,
4355
+ version: typeof parsed.version === "string" ? parsed.version : void 0,
4356
+ outcome: typeof parsed.outcome === "string" ? parsed.outcome : void 0,
4357
+ context: typeof parsed.context === "string" ? parsed.context : void 0,
4358
+ dependsOn: parseInlineList(parsed.dependsOn),
4359
+ supersededBy: typeof parsed.supersededBy === "string" ? parsed.supersededBy : parsed.supersededBy === null ? null : void 0,
4360
+ reviewedAt: typeof parsed.reviewedAt === "string" ? parsed.reviewedAt : parsed.reviewedAt === null ? null : void 0,
4361
+ reviewedBy: typeof parsed.reviewedBy === "string" ? parsed.reviewedBy : parsed.reviewedBy === null ? null : void 0,
4362
+ acCount: typeof parsed.acCount === "number" ? parsed.acCount : typeof parsed.acCount === "string" ? Number.isNaN(Number(parsed.acCount)) ? void 0 : Number(parsed.acCount) : void 0,
4363
+ acResolved: typeof parsed.acResolved === "number" ? parsed.acResolved : typeof parsed.acResolved === "string" ? Number.isNaN(Number(parsed.acResolved)) ? void 0 : Number(parsed.acResolved) : void 0
4364
+ };
4365
+ return result;
4366
+ }
4367
+
4368
+ // src/spec-frontmatter/validate.ts
4369
+ function validateSpecFrontmatter(workspaceRoot, specId) {
4370
+ const result = {
4371
+ valid: true,
4372
+ issues: [],
4373
+ frontmatter: null
4374
+ };
4375
+ const specPath = join15(workspaceRoot, "specs", specId, "spec.md");
4376
+ if (!existsSync16(specPath)) {
4377
+ result.issues.push({
4378
+ code: "SPEC_FILE_MISSING",
4379
+ message: `arquivo specs/${specId}/spec.md n\xE3o encontrado`,
4380
+ specId,
4381
+ severity: "error"
4382
+ });
4383
+ result.valid = false;
4384
+ return result;
4385
+ }
4386
+ let content;
4387
+ try {
4388
+ content = readFileSync13(specPath, "utf-8");
4389
+ } catch {
4390
+ result.issues.push({
4391
+ code: "SPEC_FILE_NOT_READABLE",
4392
+ message: `n\xE3o foi poss\xEDvel ler specs/${specId}/spec.md`,
4393
+ specId,
4394
+ severity: "error"
4395
+ });
4396
+ result.valid = false;
4397
+ return result;
4398
+ }
4399
+ const parseResult = parseSpecFrontmatter(content);
4400
+ if (parseResult.legacy) {
4401
+ result.issues.push({
4402
+ code: "LEGACY_NO_FRONTMATTER",
4403
+ message: `spec ${specId} n\xE3o possui frontmatter YAML estruturado (modo legado com heur\xEDstica)`,
4404
+ specId,
4405
+ severity: "warning"
4406
+ });
4407
+ return result;
4408
+ }
4409
+ for (const err of parseResult.errors) {
4410
+ const missingField = err.code === "MISSING_REQUIRED_FIELD" ? err.field : void 0;
4411
+ if (missingField && result.issues.some(
4412
+ (issue) => issue.code === "REQUIRED_FIELD_MISSING" && issue.field === missingField
4413
+ ))
4414
+ continue;
4415
+ result.issues.push({
4416
+ code: missingField ? "REQUIRED_FIELD_MISSING" : "FRONTMATTER_INVALID",
4417
+ message: err.message,
4418
+ specId,
4419
+ ...missingField ? { field: missingField } : {},
4420
+ severity: "error"
4421
+ });
4422
+ result.valid = false;
4423
+ }
4424
+ for (const warn of parseResult.warnings) {
4425
+ result.issues.push({
4426
+ code: "FRONTMATTER_INVALID",
4427
+ message: warn.message,
4428
+ specId,
4429
+ severity: "warning"
4430
+ });
4431
+ }
4432
+ if (parseResult.data) {
4433
+ result.frontmatter = parseResult.data;
4434
+ for (const field of SPEC_FRONTMATTER_REQUIRED_FIELDS_V1) {
4435
+ const alreadyReported = result.issues.some(
4436
+ (issue) => issue.code === "REQUIRED_FIELD_MISSING" && issue.field === field
4437
+ );
4438
+ if (!alreadyReported && !(field in parseResult.data)) {
4439
+ result.issues.push({
4440
+ code: "REQUIRED_FIELD_MISSING",
4441
+ message: `campo obrigat\xF3rio '${field}' ausente no frontmatter`,
4442
+ specId,
4443
+ field,
4444
+ severity: "error"
4445
+ });
4446
+ result.valid = false;
4447
+ }
4448
+ }
4449
+ const validStatuses = ["backlog", "design", "code", "review", "security", "done", "archived", "consolidated"];
4450
+ if ("status" in parseResult.data && typeof parseResult.data.status === "string") {
4451
+ if (!validStatuses.includes(parseResult.data.status)) {
4452
+ result.issues.push({
4453
+ code: "STATUS_UNKNOWN",
4454
+ message: `status '${parseResult.data.status}' n\xE3o \xE9 um dos status conhecidos: ${validStatuses.join(", ")} (pode ser customizado pelo workspace)`,
4455
+ specId,
4456
+ field: "status",
4457
+ severity: "warning"
4458
+ });
4459
+ }
4460
+ }
4461
+ checkDrift(result, workspaceRoot, specId, parseResult.data);
4462
+ } else {
4463
+ result.issues.push({
4464
+ code: "LEGACY_NO_FRONTMATTER",
4465
+ message: `spec ${specId} n\xE3o possui frontmatter YAML estruturado (modo legado com heur\xEDstica)`,
4466
+ specId,
4467
+ severity: "warning"
4468
+ });
4469
+ }
4470
+ return result;
4471
+ }
4472
+ function checkDrift(result, workspaceRoot, specId, frontmatter) {
4473
+ const acceptancePath = join15(workspaceRoot, "specs", specId, "acceptance.md");
4474
+ if (!existsSync16(acceptancePath)) {
4475
+ return;
4476
+ }
4477
+ let acceptanceContent;
4478
+ try {
4479
+ acceptanceContent = readFileSync13(acceptancePath, "utf-8");
4480
+ } catch {
4481
+ return;
4482
+ }
4483
+ if (frontmatter.status === "done") {
4484
+ const pendingACs = (acceptanceContent.match(/^- \[ \]\s*\*\*/gm) || []).length;
4485
+ if (pendingACs > 0) {
4486
+ result.issues.push({
4487
+ code: "DRIFT_FRONTMATTER_ACCEPTANCE",
4488
+ message: `frontmatter status='done' mas acceptance.md tem ${pendingACs} AC(s) pendente(s) [ ]`,
4489
+ specId,
4490
+ severity: "warning"
4491
+ });
4492
+ }
4493
+ }
4494
+ if (typeof frontmatter.acResolved === "number" && typeof frontmatter.acCount === "number" && frontmatter.acCount > 0) {
4495
+ const actualResolved = (acceptanceContent.match(/^- \[x\]\s*\*\*/gm) || []).length;
4496
+ if (actualResolved !== frontmatter.acResolved) {
4497
+ result.issues.push({
4498
+ code: "DRIFT_FRONTMATTER_ACCEPTANCE",
4499
+ message: `frontmatter acResolved=${frontmatter.acResolved} mas acceptance.md tem ${actualResolved} AC(s) resolvido(s) [x]`,
4500
+ specId,
4501
+ severity: "warning"
4502
+ });
4503
+ }
4504
+ }
4505
+ }
4506
+ function validateAllSpecsFrontmatter(workspaceRoot) {
4507
+ const specsDir = join15(workspaceRoot, "specs");
4508
+ const results = /* @__PURE__ */ new Map();
4509
+ if (!existsSync16(specsDir)) {
4510
+ return { results, hasErrors: false };
4511
+ }
4512
+ const specDirs = readdirSync8(specsDir);
4513
+ let hasErrors = false;
4514
+ for (const specId of specDirs) {
4515
+ const specPath = join15(specsDir, specId, "spec.md");
4516
+ if (!existsSync16(specPath)) continue;
4517
+ const result = validateSpecFrontmatter(workspaceRoot, specId);
4518
+ results.set(specId, result);
4519
+ if (!result.valid) hasErrors = true;
4520
+ }
4521
+ return { results, hasErrors };
4522
+ }
4523
+
4524
+ // src/commands/spec-lint.ts
4525
+ function specLintCommand() {
4526
+ const cmd = new Command13("spec lint").description(
4527
+ "Valida frontmatter YAML de todas as specs do workspace"
4528
+ );
4529
+ cmd.action(async () => {
4530
+ const cwd = process.cwd();
4531
+ const letraDir = getLetraDir(cwd);
4532
+ if (!letraDir) {
4533
+ console.error("\u274C N\xE3o foi poss\xEDvel localizar o diret\xF3rio .letra. Execute dentro de um workspace Letra.");
4534
+ process.exit(1);
4535
+ }
4536
+ const workspaceRoot = process.env.LETRA_WORKSPACE_ROOT || cwd;
4537
+ if (!readFileSync14(join16(letraDir, "workflow.json"), "utf-8")) {
4538
+ }
4539
+ const { results, hasErrors } = validateAllSpecsFrontmatter(workspaceRoot);
4540
+ if (results.size === 0) {
4541
+ console.log("\u2139\uFE0F Nenhuma spec encontrada em specs/ no diret\xF3rio de dados do workspace");
4542
+ return;
4543
+ }
4544
+ let hasOutput = false;
4545
+ for (const [specId, result] of results) {
4546
+ if (result.issues.length === 0 && result.frontmatter) {
4547
+ continue;
4548
+ }
4549
+ hasOutput = true;
4550
+ console.log(`
4551
+ \u{1F4C4} ${specId}:`);
4552
+ for (const issue of result.issues) {
4553
+ const icon = issue.severity === "error" ? "\u274C" : "\u26A0\uFE0F ";
4554
+ console.log(` ${icon} [${issue.code}] ${issue.message}`);
4555
+ }
4556
+ }
4557
+ if (!hasOutput) {
4558
+ console.log("\u2705 Todas as specs possuem frontmatter YAML v\xE1lido.");
4559
+ return;
4560
+ }
4561
+ const errorCount = [...results.values()].some((r) => !r.valid);
4562
+ if (errorCount) {
4563
+ console.log(`
4564
+ \u274C ${errorCount} spec(s) com frontmatter inv\xE1lido.`);
4565
+ process.exit(1);
4566
+ } else {
4567
+ console.log(`
4568
+ \u26A0\uFE0F Apenas warnings. Frontmatter est\xE1 estruturalmente v\xE1lido.`);
4569
+ }
4570
+ });
4571
+ return cmd;
4572
+ }
4573
+
4574
+ // src/commands/spec-migrate-frontmatter.ts
4575
+ import { Command as Command14 } from "commander";
4576
+
4577
+ // src/spec-frontmatter/migrate.ts
4578
+ import { readFileSync as readFileSync15, writeFileSync as writeFileSync12, existsSync as existsSync17, readdirSync as readdirSync9 } from "fs";
4579
+ import { join as join17 } from "path";
4580
+ function hasFrontmatter(specText) {
4581
+ const lines = specText.split("\n");
4582
+ return lines.length >= 3 && lines[0].trim() === "---";
4583
+ }
4584
+ function extractLegacyMetadata2(specText, specId) {
4585
+ const result = {
4586
+ data: {},
4587
+ inferred: [],
4588
+ missing: [],
4589
+ errors: []
4590
+ };
4591
+ const itemMatch = specText.match(/>\s*Item:\s*(ITEM-\d+)/i);
4592
+ if (itemMatch) {
4593
+ result.data.item = itemMatch[1];
4594
+ result.inferred.push("item (do header > Item:)");
4595
+ } else {
4596
+ result.missing.push("item");
4597
+ result.errors.push("n\xE3o foi poss\xEDvel inferir item do header do spec");
4598
+ }
4599
+ const updatedMatch = specText.match(/>\s*Updated:\s*(.+?)(?:\n|$)/i);
4600
+ if (updatedMatch) {
4601
+ let updated = updatedMatch[1].trim();
4602
+ if (/^\d{4}-\d{2}-\d{2}$/.test(updated)) {
4603
+ } else if (/^\d{2}\/\d{2}\/\d{4}$/.test(updated)) {
4604
+ const [dd, mm, yyyy] = updated.split("/");
4605
+ updated = `${yyyy}-${mm}-${dd}`;
4606
+ } else {
4607
+ const parsed = new Date(updated);
4608
+ if (!isNaN(parsed.getTime())) {
4609
+ updated = parsed.toISOString().slice(0, 10);
4610
+ }
4611
+ }
4612
+ result.data.updated = updated;
4613
+ result.inferred.push("updated (do header > Updated:)");
4614
+ } else {
4615
+ result.missing.push("updated");
4616
+ result.errors.push("n\xE3o foi poss\xEDvel inferir updated do header do spec");
4617
+ }
4618
+ const statusMatch = specText.match(/>\s*Status:\s*(.+?)(?:\n|$)/i);
4619
+ if (statusMatch) {
4620
+ result.data.status = statusMatch[1].trim();
4621
+ result.inferred.push("status (do header > Status:)");
4622
+ } else {
4623
+ result.missing.push("status");
4624
+ result.errors.push("n\xE3o foi poss\xEDvel inferir status do header do spec");
4625
+ }
4626
+ result.data.spec = specId;
4627
+ const acceptancePath = join17(
4628
+ join17(specText.split("\n")[0] ? "" : "")
4629
+ // not useful
4630
+ );
4631
+ return result;
4632
+ }
4633
+ function generateFrontmatterYaml(data) {
4634
+ const lines = ["---"];
4635
+ if (data.schemaVersion) {
4636
+ lines.push(`schemaVersion: "${data.schemaVersion}"`);
4637
+ } else {
4638
+ lines.push('schemaVersion: "1"');
4639
+ }
4640
+ if (data.item) {
4641
+ lines.push(`item: ${data.item}`);
4642
+ }
4643
+ if (data.spec) {
4644
+ lines.push(`spec: ${data.spec}`);
4645
+ }
4646
+ if (data.version) {
4647
+ lines.push(`version: "${data.version}"`);
4648
+ }
4649
+ if (data.updated) {
4650
+ lines.push(`updated: "${data.updated}"`);
4651
+ }
4652
+ if (data.status) {
4653
+ lines.push(`status: ${data.status}`);
4654
+ }
4655
+ if (data.outcome) {
4656
+ const outcomeLines = data.outcome.split("\n");
4657
+ if (outcomeLines.length > 1) {
4658
+ lines.push("outcome: |");
4659
+ for (const line of outcomeLines) {
4660
+ lines.push(` ${line}`);
4661
+ }
4662
+ } else {
4663
+ lines.push(`outcome: "${data.outcome}"`);
4664
+ }
4665
+ }
4666
+ if (data.dependsOn && data.dependsOn.length > 0) {
4667
+ lines.push("dependsOn:");
4668
+ for (const dep of data.dependsOn) {
4669
+ lines.push(` - ${dep}`);
4670
+ }
4671
+ }
4672
+ if (data.supersededBy !== void 0) {
4673
+ lines.push(`supersededBy: ${data.supersededBy === null ? "null" : data.supersededBy}`);
4674
+ }
4675
+ if (data.reviewedAt !== void 0) {
4676
+ lines.push(`reviewedAt: ${data.reviewedAt === null ? "null" : `"${data.reviewedAt}"`}`);
4677
+ }
4678
+ if (data.reviewedBy !== void 0) {
4679
+ lines.push(`reviewedBy: ${data.reviewedBy === null ? "null" : `"${data.reviewedBy}"`}`);
4680
+ }
4681
+ if (data.acCount !== void 0) {
4682
+ lines.push(`acCount: ${data.acCount}`);
4683
+ }
4684
+ if (data.acResolved !== void 0) {
4685
+ lines.push(`acResolved: ${data.acResolved}`);
4686
+ }
4687
+ lines.push("---");
4688
+ lines.push("");
4689
+ return lines.join("\n");
4690
+ }
4691
+ function migrateSpecToFrontmatterV1(workspaceRoot, specId) {
4692
+ const specPath = join17(workspaceRoot, "specs", specId, "spec.md");
4693
+ if (!existsSync17(specPath)) {
4694
+ return {
4695
+ specId,
4696
+ specPath,
4697
+ migrated: false,
4698
+ frontmatterWritten: false,
4699
+ inferredFields: [],
4700
+ missingFields: ["spec.md n\xE3o encontrado"],
4701
+ errors: ["arquivo specs/" + specId + "/spec.md n\xE3o existe"]
4702
+ };
4703
+ }
4704
+ const originalContent = readFileSync15(specPath, "utf-8");
4705
+ if (hasFrontmatter(originalContent)) {
4706
+ return {
4707
+ specId,
4708
+ specPath,
4709
+ migrated: false,
4710
+ frontmatterWritten: false,
4711
+ inferredFields: [],
4712
+ missingFields: [],
4713
+ errors: ["j\xE1 possui frontmatter YAML \u2014 ignorado (idempotente)"]
4714
+ };
4715
+ }
4716
+ const { data, inferred, missing, errors } = extractLegacyMetadata2(originalContent, specId);
4717
+ const frontmatterYaml = generateFrontmatterYaml(data);
4718
+ let body = originalContent;
4719
+ body = body.replace(/^>\s*Item:.*$/gm, "").replace(/^>\s*Updated:.*$/gm, "").replace(/^>\s*Status:.*$/gm, "");
4720
+ body = body.replace(/^\n{2,}/, "\n");
4721
+ const newContent = frontmatterYaml + body;
4722
+ writeFileSync12(specPath, newContent, "utf-8");
4723
+ return {
4724
+ specId,
4725
+ specPath,
4726
+ migrated: true,
4727
+ frontmatterWritten: true,
4728
+ inferredFields: inferred,
4729
+ missingFields: missing,
4730
+ errors
4731
+ };
4732
+ }
4733
+ function migrateAllSpecsToFrontmatterV1(workspaceRoot) {
4734
+ const specsDir = join17(workspaceRoot, "specs");
4735
+ const entries = [];
4736
+ if (!existsSync17(specsDir)) {
4737
+ return {
4738
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
4739
+ workspaceRoot,
4740
+ totalSpecs: 0,
4741
+ migratedSpecs: 0,
4742
+ entries
4743
+ };
4744
+ }
4745
+ const specDirs = readdirSync9(specsDir);
4746
+ let migratedCount = 0;
4747
+ for (const specId of specDirs) {
4748
+ const specPath = join17(specsDir, specId, "spec.md");
4749
+ if (!existsSync17(specPath)) continue;
4750
+ const entry = migrateSpecToFrontmatterV1(workspaceRoot, specId);
4751
+ if (entry) {
4752
+ entries.push(entry);
4753
+ if (entry.migrated) migratedCount++;
4754
+ }
4755
+ }
4756
+ return {
4757
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
4758
+ workspaceRoot,
4759
+ totalSpecs: entries.length,
4760
+ migratedSpecs: migratedCount,
4761
+ entries
4762
+ };
4763
+ }
4764
+
4765
+ // src/commands/spec-migrate-frontmatter.ts
4766
+ function specMigrateFrontmatterCommand() {
4767
+ const cmd = new Command14("spec migrate-frontmatter").description(
4768
+ "Migra specs sem frontmatter YAML para o schema v1 (modo legado \u2192 frontmatter)"
4769
+ );
4770
+ cmd.option("--dry-run", "Mostra o que seria migrado sem escrever");
4771
+ cmd.action(async (options) => {
4772
+ const cwd = process.cwd();
4773
+ const letraDir = getLetraDir(cwd);
4774
+ if (!letraDir) {
4775
+ console.error("\u274C N\xE3o foi poss\xEDvel localizar o diret\xF3rio .letra. Execute dentro de um workspace Letra.");
4776
+ process.exit(1);
4777
+ }
4778
+ const workspaceRoot = process.env.LETRA_WORKSPACE_ROOT || cwd;
4779
+ const { results: beforeResults } = validateAllSpecsFrontmatter(workspaceRoot);
4780
+ const legacyCount = [...beforeResults.values()].filter(
4781
+ (r) => r.issues.some((i) => i.code === "LEGACY_NO_FRONTMATTER")
4782
+ ).length;
4783
+ if (legacyCount === 0) {
4784
+ console.log("\u2705 Todas as specs j\xE1 possuem frontmatter YAML. Nada a migrar.");
4785
+ return;
4786
+ }
4787
+ console.log(`
4788
+ \u{1F4CB} ${legacyCount} spec(s) sem frontmatter YAML detectada(s).`);
4789
+ if (options.dryRun) {
4790
+ console.log("\n\u{1F50D} MODO DRY-RUN \u2014 nada ser\xE1 escrito.\n");
4791
+ }
4792
+ const report = migrateAllSpecsToFrontmatterV1(workspaceRoot);
4793
+ console.log(`
4794
+ \u2550\u2550\u2550 RELAT\xD3RIO DE MIGRA\xC7\xC3O \u2550\u2550\u2550`);
4795
+ console.log(`Tempo: ${report.timestamp}`);
4796
+ console.log(`Workspace: ${report.workspaceRoot}`);
4797
+ console.log(`Specs analisadas: ${report.totalSpecs}`);
4798
+ console.log(`Migradas: ${report.migratedSpecs}`);
4799
+ console.log(``);
4800
+ for (const entry of report.entries) {
4801
+ if (!entry.migrated) {
4802
+ console.log(`\u23ED\uFE0F ${entry.specId}: j\xE1 possui frontmatter (ignorado)`);
4803
+ continue;
4804
+ }
4805
+ console.log(`
4806
+ \u2705 ${entry.specId}:`);
4807
+ console.log(` Caminho: ${entry.specPath}`);
4808
+ console.log(` Campos inferidos: ${entry.inferredFields.join(", ") || "nenhum"}`);
4809
+ if (entry.missingFields.length > 0) {
4810
+ console.log(` Campos ausentes: ${entry.missingFields.join(", ")}`);
4811
+ }
4812
+ if (entry.errors.length > 0) {
4813
+ console.log(` \u26A0 Erros: ${entry.errors.join("; ")}`);
4814
+ }
4815
+ }
4816
+ console.log(`
4817
+ \u2550\u2550\u2550 VALIDA\xC7\xC3O P\xD3S-MIGRA\xC7\xC3O \u2550\u2550\u2550`);
4818
+ const { results: afterResults } = validateAllSpecsFrontmatter(workspaceRoot);
4819
+ const errorsAfter = [...afterResults.values()].filter((r) => !r.valid).length;
4820
+ const warningsAfter = [...afterResults.values()].reduce(
4821
+ (acc, r) => acc + r.issues.filter((i) => i.severity === "warning").length,
4822
+ 0
4823
+ );
4824
+ console.log(`Errors: ${errorsAfter}`);
4825
+ console.log(`Warnings: ${warningsAfter}`);
4826
+ if (errorsAfter > 0) {
4827
+ console.log(`
4828
+ \u274C A migra\xE7\xE3o introduziu erros. Verifique os arquivos.`);
4829
+ process.exit(1);
4830
+ }
4831
+ if (options.dryRun) {
4832
+ console.log(`
4833
+ \u{1F50D} Modo dry-run: nada foi escrito.`);
4834
+ } else {
4835
+ console.log(`
4836
+ \u2705 Migra\xE7\xE3o conclu\xEDda com sucesso.`);
4837
+ }
4838
+ });
4839
+ return cmd;
4840
+ }
4841
+
4842
+ // src/commands/security.ts
4843
+ import { resolve as resolve33 } from "path";
4844
+ import { Command as Command15 } from "commander";
4845
+ function securityCommand() {
4846
+ const command = new Command15("security").description("Executar revis\xE3o de Security escopada por item");
4847
+ command.command("review <item-id>").requiredOption("--executor <executor-id>", "Executor externo").requiredOption("--expected-revision <revision>", "Direction revision returned by Letra").requiredOption("--reason <reason>", "Reason for the operation").option("--actor <actor>", "Identidade do actor", "security").option("--idempotency-key <key>", "Chave idempotente da opera\xE7\xE3o").action(async (itemId, options) => {
4848
+ const root = resolve33(process.cwd());
4849
+ const currentRevision = directionForOperation(root, { itemId }).revision;
4850
+ const result = await runSecurityReviewOperation(root, {
4851
+ itemId,
4852
+ executorId: options.executor,
4853
+ expectedRevision: options.expectedRevision || currentRevision,
4854
+ reason: options.reason,
4855
+ actor: options.actor,
4856
+ idempotencyKey: options.idempotencyKey
4857
+ });
4858
+ printJson(result);
4859
+ });
4860
+ return command;
4861
+ }
4862
+
3753
4863
  // src/index.ts
3754
4864
  var __dirname2 = fileURLToPath2(new URL(".", import.meta.url));
3755
- var pkg = JSON.parse(readFileSync13(join16(resolve30(__dirname2, ".."), "package.json"), "utf-8"));
3756
- var program = new Command12();
4865
+ var pkg = JSON.parse(readFileSync16(join18(resolve34(__dirname2, ".."), "package.json"), "utf-8"));
4866
+ var program = new Command16();
3757
4867
  program.name("letra").description("SDD-agnostic memory framework for AI coding agents").version(pkg.version);
3758
4868
  program.command("init [path]").option("--yes", "Skip prompts and use defaults").option("--serve", "Open web UI after init (starts flow serve)").option("--workspace <name>", "Create isolated workspace in ~/.letra/ (no local .letra/)").option("--no-tui", "Disable TUI wizard, use text prompts").description("Initialize .letra/ or workspace with templates").action((path, options) => init(path, { ...options }));
3759
4869
  program.command("setup [path]").option("--port <number>", "Port for the web UI", "3000").description("Open web UI setup wizard to configure a workspace").action(async (path, options) => {
3760
4870
  const port = Number.parseInt(options.port, 10) || 3e3;
3761
- const { execSync: execSync2 } = await import("child_process");
4871
+ const { execSync: execSync3 } = await import("child_process");
3762
4872
  const { createConnection } = await import("net");
3763
- const checkPort = (p) => new Promise((resolve31) => {
4873
+ const checkPort = (p) => new Promise((resolve35) => {
3764
4874
  const client = createConnection(p, "127.0.0.1", () => {
3765
4875
  client.end();
3766
- resolve31(true);
4876
+ resolve35(true);
3767
4877
  });
3768
- client.on("error", () => resolve31(false));
4878
+ client.on("error", () => resolve35(false));
3769
4879
  });
3770
4880
  const isRunning = await checkPort(port);
3771
4881
  const cmd = process.platform === "win32" ? "start" : process.platform === "darwin" ? "open" : "xdg-open";
3772
4882
  const setupUrl = `http://localhost:${port}/?setup=true`;
3773
4883
  if (isRunning) {
3774
4884
  try {
3775
- execSync2(`${cmd} "${setupUrl}"`, { stdio: "ignore" });
4885
+ execSync3(`${cmd} "${setupUrl}"`, { stdio: "ignore" });
3776
4886
  } catch {
3777
4887
  }
3778
4888
  console.log(`
@@ -3782,8 +4892,8 @@ program.command("setup [path]").option("--port <number>", "Port for the web UI",
3782
4892
  console.log(`
3783
4893
  Starting web UI on port ${port}...
3784
4894
  `);
3785
- const root = resolve30(process.cwd(), path ?? ".");
3786
- const { FlowServer } = await import("./flow-serve-G5MSSB3G.js");
4895
+ const root = resolve34(process.cwd(), path ?? ".");
4896
+ const { FlowServer } = await import("./flow-serve-LFILD3EV.js");
3787
4897
  const server = new FlowServer(root, port);
3788
4898
  try {
3789
4899
  await server.start();
@@ -3792,14 +4902,14 @@ program.command("setup [path]").option("--port <number>", "Port for the web UI",
3792
4902
  `);
3793
4903
  if (options.open !== false) {
3794
4904
  try {
3795
- execSync2(`${cmd} "${setupUrl}"`, { stdio: "ignore" });
4905
+ execSync3(`${cmd} "${setupUrl}"`, { stdio: "ignore" });
3796
4906
  } catch {
3797
4907
  }
3798
4908
  }
3799
- await new Promise((resolve31) => {
4909
+ await new Promise((resolve35) => {
3800
4910
  process.on("SIGINT", () => {
3801
4911
  server.stop();
3802
- resolve31();
4912
+ resolve35();
3803
4913
  });
3804
4914
  });
3805
4915
  } catch (err) {
@@ -3812,9 +4922,11 @@ program.command("status").description("Show workspace status or list workspaces"
3812
4922
  var specCmd = program.command("spec").description("Manage specs");
3813
4923
  specCmd.command("new <name>").option("--template <type>", "Template type: web-api, cli-tool, mobile-feature").description("Create a new spec from template").action((name, options) => specNew(name, { ...options }));
3814
4924
  specCmd.command("link <item-id> <spec-name>").description("Link an existing spec to an item").action((itemId, specName) => specLink(itemId, specName));
4925
+ specCmd.command("catalog [path]").option("--json", "Exibir a matriz completa em JSON").description("Gerar a matriz can\xF4nica de specs e itens").action((path, options) => specCatalog(path, options));
3815
4926
  program.command("lint [path]").description("Validate spec format and completeness").action(lint);
3816
4927
  program.command("check:ds [path]").description("Validate client conformance with Letra Design System").action(checkDs);
3817
- program.command("validate [path]").option("--watch", "Watch specs and re-validate on change").option("--format <type>", "Output format: text, github-annotation, junit").description("Check if artifacts meet acceptance criteria").action(async (path, options) => {
4928
+ program.command("validate [path]").option("--watch", "Watch specs and re-validate on change").option("--format <type>", "Output format: text, github-annotation, junit").option("--json", "Output results as JSON (equivalent to --format json)").description("Check if artifacts meet acceptance criteria").action(async (path, options) => {
4929
+ if (options.json) options.format = "json";
3818
4930
  await validate(path, { ...options });
3819
4931
  });
3820
4932
  program.command("diagnose [path]").description("Detect and fix drifts between specs, code, and workflow").action((path) => diagnose(path));
@@ -3824,7 +4936,7 @@ program.addCommand(directionCommand());
3824
4936
  program.addCommand(mcpCommand());
3825
4937
  program.addCommand(operationCommand());
3826
4938
  program.addCommand(decisionCommand());
3827
- program.command("push [path]").option("--dry-run", "Show what would be pushed without writing").description("Sync workspace artifacts to target repository").action((path, options) => import("./push-VJRSQGUD.js").then((m) => m.push(path, options)));
4939
+ program.command("push [path]").option("--dry-run", "Show what would be pushed without writing").description("Sync workspace artifacts to target repository").action((path, options) => import("./push-2ZCQSOHF.js").then((m) => m.push(path, options)));
3828
4940
  program.addCommand(flowCommand());
3829
4941
  program.addCommand(focus_default());
3830
4942
  program.addCommand(health_default());
@@ -3834,4 +4946,8 @@ program.addCommand(sitrep_default());
3834
4946
  program.addCommand(sync_default());
3835
4947
  program.addCommand(migrateCommand());
3836
4948
  program.addCommand(gateCommand());
4949
+ program.addCommand(doctorCommand());
4950
+ program.addCommand(specLintCommand());
4951
+ program.addCommand(specMigrateFrontmatterCommand());
4952
+ program.addCommand(securityCommand());
3837
4953
  program.parse();