@letra-ai/cli 0.6.1 → 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 (55) 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-KGQLHMGZ.js → chunk-MUCIMQAU.js} +1918 -757
  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-N22QOXUF.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 +84 -4
  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 +4 -3
  28. package/dist/harness/default/v0.2.0/gates/security-clear.yaml +1 -0
  29. package/dist/harness/default/v0.2.0/gates/spec-approved.yaml +3 -3
  30. package/dist/{health-record-YDVXEVLR.js → health-record-JO2ZTIMR.js} +2 -2
  31. package/dist/index.js +2237 -1104
  32. package/dist/{push-5JEYSXBY.js → push-2ZCQSOHF.js} +37 -49
  33. package/dist/server-WUYVNSH7.js +677 -0
  34. package/dist/service-SVEAXQBX.js +28 -0
  35. package/dist/service-TOBY3OHO.js +22 -0
  36. package/dist/service-USTAY5E3.js +62 -0
  37. package/dist/{session-log-WTQ5JBEN.js → session-log-X2Q4XKQN.js} +6 -2
  38. package/dist/specs-CQRB7LPA.js +21 -0
  39. package/dist/sync-LIVPQXEW.js +21 -0
  40. package/package.json +1 -1
  41. package/dist/chunk-4QDEU6KP.js +0 -2765
  42. package/dist/chunk-BTPFUKHG.js +0 -275
  43. package/dist/chunk-EDD55PWL.js +0 -119
  44. package/dist/chunk-ELBTIPYN.js +0 -256
  45. package/dist/chunk-IEFSLCJL.js +0 -837
  46. package/dist/chunk-MSF44WWE.js +0 -443
  47. package/dist/chunk-QIVKP3EY.js +0 -362
  48. package/dist/client/assets/index-BuABgOyz.js +0 -232
  49. package/dist/client/assets/index-CpseCZh9.css +0 -1
  50. package/dist/fallback-UXSZ4LNR.js +0 -47
  51. package/dist/flow-serve-MTB6KZMR.js +0 -19
  52. package/dist/focus-sync-3D3XWCTI.js +0 -17
  53. package/dist/server-FUP3APZA.js +0 -415
  54. package/dist/service-OGF7BMCQ.js +0 -21
  55. package/dist/sitrep-DJXTP3JO.js +0 -16
package/dist/index.js CHANGED
@@ -1,47 +1,63 @@
1
1
  #!/usr/bin/env node
2
- import {
3
- validate
4
- } from "./chunk-IEFSLCJL.js";
5
2
  import {
6
3
  buildActivityContext,
7
4
  flowServeAction,
8
5
  migrateCommand,
9
6
  pulse_default,
10
- sync_default,
7
+ sitrep_default
8
+ } from "./chunk-MUCIMQAU.js";
9
+ import {
11
10
  validateSpecStructure
12
- } from "./chunk-KGQLHMGZ.js";
11
+ } from "./chunk-POGWTSEA.js";
12
+ import {
13
+ sync_default
14
+ } from "./chunk-HC24XMPZ.js";
13
15
  import {
14
16
  GateChecker,
17
+ activityOperation,
18
+ completeAcOperation,
19
+ createItemOperation,
20
+ directionForOperation,
21
+ directionForRunAwareOperation,
22
+ migrateRunWorkflowOperation,
23
+ requestHandoffOperation,
24
+ requestPassageOperation,
25
+ rollbackHandoffOperation,
26
+ runSecurityReviewOperation,
27
+ validate,
15
28
  writeFocusWithRecommendations
16
- } from "./chunk-ELBTIPYN.js";
17
- import {
18
- resolveActiveFlow
19
- } from "./chunk-MSF44WWE.js";
20
- import {
21
- sitrep_default
22
- } from "./chunk-BTPFUKHG.js";
29
+ } from "./chunk-TNF7XTFG.js";
23
30
  import {
24
31
  DEFAULT_HARNESS_VERSION,
25
32
  DiagnosticEngine,
33
+ clearFocusFile,
34
+ createWorkflowDefinition,
35
+ createWorkflowDraft,
26
36
  flowInitAction,
27
37
  generateAdapters,
38
+ getActiveWorkflowVersion,
39
+ getWorkflowDraft,
40
+ inspectWorkspaceIntegrity,
41
+ listWorkflowDefinitions,
42
+ listWorkflowDraftRevisions,
43
+ listWorkflowVersions,
28
44
  loadHarness,
29
45
  loadWorkflow,
46
+ publishWorkflowDraft,
47
+ resolveActiveFlow,
48
+ resolveAgentDirection,
49
+ resolveDirection,
30
50
  resolveHarnessRoot,
51
+ resolveLocalIdentity,
52
+ rollbackWorkflowVersion,
31
53
  saveWorkflow,
54
+ signLocalOperation,
55
+ validateWorkflowContent,
32
56
  writeWorkflow
33
- } from "./chunk-4QDEU6KP.js";
34
- import {
35
- logEntry,
36
- pruneSessionLog,
37
- queryLog
38
- } from "./chunk-BKAUN5QH.js";
57
+ } from "./chunk-2GRNAFBQ.js";
39
58
  import {
40
59
  supportedAdapterTools
41
60
  } from "./chunk-JMIC5NKB.js";
42
- import {
43
- clearFocusFile
44
- } from "./chunk-EDD55PWL.js";
45
61
  import {
46
62
  ackEntry,
47
63
  dismissEntry,
@@ -50,7 +66,15 @@ import {
50
66
  loadHealthRecord,
51
67
  mergeScanResults,
52
68
  saveHealthRecord
53
- } 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";
54
78
  import {
55
79
  LINK_FILE,
56
80
  clearWorkspaceCache,
@@ -61,14 +85,14 @@ import {
61
85
  initWorkspace,
62
86
  listWorkspaces,
63
87
  loadWorkspaceInfo
64
- } from "./chunk-6HSUVCTR.js";
88
+ } from "./chunk-YAQ2TKSK.js";
65
89
  import "./chunk-PDX44BCA.js";
66
90
 
67
91
  // src/index.ts
68
- import { readFileSync as readFileSync13 } from "fs";
69
- 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";
70
94
  import { fileURLToPath as fileURLToPath2 } from "url";
71
- import { Command as Command12 } from "commander";
95
+ import { Command as Command16 } from "commander";
72
96
 
73
97
  // src/commands/decision.ts
74
98
  import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "fs";
@@ -143,41 +167,20 @@ What are the trade-offs? What does this enable or prevent?
143
167
 
144
168
  // src/commands/flow.ts
145
169
  import { Command as Command2 } from "commander";
146
- import chalk16 from "chalk";
170
+ import chalk17 from "chalk";
171
+ import { resolve as resolve17 } from "path";
147
172
 
148
173
  // src/commands/flow-backlog.ts
149
- import { existsSync as existsSync2 } from "fs";
150
- import { resolve as resolve2, join as join2 } from "path";
174
+ import { resolve as resolve2 } from "path";
151
175
  import chalk2 from "chalk";
152
- function now() {
153
- return (/* @__PURE__ */ new Date()).toISOString();
154
- }
155
- function nextItemId(workflow) {
156
- let max = 0;
157
- for (const item of workflow.items) {
158
- const match = item.id.match(/^ITEM-(\d+)$/);
159
- if (match) {
160
- const num = Number.parseInt(match[1], 10);
161
- if (num > max) max = num;
162
- }
163
- }
164
- return `ITEM-${max + 1}`;
165
- }
166
176
  function workflowExists(root) {
167
177
  return loadWorkflow(root);
168
178
  }
169
- function backlogAdd(root, description, spec) {
179
+ async function backlogAdd(root, description, spec, requestedId) {
170
180
  if (!description) {
171
181
  console.log(chalk2.red("Description is required"));
172
182
  process.exit(1);
173
183
  }
174
- if (spec) {
175
- const specsDir = join2(getLetraDir(root), "specs", spec);
176
- if (!existsSync2(specsDir)) {
177
- console.log(chalk2.red(`Spec "${spec}" not found at .letra/specs/${spec}/`));
178
- return;
179
- }
180
- }
181
184
  const workflow = workflowExists(root);
182
185
  if (!workflow) {
183
186
  console.log(chalk2.red("No workflow found. Run 'letra flow init --quick' first"));
@@ -187,31 +190,21 @@ function backlogAdd(root, description, spec) {
187
190
  console.log(chalk2.red("Workflow has no stages defined"));
188
191
  process.exit(1);
189
192
  }
190
- const firstStage = workflow.stages[0].id;
191
- const item = {
192
- id: nextItemId(workflow),
193
+ const direction = resolveDirection(root);
194
+ const operation = await createItemOperation(root, {
195
+ id: requestedId,
193
196
  description,
194
- stage: firstStage,
195
- createdAt: now(),
196
- spec: spec || void 0
197
- };
198
- if (spec) {
199
- if (!workflow.specLinks) workflow.specLinks = {};
200
- if (!workflow.specLinks[spec]) {
201
- workflow.specLinks[spec] = { path: `.letra/specs/${spec}/spec.md` };
202
- }
203
- }
204
- workflow.items.push(item);
205
- workflow.updatedAt = now();
206
- writeWorkflow(root, {
207
- workflow,
208
- source: "flow-backlog",
209
- primaryItemId: item.id,
210
- skipSitrep: true
197
+ spec,
198
+ expectedRevision: direction.revision,
199
+ reason: "Cria\xE7\xE3o de item pelo backlog da CLI.",
200
+ actor: resolveLocalIdentity(root).id
211
201
  });
212
- console.log(
213
- ` ${chalk2.green("\u2713")} Item ${chalk2.cyan(item.id)} added to ${chalk2.cyan(workflow.stages[0].name)}`
214
- );
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)}`);
215
208
  }
216
209
  function backlogList(root) {
217
210
  const workflow = workflowExists(root);
@@ -242,9 +235,9 @@ function backlogList(root) {
242
235
  }
243
236
  console.log("");
244
237
  }
245
- function backlogActionAdd(targetPath, description, spec) {
238
+ function backlogActionAdd(targetPath, description, spec, requestedId) {
246
239
  const root = resolve2(process.cwd(), targetPath || ".");
247
- backlogAdd(root, description, spec);
240
+ return backlogAdd(root, description, spec, requestedId);
248
241
  }
249
242
  function backlogActionList(targetPath) {
250
243
  const root = resolve2(process.cwd(), targetPath || ".");
@@ -252,8 +245,8 @@ function backlogActionList(targetPath) {
252
245
  }
253
246
 
254
247
  // src/commands/flow-board.ts
255
- import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
256
- 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";
257
250
  import chalk3 from "chalk";
258
251
  function resolveBoardStages(workflow, resolvedStages) {
259
252
  const stages = resolvedStages?.length ? resolvedStages.map((stage) => ({ ...stage })) : workflow.stages.map((stage) => ({ ...stage }));
@@ -292,10 +285,10 @@ function flowBoard(root) {
292
285
  `);
293
286
  }
294
287
  const boardStages = resolveBoardStages(workflow, resolveActiveFlow(root).flow?.stages);
295
- const healthPath = join3(getLetraDir(root), "health-record.json");
288
+ const healthPath = join2(getLetraDir(root), "health-record.json");
296
289
  const itemAlerts = /* @__PURE__ */ new Map();
297
290
  try {
298
- if (existsSync3(healthPath)) {
291
+ if (existsSync2(healthPath)) {
299
292
  const health = JSON.parse(readFileSync2(healthPath, "utf-8"));
300
293
  const entries = health.entries || [];
301
294
  for (const entry of entries) {
@@ -332,8 +325,8 @@ function flowBoard(root) {
332
325
  if (item.spec) {
333
326
  const specLink2 = workflow.specLinks?.[item.spec];
334
327
  if (specLink2) {
335
- const specPath = join3(root, specLink2.path);
336
- 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?");
337
330
  } else {
338
331
  specInfo = chalk3.red("\u26A0reg?");
339
332
  }
@@ -355,10 +348,10 @@ function flowBoardAction(targetPath) {
355
348
  }
356
349
 
357
350
  // src/commands/flow-edit-diff.ts
358
- import { existsSync as existsSync4, readFileSync as readFileSync3, readdirSync as readdirSync2, writeFileSync as writeFileSync2 } from "fs";
359
- 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";
360
353
  import chalk4 from "chalk";
361
- function now2() {
354
+ function now() {
362
355
  return (/* @__PURE__ */ new Date()).toISOString();
363
356
  }
364
357
  function normalizeVersion(v) {
@@ -373,8 +366,8 @@ function incrementVersion(v) {
373
366
  return parts.join(".");
374
367
  }
375
368
  function loadBackup(root, version) {
376
- const path = join4(getLetraDir(root), `workflow.v${version}.json`);
377
- if (!existsSync4(path)) return null;
369
+ const path = join3(getLetraDir(root), `workflow.v${version}.json`);
370
+ if (!existsSync3(path)) return null;
378
371
  try {
379
372
  return JSON.parse(readFileSync3(path, "utf-8"));
380
373
  } catch {
@@ -390,7 +383,7 @@ function loadVersion(root, version) {
390
383
  }
391
384
  function getLatestBackupVersion(root) {
392
385
  const dir = getLetraDir(root);
393
- if (!existsSync4(dir)) return null;
386
+ if (!existsSync3(dir)) return null;
394
387
  const files = readdirSync2(dir).filter((f) => f.startsWith("workflow.v") && f.endsWith(".json"));
395
388
  if (files.length === 0) return null;
396
389
  const versions = files.map((f) => f.replace("workflow.v", "").replace(".json", ""));
@@ -405,9 +398,9 @@ function getLatestBackupVersion(root) {
405
398
  return versions[versions.length - 1];
406
399
  }
407
400
  function backupFilePath(root, version) {
408
- return join4(getLetraDir(root), `workflow.v${version}.json`);
401
+ return join3(getLetraDir(root), `workflow.v${version}.json`);
409
402
  }
410
- function flowEdit(root, options) {
403
+ async function flowEdit(root, options) {
411
404
  const workflow = loadWorkflow(root);
412
405
  if (!workflow) {
413
406
  console.log(chalk4.yellow("No workflow found. Run 'letra flow init --quick' first"));
@@ -415,7 +408,7 @@ function flowEdit(root, options) {
415
408
  }
416
409
  const currentVersion = normalizeVersion(workflow.version);
417
410
  const backupPath = backupFilePath(root, currentVersion);
418
- if (!existsSync4(backupPath)) {
411
+ if (!existsSync3(backupPath)) {
419
412
  writeFileSync2(backupPath, JSON.stringify(workflow, null, 2));
420
413
  }
421
414
  if (options.name !== void 0) {
@@ -425,8 +418,8 @@ function flowEdit(root, options) {
425
418
  workflow.description = options.desc;
426
419
  }
427
420
  workflow.version = incrementVersion(workflow.version);
428
- workflow.updatedAt = now2();
429
- writeWorkflow(root, { workflow, source: "flow-edit", skipSitrep: true });
421
+ workflow.updatedAt = now();
422
+ await writeWorkflow(root, { workflow, source: "flow-edit", skipSitrep: true });
430
423
  console.log(` ${chalk4.green("\u2713")} Workflow updated to v${workflow.version}`);
431
424
  if (options.name !== void 0) {
432
425
  console.log(` Name: ${chalk4.cyan(options.name)}`);
@@ -547,9 +540,9 @@ function flowDiff(root, v1, v2) {
547
540
  for (const line of lines) console.log(line);
548
541
  }
549
542
  }
550
- function flowEditAction(targetPath, options) {
543
+ async function flowEditAction(targetPath, options) {
551
544
  const root = resolve4(process.cwd(), targetPath || ".");
552
- flowEdit(root, options);
545
+ await flowEdit(root, options);
553
546
  }
554
547
  function flowDiffAction(targetPath, v1, v2) {
555
548
  const root = resolve4(process.cwd(), targetPath || ".");
@@ -557,8 +550,8 @@ function flowDiffAction(targetPath, v1, v2) {
557
550
  }
558
551
 
559
552
  // src/commands/flow-export-import.ts
560
- import { existsSync as existsSync5, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "fs";
561
- 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";
562
555
  import chalk5 from "chalk";
563
556
  function flowExport(root, options) {
564
557
  const workflow = loadWorkflow(root);
@@ -573,11 +566,11 @@ function flowExportAction(targetPath, options) {
573
566
  const root = resolve5(process.cwd(), targetPath || ".");
574
567
  flowExport(root, options);
575
568
  }
576
- function now3() {
569
+ function now2() {
577
570
  return (/* @__PURE__ */ new Date()).toISOString();
578
571
  }
579
572
  function flowImport(root, filePath) {
580
- if (!existsSync5(filePath)) {
573
+ if (!existsSync4(filePath)) {
581
574
  console.log(chalk5.red(`File not found: ${filePath}`));
582
575
  process.exit(1);
583
576
  }
@@ -601,31 +594,34 @@ function flowImport(root, filePath) {
601
594
  const imported = parsed;
602
595
  const existingWorkflow = loadWorkflow(root);
603
596
  if (existingWorkflow) {
604
- const backup = join5(getLetraDir(root), `workflow.v${existingWorkflow.version}.json`);
605
- if (!existsSync5(backup)) {
597
+ const backup = join4(getLetraDir(root), `workflow.v${existingWorkflow.version}.json`);
598
+ if (!existsSync4(backup)) {
606
599
  writeFileSync3(backup, JSON.stringify(existingWorkflow, null, 2));
607
600
  console.log(
608
601
  chalk5.gray(`Backup saved: .letra/workflow.v${existingWorkflow.version}.json`)
609
602
  );
610
603
  }
611
604
  }
612
- imported.createdAt = now3();
613
- imported.updatedAt = now3();
614
- writeWorkflow(root, { workflow: imported, source: "flow-import", skipSitrep: true });
615
- 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
+ );
616
612
  }
617
- function flowImportAction(targetPath, filePath) {
613
+ async function flowImportAction(targetPath, filePath) {
618
614
  const root = resolve5(process.cwd(), targetPath || ".");
619
- flowImport(root, filePath);
615
+ await flowImport(root, filePath);
620
616
  }
621
617
 
622
618
  // src/commands/flow-import-issues.ts
623
619
  import { resolve as resolve6 } from "path";
624
620
  import chalk6 from "chalk";
625
- function now4() {
621
+ function now3() {
626
622
  return (/* @__PURE__ */ new Date()).toISOString();
627
623
  }
628
- function nextItemId2(workflow) {
624
+ function nextItemId(workflow) {
629
625
  let max = 0;
630
626
  for (const item of workflow.items) {
631
627
  const match = item.id.match(/^ITEM-(\d+)$/);
@@ -702,17 +698,17 @@ async function backlogImportGitHub(root, repo, options) {
702
698
  const labels = issue.labels?.map((l) => l.name).join(", ") || "";
703
699
  const description = labels ? `[${issue.number}] ${issue.title} (${labels})` : `[${issue.number}] ${issue.title}`;
704
700
  const item = {
705
- id: nextItemId2(workflow),
701
+ id: nextItemId(workflow),
706
702
  description,
707
703
  stage: firstStage,
708
- createdAt: now4(),
704
+ createdAt: now3(),
709
705
  source: "github",
710
706
  sourceUrl: issue.html_url
711
707
  };
712
708
  workflow.items.push(item);
713
709
  imported++;
714
710
  }
715
- workflow.updatedAt = now4();
711
+ workflow.updatedAt = now3();
716
712
  writeWorkflow(root, { workflow, source: "flow-import", skipSitrep: true, quiet: true });
717
713
  console.log(
718
714
  ` ${chalk6.green("\u2713")} Imported ${chalk6.cyan(String(imported))} issue${imported !== 1 ? "s" : ""} from ${chalk6.cyan(repo)}`
@@ -786,17 +782,17 @@ async function backlogImportLinear(root, team, options) {
786
782
  for (const issue of issues) {
787
783
  const description = `${issue.identifier} ${issue.title}`;
788
784
  const item = {
789
- id: nextItemId2(workflow),
785
+ id: nextItemId(workflow),
790
786
  description,
791
787
  stage: firstStage,
792
- createdAt: now4(),
788
+ createdAt: now3(),
793
789
  source: "linear",
794
790
  sourceUrl: issue.url
795
791
  };
796
792
  workflow.items.push(item);
797
793
  imported++;
798
794
  }
799
- workflow.updatedAt = now4();
795
+ workflow.updatedAt = now3();
800
796
  writeWorkflow(root, { workflow, source: "flow-import", skipSitrep: true, quiet: true });
801
797
  console.log(
802
798
  ` ${chalk6.green("\u2713")} Imported ${chalk6.cyan(String(imported))} issue${imported !== 1 ? "s" : ""} from Linear team ${chalk6.cyan(team)}`
@@ -818,568 +814,111 @@ async function backlogImportLinearAction(targetPath, team, options) {
818
814
  }
819
815
 
820
816
  // src/commands/flow-move.ts
821
- import { existsSync as existsSync7, readFileSync as readFileSync6 } from "fs";
822
- import { join as join7, resolve as resolve7 } from "path";
817
+ import { resolve as resolve7 } from "path";
823
818
  import chalk7 from "chalk";
824
-
825
- // src/phases/runner.ts
826
- import { execSync } from "child_process";
827
- import { existsSync as existsSync6, mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync4 } from "fs";
828
- import { join as join6 } from "path";
829
- var PhaseActionRunner = class {
830
- execPhase(root, item, phaseDef) {
831
- if (!phaseDef.actions || phaseDef.actions.length === 0) {
832
- 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;
833
839
  }
834
- const checker = new GateChecker(root);
835
- const results = [];
836
- for (const action of phaseDef.actions) {
837
- try {
838
- switch (action.type) {
839
- case "command": {
840
- const output = execSync(action.cmd, {
841
- cwd: root,
842
- timeout: 3e4,
843
- stdio: "pipe"
844
- });
845
- const label = `command: ${action.cmd}`;
846
- results.push(label);
847
- logEntry(root, "system", `action:${label}`, {
848
- itemId: item.id,
849
- details: { phase: phaseDef.id }
850
- });
851
- break;
852
- }
853
- case "agent-prompt": {
854
- const promptDir = getLetraDir(root);
855
- if (!existsSync6(promptDir)) mkdirSync2(promptDir, { recursive: true });
856
- const content = [
857
- `# Phase Prompt: ${phaseDef.label}`,
858
- "",
859
- action.prompt,
860
- "",
861
- "---",
862
- `Item: ${item.id}`,
863
- `Phase: ${phaseDef.id}`
864
- ].join("\n");
865
- writeFileSync4(join6(getLetraDir(root), "phase-prompt.md"), content, "utf-8");
866
- const label = `agent-prompt: ${action.prompt}`;
867
- results.push(label);
868
- logEntry(root, "system", `action:${label}`, {
869
- itemId: item.id,
870
- details: { phase: phaseDef.id }
871
- });
872
- break;
873
- }
874
- case "generate-report": {
875
- const reportDir = join6(getLetraDir(root), "reports");
876
- if (!existsSync6(reportDir)) mkdirSync2(reportDir, { recursive: true });
877
- const reportContent = [
878
- `# Report: ${item.id} - ${phaseDef.label}`,
879
- `Generated: ${(/* @__PURE__ */ new Date()).toISOString()}`,
880
- `Template: ${action.template}`
881
- ].join("\n");
882
- const reportPath = join6(reportDir, `${item.id}-${phaseDef.id}.md`);
883
- writeFileSync4(reportPath, reportContent, "utf-8");
884
- const label = `generate-report: ${action.template}`;
885
- results.push(label);
886
- logEntry(root, "system", `action:${label}`, {
887
- itemId: item.id,
888
- details: { phase: phaseDef.id }
889
- });
890
- break;
891
- }
892
- case "notify-human": {
893
- logEntry(root, "system", `action:notify-human: ${action.message}`, {
894
- itemId: item.id,
895
- details: { phase: phaseDef.id }
896
- });
897
- const notifyPath = join6(getLetraDir(root), "human-notify.md");
898
- writeFileSync4(
899
- notifyPath,
900
- `# Human Notification
901
-
902
- ${action.message}
903
-
904
- Item: ${item.id}
905
- Phase: ${phaseDef.id}`,
906
- "utf-8"
907
- );
908
- const label = `notify-human: ${action.message}`;
909
- results.push(label);
910
- break;
911
- }
912
- case "wait-human": {
913
- const gateId = action.gate ?? "";
914
- const gateResult = checker.check(gateId, item);
915
- if (!gateResult.allowed) {
916
- logEntry(
917
- root,
918
- "system",
919
- `action:wait-human gate "${gateId}" blocking`,
920
- {
921
- itemId: item.id,
922
- details: { gate: gateId, phase: phaseDef.id }
923
- }
924
- );
925
- return {
926
- ok: false,
927
- error: gateResult.reason?.includes("humana") ? `Gate "${gateId}" not approved` : gateResult.reason ?? `Gate "${gateId}" not approved`,
928
- actions: results
929
- };
930
- }
931
- const label = `wait-human: ${gateId} (approved)`;
932
- results.push(label);
933
- break;
934
- }
935
- }
936
- } catch (e) {
937
- const msg = `Action "${action.type}" failed: ${e.message}`;
938
- logEntry(root, "system", `action:error ${msg}`, {
939
- itemId: item.id,
940
- details: { phase: phaseDef.id }
941
- });
942
- return { ok: false, error: msg, actions: results };
943
- }
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;
944
844
  }
945
- return { ok: true, actions: results };
845
+ targetStageInput = next.id;
946
846
  }
947
- };
948
-
949
- // src/phases/engine.ts
950
- function getStagePhases(workflow, stageId) {
951
- const stage = workflow.stages.find((s) => s.id === stageId);
952
- if (!stage) return null;
953
- return stage.phases ?? null;
954
- }
955
- function getPhaseDef(phases, phaseId) {
956
- return phases.states[phaseId] ?? null;
957
- }
958
- function enterStage(workflow, item) {
959
- const phases = getStagePhases(workflow, item.stage);
960
- if (!phases) {
961
- item.currentPhase = void 0;
962
- 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;
963
851
  }
964
- const initial = phases.initialState;
965
- if (!phases.states[initial]) {
966
- return {
967
- ok: false,
968
- error: `Initial phase "${initial}" not defined in stage "${item.stage}"`
969
- };
852
+ if (item.stage === targetStageId) {
853
+ console.log(chalk7.yellow(`Item ${itemId} is already in stage "${targetStageId}"`));
854
+ return true;
970
855
  }
971
- item.currentPhase = initial;
972
- return {
973
- ok: true,
974
- phase: initial,
975
- triggeredActions: ["enterStage"],
976
- triggeredAutoTransition: false
977
- };
978
- }
979
- var _runner = new PhaseActionRunner();
980
- function transitionPhase(root, workflow, item, targetPhaseId) {
981
- const phases = getStagePhases(workflow, item.stage);
982
- if (!phases) {
983
- 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;
984
861
  }
985
- const currentDef = item.currentPhase ? getPhaseDef(phases, item.currentPhase) : null;
986
- const transition = currentDef?.transitions?.find((t) => t.target === targetPhaseId);
987
- if (targetPhaseId === "__EXIT__") {
988
- if (!transition) {
989
- const allowed = (currentDef?.transitions ?? []).map((t) => t.target).join(", ");
990
- return {
991
- ok: false,
992
- error: `Transition from "${item.currentPhase}" to "__EXIT__" not allowed. Allowed: ${allowed || "none"}`
993
- };
994
- }
995
- item.currentPhase = void 0;
996
- 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;
997
868
  }
998
- if (!phases.states[targetPhaseId]) {
999
- 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;
1000
872
  }
1001
- if (currentDef && !transition) {
1002
- const allowed = (currentDef.transitions ?? []).map((t) => t.target).join(", ");
1003
- return {
1004
- ok: false,
1005
- error: `Transition from "${item.currentPhase}" to "${targetPhaseId}" not allowed. Allowed: ${allowed || "none"}`
1006
- };
1007
- }
1008
- item.currentPhase = targetPhaseId;
1009
- const targetDef = getPhaseDef(phases, targetPhaseId);
1010
- let actions = [];
1011
- if (root && targetDef) {
1012
- const result = _runner.execPhase(root, item, targetDef);
1013
- actions = result.actions;
1014
- if (!result.ok) {
1015
- return {
1016
- ok: false,
1017
- error: result.error,
1018
- phase: item.currentPhase,
1019
- triggeredActions: actions
1020
- };
1021
- }
1022
- } else {
1023
- actions = (targetDef?.actions ?? []).map((a) => {
1024
- if (a.type === "agent-prompt") return `agent-prompt: ${a.prompt}`;
1025
- if (a.type === "command") return `command: ${a.cmd}`;
1026
- if (a.type === "generate-report") return `generate-report: ${a.template}`;
1027
- if (a.type === "notify-human") return `notify-human: ${a.message}`;
1028
- if (a.type === "wait-human") return `wait-human: ${a.gate}`;
1029
- return "unknown action";
1030
- });
1031
- }
1032
- let triggeredAutoTransition = false;
1033
- if (transition?.auto) {
1034
- const nextAuto = targetDef?.transitions?.find((t) => t.auto);
1035
- if (nextAuto && phases.states[nextAuto.target]) {
1036
- item.currentPhase = nextAuto.target;
1037
- triggeredAutoTransition = true;
1038
- }
1039
- }
1040
- return {
1041
- ok: true,
1042
- phase: item.currentPhase,
1043
- triggeredActions: actions,
1044
- triggeredAutoTransition
1045
- };
1046
- }
1047
-
1048
- // src/phases/autopilot.ts
1049
- var MAX_AUTO_TRANSITIONS = 10;
1050
- var runner = new PhaseActionRunner();
1051
- function getAutoTarget(workflow, item) {
1052
- const phases = getStagePhases(workflow, item.stage);
1053
- if (!phases || !item.currentPhase) return null;
1054
- const def = getPhaseDef(phases, item.currentPhase);
1055
- if (!def) return null;
1056
- const autoTrans = (def.transitions ?? []).find((t) => t.auto);
1057
- return autoTrans?.target ?? null;
1058
- }
1059
- var PhaseAutoPilot = class {
1060
- transitionsApplied = 0;
1061
- async run(root, workflow, item) {
1062
- this.transitionsApplied = 0;
1063
- if (!item.currentPhase) {
1064
- logEntry(root, "system", `autopilot:${item.id} no current phase \u2014 nothing to do`, {
1065
- itemId: item.id
1066
- });
1067
- return { ok: true, finalPhase: void 0, transitionsApplied: 0 };
1068
- }
1069
- logEntry(
1070
- root,
1071
- "system",
1072
- `autopilot:starting for ${item.id} from phase "${item.currentPhase}"`,
1073
- { itemId: item.id }
1074
- );
1075
- while (this.transitionsApplied < MAX_AUTO_TRANSITIONS) {
1076
- const autoTarget = getAutoTarget(workflow, item);
1077
- if (!autoTarget) {
1078
- logEntry(
1079
- root,
1080
- "system",
1081
- `autopilot:${item.id} stopped at phase "${item.currentPhase}" \u2014 no auto-transition`,
1082
- {
1083
- itemId: item.id
1084
- }
1085
- );
1086
- return {
1087
- ok: true,
1088
- finalPhase: item.currentPhase,
1089
- transitionsApplied: this.transitionsApplied
1090
- };
1091
- }
1092
- const phases = getStagePhases(workflow, item.stage);
1093
- const phaseDef = item.currentPhase && phases ? getPhaseDef(phases, item.currentPhase) : null;
1094
- if (phaseDef) {
1095
- const actionResult = runner.execPhase(root, item, phaseDef);
1096
- if (!actionResult.ok) {
1097
- logEntry(
1098
- root,
1099
- "system",
1100
- `autopilot:${item.id} stopped \u2014 action failed: ${actionResult.error}`,
1101
- {
1102
- itemId: item.id
1103
- }
1104
- );
1105
- return {
1106
- ok: false,
1107
- error: actionResult.error,
1108
- finalPhase: item.currentPhase,
1109
- transitionsApplied: this.transitionsApplied
1110
- };
1111
- }
1112
- }
1113
- const prevPhase = item.currentPhase;
1114
- const result = transitionPhase(root, workflow, item, autoTarget);
1115
- if (!result.ok) {
1116
- logEntry(
1117
- root,
1118
- "system",
1119
- `autopilot:${item.id} transition failed \u2014 ${result.error}`,
1120
- { itemId: item.id }
1121
- );
1122
- return {
1123
- ok: false,
1124
- error: result.error,
1125
- finalPhase: prevPhase,
1126
- transitionsApplied: this.transitionsApplied
1127
- };
1128
- }
1129
- this.transitionsApplied++;
1130
- logEntry(
1131
- root,
1132
- "system",
1133
- `autopilot:${item.id} ${prevPhase} \u2192 ${item.currentPhase || "__EXIT__"}`,
1134
- {
1135
- itemId: item.id
1136
- }
1137
- );
1138
- if (!item.currentPhase) {
1139
- logEntry(root, "system", `autopilot:${item.id} exited phase system`, {
1140
- itemId: item.id
1141
- });
1142
- return {
1143
- ok: true,
1144
- finalPhase: void 0,
1145
- transitionsApplied: this.transitionsApplied
1146
- };
1147
- }
1148
- }
1149
- const msg = "Auto-loop limit exceeded";
1150
- logEntry(root, "system", `autopilot:${item.id} ${msg}`, { itemId: item.id });
1151
- return {
1152
- ok: false,
1153
- error: msg,
1154
- finalPhase: item.currentPhase,
1155
- transitionsApplied: this.transitionsApplied
1156
- };
1157
- }
1158
- };
1159
- async function autopilotRun(root, workflow, item) {
1160
- const pilot = new PhaseAutoPilot();
1161
- return pilot.run(root, workflow, item);
1162
- }
1163
- function canAutopilot(workflow, item) {
1164
- if (!item.currentPhase) return false;
1165
- const phases = getStagePhases(workflow, item.stage);
1166
- if (!phases) return false;
1167
- const def = getPhaseDef(phases, item.currentPhase);
1168
- if (!def) return false;
1169
- return (def.transitions ?? []).some((t) => t.auto);
1170
- }
1171
-
1172
- // src/commands/flow-move.ts
1173
- function now5() {
1174
- return (/* @__PURE__ */ new Date()).toISOString();
1175
- }
1176
- function resolveStage(workflow, input) {
1177
- const lower = input.toLowerCase();
1178
- for (const stage of workflow.stages) {
1179
- if (stage.id === lower) return stage.id;
1180
- if (stage.name.toLowerCase() === lower) return stage.id;
1181
- }
1182
- return null;
1183
- }
1184
- async function flowMove(root, itemId, targetStageInput, options) {
1185
- const workflow = loadWorkflow(root);
1186
- if (!workflow) {
1187
- console.log(chalk7.red("No workflow found. Run 'letra flow init --quick' first"));
1188
- process.exit(1);
1189
- }
1190
- 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());
1191
- if (!item) {
1192
- console.log(chalk7.red(`Item "${itemId}" not found`));
1193
- process.exit(1);
1194
- }
1195
- if (options?.auto) {
1196
- const currentStage = workflow.stages.find((s) => s.id === item.stage);
1197
- if (!currentStage) {
1198
- console.log(chalk7.red(`Stage "${item.stage}" not found in workflow`));
1199
- process.exit(1);
1200
- return;
1201
- }
1202
- const nextStage = workflow.stages.filter((s) => s.order > currentStage.order).sort((a, b) => a.order - b.order)[0];
1203
- if (!nextStage) {
1204
- console.log(
1205
- chalk7.yellow(`Item ${itemId} is already at the last stage (${currentStage.name})`)
1206
- );
1207
- return;
1208
- }
1209
- targetStageInput = nextStage.id;
1210
- if (!options?.force && item.spec) {
1211
- const specFile = join7(getLetraDir(root), "specs", item.spec, "spec.md");
1212
- if (existsSync7(specFile)) {
1213
- const content = readFileSync6(specFile, "utf-8");
1214
- const pendingACs = content.match(/^- \[ \]/gm) || [];
1215
- if (pendingACs.length > 0) {
1216
- console.log(
1217
- chalk7.yellow(
1218
- `\u26A0 Item ${itemId} has ${pendingACs.length} pending AC(s) in "${item.spec}"`
1219
- )
1220
- );
1221
- console.log(
1222
- chalk7.yellow(" Use --force to move anyway, or complete ACs first.")
1223
- );
1224
- return;
1225
- }
1226
- const doneACs = content.match(/^- \[[xX]\]/gm) || [];
1227
- if (doneACs.length > 0) {
1228
- const acLogEntries = queryLog(root, { itemId, action: "ac_done", limit: 999 });
1229
- if (acLogEntries.length < doneACs.length) {
1230
- console.log(
1231
- chalk7.yellow(
1232
- `\u26A0 ${doneACs.length - acLogEntries.length} AC(s) marked [x] without "ac done" log entry.`
1233
- )
1234
- );
1235
- console.log(
1236
- chalk7.yellow(" Run letra ac done <ID> for each completed AC.")
1237
- );
1238
- }
1239
- }
1240
- }
1241
- }
1242
- }
1243
- if (!options?.auto && !options?.force && item.spec) {
1244
- const specFile = join7(getLetraDir(root), "specs", item.spec, "spec.md");
1245
- if (existsSync7(specFile)) {
1246
- const content = readFileSync6(specFile, "utf-8");
1247
- const pendingACs = content.match(/^- \[ \]/gm) || [];
1248
- if (pendingACs.length > 0) {
1249
- console.log(
1250
- chalk7.yellow(
1251
- `\u26A0 Item ${itemId} has ${pendingACs.length} pending AC(s) in "${item.spec}"`
1252
- )
1253
- );
1254
- console.log(chalk7.yellow(" Use --force to move anyway, or complete ACs first."));
1255
- return;
1256
- }
1257
- const doneACs = content.match(/^- \[[xX]\]/gm) || [];
1258
- if (doneACs.length > 0) {
1259
- const acLogEntries = queryLog(root, { itemId, action: "ac_done", limit: 999 });
1260
- if (acLogEntries.length < doneACs.length) {
1261
- console.log(
1262
- chalk7.yellow(
1263
- `\u26A0 ${doneACs.length - acLogEntries.length} AC(s) marked [x] without "ac done" log entry.`
1264
- )
1265
- );
1266
- console.log(chalk7.yellow(" Run letra ac done <ID> for each completed AC."));
1267
- }
1268
- }
1269
- }
1270
- }
1271
- {
1272
- const resolved = resolveActiveFlow(root);
1273
- const targetDef = resolved.flow?.stages.find((stage) => stage.id === targetStageInput);
1274
- const gate = targetDef?.gate;
1275
- if (gate?.blocking) {
1276
- if (gate.type === "human") {
1277
- if (options?.force) {
1278
- console.log(chalk7.yellow(` Gate "${gate.name}" bypassado via --force`));
1279
- } else {
1280
- const resolvedTarget = resolveStage(workflow, targetStageInput) || targetStageInput;
1281
- console.log(chalk7.red(`Gate bloqueante: ${gate.name}`));
1282
- console.log(
1283
- chalk7.yellow(
1284
- ` Aprova\xE7\xE3o humana necess\xE1ria para entrar em "${resolvedTarget}".`
1285
- )
1286
- );
1287
- return;
1288
- }
1289
- } else {
1290
- const checker = new GateChecker(root);
1291
- const result2 = checker.check(gate.id, item);
1292
- if (!result2.allowed) {
1293
- const resolvedTarget = resolveStage(workflow, targetStageInput) || targetStageInput;
1294
- console.log(chalk7.red(`Gate bloqueante: ${gate.name}`));
1295
- console.log(chalk7.yellow(` ${result2.reason}`));
1296
- console.log(
1297
- chalk7.yellow(
1298
- ` Aprova\xE7\xE3o humana necess\xE1ria para entrar em "${resolvedTarget}".`
1299
- )
1300
- );
1301
- return;
1302
- }
1303
- }
1304
- }
1305
- }
1306
- const targetStageId = resolveStage(workflow, targetStageInput);
1307
- if (!targetStageId) {
1308
- const valid = workflow.stages.map((s) => `${s.id} (${s.name})`).join(", ");
1309
- console.log(chalk7.red(`Stage "${targetStageInput}" not found. Valid stages: ${valid}`));
1310
- process.exit(1);
1311
- }
1312
- if (item.stage === targetStageId) {
1313
- console.log(chalk7.yellow(`Item ${itemId} is already in stage "${targetStageId}"`));
1314
- return;
1315
- }
1316
- const fromStage = workflow.stages.find((s) => s.id === item.stage)?.name || item.stage;
1317
- const toStage = workflow.stages.find((s) => s.id === targetStageId)?.name || targetStageId;
1318
- item.stage = targetStageId;
1319
- const phaseResult = enterStage(workflow, item);
1320
- if (phaseResult.phase) {
1321
- logEntry(root, "system", `phase_entry: ${item.id} \u2192 ${phaseResult.phase}`);
1322
- }
1323
- workflow.updatedAt = now5();
1324
- if (phaseResult.ok && item.currentPhase && canAutopilot(workflow, item)) {
1325
- console.log(
1326
- ` ${chalk7.cyan("\u23E9")} Auto-pilot dispon\xEDvel para ${item.id} (fase inicial tem auto-transition)`
1327
- );
1328
- const pilotResult = await autopilotRun(root, workflow, item);
1329
- if (pilotResult.ok) {
1330
- console.log(
1331
- ` ${chalk7.green("\u2713")} Auto-pilot: ${pilotResult.transitionsApplied} transi\xE7\xE3o(\xF5es) \u2014 parou em "${pilotResult.finalPhase || "__EXIT__"}"`
1332
- );
1333
- } else {
1334
- console.log(
1335
- ` ${chalk7.yellow("\u23F8")} Auto-pilot: ${pilotResult.error} \u2014 parou em "${pilotResult.finalPhase}"`
1336
- );
1337
- }
1338
- }
1339
- const targetStageIsDone = workflow.stages.find((s) => s.id === targetStageId)?.zone === "done";
1340
- if (targetStageIsDone && item.claimedBy) {
1341
- if (item.claimedBy === "opencode") {
1342
- console.log(
1343
- ` ${chalk7.gray("Release autom\xE1tico:")} ${itemId} n\xE3o est\xE1 mais sob responsabilidade do agente`
1344
- );
1345
- }
1346
- item.claimedBy = void 0;
1347
- item.claimedAt = void 0;
1348
- }
1349
- const result = await writeWorkflow(root, {
1350
- workflow,
1351
- source: "flow-move",
1352
- primaryItemId: itemId,
1353
- skipSitrep: true
1354
- });
1355
- if (item.spec) {
1356
- writeFocusWithRecommendations(root, item.spec, item.id);
1357
- }
1358
- logEntry(root, "item_move", `Item ${itemId} movido: ${fromStage} \u2192 ${toStage}`, {
1359
- itemId,
1360
- details: { from: item.stage, to: targetStageId }
1361
- });
1362
- console.log(
1363
- ` ${chalk7.green("\u2713")} Item ${chalk7.cyan(itemId)} moved: ${chalk7.yellow(fromStage)} \u2192 ${chalk7.green(toStage)}`
1364
- );
1365
- if (result.ok && result.filesUpdated.length > 0) {
1366
- 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;
1367
901
  }
902
+ console.log(` ${chalk7.green("\u2713")} Item ${chalk7.cyan(itemId)} moved: ${chalk7.yellow(fromStage)} \u2192 ${chalk7.green(toStage)}`);
903
+ return true;
1368
904
  }
1369
905
  function normalizeItemId(input) {
1370
906
  if (/^ITEM-\d+$/i.test(input)) return input.toUpperCase();
1371
907
  if (/^\d+$/.test(input)) return `ITEM-${input}`;
1372
908
  console.log(chalk7.red(`Invalid item ID: "${input}". Use a number (e.g. 34) or ITEM-N format.`));
1373
- process.exit(1);
909
+ return input;
1374
910
  }
1375
911
  function flowMoveAction(targetPath, itemId, options) {
1376
912
  const root = resolve7(process.cwd(), targetPath || ".");
1377
- const normalized = normalizeItemId(itemId);
1378
- if (options.auto) {
1379
- flowMove(root, normalized, options.to || "", { auto: true, force: options.force });
1380
- } else {
1381
- flowMove(root, normalized, options.to || "", { force: options.force });
1382
- }
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
+ );
1383
922
  }
1384
923
 
1385
924
  // src/commands/flow-claim.ts
@@ -1389,10 +928,10 @@ import chalk8 from "chalk";
1389
928
  function askYesNo(query) {
1390
929
  if (!process.stdin.isTTY) return Promise.resolve(true);
1391
930
  const rl = createInterface({ input: process.stdin, output: process.stdout });
1392
- return new Promise((resolve31) => {
931
+ return new Promise((resolve35) => {
1393
932
  rl.question(`${chalk8.yellow(query)} (y/N) `, (answer) => {
1394
933
  rl.close();
1395
- resolve31(answer.trim().toLowerCase() === "y");
934
+ resolve35(answer.trim().toLowerCase() === "y");
1396
935
  });
1397
936
  });
1398
937
  }
@@ -1520,21 +1059,19 @@ async function handoffItem(root, itemId, options) {
1520
1059
  process.exit(1);
1521
1060
  }
1522
1061
  const previousFrom = item.handoff.from;
1523
- item.claimedBy = previousFrom;
1524
- item.claimedAt = (/* @__PURE__ */ new Date()).toISOString();
1525
- item.handoff = void 0;
1526
- workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1527
- writeWorkflow(root, {
1528
- workflow,
1529
- source: "flow-handoff-rollback",
1530
- primaryItemId: item.id,
1531
- skipSitrep: true
1532
- });
1533
- logEntry(root, "handoff_rollback", `Handoff rolled back to ${previousFrom}`, {
1534
- itemId: item.id,
1535
- to: previousFrom,
1536
- 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."
1537
1070
  });
1071
+ if (operation2.outcome !== "accepted") {
1072
+ console.log(chalk9.red(`Cannot rollback: ${operation2.reason}`));
1073
+ process.exit(1);
1074
+ }
1538
1075
  console.log(` ${chalk9.green("\u2713")} ${itemId} handoff rolled back to ${previousFrom}`);
1539
1076
  return;
1540
1077
  }
@@ -1546,15 +1083,6 @@ async function handoffItem(root, itemId, options) {
1546
1083
  console.log(chalk9.red("Summary is required (--summary)"));
1547
1084
  process.exit(1);
1548
1085
  }
1549
- const currentStage = workflow.stages.find((s) => s.id === item.stage);
1550
- if (currentStage?.gate) {
1551
- const gateChecker = new GateChecker(root);
1552
- const gateResult = gateChecker.checkHandoffAllowed(currentStage.gate, item);
1553
- if (!gateResult.allowed) {
1554
- console.log(chalk9.red(`Cannot handoff: ${gateResult.reason}`));
1555
- process.exit(1);
1556
- }
1557
- }
1558
1086
  let ttlMinutes = DEFAULT_HANDOFF_TTL_MINUTES;
1559
1087
  try {
1560
1088
  const manifest = loadHarness(resolveHarnessRoot(root, DEFAULT_HARNESS_VERSION));
@@ -1566,34 +1094,32 @@ async function handoffItem(root, itemId, options) {
1566
1094
  }
1567
1095
  } catch {
1568
1096
  }
1569
- const now6 = /* @__PURE__ */ new Date();
1570
- const expiresAt = new Date(now6.getTime() + ttlMinutes * 60 * 1e3);
1571
- item.handoff = {
1572
- 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,
1573
1107
  to: options.to,
1108
+ actor: from,
1109
+ executorId,
1574
1110
  summary: options.summary,
1575
1111
  evidence: options.evidence || [],
1576
- timestamp: now6.toISOString(),
1577
- expiresAt: expiresAt.toISOString(),
1578
- executorId: options.executor
1579
- };
1580
- workflow.updatedAt = now6.toISOString();
1581
- writeWorkflow(root, {
1582
- workflow,
1583
- source: "flow-handoff",
1584
- primaryItemId: item.id,
1585
- skipSitrep: true
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
1586
1117
  });
1587
- logEntry(root, "handoff", `Handoff from ${item.handoff.from} to ${options.to}`, {
1588
- itemId: item.id,
1589
- from: item.handoff.from,
1590
- to: options.to,
1591
- summary: options.summary,
1592
- evidence: options.evidence,
1593
- executorId: options.executor,
1594
- expiresAt: expiresAt.toISOString()
1595
- });
1596
- 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}`);
1597
1123
  console.log(` ${chalk9.dim(`Expires at: ${expiresAt.toISOString()}`)}`);
1598
1124
  }
1599
1125
  async function handoffAction(targetPath, itemId, options) {
@@ -1602,8 +1128,8 @@ async function handoffAction(targetPath, itemId, options) {
1602
1128
  }
1603
1129
 
1604
1130
  // src/commands/flow-ac.ts
1605
- import { existsSync as existsSync8, readFileSync as readFileSync7, writeFileSync as writeFileSync5 } from "fs";
1606
- 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";
1607
1133
  import chalk10 from "chalk";
1608
1134
  function findACLine(lines, n) {
1609
1135
  let count = 0;
@@ -1631,13 +1157,13 @@ function markAC(root, itemId, acNum) {
1631
1157
  console.log(chalk10.red(`Item ${itemId} has no linked spec`));
1632
1158
  process.exit(1);
1633
1159
  }
1634
- const specDir = join8(getLetraDir(root), "specs", item.spec);
1635
- const specFile = join8(specDir, "spec.md");
1636
- if (!existsSync8(specFile)) {
1160
+ const specDir = join5(getLetraDir(root), "specs", item.spec);
1161
+ const specFile = join5(specDir, "spec.md");
1162
+ if (!existsSync5(specFile)) {
1637
1163
  console.log(chalk10.red(`Spec file not found: ${specFile}`));
1638
1164
  process.exit(1);
1639
1165
  }
1640
- const content = readFileSync7(specFile, "utf-8");
1166
+ const content = readFileSync5(specFile, "utf-8");
1641
1167
  const lines = content.split("\n");
1642
1168
  const lineIdx = findACLine(lines, acNum);
1643
1169
  if (lineIdx === null) {
@@ -1650,7 +1176,7 @@ function markAC(root, itemId, acNum) {
1650
1176
  }
1651
1177
  const orig = lines[lineIdx];
1652
1178
  lines[lineIdx] = orig.replace(/^- \[ \]/, "- [x]");
1653
- writeFileSync5(specFile, lines.join("\n"), "utf-8");
1179
+ writeFileSync4(specFile, lines.join("\n"), "utf-8");
1654
1180
  if (workflow.specLinks?.[item.spec]) {
1655
1181
  writeWorkflow(root, {
1656
1182
  workflow,
@@ -1680,7 +1206,7 @@ function flowAcAction(targetPath, itemId, acNumber) {
1680
1206
  }
1681
1207
 
1682
1208
  // src/commands/flow-visualize.ts
1683
- import { writeFileSync as writeFileSync6 } from "fs";
1209
+ import { writeFileSync as writeFileSync5 } from "fs";
1684
1210
  import { resolve as resolve11 } from "path";
1685
1211
  import chalk11 from "chalk";
1686
1212
  var MERMAID_LIVE = "https://mermaid.live/edit#";
@@ -1755,7 +1281,7 @@ ${mermaid}
1755
1281
  `;
1756
1282
  label = "Diagram file";
1757
1283
  }
1758
- writeFileSync6(outputPath, content);
1284
+ writeFileSync5(outputPath, content);
1759
1285
  console.log(`${label} saved to ${options.output}`);
1760
1286
  } else {
1761
1287
  console.log(mermaid);
@@ -1771,6 +1297,210 @@ function flowVisualizeAction(targetPath, options) {
1771
1297
  // src/commands/flow-phases.ts
1772
1298
  import { resolve as resolve12 } from "path";
1773
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;
1430
+ }
1431
+ function getPhaseDef(phases, phaseId) {
1432
+ return phases.states[phaseId] ?? null;
1433
+ }
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` };
1439
+ }
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
+ };
1476
+ }
1477
+ } else {
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
+ });
1486
+ }
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
+ };
1501
+ }
1502
+
1503
+ // src/commands/flow-phases.ts
1774
1504
  function flowPhasesAction(itemId) {
1775
1505
  const root = resolve12(process.cwd());
1776
1506
  const workflow = loadWorkflow(root);
@@ -1806,39 +1536,157 @@ function flowPhasesAction(itemId) {
1806
1536
  console.log(` ${chalk12.dim(`\u2192 ${targets}`)}`);
1807
1537
  }
1808
1538
  }
1809
- console.log("");
1810
- }
1811
- function flowPhaseTransitionAction(itemId, targetPhase) {
1812
- const root = resolve12(process.cwd());
1813
- const workflow = loadWorkflow(root);
1814
- if (!workflow) {
1815
- console.log(chalk12.red("No workflow found"));
1816
- return;
1817
- }
1818
- const item = workflow.items.find((i) => i.id === itemId);
1819
- if (!item) {
1820
- console.log(chalk12.red(`Item "${itemId}" not found`));
1821
- return;
1822
- }
1823
- const result = transitionPhase(root, workflow, item, targetPhase);
1824
- if (!result.ok) {
1825
- console.log(chalk12.red(result.error));
1826
- return;
1827
- }
1828
- saveWorkflow(root, workflow);
1829
- logEntry(root, "system", `phase_transition: ${item.id} \u2192 ${targetPhase}`);
1830
- console.log(` ${chalk12.green("\u2713")} Phase transition: ${chalk12.cyan(item.currentPhase || "")}`);
1831
- if (result.triggeredActions && result.triggeredActions.length > 0) {
1832
- console.log(` ${chalk12.gray("Actions:")} ${result.triggeredActions.join(", ")}`);
1833
- }
1834
- if (result.triggeredAutoTransition) {
1835
- console.log(` ${chalk12.yellow("\u21BB Auto-transition triggered")}`);
1836
- }
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);
1837
1687
  }
1838
1688
 
1839
1689
  // src/commands/flow-autopilot.ts
1840
- import { resolve as resolve13 } from "path";
1841
- import chalk13 from "chalk";
1842
1690
  async function flowAutopilotAction(itemId) {
1843
1691
  const root = resolve13(process.cwd());
1844
1692
  const workflow = loadWorkflow(root);
@@ -1993,6 +1841,202 @@ async function flowBindAction(targetPath, options) {
1993
1841
  await flowBind(root, options);
1994
1842
  }
1995
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
+
1996
2040
  // src/commands/flow.ts
1997
2041
  function flowCommand() {
1998
2042
  const cmd = new Command2("flow");
@@ -2003,8 +2047,8 @@ function flowCommand() {
2003
2047
  flowInitAction(void 0, { quick: true, template: options.template || "flow-main" });
2004
2048
  });
2005
2049
  const backlog = cmd.command("backlog").description("Manage backlog items");
2006
- backlog.command("add <description>").option("--spec <name>", "Spec name to link").description("Add item to the first stage").action((description, options) => {
2007
- 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);
2008
2052
  });
2009
2053
  backlog.command("list").description("List all items with stage and age").action(() => {
2010
2054
  backlogActionList(void 0);
@@ -2016,12 +2060,12 @@ function flowCommand() {
2016
2060
  importCmd.command("linear <team>").option("--limit <number>", "Max issues to import", "50").description("Import issues from a Linear team").action((team, options) => {
2017
2061
  backlogImportLinearAction(void 0, team, options);
2018
2062
  });
2019
- 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) => {
2020
2064
  if (!options.to && !options.auto) {
2021
- console.log(chalk16.red("Either --to or --auto is required"));
2065
+ console.log(chalk17.red("Either --to or --auto is required"));
2022
2066
  process.exit(1);
2023
2067
  }
2024
- flowMoveAction(void 0, itemId, options);
2068
+ return flowMoveAction(void 0, itemId, options);
2025
2069
  });
2026
2070
  cmd.command("board").description("Show board with all stages and items").action(() => {
2027
2071
  flowBoardAction(void 0);
@@ -2029,13 +2073,14 @@ function flowCommand() {
2029
2073
  cmd.command("export").option("--minified", "Output JSON without indentation").description("Export workflow to stdout").action((options) => {
2030
2074
  flowExportAction(void 0, options);
2031
2075
  });
2032
- cmd.command("import <file>").description("Import workflow from a JSON file").action((file) => {
2033
- 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);
2034
2078
  });
2035
- cmd.command("serve").option("--port <number>", "Port to listen on", "3000").option("--open", "Open browser automatically").description("Start local web server with live board").action((options) => {
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) => {
2036
2080
  flowServeAction(void 0, {
2037
2081
  port: options.port ? Number(options.port) : void 0,
2038
- open: options.open
2082
+ open: options.open,
2083
+ autopilot: options.autopilot
2039
2084
  });
2040
2085
  });
2041
2086
  cmd.command("visualize").option("--output <file>", "Save diagram to file").description("Generate Mermaid diagram of workflow").action((options) => {
@@ -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,84 +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-UXSZ4LNR.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-FUP3APZA.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("validate").requiredOption("--expected-revision <revision>", "Direction revision returned by Letra").requiredOption("--reason <reason>", "Reason for the operation").action(async (options) => {
2697
- const { runValidationOperation } = await import("./service-OGF7BMCQ.js");
2698
- printJson(await runValidationOperation(resolve23(process.cwd()), options));
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 }));
2818
+ });
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 }));
2699
2832
  });
2700
- command.command("complete-ac <ac-id>").requiredOption("--expected-revision <revision>", "Direction revision returned by Letra").requiredOption("--reason <reason>", "Reason for completing the criterion").addOption(
2701
- new Option("--evidence <evidence>", "Regression evidence").argParser(collectEvidence).default([])
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 }));
2854
+ });
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 }));
2858
+ });
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 }));
2867
+ });
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 }));
2871
+ });
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([])
2702
2880
  ).action(
2703
2881
  async (acId, options) => {
2704
- const { completeAcOperation } = await import("./service-OGF7BMCQ.js");
2705
- 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 }));
2706
2884
  }
2707
2885
  );
2708
- 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(
2709
2887
  async (itemId, options) => {
2710
- const { requestTransitionOperation } = await import("./service-OGF7BMCQ.js");
2888
+ const { requestTransitionOperation } = await import("./service-USTAY5E3.js");
2711
2889
  printJson(
2712
- await requestTransitionOperation(resolve23(process.cwd()), {
2890
+ await requestTransitionOperation(resolve25(process.cwd()), {
2713
2891
  itemId,
2714
2892
  targetStageId: options.to,
2715
2893
  expectedRevision: options.expectedRevision,
2716
- reason: options.reason
2894
+ reason: options.reason,
2895
+ actor: options.actor,
2896
+ idempotencyKey: options.idempotencyKey
2717
2897
  })
2718
2898
  );
2719
2899
  }
2720
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
+ });
2721
2919
  return command;
2722
2920
  }
2723
2921
 
2724
2922
  // src/commands/init.ts
2725
- import { existsSync as existsSync12, mkdirSync as mkdirSync3, writeFileSync as writeFileSync8 } from "fs";
2726
- 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";
2727
2925
  import { createInterface as createInterface2 } from "readline";
2728
2926
  import { fileURLToPath } from "url";
2729
- import chalk21 from "chalk";
2927
+ import chalk22 from "chalk";
2730
2928
  import ora from "ora";
2731
2929
 
2732
2930
  // src/adapters/language-registry.ts
@@ -2768,18 +2966,18 @@ var __dirname = fileURLToPath(new URL(".", import.meta.url));
2768
2966
  function ask(query, options) {
2769
2967
  if (!process.stdin.isTTY) return Promise.resolve(options[0]);
2770
2968
  const rl = createInterface2({ input: process.stdin, output: process.stdout });
2771
- return new Promise((resolve31) => {
2772
- 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(" ")}
2773
2971
  > `;
2774
2972
  rl.question(formatted, (answer) => {
2775
2973
  rl.close();
2776
2974
  const trimmed = answer.trim().toLowerCase();
2777
2975
  if (trimmed && options.some((o) => o.toLowerCase().startsWith(trimmed))) {
2778
- resolve31(options.find((o) => o.toLowerCase().startsWith(trimmed)) ?? options[0]);
2976
+ resolve35(options.find((o) => o.toLowerCase().startsWith(trimmed)) ?? options[0]);
2779
2977
  } else if (trimmed && options.includes(trimmed)) {
2780
- resolve31(trimmed);
2978
+ resolve35(trimmed);
2781
2979
  } else {
2782
- resolve31(options[0]);
2980
+ resolve35(options[0]);
2783
2981
  }
2784
2982
  });
2785
2983
  });
@@ -2832,13 +3030,13 @@ function stableLocationId(path) {
2832
3030
  return `loc-${name}-${(hash >>> 0).toString(36)}`;
2833
3031
  }
2834
3032
  function externalWorkspaceWorkflow(workspaceName, projectRoot, harnessVersion) {
2835
- const now6 = (/* @__PURE__ */ new Date()).toISOString();
3033
+ const now4 = (/* @__PURE__ */ new Date()).toISOString();
2836
3034
  const locationPath = normalizedPath(projectRoot);
2837
3035
  return {
2838
3036
  version: "1.0",
2839
3037
  name: workspaceName,
2840
- createdAt: now6,
2841
- updatedAt: now6,
3038
+ createdAt: now4,
3039
+ updatedAt: now4,
2842
3040
  stages: [
2843
3041
  { id: "backlog", name: "Backlog", order: 0, zone: "todo" },
2844
3042
  { id: "design", name: "Design", order: 1, zone: "doing" },
@@ -2861,7 +3059,7 @@ function externalWorkspaceWorkflow(workspaceName, projectRoot, harnessVersion) {
2861
3059
  };
2862
3060
  }
2863
3061
  async function init(targetPath, options) {
2864
- const root = resolve24(process.cwd(), targetPath || ".");
3062
+ const root = resolve26(process.cwd(), targetPath || ".");
2865
3063
  if (options?.workspace) {
2866
3064
  const spinner2 = ora("Creating workspace...").start();
2867
3065
  try {
@@ -2873,38 +3071,43 @@ async function init(targetPath, options) {
2873
3071
  root,
2874
3072
  info.harnessVersion
2875
3073
  );
2876
- writeFileSync8(
2877
- join11(workspaceDir, "workflow.json"),
3074
+ writeFileSync9(
3075
+ join10(workspaceDir, "workflow.json"),
2878
3076
  JSON.stringify(workflow, null, 2),
2879
3077
  "utf-8"
2880
3078
  );
2881
- writeFileSync8(join11(root, LINK_FILE), `${workspaceDir}
3079
+ writeFileSync9(join10(root, LINK_FILE), `${workspaceDir}
2882
3080
  `, "utf-8");
2883
3081
  clearWorkspaceCache();
2884
- spinner2.succeed(chalk21.green(`Workspace "${options.workspace}" created`));
2885
- console.log(` ${chalk21.gray("Data dir:")} ${workspaceDir}`);
2886
- console.log(` ${chalk21.gray("Project:")} ${root}`);
2887
- console.log(` ${chalk21.gray("Link:")} ${join11(root, LINK_FILE)}`);
2888
- 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}`);
2889
3092
  console.log("");
2890
3093
  console.log(" Next steps:");
2891
- console.log(` ${chalk21.cyan("letra status")} View workspace info`);
2892
- 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`);
2893
3096
  return;
2894
3097
  } catch (error) {
2895
- spinner2.fail(chalk21.red("Failed to create workspace"));
2896
- 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}`));
2897
3100
  process.exit(1);
2898
3101
  }
2899
3102
  }
2900
3103
  const letraDir = getLetraDir(root);
2901
- if (existsSync12(letraDir)) {
3104
+ if (existsSync10(letraDir)) {
2902
3105
  if (options?.serve) {
2903
- console.log(chalk21.cyan(".letra/ already exists \u2014 starting UI..."));
3106
+ console.log(chalk22.cyan(".letra/ already exists \u2014 starting UI..."));
2904
3107
  await flowServeAction(targetPath, { open: true });
2905
3108
  return;
2906
3109
  }
2907
- console.log(chalk21.yellow(".letra/ already exists"));
3110
+ console.log(chalk22.yellow(".letra/ already exists"));
2908
3111
  return;
2909
3112
  }
2910
3113
  const spinner = ora("Initializing Letra...").start();
@@ -2932,9 +3135,9 @@ async function init(targetPath, options) {
2932
3135
  tool = answer.toLowerCase();
2933
3136
  spinner.start();
2934
3137
  }
2935
- mkdirSync3(join11(letraDir, "decisions"), { recursive: true });
2936
- mkdirSync3(join11(letraDir, "specs", "_template"), { recursive: true });
2937
- 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 });
2938
3141
  const lang = detectLanguage(root);
2939
3142
  const langDisplay = lang ?? "general";
2940
3143
  const stackLine = lang ? `- **Stack**: ${lang}` : "- Sem stack espec\xEDfica (projeto general)";
@@ -2942,25 +3145,56 @@ async function init(targetPath, options) {
2942
3145
  const templateFiles = {
2943
3146
  "context.md": `# Context
2944
3147
 
2945
- > Updated: 2026-06-16
2946
- > 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\`.
2947
3150
 
2948
3151
  ## Intent
2949
3152
 
2950
- Este projeto segue Specification-Driven Development (SDD).
2951
- 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
2952
3160
 
2953
- ## Dom\xEDnio
3161
+ Quem usa este projeto e em quais situa\xE7\xF5es.
3162
+
3163
+ ## Domain
2954
3164
 
2955
3165
  - ${stackLine}
2956
3166
  - Ferramenta: .letra/ memory format
2957
3167
  - P\xFAblico: equipe de desenvolvimento
2958
3168
 
2959
- ## 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
2960
3190
 
2961
3191
  - Specs devem ser thin (m\xE1x 1 p\xE1gina por feature)
2962
3192
  - Sem lock-in de IDE
2963
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.
2964
3198
  `,
2965
3199
  "constitution.md": `# Constitution
2966
3200
 
@@ -3009,9 +3243,9 @@ ${codeRules}
3009
3243
  `
3010
3244
  };
3011
3245
  for (const [file, content] of Object.entries(templateFiles)) {
3012
- writeFileSync8(join11(letraDir, file), content, "utf-8");
3246
+ writeFileSync9(join10(letraDir, file), content, "utf-8");
3013
3247
  }
3014
- const specTemplate = join11(letraDir, "specs", "_template.md");
3248
+ const specTemplate = join10(letraDir, "specs", "_template.md");
3015
3249
  const specContent = `# Spec Template
3016
3250
 
3017
3251
  > Updated: YYYY-MM-DD
@@ -3031,16 +3265,16 @@ O que explicitamente N\xC3O est\xE1 neste escopo.
3031
3265
  ## Context
3032
3266
  Por que estamos construindo isso.
3033
3267
  `;
3034
- writeFileSync8(specTemplate, specContent);
3035
- const configPath = join11(letraDir, "config.json");
3036
- writeFileSync8(configPath, adaptConfig(projectType));
3037
- 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`);
3038
3272
  const tools = TOOL_MAP[tool] || TOOL_MAP.todos;
3039
3273
  generateAdapters(root, tools, { source: "init" });
3040
3274
  if ((tool === "todos" || tool === "vscode") && lang === "Node.js") {
3041
- const vscodeDir = join11(root, ".vscode");
3042
- if (!existsSync12(vscodeDir)) mkdirSync3(vscodeDir, { recursive: true });
3043
- 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");
3044
3278
  const vscodeSettingsContent = `{
3045
3279
  "editor.formatOnSave": true,
3046
3280
  "editor.defaultFormatter": "esbenp.prettier-vscode",
@@ -3050,19 +3284,19 @@ Por que estamos construindo isso.
3050
3284
  "files.autoSave": "onFocusChange"
3051
3285
  }
3052
3286
  `;
3053
- writeFileSync8(vscodeSettingsPath, vscodeSettingsContent);
3054
- console.log(` ${chalk21.gray("Created")} .vscode/settings.json`);
3287
+ writeFileSync9(vscodeSettingsPath, vscodeSettingsContent);
3288
+ console.log(` ${chalk22.gray("Created")} .vscode/settings.json`);
3055
3289
  }
3056
- spinner.succeed(chalk21.green(".letra/ initialized successfully"));
3290
+ spinner.succeed(chalk22.green(".letra/ initialized successfully"));
3057
3291
  console.log("");
3058
3292
  console.log(" Next steps:");
3059
- console.log(` ${chalk21.cyan("letra spec new <name>")} Create your first spec`);
3060
- console.log(` ${chalk21.cyan("letra lint")} Validate specs`);
3061
- 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`);
3062
3296
  if (lang) {
3063
3297
  const workflow = {
3064
3298
  version: "1.0",
3065
- name: resolve24(root).split(/[\\/]/).pop() || "meu-projeto",
3299
+ name: resolve26(root).split(/[\\/]/).pop() || "meu-projeto",
3066
3300
  language: lang,
3067
3301
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
3068
3302
  updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -3080,41 +3314,27 @@ Por que estamos construindo isso.
3080
3314
  }
3081
3315
  if (options?.serve) {
3082
3316
  console.log(`
3083
- ${chalk21.cyan("Opening web UI...")}
3317
+ ${chalk22.cyan("Opening web UI...")}
3084
3318
  `);
3085
3319
  await flowServeAction(targetPath, { open: true });
3086
3320
  return;
3087
3321
  }
3088
3322
  } catch (error) {
3089
- spinner.fail(chalk21.red("Failed to initialize Letra"));
3323
+ spinner.fail(chalk22.red("Failed to initialize Letra"));
3090
3324
  process.exit(1);
3091
3325
  }
3092
3326
  }
3093
3327
 
3094
3328
  // src/commands/lint.ts
3095
- import { existsSync as existsSync13, readdirSync as readdirSync5 } from "fs";
3096
- import { join as join12, resolve as resolve25, dirname } from "path";
3097
- 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";
3098
3332
  async function lint(targetPath) {
3099
- const root = resolve25(process.cwd(), targetPath || ".");
3100
- let specsDir = join12(getLetraDir(root), "specs");
3101
- if (!existsSync13(specsDir)) {
3102
- let found = false;
3103
- let search = root;
3104
- const fsRoot = resolve25("/").replace(/\\/g, "/");
3105
- while (search && search !== fsRoot && search !== dirname(search)) {
3106
- const candidate = join12(search, ".letra", "specs");
3107
- if (existsSync13(candidate)) {
3108
- specsDir = candidate;
3109
- found = true;
3110
- break;
3111
- }
3112
- search = dirname(search);
3113
- }
3114
- if (!found) {
3115
- console.log(chalk22.red("Error: .letra/specs/ not found. Run 'letra init' first."));
3116
- process.exit(1);
3117
- }
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);
3118
3338
  }
3119
3339
  let totalErrors = 0;
3120
3340
  let totalWarnings = 0;
@@ -3122,7 +3342,7 @@ async function lint(targetPath) {
3122
3342
  const entries = readdirSync5(specsDir, { withFileTypes: true });
3123
3343
  for (const entry of entries) {
3124
3344
  if (!entry.isDirectory() || entry.name.startsWith("_")) continue;
3125
- const specFile = join12(specsDir, entry.name, "spec.md");
3345
+ const specFile = join11(specsDir, entry.name, "spec.md");
3126
3346
  const { errors, warnings } = validateSpecStructure(specFile);
3127
3347
  if (errors.length > 0 || warnings.length > 0) {
3128
3348
  results.push({ file: entry.name, errors, warnings });
@@ -3131,22 +3351,22 @@ async function lint(targetPath) {
3131
3351
  }
3132
3352
  }
3133
3353
  if (results.length === 0) {
3134
- console.log(chalk22.green("All specs are valid"));
3354
+ console.log(chalk23.green("All specs are valid"));
3135
3355
  process.exit(0);
3136
3356
  }
3137
3357
  console.log("");
3138
3358
  for (const result of results) {
3139
- console.log(chalk22.bold(`
3359
+ console.log(chalk23.bold(`
3140
3360
  Spec: ${result.file}`));
3141
3361
  for (const error of result.errors) {
3142
- console.log(chalk22.red(` \u2717 ${error}`));
3362
+ console.log(chalk23.red(` \u2717 ${error}`));
3143
3363
  }
3144
3364
  for (const warning of result.warnings) {
3145
- console.log(chalk22.yellow(` \u26A0 ${warning}`));
3365
+ console.log(chalk23.yellow(` \u26A0 ${warning}`));
3146
3366
  }
3147
3367
  }
3148
3368
  console.log(
3149
- chalk22.gray(
3369
+ chalk23.gray(
3150
3370
  `
3151
3371
  ${results.length} spec(s) with issues: ${totalErrors} error(s), ${totalWarnings} warning(s)`
3152
3372
  )
@@ -3155,9 +3375,9 @@ ${results.length} spec(s) with issues: ${totalErrors} error(s), ${totalWarnings}
3155
3375
  }
3156
3376
 
3157
3377
  // src/commands/spec.ts
3158
- import { existsSync as existsSync14, mkdirSync as mkdirSync4, readFileSync as readFileSync10, readdirSync as readdirSync6, writeFileSync as writeFileSync9 } from "fs";
3159
- import { join as join13, resolve as resolve26 } from "path";
3160
- 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";
3161
3381
  import ora2 from "ora";
3162
3382
  var builtInTemplates = {
3163
3383
  "web-api": {
@@ -3370,8 +3590,8 @@ Template para eventos corporativos, comunit\xE1rios ou t\xE9cnicos. Adaptado par
3370
3590
  };
3371
3591
  function listTemplates(root) {
3372
3592
  const names = Object.keys(builtInTemplates);
3373
- const customDir = join13(getLetraDir(root), "templates");
3374
- if (existsSync14(customDir)) {
3593
+ const customDir = join12(getLetraDir(root), "templates");
3594
+ if (existsSync12(customDir)) {
3375
3595
  for (const file of readdirSync6(customDir)) {
3376
3596
  if (file.endsWith(".md")) {
3377
3597
  const name = file.replace(/\.md$/, "");
@@ -3384,11 +3604,11 @@ function listTemplates(root) {
3384
3604
  function findTemplate(root, type) {
3385
3605
  const lower = type.toLowerCase();
3386
3606
  if (builtInTemplates[lower]) return builtInTemplates[lower];
3387
- const customFile = join13(getLetraDir(root), "templates", `${type}.md`);
3388
- const customAcceptance = join13(getLetraDir(root), "templates", `${type}-acceptance.md`);
3389
- 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)) {
3390
3610
  const spec = readFileSync10(customFile, "utf-8");
3391
- 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}
3392
3612
 
3393
3613
  - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
3394
3614
  `;
@@ -3400,47 +3620,47 @@ function applyPlaceholders(content, name, date) {
3400
3620
  return content.replace(/\{\{name\}\}/g, name).replace(/\{\{date\}\}/g, date);
3401
3621
  }
3402
3622
  function specLink(itemId, specName) {
3403
- const root = resolve26(process.cwd());
3623
+ const root = resolve28(process.cwd());
3404
3624
  const workflow = loadWorkflow(root);
3405
3625
  if (!workflow) {
3406
- console.log(chalk23.red("No workflow found"));
3626
+ console.log(chalk24.red("No workflow found"));
3407
3627
  process.exit(1);
3408
3628
  }
3409
3629
  const item = workflow.items.find((i) => i.id === itemId);
3410
3630
  if (!item) {
3411
- console.log(chalk23.red(`Item ${itemId} not found`));
3631
+ console.log(chalk24.red(`Item ${itemId} not found`));
3412
3632
  process.exit(1);
3413
3633
  }
3414
- const specDir = join13(getLetraDir(root), "specs", specName);
3415
- if (!existsSync14(specDir)) {
3416
- 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)}/`));
3417
3637
  return;
3418
3638
  }
3419
3639
  item.spec = specName;
3420
3640
  if (!workflow.specLinks) workflow.specLinks = {};
3421
- workflow.specLinks[specName] = { path: `.letra/specs/${specName}/spec.md` };
3641
+ workflow.specLinks[specName] = { path: `specs/${specName}/spec.md` };
3422
3642
  workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
3423
3643
  writeWorkflow(root, { workflow, source: "flow-edit", skipSitrep: true });
3424
3644
  logEntry(root, "manual", `spec linked: ${itemId} \u2192 ${specName}`, { itemId });
3425
- console.log(` ${chalk23.green("\u2713")} ${itemId} \u2192 ${chalk23.cyan(specName)}`);
3645
+ console.log(` ${chalk24.green("\u2713")} ${itemId} \u2192 ${chalk24.cyan(specName)}`);
3426
3646
  }
3427
3647
  async function specNew(name, options) {
3428
- const root = resolve26(process.cwd());
3648
+ const root = resolve28(process.cwd());
3429
3649
  const letraDir = getLetraDir(root);
3430
- const specDir = join13(letraDir, "specs", name);
3431
- if (!existsSync14(letraDir)) {
3432
- 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."));
3433
3653
  process.exit(1);
3434
3654
  }
3435
- if (existsSync14(specDir)) {
3436
- console.log(chalk23.yellow(`Spec "${name}" already exists`));
3655
+ if (existsSync12(specDir)) {
3656
+ console.log(chalk24.yellow(`Spec "${name}" already exists`));
3437
3657
  return;
3438
3658
  }
3439
3659
  const templateType = options?.template || "_default";
3440
3660
  const template = templateType === "_default" ? null : findTemplate(root, templateType);
3441
3661
  if (options?.template && !template) {
3442
3662
  const available = listTemplates(root).join(", ");
3443
- console.log(chalk23.red(`Template "${options.template}" not found. Available: ${available}`));
3663
+ console.log(chalk24.red(`Template "${options.template}" not found. Available: ${available}`));
3444
3664
  process.exit(1);
3445
3665
  }
3446
3666
  const spinner = ora2(`Creating spec "${name}"...`).start();
@@ -3450,8 +3670,8 @@ async function specNew(name, options) {
3450
3670
  if (template) {
3451
3671
  const specContent = applyPlaceholders(template.spec, name, today2);
3452
3672
  const acceptanceContent = applyPlaceholders(template.acceptance, name, today2);
3453
- writeFileSync9(join13(specDir, "spec.md"), specContent);
3454
- writeFileSync9(join13(specDir, "acceptance.md"), acceptanceContent);
3673
+ writeFileSync10(join12(specDir, "spec.md"), specContent);
3674
+ writeFileSync10(join12(specDir, "acceptance.md"), acceptanceContent);
3455
3675
  } else {
3456
3676
  const specContent = `# Spec: ${name}
3457
3677
 
@@ -3476,20 +3696,30 @@ Por que estamos construindo isso. Trade-offs considerados.
3476
3696
 
3477
3697
  - [ ] **Crit\xE9rio 1**: Descri\xE7\xE3o bin\xE1ria (passa/falha).
3478
3698
  `;
3479
- writeFileSync9(join13(specDir, "spec.md"), specContent);
3480
- writeFileSync9(join13(specDir, "acceptance.md"), acceptanceContent);
3699
+ writeFileSync10(join12(specDir, "spec.md"), specContent);
3700
+ writeFileSync10(join12(specDir, "acceptance.md"), acceptanceContent);
3481
3701
  }
3482
- spinner.succeed(chalk23.green(`Spec "${name}" created at .letra/specs/${name}/`));
3702
+ spinner.succeed(chalk24.green(`Spec "${name}" created at ${join12(letraDir, "specs", name)}/`));
3483
3703
  } catch (error) {
3484
- spinner.fail(chalk23.red("Failed to create spec"));
3704
+ spinner.fail(chalk24.red("Failed to create spec"));
3485
3705
  process.exit(1);
3486
3706
  }
3487
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
+ }
3488
3718
 
3489
3719
  // src/commands/diagnose.ts
3490
- import { resolve as resolve27 } from "path";
3720
+ import { resolve as resolve29 } from "path";
3491
3721
  async function diagnose(targetPath) {
3492
- const root = resolve27(process.cwd(), targetPath ?? ".");
3722
+ const root = resolve29(process.cwd(), targetPath ?? ".");
3493
3723
  const engine = new DiagnosticEngine(root);
3494
3724
  engine.ensureDirs();
3495
3725
  console.log("\n\u{1F50D} Auto-diagn\xF3stico do Letra\n");
@@ -3561,46 +3791,46 @@ async function diagnose(targetPath) {
3561
3791
  }
3562
3792
 
3563
3793
  // src/commands/status.ts
3564
- import { existsSync as existsSync15 } from "fs";
3565
- import { resolve as resolve28 } from "path";
3794
+ import { existsSync as existsSync13 } from "fs";
3795
+ import { resolve as resolve30 } from "path";
3566
3796
  import { pathToFileURL } from "url";
3567
- import chalk24 from "chalk";
3797
+ import chalk25 from "chalk";
3568
3798
  async function status(cwd) {
3569
- const root = resolve28(process.cwd(), cwd || ".");
3799
+ const root = resolve30(process.cwd(), cwd || ".");
3570
3800
  const manifest = detectManifest(root);
3571
3801
  if (manifest) {
3572
3802
  const { manifest: m } = manifest;
3573
- 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"));
3574
- console.log(chalk24.bold("\u2551 Status do Workspace \u2551"));
3575
- 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"));
3576
- console.log(` ${chalk24.bold("Workspace:")} ${m.workspaceId}`);
3577
- console.log(` ${chalk24.bold("Projeto:")} ${m.projectId}`);
3578
- console.log(` ${chalk24.bold("Template:")} ${m.templateId}`);
3579
- console.log(` ${chalk24.bold("Harness:")} ${m.harnessVersion}`);
3580
- console.log(` ${chalk24.bold("Gates:")} ${m.gates.join(", ")}`);
3581
- console.log(` ${chalk24.bold("Repos:")} ${m.repositories.length}`);
3582
- 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}`);
3583
3813
  const wsPath = getWorkspacePath(m.workspaceId);
3584
- if (existsSync15(wsPath)) {
3814
+ if (existsSync13(wsPath)) {
3585
3815
  const info = loadWorkspaceInfo(m.workspaceId);
3586
3816
  if (info) {
3587
3817
  console.log(
3588
3818
  `
3589
- ${chalk24.gray(`Workspace criado: ${new Date(info.createdAt).toLocaleDateString()}`)}`
3819
+ ${chalk25.gray(`Workspace criado: ${new Date(info.createdAt).toLocaleDateString()}`)}`
3590
3820
  );
3591
3821
  }
3592
3822
  }
3593
3823
  } else {
3594
- 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"));
3595
- console.log(chalk24.bold("\u2551 Workspaces Dispon\xEDveis \u2551"));
3596
- 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"));
3597
3827
  const workspaces = listWorkspaces();
3598
3828
  if (workspaces.length === 0) {
3599
3829
  console.log(" Nenhum workspace encontrado.");
3600
- console.log(` Crie um com: ${chalk24.cyan("letra init --workspace <nome>")}`);
3830
+ console.log(` Crie um com: ${chalk25.cyan("letra init --workspace <nome>")}`);
3601
3831
  } else {
3602
3832
  for (const ws of workspaces) {
3603
- console.log(` ${chalk24.green("\u25CF")} ${chalk24.bold(ws.name)}`);
3833
+ console.log(` ${chalk25.green("\u25CF")} ${chalk25.bold(ws.name)}`);
3604
3834
  console.log(` ID: ${ws.id}`);
3605
3835
  console.log(` Template: ${ws.templateId}`);
3606
3836
  console.log(` Criado: ${new Date(ws.createdAt).toLocaleDateString()}`);
@@ -3615,30 +3845,37 @@ async function status(cwd) {
3615
3845
  }
3616
3846
 
3617
3847
  // src/commands/gate.ts
3618
- import { existsSync as existsSync16, readFileSync as readFileSync11, writeFileSync as writeFileSync10 } from "fs";
3619
- 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";
3620
3850
  import { Command as Command11 } from "commander";
3621
- import chalk25 from "chalk";
3622
- var GATE_DIR = join14(".letra", "harness", "gates");
3851
+ import chalk26 from "chalk";
3852
+ var GATE_DIR = join13(".letra", "harness", "gates");
3623
3853
  function gateCommand() {
3624
3854
  const cmd = new Command11("gate");
3625
3855
  cmd.description("Gerenciar gates do harness");
3626
3856
  cmd.command("approve <id>").description("Marca um gate como approved").action((id) => {
3627
3857
  const root = process.cwd();
3858
+ const dataDir = getLetraDir(root);
3628
3859
  const candidates = [
3629
- join14(root, GATE_DIR, `${id}.yaml`),
3630
- 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`)
3631
3868
  ];
3632
- const file = candidates.find((c) => existsSync16(c));
3869
+ const file = candidates.find((c) => existsSync14(c));
3633
3870
  if (!file) {
3634
- console.error(`${chalk25.red("Gate n\xE3o encontrado:")} ${id}`);
3871
+ console.error(`${chalk26.red("Gate n\xE3o encontrado:")} ${id}`);
3635
3872
  console.error(`Procurado em: ${candidates.join(", ")}`);
3636
3873
  process.exitCode = 1;
3637
3874
  return;
3638
3875
  }
3639
3876
  let raw = readFileSync11(file, "utf-8");
3640
3877
  if (raw.includes("status: approved")) {
3641
- console.log(chalk25.yellow(`Gate "${id}" j\xE1 estava approved.`));
3878
+ console.log(chalk26.yellow(`Gate "${id}" j\xE1 estava approved.`));
3642
3879
  return;
3643
3880
  }
3644
3881
  if (raw.includes("status:")) {
@@ -3648,18 +3885,18 @@ function gateCommand() {
3648
3885
  status: approved
3649
3886
  `;
3650
3887
  }
3651
- writeFileSync10(file, raw, "utf-8");
3888
+ writeFileSync11(file, raw, "utf-8");
3652
3889
  logEntry(root, "system", `gate approve ${id}`, { details: { gateId: id } });
3653
- console.log(chalk25.green(`Gate "${id}" aprovado.`));
3654
- console.log(chalk25.dim(`Arquivo: ${file}`));
3890
+ console.log(chalk26.green(`Gate "${id}" aprovado.`));
3891
+ console.log(chalk26.dim(`Arquivo: ${file}`));
3655
3892
  });
3656
3893
  return cmd;
3657
3894
  }
3658
3895
 
3659
3896
  // src/commands/check-ds.ts
3660
- import { existsSync as existsSync17, readdirSync as readdirSync7, readFileSync as readFileSync12 } from "fs";
3661
- import { join as join15, resolve as resolve29 } from "path";
3662
- 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";
3663
3900
  var FORBIDDEN = [
3664
3901
  /\bvar\(\s*--muted\s*\)/,
3665
3902
  /\bvar\(\s*--foreground\s*\)/,
@@ -3682,7 +3919,7 @@ function collectFiles(dir) {
3682
3919
  const entries = readdirSync7(dir, { withFileTypes: true });
3683
3920
  const files = [];
3684
3921
  for (const entry of entries) {
3685
- const full = join15(dir, entry.name);
3922
+ const full = join14(dir, entry.name);
3686
3923
  if (entry.isDirectory() && entry.name !== "node_modules" && entry.name !== "dist" && !entry.name.startsWith(".")) {
3687
3924
  files.push(...collectFiles(full));
3688
3925
  } else if (entry.isFile() && entry.name.endsWith(".tsx")) {
@@ -3701,10 +3938,10 @@ function checkFile(path) {
3701
3938
  return issues;
3702
3939
  }
3703
3940
  async function checkDs(targetPath) {
3704
- const root = resolve29(process.cwd(), targetPath || ".");
3705
- const clientDir = join15(root, "packages", "client", "src");
3706
- if (!existsSync17(clientDir)) {
3707
- 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."));
3708
3945
  process.exit(1);
3709
3946
  }
3710
3947
  const files = collectFiles(clientDir);
@@ -3718,44 +3955,934 @@ async function checkDs(targetPath) {
3718
3955
  }
3719
3956
  }
3720
3957
  if (results.length === 0) {
3721
- console.log(chalk26.green("DS conformance: OK"));
3958
+ console.log(chalk27.green("DS conformance: OK"));
3722
3959
  process.exit(0);
3723
3960
  }
3724
- console.log(chalk26.red(`DS conformance: ${totalIssues} issue(s) found
3961
+ console.log(chalk27.red(`DS conformance: ${totalIssues} issue(s) found
3725
3962
  `));
3726
3963
  for (const result of results) {
3727
- console.log(chalk26.bold(`
3964
+ console.log(chalk27.bold(`
3728
3965
  File: ${result.file}`));
3729
3966
  for (const issue of result.issues) {
3730
- console.log(chalk26.red(` \u2717 ${issue}`));
3967
+ console.log(chalk27.red(` \u2717 ${issue}`));
3731
3968
  }
3732
3969
  }
3733
3970
  process.exit(1);
3734
3971
  }
3735
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
+
3736
4863
  // src/index.ts
3737
4864
  var __dirname2 = fileURLToPath2(new URL(".", import.meta.url));
3738
- var pkg = JSON.parse(readFileSync13(join16(resolve30(__dirname2, ".."), "package.json"), "utf-8"));
3739
- var program = new Command12();
4865
+ var pkg = JSON.parse(readFileSync16(join18(resolve34(__dirname2, ".."), "package.json"), "utf-8"));
4866
+ var program = new Command16();
3740
4867
  program.name("letra").description("SDD-agnostic memory framework for AI coding agents").version(pkg.version);
3741
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 }));
3742
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) => {
3743
4870
  const port = Number.parseInt(options.port, 10) || 3e3;
3744
- const { execSync: execSync2 } = await import("child_process");
4871
+ const { execSync: execSync3 } = await import("child_process");
3745
4872
  const { createConnection } = await import("net");
3746
- const checkPort = (p) => new Promise((resolve31) => {
4873
+ const checkPort = (p) => new Promise((resolve35) => {
3747
4874
  const client = createConnection(p, "127.0.0.1", () => {
3748
4875
  client.end();
3749
- resolve31(true);
4876
+ resolve35(true);
3750
4877
  });
3751
- client.on("error", () => resolve31(false));
4878
+ client.on("error", () => resolve35(false));
3752
4879
  });
3753
4880
  const isRunning = await checkPort(port);
3754
4881
  const cmd = process.platform === "win32" ? "start" : process.platform === "darwin" ? "open" : "xdg-open";
3755
4882
  const setupUrl = `http://localhost:${port}/?setup=true`;
3756
4883
  if (isRunning) {
3757
4884
  try {
3758
- execSync2(`${cmd} "${setupUrl}"`, { stdio: "ignore" });
4885
+ execSync3(`${cmd} "${setupUrl}"`, { stdio: "ignore" });
3759
4886
  } catch {
3760
4887
  }
3761
4888
  console.log(`
@@ -3765,8 +4892,8 @@ program.command("setup [path]").option("--port <number>", "Port for the web UI",
3765
4892
  console.log(`
3766
4893
  Starting web UI on port ${port}...
3767
4894
  `);
3768
- const root = resolve30(process.cwd(), path ?? ".");
3769
- const { FlowServer } = await import("./flow-serve-MTB6KZMR.js");
4895
+ const root = resolve34(process.cwd(), path ?? ".");
4896
+ const { FlowServer } = await import("./flow-serve-LFILD3EV.js");
3770
4897
  const server = new FlowServer(root, port);
3771
4898
  try {
3772
4899
  await server.start();
@@ -3775,14 +4902,14 @@ program.command("setup [path]").option("--port <number>", "Port for the web UI",
3775
4902
  `);
3776
4903
  if (options.open !== false) {
3777
4904
  try {
3778
- execSync2(`${cmd} "${setupUrl}"`, { stdio: "ignore" });
4905
+ execSync3(`${cmd} "${setupUrl}"`, { stdio: "ignore" });
3779
4906
  } catch {
3780
4907
  }
3781
4908
  }
3782
- await new Promise((resolve31) => {
4909
+ await new Promise((resolve35) => {
3783
4910
  process.on("SIGINT", () => {
3784
4911
  server.stop();
3785
- resolve31();
4912
+ resolve35();
3786
4913
  });
3787
4914
  });
3788
4915
  } catch (err) {
@@ -3795,9 +4922,11 @@ program.command("status").description("Show workspace status or list workspaces"
3795
4922
  var specCmd = program.command("spec").description("Manage specs");
3796
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 }));
3797
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));
3798
4926
  program.command("lint [path]").description("Validate spec format and completeness").action(lint);
3799
4927
  program.command("check:ds [path]").description("Validate client conformance with Letra Design System").action(checkDs);
3800
- 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";
3801
4930
  await validate(path, { ...options });
3802
4931
  });
3803
4932
  program.command("diagnose [path]").description("Detect and fix drifts between specs, code, and workflow").action((path) => diagnose(path));
@@ -3807,7 +4936,7 @@ program.addCommand(directionCommand());
3807
4936
  program.addCommand(mcpCommand());
3808
4937
  program.addCommand(operationCommand());
3809
4938
  program.addCommand(decisionCommand());
3810
- 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-5JEYSXBY.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)));
3811
4940
  program.addCommand(flowCommand());
3812
4941
  program.addCommand(focus_default());
3813
4942
  program.addCommand(health_default());
@@ -3817,4 +4946,8 @@ program.addCommand(sitrep_default());
3817
4946
  program.addCommand(sync_default());
3818
4947
  program.addCommand(migrateCommand());
3819
4948
  program.addCommand(gateCommand());
4949
+ program.addCommand(doctorCommand());
4950
+ program.addCommand(specLintCommand());
4951
+ program.addCommand(specMigrateFrontmatterCommand());
4952
+ program.addCommand(securityCommand());
3820
4953
  program.parse();