@letra-ai/cli 0.6.2 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/chunk-2GRNAFBQ.js +5305 -0
  2. package/dist/{chunk-MJ2QXNH6.js → chunk-42RST74I.js} +1 -1
  3. package/dist/chunk-HC24XMPZ.js +269 -0
  4. package/dist/chunk-LUPN3TRC.js +554 -0
  5. package/dist/{chunk-URUC6ZZP.js → chunk-MUCIMQAU.js} +1735 -861
  6. package/dist/chunk-POGWTSEA.js +125 -0
  7. package/dist/chunk-TNF7XTFG.js +6178 -0
  8. package/dist/{chunk-BKAUN5QH.js → chunk-UMC5PDL2.js} +227 -33
  9. package/dist/{chunk-6HSUVCTR.js → chunk-YAQ2TKSK.js} +82 -30
  10. package/dist/client/assets/index-C-6kWNFi.js +232 -0
  11. package/dist/client/assets/index-QV-zN0V8.css +1 -0
  12. package/dist/client/index.html +2 -2
  13. package/dist/fallback-CXCCKHBA.js +56 -0
  14. package/dist/flow-serve-LFILD3EV.js +19 -0
  15. package/dist/{generate-UPFERQMD.js → generate-3R7POT7L.js} +4 -5
  16. package/dist/harness/default/v0.1.0/gates/all-acs-passing.yaml +1 -0
  17. package/dist/harness/default/v0.1.0/gates/has-spec-file.yaml +1 -0
  18. package/dist/harness/default/v0.1.1/gates/all-acs-passing.yaml +1 -0
  19. package/dist/harness/default/v0.1.1/gates/has-spec-file.yaml +1 -0
  20. package/dist/harness/default/v0.1.2/gates/all-acs-passing.yaml +1 -0
  21. package/dist/harness/default/v0.1.2/gates/has-spec-file.yaml +1 -0
  22. package/dist/harness/default/v0.1.3/gates/all-acs-passing.yaml +1 -0
  23. package/dist/harness/default/v0.1.3/gates/has-spec-file.yaml +1 -0
  24. package/dist/harness/default/v0.2.0/executors/registry.yaml +17 -0
  25. package/dist/harness/default/v0.2.0/flows/flow-main.yaml +81 -3
  26. package/dist/harness/default/v0.2.0/gates/code-reviewed.yaml +1 -0
  27. package/dist/harness/default/v0.2.0/gates/human-approved.yaml +1 -0
  28. package/dist/harness/default/v0.2.0/gates/security-clear.yaml +1 -0
  29. package/dist/{health-record-YDVXEVLR.js → health-record-JO2ZTIMR.js} +2 -2
  30. package/dist/index.js +2284 -1168
  31. package/dist/{push-VJRSQGUD.js → push-2ZCQSOHF.js} +37 -49
  32. package/dist/server-WUYVNSH7.js +677 -0
  33. package/dist/service-SVEAXQBX.js +28 -0
  34. package/dist/service-TOBY3OHO.js +22 -0
  35. package/dist/service-USTAY5E3.js +62 -0
  36. package/dist/{session-log-WTQ5JBEN.js → session-log-X2Q4XKQN.js} +6 -2
  37. package/dist/specs-CQRB7LPA.js +21 -0
  38. package/dist/sync-LIVPQXEW.js +21 -0
  39. package/package.json +1 -1
  40. package/dist/chunk-DMOLJWWW.js +0 -3321
  41. package/dist/chunk-EDD55PWL.js +0 -119
  42. package/dist/chunk-H64RC3YS.js +0 -254
  43. package/dist/chunk-L6YKDTAQ.js +0 -275
  44. package/dist/chunk-OIHMDOIN.js +0 -1326
  45. package/dist/client/assets/index-EyRsq1SH.css +0 -1
  46. package/dist/client/assets/index-WfKR7Xp6.js +0 -232
  47. package/dist/fallback-MQLGS4KL.js +0 -46
  48. package/dist/flow-serve-G5MSSB3G.js +0 -18
  49. package/dist/focus-sync-3D3XWCTI.js +0 -17
  50. package/dist/server-P6GKRWDX.js +0 -423
  51. package/dist/service-2JN2KI4D.js +0 -29
  52. package/dist/sitrep-OKNZJICV.js +0 -16
@@ -1,48 +1,86 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ clearSpec,
4
+ loadResolvedSpecs,
5
+ readAllowedContextFile,
6
+ validateSpec,
7
+ writeSpec
8
+ } from "./chunk-POGWTSEA.js";
9
+ import {
10
+ syncNow
11
+ } from "./chunk-HC24XMPZ.js";
2
12
  import {
3
13
  GateChecker,
14
+ activateWorkOperation,
15
+ claimOperation,
16
+ createItemOperation,
17
+ decideGateOperation,
18
+ deleteItemOperation,
19
+ directionForOperation,
20
+ directionForRunAwareOperation,
21
+ hasLiveClaim,
22
+ reclaimExpiredClaimsOperation,
23
+ recordExecutionEvent,
24
+ releaseClaimOperation,
25
+ requestHandoffOperation,
26
+ requestPassageOperation,
27
+ requestReworkOperation,
28
+ requestTransitionOperation,
29
+ resolveExecutionWorkspace,
4
30
  resolveFocusRecommendations,
31
+ runSecurityReviewOperation,
32
+ runValidationOperation,
33
+ securityReportPath,
34
+ submitEvidenceOperation,
35
+ updateItemOperation,
5
36
  writeFocusWithRecommendations
6
- } from "./chunk-H64RC3YS.js";
7
- import {
8
- sitrep
9
- } from "./chunk-L6YKDTAQ.js";
37
+ } from "./chunk-TNF7XTFG.js";
10
38
  import {
11
39
  DEFAULT_HARNESS_VERSION,
12
40
  DiagnosticEngine,
41
+ clearFocusFile,
13
42
  createAgent,
43
+ createWorkflowDefinition,
44
+ createWorkflowDraft,
14
45
  deleteAgent,
15
46
  detectExistingTools,
16
47
  detectProjectName,
17
48
  ensureSharedHarness,
18
49
  generateAdapters,
50
+ getActiveWorkflowVersion,
51
+ getWorkflowDraft,
52
+ getWorkflowVersion,
53
+ inspectWorkspaceIntegrity,
19
54
  listAgents,
55
+ listWorkflowDefinitions,
56
+ listWorkflowDraftRevisions,
57
+ listWorkflowVersions,
20
58
  loadHarness,
59
+ loadRuntimeAgentRegistry,
21
60
  loadWorkflow,
61
+ projectAgentPresence,
62
+ publishWorkflowDraft,
63
+ readExecutionRuns,
64
+ readFocusFile,
22
65
  renderAdapterFiles,
23
- resolveActiveFlow,
24
66
  resolveActiveFlowFor,
25
- resolveAgentDirection,
67
+ resolveDirection,
26
68
  resolveHarnessRoot,
69
+ resolveLocalIdentity,
70
+ resolveRuntimeBinding,
71
+ rollbackWorkflowVersion,
72
+ signLocalOperation,
27
73
  stageFromTemplateStage,
74
+ syncFocus,
28
75
  updateAgent,
76
+ updateWorkflowDraft,
77
+ validateWorkflowContent,
29
78
  writeWorkflow
30
- } from "./chunk-DMOLJWWW.js";
31
- import {
32
- loadSessionLog,
33
- logEntry,
34
- queryLog,
35
- queryLogWithMeta
36
- } from "./chunk-BKAUN5QH.js";
79
+ } from "./chunk-2GRNAFBQ.js";
37
80
  import {
38
81
  ADAPTER_REGISTRY,
39
82
  supportedAdapterTools
40
83
  } from "./chunk-JMIC5NKB.js";
41
- import {
42
- clearFocusFile,
43
- readFocusFile,
44
- syncFocus
45
- } from "./chunk-EDD55PWL.js";
46
84
  import {
47
85
  ackEntry,
48
86
  dismissEntry,
@@ -51,7 +89,16 @@ import {
51
89
  loadHealthRecord,
52
90
  mergeScanResults,
53
91
  saveHealthRecord
54
- } from "./chunk-MJ2QXNH6.js";
92
+ } from "./chunk-42RST74I.js";
93
+ import {
94
+ readSpecCatalog
95
+ } from "./chunk-LUPN3TRC.js";
96
+ import {
97
+ loadSessionLog,
98
+ logEntry,
99
+ queryLog,
100
+ queryLogWithMeta
101
+ } from "./chunk-UMC5PDL2.js";
55
102
  import {
56
103
  LINK_FILE,
57
104
  clearWorkspaceCache,
@@ -62,10 +109,7 @@ import {
62
109
  listWorkspaces,
63
110
  resolveWorkspaceRoot,
64
111
  slugifyWorkspaceName
65
- } from "./chunk-6HSUVCTR.js";
66
- import {
67
- __require
68
- } from "./chunk-PDX44BCA.js";
112
+ } from "./chunk-YAQ2TKSK.js";
69
113
 
70
114
  // src/commands/flow-serve.ts
71
115
  import { createServer } from "http";
@@ -118,17 +162,9 @@ function countSpecACs(stateDir, specName) {
118
162
  if (!existsSync(specFile)) return { pending: 0, done: 0, total: 0 };
119
163
  try {
120
164
  const content = readFileSync(specFile, "utf-8");
121
- const boldPending = content.match(/-\s*\[ \]\s*\*\*AC[-]?\d+\*\*/g) || [];
122
- const boldDone = content.match(/-\s*\[[xX]\]\s*\*\*AC[-]?\d+\*\*/g) || [];
123
- if (boldPending.length > 0 || boldDone.length > 0) {
124
- return {
125
- pending: boldPending.length,
126
- done: boldDone.length,
127
- total: boldPending.length + boldDone.length
128
- };
129
- }
130
- const genericPending = content.match(/^- \[ \]\s+AC[-]?\d+/gm) || [];
131
- const genericDone = content.match(/^- \[[xX]\]\s+AC[-]?\d+/gm) || [];
165
+ const checklist = content.match(/^-\s*\[[ xX]\]\s+(?:\*\*)?AC[- ]?\d+\b[^\r\n]*/gm) || [];
166
+ const genericPending = checklist.filter((line) => /^-\s*\[ \]/.test(line));
167
+ const genericDone = checklist.filter((line) => /^-\s*\[[xX]\]/.test(line));
132
168
  return {
133
169
  pending: genericPending.length,
134
170
  done: genericDone.length,
@@ -282,7 +318,7 @@ ${chalk.bold("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
282
318
  );
283
319
  }
284
320
  if (ci.spec) {
285
- const specReference = statePath ? pathToFileURL(join(statePath, "specs", ci.spec, "spec.md")).href : `.letra/specs/${ci.spec}/spec.md`;
321
+ const specReference = statePath ? pathToFileURL(join(statePath, "specs", ci.spec, "spec.md")).href : `specs/${ci.spec}/spec.md`;
286
322
  console.log(` ${chalk.gray(`Spec: ${specReference}`)}`);
287
323
  } else {
288
324
  console.log(` ${chalk.yellow("\u26A0 sem spec associada")}`);
@@ -379,6 +415,148 @@ function pulse_default() {
379
415
  return cmd;
380
416
  }
381
417
 
418
+ // src/commands/sitrep.ts
419
+ import { existsSync as existsSync2, readFileSync as readFileSync2, readdirSync, statSync } from "fs";
420
+ import { join as join2 } from "path";
421
+ import chalk2 from "chalk";
422
+ import { Command as Command2 } from "commander";
423
+ var DEPRECATION_MESSAGE = "`letra sitrep` n\xE3o atualiza mais context.md. Use `letra direction --json` para estado vivo; edite context.md apenas como mem\xF3ria humana curada.";
424
+ function getRecentDecisions(root, max) {
425
+ const dir = join2(getLetraDir2(root), "decisions");
426
+ if (!existsSync2(dir)) return [];
427
+ try {
428
+ const files = readdirSync(dir).filter((f) => f.endsWith(".md")).map((f) => ({
429
+ name: f,
430
+ mtime: statSync(join2(dir, f)).mtimeMs
431
+ })).sort((a, b) => b.mtime - a.mtime).slice(0, max);
432
+ return files.map((f) => ({
433
+ title: f.name.replace(/\.md$/, "").replace(/-/g, " "),
434
+ date: new Date(f.mtime).toLocaleDateString("pt-BR")
435
+ }));
436
+ } catch {
437
+ return [];
438
+ }
439
+ }
440
+ function countItemACs(root, specName) {
441
+ const specDir = join2(getLetraDir2(root), "specs", specName);
442
+ const acceptanceFile = join2(specDir, "acceptance.md");
443
+ const specFile = join2(specDir, "spec.md");
444
+ const countInText = (text) => {
445
+ const pending = (text.match(/-\s*\[ \]\s*\*\*(.+?)\*\*/g) || []).length;
446
+ const done = (text.match(/-\s*\[[xX]\]\s*\*\*(.+?)\*\*/g) || []).length;
447
+ return { pending, total: pending + done };
448
+ };
449
+ if (existsSync2(acceptanceFile)) {
450
+ return countInText(readFileSync2(acceptanceFile, "utf-8"));
451
+ }
452
+ if (existsSync2(specFile)) {
453
+ const content = readFileSync2(specFile, "utf-8");
454
+ const match = content.match(/## Acceptance Criteria\s+([\s\S]*?)(?=\n## |\n*$)/);
455
+ return match ? countInText(match[1]) : { pending: 0, total: 0 };
456
+ }
457
+ return { pending: 0, total: 0 };
458
+ }
459
+ function findCurrentItem2(workflow) {
460
+ const activeStages = workflow.stages.filter(
461
+ (s) => s.zone === "doing" || !s.zone && s.order > 0 && s.order < workflow.stages.length - 1
462
+ ).map((s) => s.id);
463
+ const stageSet = new Set(activeStages);
464
+ if (stageSet.size === 0) {
465
+ const mid = Math.floor(workflow.stages.length / 2);
466
+ const stage = workflow.stages[mid];
467
+ if (stage) stageSet.add(stage.id);
468
+ }
469
+ const items = workflow.items.filter((i) => stageSet.has(i.stage));
470
+ if (items.length === 0) return null;
471
+ return items.reduce((a, b) => new Date(a.createdAt) > new Date(b.createdAt) ? a : b);
472
+ }
473
+ function getStageName2(stageId, workflow) {
474
+ if (!workflow) return stageId;
475
+ return workflow.stages?.find((s) => s.id === stageId)?.name ?? stageId;
476
+ }
477
+ function buildSitrepBlock(data) {
478
+ const lines = [];
479
+ if (data.currentItem) {
480
+ lines.push(`**Est\xE1gio**: ${getStageName2(data.currentItem.stage, data.workflow)}`);
481
+ const item = data.currentItem;
482
+ let itemLine = `**Item atual**: ${item.id} \u2014 ${item.description}`;
483
+ if (item.spec) itemLine += ` (spec: ${item.spec})`;
484
+ lines.push(itemLine);
485
+ if (data.acCounts) {
486
+ const { pending, total } = data.acCounts;
487
+ const done = total - pending;
488
+ lines.push(`**ACs**: ${pending}/${total} pendentes | ${done} feito(s)`);
489
+ }
490
+ } else if (data.workflow) {
491
+ lines.push("**Est\xE1gio**: sem item ativo");
492
+ } else {
493
+ lines.push("**Est\xE1gio**: sem workflow definido");
494
+ }
495
+ const s = data.alertSummary;
496
+ const alertParts = [];
497
+ if (s.novo > 0) alertParts.push(`${s.novo} novo(s)`);
498
+ if (s.ciente > 0) alertParts.push(`${s.ciente} em acompanhamento`);
499
+ if (s.resolvido > 0) alertParts.push(`${s.resolvido} resolvido(s)`);
500
+ lines.push(`**Alertas**: ${alertParts.length > 0 ? alertParts.join(" \xB7 ") : "0 alertas"}`);
501
+ if (s.alta > 0) {
502
+ lines.push(`\u26A0 ${s.alta} alerta(s) de severidade alta`);
503
+ }
504
+ if (data.decisions.length > 0) {
505
+ const decStr = data.decisions.map((d) => `"${d.title}" (${d.date})`).join(", ");
506
+ lines.push(`**\xDAltimas decis\xF5es**: ${decStr}`);
507
+ }
508
+ return lines.join("\n");
509
+ }
510
+ async function sitrep(rootPath, options) {
511
+ const workflow = loadWorkflow(rootPath);
512
+ const healthRecord = loadHealthRecord(rootPath);
513
+ const alertSummary = getSummary(healthRecord);
514
+ let currentItem = null;
515
+ let acCounts = null;
516
+ if (workflow) {
517
+ currentItem = findCurrentItem2(workflow);
518
+ if (currentItem?.spec) {
519
+ acCounts = countItemACs(rootPath, currentItem.spec);
520
+ }
521
+ }
522
+ const decisions = getRecentDecisions(rootPath, 4);
523
+ const data = {
524
+ stage: currentItem?.stage ?? "sem item ativo",
525
+ currentItem,
526
+ acCounts,
527
+ alertSummary,
528
+ decisions,
529
+ workflow
530
+ };
531
+ const dynamicBlock = buildSitrepBlock(data);
532
+ if (!options?.quiet) {
533
+ console.log(chalk2.yellow(DEPRECATION_MESSAGE));
534
+ console.log(chalk2.bold("\nResumo vivo atual\n"));
535
+ console.log(dynamicBlock);
536
+ }
537
+ if (!options?.skipLog) {
538
+ logEntry(rootPath, "sitrep", "sitrep consultado sem atualizar context.md", {
539
+ details: {
540
+ hasItem: !!currentItem,
541
+ itemId: currentItem?.id,
542
+ alertsNovo: alertSummary.novo
543
+ }
544
+ });
545
+ }
546
+ }
547
+ function sitrep_default() {
548
+ const cmd = new Command2("sitrep").description(
549
+ "Compatibilidade: imprimir resumo vivo; n\xE3o atualiza context.md"
550
+ );
551
+ cmd.option("--dry-run", "Exibir diff sem modificar o arquivo").action(
552
+ async (options) => {
553
+ const resolution = resolveWorkspaceRoot(process.cwd());
554
+ await sitrep(resolution.workspaceRoot, options);
555
+ }
556
+ );
557
+ return cmd;
558
+ }
559
+
382
560
  // src/flow-serve/events.ts
383
561
  var FlowServerEvents = class {
384
562
  clients = /* @__PURE__ */ new Set();
@@ -445,106 +623,8 @@ async function runDiagnosticsAndSyncHealth(engine, root) {
445
623
  return output;
446
624
  }
447
625
 
448
- // src/flow-serve/specs.ts
449
- import { existsSync as existsSync3, mkdirSync, readFileSync as readFileSync3, readdirSync, writeFileSync } from "fs";
450
- import { join as join2 } from "path";
451
-
452
- // src/validation/structure.ts
453
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
454
- var REQUIRED_SECTIONS = [
455
- "## Outcome",
456
- "## Constraints",
457
- "## Exclusions",
458
- "## Acceptance Criteria",
459
- "## Context"
460
- ];
461
- function checkRequiredSections(content) {
462
- return REQUIRED_SECTIONS.filter((section) => !content.includes(section));
463
- }
464
- function checkSpecLength(content, maxChars = 3e3) {
465
- return content.length > maxChars ? `Spec exceeds ${maxChars} chars (should be thin \u2014 max 1 page)` : null;
466
- }
467
- function checkChecklist(content) {
468
- const hasChecklist = /-\s*\[[ x]\]\s*\*\*/i.test(content);
469
- if (!hasChecklist && content.includes("## Acceptance Criteria")) {
470
- return "Acceptance Criteria section exists but has no checklist items";
471
- }
472
- return null;
473
- }
474
- function validateSpecStructure(specFile) {
475
- const errors = [];
476
- const warnings = [];
477
- if (!existsSync2(specFile)) {
478
- errors.push("Missing spec.md");
479
- return { errors, warnings };
480
- }
481
- const content = readFileSync2(specFile, "utf-8");
482
- const missingSections = checkRequiredSections(content);
483
- errors.push(...missingSections.map((s) => `Missing section: ${s}`));
484
- const lengthWarning = checkSpecLength(content);
485
- if (lengthWarning) warnings.push(lengthWarning);
486
- const checklistError = checkChecklist(content);
487
- if (checklistError) errors.push(checklistError);
488
- return { errors, warnings };
489
- }
490
-
491
- // src/flow-serve/specs.ts
492
- function loadResolvedSpecs(root, workflow) {
493
- const result = [];
494
- if (workflow?.specLinks) {
495
- for (const [id, link] of Object.entries(workflow.specLinks)) {
496
- const filePath = join2(root, link.path);
497
- if (existsSync3(filePath)) {
498
- result.push({ id, content: readFileSync3(filePath, "utf-8") });
499
- }
500
- }
501
- }
502
- const specsDir = join2(getLetraDir2(root), "specs");
503
- const registered = new Set(result.map((entry) => entry.id));
504
- if (!existsSync3(specsDir)) return result;
505
- for (const entry of readdirSync(specsDir, { withFileTypes: true })) {
506
- if (!entry.isDirectory() || registered.has(entry.name)) continue;
507
- const specPath = join2(specsDir, entry.name, "spec.md");
508
- if (!existsSync3(specPath)) continue;
509
- result.push({ id: entry.name, content: readFileSync3(specPath, "utf-8") });
510
- }
511
- return result;
512
- }
513
- function readAllowedContextFile(workspaceDir, file) {
514
- const allowedFiles = /* @__PURE__ */ new Set(["context.md", "constitution.md", "glossary.md"]);
515
- if (!allowedFiles.has(file)) return null;
516
- const filePath = join2(workspaceDir, file);
517
- if (!existsSync3(filePath)) return null;
518
- return readFileSync3(filePath, "utf-8");
519
- }
520
- function writeSpec(workspaceDir, id, content) {
521
- const specDir = join2(workspaceDir, "specs", id);
522
- if (!existsSync3(specDir)) mkdirSync(specDir, { recursive: true });
523
- writeFileSync(join2(specDir, "spec.md"), content, "utf-8");
524
- }
525
- function clearSpec(workspaceDir, id) {
526
- const specFile = join2(workspaceDir, "specs", id, "spec.md");
527
- if (existsSync3(specFile)) writeFileSync(specFile, "", "utf-8");
528
- }
529
- function validateSpec(workspaceDir, id) {
530
- const specFile = join2(workspaceDir, "specs", id, "spec.md");
531
- if (!existsSync3(specFile)) {
532
- return {
533
- id,
534
- issues: [{ type: "error", msg: "spec.md not found" }],
535
- valid: false
536
- };
537
- }
538
- const { errors, warnings } = validateSpecStructure(specFile);
539
- const issues = [
540
- ...errors.map((msg) => ({ type: "error", msg })),
541
- ...warnings.map((msg) => ({ type: "warning", msg }))
542
- ];
543
- return { id, issues, valid: errors.length === 0 };
544
- }
545
-
546
626
  // src/flow-serve/context.ts
547
- import { existsSync as existsSync5, readFileSync as readFileSync5, readdirSync as readdirSync2 } from "fs";
627
+ import { existsSync as existsSync4, readFileSync as readFileSync4, readdirSync as readdirSync2 } from "fs";
548
628
  import { join as join4 } from "path";
549
629
 
550
630
  // src/activity-context/compatibility.ts
@@ -562,10 +642,10 @@ var MUST_NOT_DO = {
562
642
  ],
563
643
  implement: [
564
644
  "N\xE3o editar `workflow.json` manualmente.",
565
- "N\xE3o implementar fora do escopo da spec ativa."
645
+ "N\xE3o implementar fora do escopo da dire\xE7\xE3o atribu\xEDda."
566
646
  ],
567
647
  review: [
568
- "N\xE3o focar em novas features fora do diff/spec analisado.",
648
+ "N\xE3o focar em novas features fora do diff/dire\xE7\xE3o analisada.",
569
649
  "N\xE3o aprovar sem checar riscos, ACs e sinais ativos."
570
650
  ],
571
651
  diagnose: [
@@ -579,15 +659,17 @@ var MUST_NOT_DO = {
579
659
  };
580
660
  function compatibilityReferences(activity, context) {
581
661
  const references = [
582
- { path: ".letra/context.md", reason: "Contexto operacional do workspace" },
583
662
  { path: ".letra/constitution.md", reason: "Regras n\xE3o negoci\xE1veis do Letra" }
584
663
  ];
585
- if (context.hasFocus) {
586
- references.push({ path: ".letra/focus.md", reason: "Foco e outcome da sess\xE3o atual" });
664
+ if (activity === "design" || activity === "diagnose") {
665
+ references.push({
666
+ path: ".letra/context.md",
667
+ reason: "Mem\xF3ria humana curada de produto/dom\xEDnio; n\xE3o usar como estado vivo"
668
+ });
587
669
  }
588
670
  if (context.specName) {
589
671
  references.push({
590
- path: `.letra/specs/${context.specName}/spec.md`,
672
+ path: `specs/${context.specName}/spec.md`,
591
673
  reason: "Spec e crit\xE9rios do trabalho atual"
592
674
  });
593
675
  }
@@ -603,12 +685,6 @@ function compatibilityReferences(activity, context) {
603
685
  reason: "Estado persistente dos alertas ativos"
604
686
  });
605
687
  }
606
- if (!context.hasCurrentItem) {
607
- references.push({
608
- path: ".letra/workflow.json",
609
- reason: "Fonte de verdade para triagem e escolha do pr\xF3ximo item"
610
- });
611
- }
612
688
  return references;
613
689
  }
614
690
  function currentItemActions(activity, context) {
@@ -632,7 +708,7 @@ function currentItemActions(activity, context) {
632
708
  case "implement":
633
709
  return [
634
710
  {
635
- label: "Executar item ativo",
711
+ label: "Executar item atribu\xEDdo",
636
712
  description: `Implementar o pr\xF3ximo passo observando os ACs da ${specRef}.`
637
713
  },
638
714
  {
@@ -702,8 +778,8 @@ function getCompatibilityActivityIntent(activity, context) {
702
778
  description: "Escolher ou criar um item ativo antes de aprofundar a execu\xE7\xE3o."
703
779
  },
704
780
  {
705
- label: "Confirmar foco",
706
- description: "Validar se a sess\xE3o deve seguir descoberta, design ou backlog."
781
+ label: "Confirmar atribui\xE7\xE3o",
782
+ description: "Aguardar atribui\xE7\xE3o ou solicitar sele\xE7\xE3o expl\xEDcita de execu\xE7\xE3o."
707
783
  }
708
784
  ]
709
785
  };
@@ -842,27 +918,11 @@ function resolveActivityIntent(activity, sources) {
842
918
  }
843
919
 
844
920
  // src/activity-context/sources.ts
845
- import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
921
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
846
922
  import { join as join3 } from "path";
847
- function getStageName2(workflow, stageId) {
923
+ function getStageName3(workflow, stageId) {
848
924
  return workflow.stages.find((stage) => stage.id === stageId)?.name ?? stageId;
849
925
  }
850
- function findCurrentItem2(workflow) {
851
- const activeStages = workflow.stages.filter(
852
- (stage) => stage.zone === "doing" || !stage.zone && stage.order > 0 && stage.order < workflow.stages.length - 1
853
- ).map((stage) => stage.id);
854
- const stageSet = new Set(activeStages);
855
- if (stageSet.size === 0) {
856
- const middle = Math.floor(workflow.stages.length / 2);
857
- const stage = workflow.stages[middle];
858
- if (stage) stageSet.add(stage.id);
859
- }
860
- const items = workflow.items.filter((item) => stageSet.has(item.stage));
861
- if (items.length === 0) return null;
862
- return items.reduce(
863
- (left, right) => new Date(left.createdAt) > new Date(right.createdAt) ? left : right
864
- );
865
- }
866
926
  function extractOutcome(content) {
867
927
  const match = content.match(/## Outcome\s+([\s\S]*?)(?=\n## |\n*$)/);
868
928
  return match ? match[1].trim() : null;
@@ -888,36 +948,40 @@ function countSpecACs2(content) {
888
948
  function loadSpecMeta(root, specName) {
889
949
  if (!specName) return null;
890
950
  const specPath = join3(getLetraDir2(root), "specs", specName, "spec.md");
891
- if (!existsSync4(specPath)) {
951
+ if (!existsSync3(specPath)) {
892
952
  return {
893
953
  name: specName,
894
- path: `.letra/specs/${specName}/spec.md`,
954
+ path: `specs/${specName}/spec.md`,
895
955
  outcome: null,
896
956
  acs: { pending: 0, done: 0, total: 0 }
897
957
  };
898
958
  }
899
- const content = readFileSync4(specPath, "utf-8");
959
+ const content = readFileSync3(specPath, "utf-8");
900
960
  return {
901
961
  name: specName,
902
- path: `.letra/specs/${specName}/spec.md`,
962
+ path: `specs/${specName}/spec.md`,
903
963
  outcome: extractOutcome(content),
904
964
  acs: countSpecACs2(content)
905
965
  };
906
966
  }
907
- function loadActivityContextSources(root) {
967
+ function loadActivityContextSources(root, itemId, runId) {
908
968
  const workflow = loadWorkflow(root);
909
- const flowResolution = resolveActiveFlow(root);
910
- const focus = readFocusFile(root);
911
- const focusedItem = workflow && focus?.itemId ? workflow.items.find((item) => item.id === focus.itemId) ?? null : null;
912
- const currentItem = focusedItem ?? (workflow ? findCurrentItem2(workflow) : null);
969
+ const selectedRun = runId ? readExecutionRuns(root).runs.find((run) => run.id === runId) : null;
970
+ const flowResolution = resolveActiveFlowFor(root, workflow, {
971
+ itemId: itemId ?? void 0,
972
+ workflowVersionId: selectedRun?.workflowVersionId
973
+ });
974
+ const focus = null;
975
+ const focusedItem = workflow && itemId ? workflow.items.find((item) => item.id === itemId) ?? null : null;
976
+ const currentItem = focusedItem ?? null;
913
977
  const currentPhase = currentItem?.currentPhase ?? null;
914
978
  const activeFlowStage = currentItem ? flowResolution.flow?.stages.find((stage) => stage.id === currentItem.stage) ?? null : null;
915
979
  const activePhaseDef = currentPhase && activeFlowStage?.phases?.states?.[currentPhase] ? activeFlowStage.phases.states[currentPhase] : null;
916
980
  const activePhaseHarness = activePhaseDef?.harness ?? null;
917
981
  const activeReviewExpectation = activePhaseHarness?.activity?.review ?? activePhaseHarness?.review ?? activeFlowStage?.activity?.review ?? null;
918
982
  const activeGateExpectation = activePhaseHarness?.activity?.gate ?? activePhaseHarness?.gate ?? activeFlowStage?.activity?.gate ?? null;
919
- const focusDiverged = !!(focus && currentItem?.spec && focus.specName !== currentItem.spec);
920
- const specName = focus?.specName || currentItem?.spec || null;
983
+ const focusDiverged = false;
984
+ const specName = currentItem?.spec ?? null;
921
985
  const spec = loadSpecMeta(root, specName);
922
986
  const activeAlerts = getActiveEntries(loadHealthRecord(root));
923
987
  const lastActions = queryLog(root, { all: false, limit: 5 });
@@ -945,14 +1009,14 @@ function buildSignals(activity, intentSignal, focusDiverged, alertCount, highSev
945
1009
  signals.push({
946
1010
  level: "warning",
947
1011
  code: "no-current-item",
948
- message: "Nenhum item em andamento. Selecione um item no Kanban para come\xE7ar."
1012
+ message: "Nenhuma execu\xE7\xE3o atribu\xEDda. Aguarde uma atribui\xE7\xE3o ou selecione uma execu\xE7\xE3o explicitamente."
949
1013
  });
950
1014
  }
951
1015
  if (focusDiverged) {
952
1016
  signals.push({
953
1017
  level: "error",
954
1018
  code: "focus-diverged",
955
- message: "Foco desatualizado. Atualize focus.md ou selecione o item correto."
1019
+ message: "O foco visual diverge da execu\xE7\xE3o. A dire\xE7\xE3o da execu\xE7\xE3o permanece can\xF4nica."
956
1020
  });
957
1021
  }
958
1022
  if (alertCount > 0) {
@@ -998,22 +1062,34 @@ function buildRisks(activity, alertCount, highSeverityCount, pendingAcs) {
998
1062
  }
999
1063
  function buildActivityContext(options) {
1000
1064
  const { activity, workspaceRoot } = options;
1001
- const sources = loadActivityContextSources(workspaceRoot);
1065
+ const direction = resolveDirection(workspaceRoot, {
1066
+ runId: options.runId,
1067
+ executorId: options.executorId,
1068
+ itemId: options.itemId
1069
+ });
1070
+ const selectedRunId = options.runId ?? direction.assignment?.runId;
1071
+ const selectedItemId = options.itemId ?? direction.item?.id;
1072
+ const sources = loadActivityContextSources(workspaceRoot, selectedItemId, selectedRunId);
1002
1073
  const intent = resolveActivityIntent(activity, sources);
1003
- const currentItem = sources.currentItem;
1074
+ const currentItem = direction.item ? { id: direction.item.id, description: direction.item.description, stage: direction.item.stage, spec: direction.item.spec } : null;
1075
+ if (!currentItem) {
1076
+ intent.objective = direction.assignment?.status === "selection-required" ? "H\xE1 m\xFAltiplas execu\xE7\xF5es; selecione uma antes de receber contexto de trabalho." : "Nenhuma execu\xE7\xE3o foi atribu\xEDda a esta sess\xE3o.";
1077
+ intent.nextActions = [{ label: "Aguardar atribui\xE7\xE3o", description: "Uma execu\xE7\xE3o ou item deve ser selecionado explicitamente antes de receber contexto de trabalho." }];
1078
+ intent.mustRead = intent.mustRead.filter((reference) => !reference.path.includes("/specs/"));
1079
+ }
1004
1080
  const currentItemContext = currentItem ? {
1005
1081
  id: currentItem.id,
1006
1082
  description: currentItem.description,
1007
1083
  stage: currentItem.stage,
1008
- stageName: sources.activeFlowStage?.name ?? (sources.workflow ? getStageName2(sources.workflow, currentItem.stage) : currentItem.stage),
1084
+ stageName: sources.activeFlowStage?.name ?? (sources.workflow ? getStageName3(sources.workflow, currentItem.stage) : currentItem.stage),
1009
1085
  currentPhase: sources.currentPhase ?? void 0,
1010
1086
  spec: currentItem.spec ?? null,
1011
- outcome: sources.spec?.outcome ?? sources.focus?.outcome ?? null,
1087
+ outcome: sources.spec?.outcome ?? null,
1012
1088
  acs: sources.spec?.acs ?? { pending: 0, done: 0, total: 0 }
1013
1089
  } : null;
1014
1090
  const stage = currentItem ? {
1015
1091
  id: currentItem.stage,
1016
- name: sources.activeFlowStage?.name ?? (sources.workflow ? getStageName2(sources.workflow, currentItem.stage) : currentItem.stage)
1092
+ name: sources.activeFlowStage?.name ?? (sources.workflow ? getStageName3(sources.workflow, currentItem.stage) : currentItem.stage)
1017
1093
  } : null;
1018
1094
  const highSeverityCount = sources.activeAlerts.filter(
1019
1095
  (entry) => entry.severity === "alta"
@@ -1021,6 +1097,8 @@ function buildActivityContext(options) {
1021
1097
  const pendingAcs = sources.spec?.acs.pending ?? 0;
1022
1098
  return {
1023
1099
  activity,
1100
+ assignment: direction.assignment,
1101
+ directionRevision: direction.revision,
1024
1102
  objective: intent.objective,
1025
1103
  currentItem: currentItemContext,
1026
1104
  stage,
@@ -1044,16 +1122,19 @@ function buildActivityContext(options) {
1044
1122
  function resolveRequestedActivity(value) {
1045
1123
  return value === "design" || value === "implement" || value === "review" || value === "diagnose" || value === "gate" ? value : "implement";
1046
1124
  }
1047
- function buildRequestedActivityContext(workspaceRoot, activityParam) {
1125
+ function buildRequestedActivityContext(workspaceRoot, activityParam, runId, executorId, itemId) {
1048
1126
  return buildActivityContext({
1049
1127
  activity: resolveRequestedActivity(activityParam),
1050
- workspaceRoot
1128
+ workspaceRoot,
1129
+ runId: runId ?? void 0,
1130
+ executorId: executorId ?? void 0,
1131
+ itemId: itemId ?? void 0
1051
1132
  });
1052
1133
  }
1053
1134
  function readFocusState(workspaceDir) {
1054
1135
  const focusFile = join4(workspaceDir, "focus.md");
1055
- if (!existsSync5(focusFile)) return { active: false };
1056
- const lines = readFileSync5(focusFile, "utf-8").split(/\r?\n/);
1136
+ if (!existsSync4(focusFile)) return { active: false };
1137
+ const lines = readFileSync4(focusFile, "utf-8").split(/\r?\n/);
1057
1138
  const itemLine = lines.find((line) => line.startsWith("**Item**: "));
1058
1139
  return {
1059
1140
  active: true,
@@ -1063,33 +1144,33 @@ function readFocusState(workspaceDir) {
1063
1144
  }
1064
1145
  function readFocusDocument(workspaceDir) {
1065
1146
  const focusFile = join4(workspaceDir, "focus.md");
1066
- return existsSync5(focusFile) ? readFileSync5(focusFile, "utf-8") : null;
1147
+ return existsSync4(focusFile) ? readFileSync4(focusFile, "utf-8") : null;
1067
1148
  }
1068
1149
  function readDecisions(workspaceDir) {
1069
1150
  const decisionsDir = join4(workspaceDir, "decisions");
1070
- if (!existsSync5(decisionsDir)) return [];
1151
+ if (!existsSync4(decisionsDir)) return [];
1071
1152
  return readdirSync2(decisionsDir).filter((name) => name.endsWith(".md")).sort().reverse().map((name) => ({
1072
1153
  name,
1073
- content: readFileSync5(join4(decisionsDir, name), "utf-8")
1154
+ content: readFileSync4(join4(decisionsDir, name), "utf-8")
1074
1155
  }));
1075
1156
  }
1076
1157
  function contextFileExists(workspaceDir, file) {
1077
- return existsSync5(join4(workspaceDir, file));
1158
+ return existsSync4(join4(workspaceDir, file));
1078
1159
  }
1079
1160
 
1080
1161
  // src/flow-serve/workspace.ts
1081
1162
  import {
1082
1163
  accessSync,
1083
1164
  constants,
1084
- existsSync as existsSync6,
1085
- mkdirSync as mkdirSync2,
1165
+ existsSync as existsSync5,
1166
+ mkdirSync,
1086
1167
  rmSync,
1087
- readFileSync as readFileSync6,
1168
+ readFileSync as readFileSync5,
1088
1169
  readdirSync as readdirSync3,
1089
- statSync,
1090
- writeFileSync as writeFileSync2
1170
+ statSync as statSync2,
1171
+ writeFileSync
1091
1172
  } from "fs";
1092
- import { basename, join as join5, resolve as resolve2 } from "path";
1173
+ import { basename, join as join5, resolve as resolve3 } from "path";
1093
1174
  var LEGACY_BOOTSTRAP_TEMPLATES = {
1094
1175
  padrao: {
1095
1176
  name: "Padr\xE3o",
@@ -1131,17 +1212,17 @@ var TARGET_MARKERS = [
1131
1212
  "build.gradle.kts"
1132
1213
  ];
1133
1214
  function hasTargetMarker(path) {
1134
- return TARGET_MARKERS.some((marker) => existsSync6(join5(path, marker))) || existsSync6(join5(path, ".git"));
1215
+ return TARGET_MARKERS.some((marker) => existsSync5(join5(path, marker))) || existsSync5(join5(path, ".git"));
1135
1216
  }
1136
1217
  function detectStack(path) {
1137
1218
  const stack = /* @__PURE__ */ new Set();
1138
1219
  const evidence = [];
1139
1220
  const packagePath = join5(path, "package.json");
1140
- if (existsSync6(packagePath)) {
1221
+ if (existsSync5(packagePath)) {
1141
1222
  stack.add("Node.js");
1142
1223
  evidence.push("package.json");
1143
1224
  try {
1144
- const pkg = JSON.parse(readFileSync6(packagePath, "utf-8"));
1225
+ const pkg = JSON.parse(readFileSync5(packagePath, "utf-8"));
1145
1226
  const deps = { ...pkg.dependencies, ...pkg.devDependencies };
1146
1227
  if (deps.react) stack.add("React");
1147
1228
  if (deps.vite) stack.add("Vite");
@@ -1151,17 +1232,17 @@ function detectStack(path) {
1151
1232
  evidence.push("package.json inv\xE1lido");
1152
1233
  }
1153
1234
  }
1154
- if (existsSync6(join5(path, "pyproject.toml")) || existsSync6(join5(path, "requirements.txt"))) {
1235
+ if (existsSync5(join5(path, "pyproject.toml")) || existsSync5(join5(path, "requirements.txt"))) {
1155
1236
  stack.add("Python");
1156
1237
  evidence.push(
1157
- existsSync6(join5(path, "pyproject.toml")) ? "pyproject.toml" : "requirements.txt"
1238
+ existsSync5(join5(path, "pyproject.toml")) ? "pyproject.toml" : "requirements.txt"
1158
1239
  );
1159
1240
  }
1160
- if (existsSync6(join5(path, "go.mod"))) {
1241
+ if (existsSync5(join5(path, "go.mod"))) {
1161
1242
  stack.add("Go");
1162
1243
  evidence.push("go.mod");
1163
1244
  }
1164
- if (existsSync6(join5(path, "Cargo.toml"))) {
1245
+ if (existsSync5(join5(path, "Cargo.toml"))) {
1165
1246
  stack.add("Rust");
1166
1247
  evidence.push("Cargo.toml");
1167
1248
  }
@@ -1172,9 +1253,9 @@ function detectStack(path) {
1172
1253
  }
1173
1254
  } catch {
1174
1255
  }
1175
- if (existsSync6(join5(path, "Dockerfile")) || existsSync6(join5(path, "docker-compose.yml"))) {
1256
+ if (existsSync5(join5(path, "Dockerfile")) || existsSync5(join5(path, "docker-compose.yml"))) {
1176
1257
  stack.add("Docker");
1177
- evidence.push(existsSync6(join5(path, "Dockerfile")) ? "Dockerfile" : "docker-compose.yml");
1258
+ evidence.push(existsSync5(join5(path, "Dockerfile")) ? "Dockerfile" : "docker-compose.yml");
1178
1259
  }
1179
1260
  return { stack: [...stack], evidence };
1180
1261
  }
@@ -1210,8 +1291,8 @@ function discoverTargetPaths(root) {
1210
1291
  return [...candidates].slice(0, 100);
1211
1292
  }
1212
1293
  function analyzeWorkspaceSetup(input) {
1213
- const root = resolve2(input.root);
1214
- if (!existsSync6(root) || !statSync(root).isDirectory()) {
1294
+ const root = resolve3(input.root);
1295
+ if (!existsSync5(root) || !statSync2(root).isDirectory()) {
1215
1296
  throw new Error("A pasta inicial n\xE3o existe ou n\xE3o \xE9 um diret\xF3rio.");
1216
1297
  }
1217
1298
  try {
@@ -1238,7 +1319,7 @@ function analyzeWorkspaceSetup(input) {
1238
1319
  state: isDetected ? "detected" : "available",
1239
1320
  selected: isDetected,
1240
1321
  evidence: isDetected ? tool.detectionPaths.filter(
1241
- (adapterPath) => existsSync6(join5(path, adapterPath))
1322
+ (adapterPath) => existsSync5(join5(path, adapterPath))
1242
1323
  ) : []
1243
1324
  };
1244
1325
  })
@@ -1280,7 +1361,7 @@ function buildLineDiff(before, after) {
1280
1361
  return lines.length > limit ? [...lines.slice(0, limit), ` ... ${lines.length - limit} linha(s) omitida(s)`].join("\n") : lines.join("\n");
1281
1362
  }
1282
1363
  function operationFor(path, context, after) {
1283
- if (!existsSync6(path)) {
1364
+ if (!existsSync5(path)) {
1284
1365
  return {
1285
1366
  kind: "create",
1286
1367
  path: path.replace(/\\/g, "/"),
@@ -1290,7 +1371,7 @@ function operationFor(path, context, after) {
1290
1371
  diff: buildLineDiff("", after)
1291
1372
  };
1292
1373
  }
1293
- const current = readFileSync6(path, "utf-8");
1374
+ const current = readFileSync5(path, "utf-8");
1294
1375
  const generated = /(?:Generated by letra|Gerado (?:por|by) letra)/i.test(current.slice(0, 500));
1295
1376
  const managedSection = context.artifactId === "codex-project-config";
1296
1377
  return {
@@ -1304,11 +1385,11 @@ function operationFor(path, context, after) {
1304
1385
  };
1305
1386
  }
1306
1387
  function planWorkspaceSetup(input) {
1307
- const workspaceRoot = resolve2(input.workspaceRoot);
1388
+ const workspaceRoot = resolve3(input.workspaceRoot);
1308
1389
  const normalizedRoot = workspaceRoot.replace(/\\/g, "/");
1309
1390
  const operations = [];
1310
1391
  const workflowPath = join5(workspaceRoot, "workflow.json");
1311
- const workflowBefore = existsSync6(workflowPath) ? readFileSync6(workflowPath, "utf-8") : void 0;
1392
+ const workflowBefore = existsSync5(workflowPath) ? readFileSync5(workflowPath, "utf-8") : void 0;
1312
1393
  const workflowAfter = input.workflow ? JSON.stringify(input.workflow, null, 2) : void 0;
1313
1394
  operations.push({
1314
1395
  kind: workflowBefore ? "conflict" : "create",
@@ -1319,12 +1400,12 @@ function planWorkspaceSetup(input) {
1319
1400
  diff: workflowAfter ? buildLineDiff(workflowBefore || "", workflowAfter) : void 0
1320
1401
  });
1321
1402
  for (const target of input.targets) {
1322
- const resolvedTarget = resolve2(target.path);
1323
- if (!existsSync6(resolvedTarget) || !statSync(resolvedTarget).isDirectory()) {
1403
+ const resolvedTarget = resolve3(target.path);
1404
+ if (!existsSync5(resolvedTarget) || !statSync2(resolvedTarget).isDirectory()) {
1324
1405
  throw new Error(`O projeto "${target.label}" n\xE3o existe ou n\xE3o \xE9 um diret\xF3rio.`);
1325
1406
  }
1326
1407
  const linkPath = join5(resolvedTarget, ".letra-link");
1327
- const linkBefore = existsSync6(linkPath) ? readFileSync6(linkPath, "utf-8") : void 0;
1408
+ const linkBefore = existsSync5(linkPath) ? readFileSync5(linkPath, "utf-8") : void 0;
1328
1409
  const linkAfter = `${normalizedRoot}
1329
1410
  `;
1330
1411
  const linkMatches = linkBefore?.trim().replace(/\\/g, "/") === normalizedRoot;
@@ -1401,11 +1482,11 @@ function createWorkflowFromTemplate(root, templateId, options, harness) {
1401
1482
  function registerWorkspaceSetup(input) {
1402
1483
  const name = input.name.trim();
1403
1484
  const description = input.description.trim();
1404
- const workspaceRoot = input.workspacePath ? resolve2(input.workspacePath) : resolve2(process.cwd());
1405
- mkdirSync2(workspaceRoot, { recursive: true });
1485
+ const workspaceRoot = input.workspacePath ? resolve3(input.workspacePath) : resolve3(process.cwd());
1486
+ mkdirSync(workspaceRoot, { recursive: true });
1406
1487
  const slug2 = name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 64);
1407
1488
  const registryDir = join5(getLetraDir(), "workspaces", slug2);
1408
- mkdirSync2(registryDir, { recursive: true });
1489
+ mkdirSync(registryDir, { recursive: true });
1409
1490
  const workspaceId = `ws_${Date.now().toString(36)}`;
1410
1491
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
1411
1492
  const workspace = {
@@ -1420,18 +1501,18 @@ function registerWorkspaceSetup(input) {
1420
1501
  template: input.template
1421
1502
  };
1422
1503
  const registryFile = join5(registryDir, "workspace.json");
1423
- if (existsSync6(registryFile)) {
1504
+ if (existsSync5(registryFile)) {
1424
1505
  throw new Error("J\xE1 existe um workspace registrado com este nome.");
1425
1506
  }
1426
- writeFileSync2(registryFile, JSON.stringify(workspace, null, 2), "utf-8");
1507
+ writeFileSync(registryFile, JSON.stringify(workspace, null, 2), "utf-8");
1427
1508
  return { workspace, workspaceRoot, registryFile };
1428
1509
  }
1429
1510
  function writeWorkspaceTargetAdapters(workspaceRoot, targets, workflow) {
1430
1511
  const workspaceRootNormalized = workspaceRoot.replace(/\\/g, "/");
1431
1512
  for (const target of targets) {
1432
- const targetPath = resolve2(target.path);
1433
- if (!existsSync6(targetPath)) continue;
1434
- writeFileSync2(join5(targetPath, ".letra-link"), `${workspaceRootNormalized}
1513
+ const targetPath = resolve3(target.path);
1514
+ if (!existsSync5(targetPath)) continue;
1515
+ writeFileSync(join5(targetPath, ".letra-link"), `${workspaceRootNormalized}
1435
1516
  `, "utf-8");
1436
1517
  generateAdapters(targetPath, target.adapters, {
1437
1518
  source: "init",
@@ -1447,10 +1528,10 @@ function writeWorkspaceTargetAdapters(workspaceRoot, targets, workflow) {
1447
1528
  }
1448
1529
  }
1449
1530
  function writeExternalWorkspaceSetup(workspaceRoot, workflow, workspace) {
1450
- const root = resolve2(workspaceRoot);
1531
+ const root = resolve3(workspaceRoot);
1451
1532
  ensureExternalWorkspaceLayout(root, { workflow, workspace });
1452
- writeFileSync2(join5(root, "workflow.json"), JSON.stringify(workflow, null, 2), "utf-8");
1453
- writeFileSync2(join5(root, "workspace.json"), JSON.stringify(workspace, null, 2), "utf-8");
1533
+ writeFileSync(join5(root, "workflow.json"), JSON.stringify(workflow, null, 2), "utf-8");
1534
+ writeFileSync(join5(root, "workspace.json"), JSON.stringify(workspace, null, 2), "utf-8");
1454
1535
  }
1455
1536
  function workflowLocations(targets, workspaceRoot) {
1456
1537
  return targets.map((target) => ({
@@ -1459,31 +1540,31 @@ function workflowLocations(targets, workspaceRoot) {
1459
1540
  label: target.label,
1460
1541
  adapters: [...target.adapters]
1461
1542
  })).filter(
1462
- (target) => resolve2(target.path) !== resolve2(workspaceRoot) || target.adapters.length > 0
1543
+ (target) => resolve3(target.path) !== resolve3(workspaceRoot) || target.adapters.length > 0
1463
1544
  );
1464
1545
  }
1465
1546
  function captureWorkspaceSetup(plan) {
1466
1547
  return plan.operations.filter((operation) => operation.kind === "create" || operation.kind === "update").map((operation) => ({
1467
1548
  path: operation.path,
1468
- existed: existsSync6(operation.path),
1469
- contentBase64: existsSync6(operation.path) ? Buffer.from(readFileSync6(operation.path)).toString("base64") : void 0
1549
+ existed: existsSync5(operation.path),
1550
+ contentBase64: existsSync5(operation.path) ? Buffer.from(readFileSync5(operation.path)).toString("base64") : void 0
1470
1551
  }));
1471
1552
  }
1472
1553
  function restoreWorkspaceSetup(snapshots) {
1473
1554
  for (const snapshot of [...snapshots].reverse()) {
1474
1555
  if (snapshot.existed) {
1475
- mkdirSync2(join5(snapshot.path, ".."), { recursive: true });
1476
- writeFileSync2(snapshot.path, Buffer.from(snapshot.contentBase64 || "", "base64"));
1477
- } else if (existsSync6(snapshot.path)) {
1556
+ mkdirSync(join5(snapshot.path, ".."), { recursive: true });
1557
+ writeFileSync(snapshot.path, Buffer.from(snapshot.contentBase64 || "", "base64"));
1558
+ } else if (existsSync5(snapshot.path)) {
1478
1559
  rmSync(snapshot.path, { force: true });
1479
1560
  }
1480
1561
  }
1481
1562
  }
1482
1563
  function saveWorkspaceSetupManifest(workspaceRoot, proposalId, operations, snapshots) {
1483
1564
  const manifestId = `setup-${Date.now().toString(36)}`;
1484
- const manifestDir = join5(resolve2(workspaceRoot), "operations", "setup-manifests");
1485
- mkdirSync2(manifestDir, { recursive: true });
1486
- writeFileSync2(
1565
+ const manifestDir = join5(resolve3(workspaceRoot), "operations", "setup-manifests");
1566
+ mkdirSync(manifestDir, { recursive: true });
1567
+ writeFileSync(
1487
1568
  join5(manifestDir, `${manifestId}.json`),
1488
1569
  JSON.stringify(
1489
1570
  {
@@ -1502,14 +1583,14 @@ function saveWorkspaceSetupManifest(workspaceRoot, proposalId, operations, snaps
1502
1583
  }
1503
1584
  function rollbackWorkspaceSetup(workspaceRoot, manifestId) {
1504
1585
  if (!/^setup-[a-z0-9]+$/i.test(manifestId)) throw new Error("Manifest de rollback inv\xE1lido.");
1505
- const root = resolve2(workspaceRoot);
1506
- const manifestPath = existsSync6(
1586
+ const root = resolve3(workspaceRoot);
1587
+ const manifestPath = existsSync5(
1507
1588
  join5(root, "operations", "setup-manifests", `${manifestId}.json`)
1508
1589
  ) ? join5(root, "operations", "setup-manifests", `${manifestId}.json`) : join5(root, ".letra", "setup-manifests", `${manifestId}.json`);
1509
- if (!existsSync6(manifestPath)) throw new Error("Manifest de rollback n\xE3o encontrado.");
1510
- const manifest = JSON.parse(readFileSync6(manifestPath, "utf-8"));
1590
+ if (!existsSync5(manifestPath)) throw new Error("Manifest de rollback n\xE3o encontrado.");
1591
+ const manifest = JSON.parse(readFileSync5(manifestPath, "utf-8"));
1511
1592
  restoreWorkspaceSetup(Array.isArray(manifest.snapshots) ? manifest.snapshots : []);
1512
- writeFileSync2(
1593
+ writeFileSync(
1513
1594
  join5(manifestPath, "..", `${manifestId}.rollback.json`),
1514
1595
  JSON.stringify({ manifestId, rolledBackAt: (/* @__PURE__ */ new Date()).toISOString() }, null, 2),
1515
1596
  "utf-8"
@@ -1531,7 +1612,7 @@ var RECURRING_SYSTEM_ACTIONS = [
1531
1612
  label: "Specs watcher",
1532
1613
  trigger: "watch",
1533
1614
  cadence: "sob mudan\xE7a de arquivo",
1534
- cause: "Mudan\xE7a em `.letra/specs/**`",
1615
+ cause: "Mudan\xE7a em `specs/**` no diret\xF3rio de dados do workspace",
1535
1616
  effect: "Atualiza a vis\xE3o derivada de specs e emite `workflow-updated`"
1536
1617
  },
1537
1618
  {
@@ -1645,6 +1726,16 @@ function sendJson(res, status, payload) {
1645
1726
  function sendError(res, status, message) {
1646
1727
  sendJson(res, status, { error: message });
1647
1728
  }
1729
+ function sendRefusal(res, status, operation) {
1730
+ sendJson(res, status, {
1731
+ error: operation.reason,
1732
+ code: operation.reasonCode,
1733
+ reason: operation.reason,
1734
+ recoveryActions: operation.recoveryActions ?? [],
1735
+ nextCommand: operation.nextCommand ?? null,
1736
+ humanRequired: operation.humanRequired ?? false
1737
+ });
1738
+ }
1648
1739
  function routeParam(path, pattern) {
1649
1740
  const pathSegments = path.split("/").filter(Boolean);
1650
1741
  const patternSegments = pattern.split("/").filter(Boolean);
@@ -1663,14 +1754,6 @@ function routeParam(path, pattern) {
1663
1754
  }
1664
1755
 
1665
1756
  // src/flow-serve/routes/item-routes.ts
1666
- function resolveDecisionTarget(flow, currentStageId, target) {
1667
- const currentIndex = flow.stages.findIndex((stage) => stage.id === currentStageId);
1668
- if (currentIndex === -1) return null;
1669
- if (target === "next") return flow.stages[currentIndex + 1]?.id ?? null;
1670
- if (target === "previous") return flow.stages[currentIndex - 1]?.id ?? null;
1671
- if (target === "first") return flow.stages[0]?.id ?? null;
1672
- return flow.stages.some((stage) => stage.id === target) ? target : null;
1673
- }
1674
1757
  function sendBodyError(error, res) {
1675
1758
  if (error instanceof HttpBodyError) {
1676
1759
  sendError(res, error.status, error.message);
@@ -1681,6 +1764,87 @@ function sendBodyError(error, res) {
1681
1764
  function createItemRoutes(dependencies) {
1682
1765
  return async (context) => {
1683
1766
  const { method, path, req, res, workspaceRoot, workflow } = context;
1767
+ const itemMutation = method !== "GET" && (path === "/api/operations/validate" || path === "/api/items" || path.startsWith("/api/items/"));
1768
+ const sessionActor = itemMutation ? dependencies.resolveHumanActor?.(req) : null;
1769
+ if (itemMutation && !sessionActor) {
1770
+ sendError(res, 403, "HUMAN_CONFIRMATION_REQUIRED");
1771
+ return true;
1772
+ }
1773
+ if (path === "/api/operations/validate" && method === "POST") {
1774
+ try {
1775
+ if (!dependencies.runValidationOperation) {
1776
+ sendError(res, 503, "Canonical validation operation unavailable");
1777
+ return true;
1778
+ }
1779
+ const data = await readJson(req);
1780
+ if (!data.expectedRevision && !data.itemId) {
1781
+ sendError(res, 400, "itemId or expectedRevision required");
1782
+ return true;
1783
+ }
1784
+ const operation = await dependencies.runValidationOperation(
1785
+ workspaceRoot,
1786
+ {
1787
+ itemId: data.itemId,
1788
+ expectedRevision: data.expectedRevision ?? directionForOperation(workspaceRoot, { itemId: data.itemId }).revision,
1789
+ reason: data.reason?.trim() || "Valida\xE7\xE3o solicitada pela UI.",
1790
+ actor: sessionActor
1791
+ }
1792
+ );
1793
+ if (operation.outcome !== "accepted") {
1794
+ sendRefusal(res, operation.reasonCode === "DIRECTION_STALE" ? 409 : 422, operation);
1795
+ return true;
1796
+ }
1797
+ dependencies.broadcast();
1798
+ sendJson(res, 200, operation);
1799
+ } catch (error) {
1800
+ sendBodyError(error, res);
1801
+ }
1802
+ return true;
1803
+ }
1804
+ const passageMatch = method === "POST" ? path.match(/^\/api\/items\/([^/]+)\/passage$/) : null;
1805
+ if (passageMatch) {
1806
+ if (!dependencies.requestPassageOperation) {
1807
+ sendError(res, 503, "Canonical passage operation unavailable");
1808
+ return true;
1809
+ }
1810
+ try {
1811
+ const data = await readJson(req);
1812
+ const itemId2 = decodeURIComponent(passageMatch[1]);
1813
+ const claimHolder = workflow?.items.find(
1814
+ (candidate) => candidate.id === itemId2
1815
+ )?.claimedBy;
1816
+ const passageReason = data.reason?.trim() || "Passagem solicitada pela UI.";
1817
+ const operation = await dependencies.requestPassageOperation(
1818
+ workspaceRoot,
1819
+ {
1820
+ itemId: itemId2,
1821
+ targetStageId: data.targetStageId,
1822
+ to: data.to,
1823
+ executorId: data.executorId,
1824
+ runId: data.runId,
1825
+ summary: data.summary,
1826
+ evidence: data.evidence ?? [],
1827
+ actor: claimHolder ?? sessionActor,
1828
+ expectedRevision: data.expectedRevision ?? directionForRunAwareOperation(workspaceRoot, {
1829
+ itemId: itemId2,
1830
+ runId: data.runId,
1831
+ executorId: data.executorId
1832
+ }).revision,
1833
+ reason: claimHolder && claimHolder !== sessionActor ? `${passageReason} (solicitada por ${sessionActor})` : passageReason,
1834
+ idempotencyKey: data.idempotencyKey
1835
+ }
1836
+ );
1837
+ if (operation.outcome !== "accepted") {
1838
+ sendRefusal(res, operation.reasonCode === "DIRECTION_STALE" ? 409 : 422, operation);
1839
+ return true;
1840
+ }
1841
+ dependencies.broadcast();
1842
+ sendJson(res, 200, operation);
1843
+ } catch (error) {
1844
+ sendBodyError(error, res);
1845
+ }
1846
+ return true;
1847
+ }
1684
1848
  if (path === "/api/items/alerts" && method === "GET") {
1685
1849
  const record = dependencies.loadHealthRecord(workspaceRoot);
1686
1850
  const itemAlerts = {};
@@ -1701,34 +1865,38 @@ function createItemRoutes(dependencies) {
1701
1865
  sendError(res, 400, "id, description, and stage required");
1702
1866
  return true;
1703
1867
  }
1704
- if (!workflow) {
1705
- sendError(res, 404, "No workflow");
1868
+ if (!dependencies.createItemOperation) {
1869
+ sendError(res, 503, "Canonical item creation operation unavailable");
1870
+ return true;
1871
+ }
1872
+ const operation = await dependencies.createItemOperation(
1873
+ workspaceRoot,
1874
+ {
1875
+ id: data.id,
1876
+ description: data.description,
1877
+ stage: data.stage,
1878
+ actor: sessionActor,
1879
+ expectedRevision: data.expectedRevision ?? directionForOperation(workspaceRoot, {}).revision,
1880
+ reason: data.reason?.trim() || "Item criado pela UI.",
1881
+ idempotencyKey: data.idempotencyKey
1882
+ }
1883
+ );
1884
+ if (operation.outcome !== "accepted") {
1885
+ const status = operation.reasonCode === "DIRECTION_STALE" ? 409 : operation.reasonCode === "ITEM_NOT_FOUND" ? 404 : operation.reasonCode === "ITEM_COMPLETED" ? 400 : 422;
1886
+ sendRefusal(res, status, operation);
1706
1887
  return true;
1707
1888
  }
1708
- const item = {
1709
- id: data.id,
1710
- description: data.description,
1711
- stage: data.stage,
1712
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1713
- tasks: []
1714
- };
1715
- workflow.items.push(item);
1716
- workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1717
- dependencies.writeWorkflow(workspaceRoot, {
1718
- workflow,
1719
- source: "web-ui",
1720
- primaryItemId: item.id,
1721
- skipSitrep: true,
1722
- quiet: true
1723
- });
1724
1889
  dependencies.broadcast();
1725
- sendJson(res, 200, item);
1890
+ sendJson(res, 200, operation);
1726
1891
  } catch (error) {
1727
1892
  sendBodyError(error, res);
1728
1893
  }
1729
1894
  return true;
1730
1895
  }
1731
- const gateDecisionItemId = routeParam(path, "/api/items/:id/gate-decisions");
1896
+ const gateDecisionItemId = routeParam(
1897
+ path,
1898
+ "/api/items/:id/gate-decisions"
1899
+ );
1732
1900
  if (gateDecisionItemId !== null && method === "POST") {
1733
1901
  try {
1734
1902
  const data = await readJson(req);
@@ -1737,111 +1905,133 @@ function createItemRoutes(dependencies) {
1737
1905
  return true;
1738
1906
  }
1739
1907
  if (!data.decision || !["approve", "request-changes", "reject"].includes(data.decision)) {
1740
- sendError(res, 400, "decision must be approve, request-changes, or reject");
1908
+ sendError(
1909
+ res,
1910
+ 400,
1911
+ "decision must be approve, request-changes, or reject"
1912
+ );
1741
1913
  return true;
1742
1914
  }
1743
1915
  const reason = data.reason?.trim();
1744
1916
  if (data.decision !== "approve" && !reason) {
1745
- sendError(res, 400, "reason is required for request-changes and reject");
1746
- return true;
1747
- }
1748
- const item = workflow.items.find(
1749
- (candidate) => candidate.id === gateDecisionItemId
1750
- );
1751
- if (!item) {
1752
- sendError(res, 404, "Item not found");
1753
- return true;
1754
- }
1755
- const resolved = dependencies.resolveActiveFlow(workspaceRoot, workflow);
1756
- const flow = resolved.flow;
1757
- const currentStage = flow?.stages.find((stage) => stage.id === item.stage);
1758
- const gate = currentStage?.gate;
1759
- if (!flow || gate?.type !== "human" || !gate.blocking) {
1760
- sendError(res, 422, "Item is not waiting at a blocking human gate");
1761
- return true;
1762
- }
1763
- const targetRule = gate.decisions?.[data.decision];
1764
- if (!targetRule) {
1765
1917
  sendError(
1766
1918
  res,
1767
- 422,
1768
- `Gate "${gate.name}" does not define the "${data.decision}" decision in the harness`
1919
+ 400,
1920
+ "reason is required for request-changes and reject"
1769
1921
  );
1770
1922
  return true;
1771
1923
  }
1772
- const targetStage = resolveDecisionTarget(flow, item.stage, targetRule);
1773
- if (!targetStage) {
1774
- sendError(
1775
- res,
1776
- 422,
1777
- `Gate "${gate.name}" resolves "${data.decision}" to an invalid stage`
1778
- );
1924
+ if (!dependencies.decideGateOperation) {
1925
+ sendError(res, 503, "Canonical gate decision operation unavailable");
1779
1926
  return true;
1780
1927
  }
1781
- const sourceStage = item.stage;
1782
- item.stage = targetStage;
1783
- const targetStageDefinition = flow.stages.find((stage) => stage.id === targetStage);
1784
- const targetActor = targetStageDefinition?.agents[0];
1785
- if (targetActor) {
1786
- item.handoff = {
1787
- from: "human:web-ui",
1788
- to: targetActor,
1789
- summary: `Gate ${gate.name} decision ${data.decision}; continue at ${targetStageDefinition?.name ?? targetStage}.`,
1790
- evidence: [`gate:${gate.id}:${data.decision}`],
1791
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1792
- expiresAt: new Date(Date.now() + 30 * 6e4).toISOString()
1793
- };
1794
- } else {
1795
- item.handoff = void 0;
1928
+ {
1929
+ const expectedRevision = data.expectedRevision ?? directionForOperation(workspaceRoot, { itemId: gateDecisionItemId }).revision;
1930
+ const operationReason = reason ?? "Aprova\xE7\xE3o humana registrada pela UI.";
1931
+ const proof = signLocalOperation(
1932
+ workspaceRoot,
1933
+ sessionActor,
1934
+ "gate.decision",
1935
+ {
1936
+ itemId: gateDecisionItemId,
1937
+ decision: data.decision,
1938
+ expectedRevision,
1939
+ reason: operationReason
1940
+ }
1941
+ );
1942
+ const operation = await dependencies.decideGateOperation(
1943
+ workspaceRoot,
1944
+ {
1945
+ itemId: gateDecisionItemId,
1946
+ decision: data.decision,
1947
+ actor: sessionActor,
1948
+ expectedRevision,
1949
+ reason: operationReason,
1950
+ proof,
1951
+ idempotencyKey: data.idempotencyKey
1952
+ }
1953
+ );
1954
+ if (operation.outcome !== "accepted") {
1955
+ sendRefusal(res, operation.reasonCode === "DIRECTION_STALE" ? 409 : 422, operation);
1956
+ return true;
1957
+ }
1958
+ dependencies.broadcast();
1959
+ void dependencies.fireWebhooks(workspaceRoot, "gate.decided", {
1960
+ itemId: gateDecisionItemId,
1961
+ decision: data.decision,
1962
+ reason: reason ?? null
1963
+ });
1964
+ sendJson(res, 200, operation);
1965
+ return true;
1796
1966
  }
1797
- workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1798
- await dependencies.writeWorkflow(workspaceRoot, {
1799
- workflow,
1800
- source: "web-ui-gate-decision",
1801
- primaryItemId: item.id,
1802
- skipSitrep: true,
1803
- quiet: true
1804
- });
1805
- dependencies.logEntry(
1967
+ } catch (error) {
1968
+ sendBodyError(error, res);
1969
+ }
1970
+ return true;
1971
+ }
1972
+ const activateItemId = routeParam(path, "/api/items/:id/activate");
1973
+ if (activateItemId !== null && method === "POST") {
1974
+ if (!dependencies.activateWorkOperation) {
1975
+ sendError(res, 501, "Ativa\xE7\xE3o can\xF4nica n\xE3o est\xE1 dispon\xEDvel.");
1976
+ return true;
1977
+ }
1978
+ try {
1979
+ const data = await readJson(req);
1980
+ const operation = await dependencies.activateWorkOperation(
1806
1981
  workspaceRoot,
1807
- "decision",
1808
- `Gate ${gate.name}: ${data.decision} (${item.id})`,
1809
1982
  {
1810
- itemId: item.id,
1811
- details: {
1812
- kind: "gate",
1813
- gateId: gate.id,
1814
- decision: data.decision,
1815
- reason: reason ?? null,
1816
- from: sourceStage,
1817
- to: targetStage,
1818
- by: "human:web-ui",
1819
- outcome: "completed"
1820
- }
1983
+ itemId: activateItemId,
1984
+ actor: sessionActor,
1985
+ // The revision activateWorkOperation compares (ITEM-39).
1986
+ expectedRevision: data.expectedRevision ?? directionForOperation(workspaceRoot, { itemId: activateItemId }).revision,
1987
+ reason: data.reason?.trim() || "Item priorizado para in\xEDcio do fluxo."
1821
1988
  }
1822
1989
  );
1823
- if (item.spec) {
1824
- dependencies.writeFocusFile(workspaceRoot, item.spec, item.id);
1990
+ if (operation.outcome !== "accepted") {
1991
+ sendRefusal(res, operation.reasonCode === "DIRECTION_STALE" ? 409 : 422, operation);
1992
+ return true;
1825
1993
  }
1826
1994
  dependencies.broadcast();
1827
- void dependencies.fireWebhooks(workspaceRoot, "gate.decided", {
1828
- itemId: item.id,
1829
- gateId: gate.id,
1830
- decision: data.decision,
1831
- reason: reason ?? null,
1832
- sourceStage,
1833
- targetStage
1834
- });
1835
- sendJson(res, 200, {
1836
- item,
1837
- decision: {
1838
- gateId: gate.id,
1839
- value: data.decision,
1840
- reason: reason ?? null,
1841
- sourceStage,
1842
- targetStage
1995
+ sendJson(res, 200, operation);
1996
+ } catch (error) {
1997
+ sendBodyError(error, res);
1998
+ }
1999
+ return true;
2000
+ }
2001
+ const reworkItemId = routeParam(path, "/api/items/:id/request-rework");
2002
+ if (reworkItemId !== null && method === "POST") {
2003
+ if (!dependencies.requestReworkOperation) {
2004
+ sendError(
2005
+ res,
2006
+ 501,
2007
+ "Retorno can\xF4nico para retrabalho n\xE3o est\xE1 dispon\xEDvel."
2008
+ );
2009
+ return true;
2010
+ }
2011
+ try {
2012
+ const data = await readJson(req);
2013
+ const acceptanceCriteria = (data.acceptanceCriteria ?? []).map(
2014
+ (criterion) => ({
2015
+ id: criterion.id,
2016
+ description: criterion.description?.trim() ?? ""
2017
+ })
2018
+ );
2019
+ const operation = await dependencies.requestReworkOperation(
2020
+ workspaceRoot,
2021
+ {
2022
+ itemId: reworkItemId,
2023
+ actor: sessionActor,
2024
+ expectedRevision: data.expectedRevision ?? directionForOperation(workspaceRoot, { itemId: reworkItemId }).revision,
2025
+ reason: data.reason?.trim() || "A revis\xE3o encontrou corre\xE7\xF5es necess\xE1rias.",
2026
+ acceptanceCriteria
1843
2027
  }
1844
- });
2028
+ );
2029
+ if (operation.outcome !== "accepted") {
2030
+ sendRefusal(res, operation.reasonCode === "DIRECTION_STALE" ? 409 : 422, operation);
2031
+ return true;
2032
+ }
2033
+ dependencies.broadcast();
2034
+ sendJson(res, 200, operation);
1845
2035
  } catch (error) {
1846
2036
  sendBodyError(error, res);
1847
2037
  }
@@ -1864,154 +2054,142 @@ function createItemRoutes(dependencies) {
1864
2054
  if (itemId !== null && method === "PATCH") {
1865
2055
  try {
1866
2056
  const data = await readJson(req);
1867
- if (!workflow) {
1868
- sendError(res, 404, "No workflow");
1869
- return true;
1870
- }
1871
- const item = workflow.items.find((candidate) => candidate.id === itemId);
1872
- if (!item) {
2057
+ const item = workflow?.items.find(
2058
+ (candidate) => candidate.id === itemId
2059
+ );
2060
+ if (!workflow || !item) {
1873
2061
  sendError(res, 404, "Item not found");
1874
2062
  return true;
1875
2063
  }
1876
2064
  const oldStage = item.stage;
1877
2065
  if (data.stage !== void 0 && data.stage !== oldStage) {
1878
- const resolved = dependencies.resolveActiveFlow(workspaceRoot, workflow);
1879
- const sourceStage = resolved.flow?.stages.find(
1880
- (stage) => stage.id === oldStage
1881
- );
1882
- if (sourceStage?.gate?.type === "human" && sourceStage.gate.blocking) {
1883
- sendError(
1884
- res,
1885
- 422,
1886
- `Gate bloqueante: ${sourceStage.gate.name}. Use uma decis\xE3o humana expl\xEDcita para sair de "${sourceStage.name}".`
1887
- );
1888
- return true;
1889
- }
1890
- const targetStage = resolved.flow?.stages.find(
1891
- (stage) => stage.id === data.stage
2066
+ sendError(res, 422, "Stage changes require the canonical /passage operation with destination role, executor, summary and evidence.");
2067
+ return true;
2068
+ }
2069
+ if (data.stage !== void 0 && data.stage !== oldStage && (data.description !== void 0 || data.tasks !== void 0)) {
2070
+ sendError(
2071
+ res,
2072
+ 400,
2073
+ "Stage transition must be submitted separately from item edits"
1892
2074
  );
1893
- const gate = targetStage?.gate;
1894
- if (gate?.type === "human" && gate.blocking) {
1895
- sendError(
1896
- res,
1897
- 422,
1898
- `Gate bloqueante: ${gate.name}. Aprova\xE7\xE3o humana necess\xE1ria para entrar em "${targetStage?.name ?? data.stage}".`
1899
- );
1900
- return true;
1901
- }
1902
- item.stage = data.stage;
2075
+ return true;
1903
2076
  }
1904
- if (data.description !== void 0) item.description = data.description;
1905
- if (data.tasks !== void 0) item.tasks = data.tasks;
1906
- workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1907
- dependencies.writeWorkflow(workspaceRoot, {
1908
- workflow,
1909
- source: "web-ui",
1910
- primaryItemId: itemId,
1911
- skipSitrep: true,
1912
- quiet: true
1913
- });
1914
- dependencies.broadcast();
1915
- if (data.stage !== void 0 && data.stage !== oldStage) {
1916
- if (item.spec) {
1917
- dependencies.writeFocusFile(workspaceRoot, item.spec, item.id);
1918
- dependencies.logEntry(
1919
- workspaceRoot,
1920
- "focus_sync",
1921
- `Focus synced to ${item.spec} via item move (${item.id})`,
1922
- { itemId: item.id, spec: item.spec }
1923
- );
1924
- console.log(` [focus] Synced to ${item.spec} via drag`);
2077
+ if (!dependencies.updateItemOperation) {
2078
+ sendError(res, 503, "Canonical item update operation unavailable");
2079
+ return true;
2080
+ }
2081
+ const operation = await dependencies.updateItemOperation(
2082
+ workspaceRoot,
2083
+ {
2084
+ itemId,
2085
+ description: data.description,
2086
+ tasks: data.tasks,
2087
+ actor: sessionActor,
2088
+ expectedRevision: data.expectedRevision ?? directionForOperation(workspaceRoot, { itemId }).revision,
2089
+ reason: "Altera\xE7\xE3o de item solicitada pela UI.",
2090
+ idempotencyKey: data.idempotencyKey
1925
2091
  }
1926
- void dependencies.fireWebhooks(workspaceRoot, "item.moved", {
1927
- itemId: item.id,
1928
- itemDescription: item.description,
1929
- sourceStage: oldStage,
1930
- targetStage: data.stage
1931
- });
2092
+ );
2093
+ if (operation.outcome !== "accepted") {
2094
+ sendRefusal(res, operation.reasonCode === "DIRECTION_STALE" ? 409 : 422, operation);
2095
+ return true;
1932
2096
  }
1933
- sendJson(res, 200, item);
2097
+ dependencies.broadcast();
2098
+ sendJson(res, 200, operation);
1934
2099
  } catch (error) {
1935
2100
  sendBodyError(error, res);
1936
2101
  }
1937
2102
  return true;
1938
2103
  }
1939
2104
  if (itemId !== null && method === "DELETE") {
1940
- if (!workflow) {
1941
- sendError(res, 404, "No workflow");
2105
+ if (!dependencies.deleteItemOperation) {
2106
+ sendError(res, 503, "Canonical item deletion operation unavailable");
1942
2107
  return true;
1943
2108
  }
1944
- const index = workflow.items.findIndex((candidate) => candidate.id === itemId);
1945
- if (index === -1) {
1946
- sendError(res, 404, "Item not found");
1947
- return true;
2109
+ let data = {};
2110
+ try {
2111
+ data = await readJson(req);
2112
+ } catch {
1948
2113
  }
1949
- workflow.items.splice(index, 1);
1950
- workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1951
- dependencies.writeWorkflow(workspaceRoot, {
1952
- workflow,
1953
- source: "web-ui",
1954
- skipSitrep: true,
1955
- quiet: true
2114
+ const operation = await dependencies.deleteItemOperation(workspaceRoot, {
2115
+ itemId,
2116
+ actor: sessionActor,
2117
+ expectedRevision: data.expectedRevision ?? directionForOperation(workspaceRoot, { itemId }).revision,
2118
+ reason: "Remo\xE7\xE3o de item solicitada pela UI.",
2119
+ idempotencyKey: data.idempotencyKey
1956
2120
  });
2121
+ if (operation.outcome !== "accepted") {
2122
+ sendRefusal(res, operation.reasonCode === "DIRECTION_STALE" ? 409 : 422, operation);
2123
+ return true;
2124
+ }
1957
2125
  dependencies.broadcast();
1958
- sendJson(res, 200, { deleted: itemId });
2126
+ sendJson(res, 200, operation);
1959
2127
  return true;
1960
2128
  }
1961
2129
  const claimId = routeParam(path, "/api/items/:id/claim");
1962
2130
  if (claimId !== null && method === "POST") {
1963
- if (!workflow) {
1964
- sendError(res, 404, "No workflow");
2131
+ if (!dependencies.claimOperation) {
2132
+ sendError(res, 503, "Canonical claim operation unavailable");
1965
2133
  return true;
1966
2134
  }
1967
- const item = workflow.items.find((candidate) => candidate.id === claimId);
1968
- if (!item) {
1969
- sendError(res, 404, "Item not found");
1970
- return true;
1971
- }
1972
- const doneZones = new Set(
1973
- workflow.stages.filter((stage) => stage.zone === "done").map((stage) => stage.id)
1974
- );
1975
- if (doneZones.has(item.stage)) {
1976
- sendError(res, 400, "Cannot claim a completed item");
1977
- return true;
2135
+ try {
2136
+ const data = await readJson(req);
2137
+ const role = data.role?.trim();
2138
+ if (role && /^(human|mcp)(:|$)/.test(role)) {
2139
+ sendError(res, 400, "role must be a workflow role id");
2140
+ return true;
2141
+ }
2142
+ const operation = await dependencies.claimOperation(workspaceRoot, {
2143
+ itemId: claimId,
2144
+ actor: role || sessionActor,
2145
+ executorId: data.executorId ?? "web-ui",
2146
+ capability: data.capability ?? "read_code",
2147
+ // claimOperation compares directionForOperation, which accounts for
2148
+ // the item's active Run (present after any handoff). The item-only
2149
+ // direction made the board's handoff claim DIRECTION_STALE (ITEM-39).
2150
+ expectedRevision: data.expectedRevision ?? directionForOperation(workspaceRoot, { itemId: claimId }).revision,
2151
+ reason: role ? `Claim solicitado pela UI para o papel ${role} por ${sessionActor}.` : "Claim solicitado pela UI.",
2152
+ idempotencyKey: data.idempotencyKey
2153
+ });
2154
+ if (operation.outcome !== "accepted") {
2155
+ const status = operation.reasonCode === "DIRECTION_STALE" ? 409 : operation.reasonCode === "ITEM_NOT_FOUND" ? 404 : operation.reasonCode === "ITEM_COMPLETED" ? 400 : 422;
2156
+ sendRefusal(res, status, operation);
2157
+ return true;
2158
+ }
2159
+ dependencies.broadcast();
2160
+ sendJson(res, 200, operation);
2161
+ } catch (error) {
2162
+ sendBodyError(error, res);
1978
2163
  }
1979
- item.claimedBy = "web-ui";
1980
- item.claimedAt = (/* @__PURE__ */ new Date()).toISOString();
1981
- workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1982
- dependencies.writeWorkflow(workspaceRoot, {
1983
- workflow,
1984
- source: "web-ui",
1985
- primaryItemId: item.id,
1986
- skipSitrep: true,
1987
- quiet: true
1988
- });
1989
- dependencies.broadcast();
1990
- sendJson(res, 200, item);
1991
2164
  return true;
1992
2165
  }
1993
2166
  const releaseId = routeParam(path, "/api/items/:id/release");
1994
2167
  if (releaseId !== null && method === "POST") {
1995
- if (!workflow) {
1996
- sendError(res, 404, "No workflow");
2168
+ if (!dependencies.releaseClaimOperation) {
2169
+ sendError(res, 503, "Canonical release operation unavailable");
1997
2170
  return true;
1998
2171
  }
1999
- const item = workflow.items.find((candidate) => candidate.id === releaseId);
2000
- if (!item) {
2001
- sendError(res, 404, "Item not found");
2002
- return true;
2172
+ try {
2173
+ const data = await readJson(req);
2174
+ const operation = await dependencies.releaseClaimOperation(
2175
+ workspaceRoot,
2176
+ {
2177
+ itemId: releaseId,
2178
+ actor: sessionActor,
2179
+ expectedRevision: data.expectedRevision ?? directionForOperation(workspaceRoot, { itemId: releaseId }).revision,
2180
+ reason: "Release solicitado pela UI.",
2181
+ idempotencyKey: data.idempotencyKey
2182
+ }
2183
+ );
2184
+ if (operation.outcome !== "accepted") {
2185
+ sendRefusal(res, operation.reasonCode === "DIRECTION_STALE" ? 409 : 422, operation);
2186
+ return true;
2187
+ }
2188
+ dependencies.broadcast();
2189
+ sendJson(res, 200, operation);
2190
+ } catch (error) {
2191
+ sendBodyError(error, res);
2003
2192
  }
2004
- item.claimedBy = void 0;
2005
- item.claimedAt = void 0;
2006
- workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2007
- dependencies.writeWorkflow(workspaceRoot, {
2008
- workflow,
2009
- source: "web-ui",
2010
- skipSitrep: true,
2011
- quiet: true
2012
- });
2013
- dependencies.broadcast();
2014
- sendJson(res, 200, item);
2015
2193
  return true;
2016
2194
  }
2017
2195
  const focusId = routeParam(path, "/api/items/:id/focus");
@@ -2027,9 +2205,14 @@ function createItemRoutes(dependencies) {
2027
2205
  }
2028
2206
  const specName = item.spec || focusId;
2029
2207
  dependencies.writeFocusFile(workspaceRoot, specName, item.id);
2030
- dependencies.logEntry(workspaceRoot, "focus_set", `Focus set via UI: ${specName}`, {
2031
- itemId: focusId
2032
- });
2208
+ dependencies.logEntry(
2209
+ workspaceRoot,
2210
+ "focus_set",
2211
+ `Focus set via UI: ${specName}`,
2212
+ {
2213
+ itemId: focusId
2214
+ }
2215
+ );
2033
2216
  dependencies.broadcast();
2034
2217
  sendJson(res, 200, { itemId: focusId, spec: specName });
2035
2218
  return true;
@@ -2051,6 +2234,14 @@ function sendBodyError2(error, res) {
2051
2234
  }
2052
2235
  function createSpecRoutes(dependencies) {
2053
2236
  return async ({ method, path, req, res, workspaceRoot, workspaceDir, workflow }) => {
2237
+ if (path === "/api/spec-catalog" && method === "GET") {
2238
+ try {
2239
+ sendJson(res, 200, readSpecCatalog(workspaceRoot));
2240
+ } catch {
2241
+ sendJson(res, 200, null);
2242
+ }
2243
+ return true;
2244
+ }
2054
2245
  if (path === "/api/specs" && method === "GET") {
2055
2246
  try {
2056
2247
  sendJson(res, 200, dependencies.loadResolvedSpecs(workspaceRoot, workflow));
@@ -2069,7 +2260,7 @@ function createSpecRoutes(dependencies) {
2069
2260
  dependencies.writeSpec(workspaceDir, id, content);
2070
2261
  if (workflow) {
2071
2262
  workflow.specLinks ??= {};
2072
- workflow.specLinks[id] = { path: `.letra/specs/${id}/spec.md` };
2263
+ workflow.specLinks[id] = { path: `specs/${id}/spec.md` };
2073
2264
  workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2074
2265
  dependencies.writeWorkflow(workspaceRoot, {
2075
2266
  workflow,
@@ -2150,6 +2341,10 @@ function sendBodyError3(error, res) {
2150
2341
  function createDiagnosticsRoutes(dependencies) {
2151
2342
  return async ({ method, path, req, res, url, workspaceRoot }) => {
2152
2343
  const engine = dependencies.engineFor(workspaceRoot);
2344
+ if (path === "/api/diagnostics/workspace" && method === "GET") {
2345
+ sendJson(res, 200, dependencies.inspectWorkspaceIntegrity(workspaceRoot));
2346
+ return true;
2347
+ }
2153
2348
  if (path === "/api/diagnostics" && method === "GET") {
2154
2349
  sendJson(res, 200, engine.getLastOutput());
2155
2350
  return true;
@@ -2463,6 +2658,7 @@ function createContextRoutes(dependencies) {
2463
2658
  const result = dependencies.queryLogWithMeta(workspaceRoot, {
2464
2659
  all: url.searchParams.get("all") === "true",
2465
2660
  itemId: url.searchParams.get("item") ?? void 0,
2661
+ runId: url.searchParams.get("run") ?? void 0,
2466
2662
  action: url.searchParams.get("action") ?? void 0,
2467
2663
  since: url.searchParams.get("since") ?? void 0,
2468
2664
  q: url.searchParams.get("q") ?? void 0,
@@ -2492,9 +2688,9 @@ function createContextRoutes(dependencies) {
2492
2688
  var readFile = readFile2;
2493
2689
  const { existsSync: existsSync16, readFileSync: readFileSync12 } = await import("fs");
2494
2690
  const { join: join14 } = await import("path");
2495
- const { readFocusFile: readFocusFile2 } = await import("./focus-sync-3D3XWCTI.js");
2496
- const { loadSessionLog: loadSessionLog2 } = await import("./session-log-WTQ5JBEN.js");
2497
- const { loadHealthRecord: loadHealthRecord2, getActiveEntries: getActiveEntries2 } = await import("./health-record-YDVXEVLR.js");
2691
+ const { loadSessionLog: loadSessionLog2 } = await import("./session-log-X2Q4XKQN.js");
2692
+ const { loadHealthRecord: loadHealthRecord2, getActiveEntries: getActiveEntries2 } = await import("./health-record-JO2ZTIMR.js");
2693
+ const { stripSitrepSnapshots } = await import("./specs-CQRB7LPA.js");
2498
2694
  const l1Files = [
2499
2695
  "constitution.md",
2500
2696
  "context.md",
@@ -2503,14 +2699,14 @@ function createContextRoutes(dependencies) {
2503
2699
  ];
2504
2700
  const l1 = l1Files.map((f) => ({
2505
2701
  path: `.letra/${f}`,
2506
- content: readFile2(f)
2702
+ content: f === "context.md" ? stripSitrepSnapshots(readFile2(f)) : readFile2(f)
2507
2703
  }));
2508
- const focus = readFocusFile2(workspaceRoot);
2509
- const focusContent = readFile2("focus.md");
2510
- const specContent = focus?.specName ? readFile2(`specs/${focus.specName}/spec.md`) : "";
2704
+ const direction = (await import("./service-TOBY3OHO.js")).resolveDirection(workspaceRoot);
2705
+ const specName = direction.item?.spec ?? null;
2706
+ const specContent = specName ? readFile2(`specs/${specName}/spec.md`) : "";
2511
2707
  const l2 = {
2512
- focus: focus ? { ...focus, content: focusContent } : null,
2513
- spec: specContent ? { path: `.letra/specs/${focus?.specName}/spec.md`, content: specContent } : null
2708
+ direction,
2709
+ spec: specContent ? { path: `specs/${specName}/spec.md`, content: specContent } : null
2514
2710
  };
2515
2711
  const healthRecord = loadHealthRecord2(workspaceRoot);
2516
2712
  const alerts = getActiveEntries2(healthRecord);
@@ -2535,10 +2731,10 @@ function createContextRoutes(dependencies) {
2535
2731
  return true;
2536
2732
  }
2537
2733
  if (path === "/api/sitrep" && method === "POST") {
2538
- await dependencies.sitrep(workspaceRoot, {
2539
- dryRun: url.searchParams.get("dryRun") === "true"
2734
+ sendJson(res, 410, {
2735
+ ok: false,
2736
+ message: "sitrep n\xE3o atualiza mais context.md. Use /api/activity-context ou letra direction --json para estado vivo."
2540
2737
  });
2541
- sendJson(res, 200, { ok: true });
2542
2738
  return true;
2543
2739
  }
2544
2740
  if (path === "/api/pulse" && method === "GET") {
@@ -2546,10 +2742,13 @@ function createContextRoutes(dependencies) {
2546
2742
  return true;
2547
2743
  }
2548
2744
  if (path === "/api/activity-context" && method === "GET") {
2745
+ const runId = url.searchParams.get("run");
2746
+ const executorId = url.searchParams.get("executor");
2747
+ const itemId = url.searchParams.get("item");
2549
2748
  sendJson(
2550
2749
  res,
2551
2750
  200,
2552
- dependencies.buildActivityContext(workspaceRoot, url.searchParams.get("activity"))
2751
+ dependencies.buildActivityContext(workspaceRoot, url.searchParams.get("activity"), runId, executorId, itemId)
2553
2752
  );
2554
2753
  return true;
2555
2754
  }
@@ -2558,8 +2757,8 @@ function createContextRoutes(dependencies) {
2558
2757
  }
2559
2758
 
2560
2759
  // src/flow-serve/routes/workflow-routes.ts
2561
- import { existsSync as existsSync7, readFileSync as readFileSync7, unlinkSync, writeFileSync as writeFileSync3 } from "fs";
2562
- import { join as join6, resolve as resolve3 } from "path";
2760
+ import { existsSync as existsSync6, readFileSync as readFileSync6, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
2761
+ import { join as join6, resolve as resolve4 } from "path";
2563
2762
  function sendBodyError5(error, res) {
2564
2763
  if (error instanceof HttpBodyError) sendError(res, error.status, error.message);
2565
2764
  else sendError(res, 400, error.message);
@@ -2581,21 +2780,21 @@ function labelFromPath(path, fallback = "Projeto") {
2581
2780
  return normalizedPath(path).split("/").filter(Boolean).pop() || fallback;
2582
2781
  }
2583
2782
  function assertProjectDirectory(path) {
2584
- const resolved = resolve3(path);
2585
- if (!existsSync7(resolved)) throw new Error("A pasta de projeto n\xE3o existe.");
2783
+ const resolved = resolve4(path);
2784
+ if (!existsSync6(resolved)) throw new Error("A pasta de projeto n\xE3o existe.");
2586
2785
  return resolved;
2587
2786
  }
2588
2787
  function linkPathFor(locationPath) {
2589
- return join6(resolve3(locationPath), ".letra-link");
2788
+ return join6(resolve4(locationPath), ".letra-link");
2590
2789
  }
2591
2790
  function readLink(locationPath) {
2592
2791
  const path = linkPathFor(locationPath);
2593
- if (!existsSync7(path)) return null;
2594
- return readFileSync7(path, "utf-8").trim();
2792
+ if (!existsSync6(path)) return null;
2793
+ return readFileSync6(path, "utf-8").trim();
2595
2794
  }
2596
2795
  function writeLocationLink(locationPath, dataDir) {
2597
2796
  const resolved = assertProjectDirectory(locationPath);
2598
- writeFileSync3(join6(resolved, ".letra-link"), `${dataDir}
2797
+ writeFileSync2(join6(resolved, ".letra-link"), `${dataDir}
2599
2798
  `, "utf-8");
2600
2799
  }
2601
2800
  function removeLocationLinkIfOwned(locationPath, dataDir) {
@@ -2607,6 +2806,78 @@ function removeLocationLinkIfOwned(locationPath, dataDir) {
2607
2806
  }
2608
2807
  function createWorkflowRoutes(dependencies) {
2609
2808
  return async ({ method, path, req, res, url, workspaceRoot, workspaceDir, workflow }) => {
2809
+ if (path === "/api/workflow-definitions" && method === "GET") {
2810
+ sendJson(res, 200, listWorkflowDefinitions(workspaceRoot));
2811
+ return true;
2812
+ }
2813
+ if (path === "/api/workflow-definitions" && method === "POST") {
2814
+ try {
2815
+ const actor = dependencies.resolveHumanActor?.(req);
2816
+ if (!actor) {
2817
+ sendError(res, 403, "HUMAN_CONFIRMATION_REQUIRED");
2818
+ return true;
2819
+ }
2820
+ const data = await readJson(req);
2821
+ sendJson(res, 201, createWorkflowDefinition(workspaceRoot, { ...data, actor }));
2822
+ } catch (error) {
2823
+ sendBodyError5(error, res);
2824
+ }
2825
+ return true;
2826
+ }
2827
+ const definitionMatch = path.match(/^\/api\/workflow-definitions\/([^/]+)(?:\/(.+))?$/);
2828
+ if (definitionMatch) {
2829
+ const workflowId = decodeURIComponent(definitionMatch[1]);
2830
+ const action = definitionMatch[2] ?? "";
2831
+ try {
2832
+ if (action === "versions" && method === "GET") sendJson(res, 200, listWorkflowVersions(workspaceRoot, workflowId));
2833
+ else if (action.startsWith("versions/") && method === "GET") sendJson(res, 200, getWorkflowVersion(workspaceRoot, workflowId, Number(action.split("/")[1])));
2834
+ else if (action === "draft" && method === "GET") sendJson(res, 200, getWorkflowDraft(workspaceRoot, workflowId));
2835
+ else if (action === "draft-revisions" && method === "GET") sendJson(res, 200, listWorkflowDraftRevisions(workspaceRoot, workflowId));
2836
+ else if (action === "active" && method === "GET") sendJson(res, 200, getActiveWorkflowVersion(workspaceRoot, workflowId));
2837
+ else if (action === "draft" && method === "POST") {
2838
+ const actor = dependencies.resolveHumanActor?.(req);
2839
+ if (!actor) {
2840
+ sendError(res, 403, "HUMAN_CONFIRMATION_REQUIRED");
2841
+ return true;
2842
+ }
2843
+ const data = await readJson(req);
2844
+ sendJson(res, 201, createWorkflowDraft(workspaceRoot, workflowId, actor, data.basedOnVersionNumber));
2845
+ } else if (action === "draft" && method === "PATCH") {
2846
+ const actor = dependencies.resolveHumanActor?.(req);
2847
+ if (!actor) {
2848
+ sendError(res, 403, "HUMAN_CONFIRMATION_REQUIRED");
2849
+ return true;
2850
+ }
2851
+ const data = await readJson(req);
2852
+ sendJson(res, 200, updateWorkflowDraft(workspaceRoot, workflowId, { ...data, actor }));
2853
+ } else if (action === "validate" && method === "POST") sendJson(res, 200, validateWorkflowContent(getWorkflowDraft(workspaceRoot, workflowId).content));
2854
+ else if (action === "publish" && method === "POST") {
2855
+ const data = await readJson(req);
2856
+ const actor = dependencies.resolveHumanActor?.(req);
2857
+ if (!actor) {
2858
+ sendError(res, 403, "HUMAN_CONFIRMATION_REQUIRED");
2859
+ return true;
2860
+ }
2861
+ sendJson(res, 201, publishWorkflowDraft(workspaceRoot, workflowId, { ...data, actor }));
2862
+ dependencies.broadcast();
2863
+ } else if (action === "rollback" && method === "POST") {
2864
+ const data = await readJson(req);
2865
+ const actor = dependencies.resolveHumanActor?.(req);
2866
+ if (!actor) {
2867
+ sendError(res, 403, "HUMAN_CONFIRMATION_REQUIRED");
2868
+ return true;
2869
+ }
2870
+ const proof = signLocalOperation(workspaceRoot, actor, "workflow.rollback", { workflowId, versionNumber: data.versionNumber, reason: data.reason });
2871
+ sendJson(res, 201, rollbackWorkflowVersion(workspaceRoot, workflowId, { ...data, actor, proof }));
2872
+ dependencies.broadcast();
2873
+ } else return false;
2874
+ } catch (error) {
2875
+ const message = error instanceof Error ? error.message : String(error);
2876
+ const status = message.startsWith("DRAFT_REVISION_CONFLICT") ? 409 : message.startsWith("WORKFLOW_INVALID") ? 422 : message.includes("NOT_FOUND") ? 404 : 400;
2877
+ sendError(res, status, message);
2878
+ }
2879
+ return true;
2880
+ }
2610
2881
  if (path === "/api/workflow" && method === "GET") {
2611
2882
  sendJson(res, 200, workflow ?? { error: "No workflow found" });
2612
2883
  return true;
@@ -2901,32 +3172,110 @@ function createWorkflowRoutes(dependencies) {
2901
3172
  }
2902
3173
 
2903
3174
  // src/flow-serve/routes/workspace-routes.ts
2904
- import { readdirSync as readdirSync5, existsSync as existsSync9, readFileSync as readFileSync8 } from "fs";
2905
- import { join as join8, resolve as resolve5 } from "path";
3175
+ import { readdirSync as readdirSync5, existsSync as existsSync8, readFileSync as readFileSync8 } from "fs";
3176
+ import { join as join8, resolve as resolve6 } from "path";
2906
3177
  import { homedir } from "os";
2907
3178
 
2908
3179
  // src/commands/migrate.ts
2909
- import { existsSync as existsSync8, cpSync, rmSync as rmSync2, mkdirSync as mkdirSync3, writeFileSync as writeFileSync4, readdirSync as readdirSync4 } from "fs";
2910
- import { join as join7, isAbsolute, resolve as resolve4 } from "path";
2911
- import { Command as Command2 } from "commander";
2912
- import chalk2 from "chalk";
3180
+ import { existsSync as existsSync7, cpSync, rmSync as rmSync2, mkdirSync as mkdirSync2, writeFileSync as writeFileSync3, readdirSync as readdirSync4, lstatSync, readFileSync as readFileSync7, readlinkSync } from "fs";
3181
+ import { createHash } from "crypto";
3182
+ import { join as join7, isAbsolute, resolve as resolve5, relative, sep, basename as basename2 } from "path";
3183
+ import { Command as Command3 } from "commander";
3184
+ import chalk3 from "chalk";
2913
3185
  var EXTERNAL_ROOT = getWorkspacesDir();
2914
3186
  function workspaceName(root) {
2915
3187
  const wf = loadWorkflow(root);
2916
3188
  return wf?.name || slugifyWorkspaceName(root);
2917
3189
  }
2918
3190
  function copyDirectoryContents(source, target) {
2919
- mkdirSync3(target, { recursive: true });
3191
+ mkdirSync2(target, { recursive: true });
2920
3192
  for (const entry of readdirSync4(source)) {
2921
3193
  cpSync(join7(source, entry), join7(target, entry), { recursive: true, force: true });
2922
3194
  }
2923
3195
  }
3196
+ function reconcileExternalizedCopy(source, target) {
3197
+ const conflicts = [];
3198
+ const missing = [];
3199
+ const visit = (from, to) => {
3200
+ for (const entry of readdirSync4(from, { withFileTypes: true })) {
3201
+ const src = join7(from, entry.name);
3202
+ const dst = join7(to, entry.name);
3203
+ if (!existsSync7(dst)) {
3204
+ missing.push(relative(source, src).split(sep).join("/"));
3205
+ continue;
3206
+ }
3207
+ const srcStat = lstatSync(src);
3208
+ const dstStat = lstatSync(dst);
3209
+ if (srcStat.isDirectory() !== dstStat.isDirectory() || srcStat.isSymbolicLink() !== dstStat.isSymbolicLink()) {
3210
+ conflicts.push(relative(source, src).split(sep).join("/"));
3211
+ continue;
3212
+ }
3213
+ if (srcStat.isSymbolicLink()) {
3214
+ if (readlinkSync(src) !== readlinkSync(dst)) conflicts.push(relative(source, src).split(sep).join("/"));
3215
+ } else if (srcStat.isDirectory()) visit(src, dst);
3216
+ else if (srcStat.isFile()) {
3217
+ const srcHash = createHash("sha256").update(readFileSync7(src)).digest("hex");
3218
+ const dstHash = createHash("sha256").update(readFileSync7(dst)).digest("hex");
3219
+ if (srcHash !== dstHash) conflicts.push(relative(source, src).split(sep).join("/"));
3220
+ } else conflicts.push(relative(source, src).split(sep).join("/"));
3221
+ }
3222
+ };
3223
+ visit(source, target);
3224
+ return { conflicts, missing };
3225
+ }
3226
+ function cleanupLegacyDirectory(legacy, target, kind, dryRun) {
3227
+ const legacyPath = resolve5(legacy);
3228
+ const targetPath = resolve5(target);
3229
+ if (basename2(legacyPath) !== ".letra" || legacyPath === targetPath) {
3230
+ return { ok: false, from: legacyPath, to: targetPath, cleaned: false, message: `Cleanup refused an unexpected legacy path: ${legacyPath}` };
3231
+ }
3232
+ const reconciliation = reconcileExternalizedCopy(legacyPath, targetPath);
3233
+ if (dryRun) {
3234
+ return {
3235
+ ok: true,
3236
+ from: legacyPath,
3237
+ to: targetPath,
3238
+ cleaned: false,
3239
+ message: `[dry-run] Would snapshot ${kind} .letra, copy ${reconciliation.missing.length} missing path(s), preserve ${reconciliation.conflicts.length} divergent path(s) in the snapshot while keeping ${targetPath} canonical, verify, then remove ${legacyPath}.${reconciliation.conflicts.length ? ` Conflicts: ${reconciliation.conflicts.join(", ")}` : ""}`
3240
+ };
3241
+ }
3242
+ const migrationId = `cleanup-${kind}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
3243
+ const rollbackDir = join7(targetPath, "operations", "rollbacks", migrationId);
3244
+ const snapshotPath = join7(rollbackDir, "legacy-letra");
3245
+ mkdirSync2(rollbackDir, { recursive: true });
3246
+ copyDirectoryContents(legacyPath, snapshotPath);
3247
+ for (const path of reconciliation.missing) {
3248
+ const src = join7(legacyPath, ...path.split("/"));
3249
+ const dst = join7(targetPath, ...path.split("/"));
3250
+ mkdirSync2(join7(dst, ".."), { recursive: true });
3251
+ cpSync(src, dst, { recursive: true, errorOnExist: true, force: false });
3252
+ }
3253
+ const finalCheck = reconcileExternalizedCopy(legacyPath, targetPath);
3254
+ const snapshotCheck = reconcileExternalizedCopy(legacyPath, snapshotPath);
3255
+ const expectedConflicts = [...reconciliation.conflicts].sort();
3256
+ const finalConflicts = [...finalCheck.conflicts].sort();
3257
+ if (finalCheck.missing.length > 0 || JSON.stringify(finalConflicts) !== JSON.stringify(expectedConflicts) || snapshotCheck.conflicts.length > 0 || snapshotCheck.missing.length > 0) {
3258
+ return {
3259
+ ok: false,
3260
+ from: legacyPath,
3261
+ to: targetPath,
3262
+ cleaned: false,
3263
+ message: `Cleanup stopped after snapshot: source or target changed during reconciliation (conflicts: ${finalCheck.conflicts.join(", ")}; missing: ${finalCheck.missing.join(", ")}; snapshot conflicts: ${snapshotCheck.conflicts.join(", ")}; snapshot missing: ${snapshotCheck.missing.join(", ")}). Snapshot: ${snapshotPath}`
3264
+ };
3265
+ }
3266
+ writeFileSync3(join7(rollbackDir, "rollback.json"), JSON.stringify({ id: migrationId, kind, source: legacyPath, target: targetPath, snapshotPath, canonicalTarget: targetPath, conflicts: reconciliation.conflicts, restore: "Copy snapshotPath back to source. Divergent files in target remain authoritative." }, null, 2), "utf-8");
3267
+ const evidenceDir = join7(targetPath, "operations", "migrations");
3268
+ mkdirSync2(evidenceDir, { recursive: true });
3269
+ writeFileSync3(join7(evidenceDir, `${migrationId}.json`), JSON.stringify({ id: migrationId, migratedAt: (/* @__PURE__ */ new Date()).toISOString(), kind, from: legacyPath, to: targetPath, cleaned: true, canonicalTarget: targetPath, rollbackSnapshotPath: snapshotPath, conflicts: reconciliation.conflicts, copiedPaths: reconciliation.missing, conflictPolicy: "preserve-in-snapshot; canonical-target-wins" }, null, 2), "utf-8");
3270
+ rmSync2(legacyPath, { recursive: true });
3271
+ return { ok: true, from: legacyPath, to: targetPath, cleaned: true, message: `Reconciled ${reconciliation.missing.length} missing path(s), preserved ${reconciliation.conflicts.length} divergent path(s) in the rollback snapshot, kept the external data directory canonical, and removed ${kind} .letra. Snapshot: ${snapshotPath}` };
3272
+ }
2924
3273
  async function migrateWorkspace(rootPath, options) {
2925
- const cwd = rootPath ? resolve4(process.cwd(), rootPath) : process.cwd();
3274
+ const cwd = rootPath ? resolve5(process.cwd(), rootPath) : process.cwd();
2926
3275
  const resolution = resolveWorkspaceRoot(cwd);
2927
3276
  const source = resolution.workspaceDir;
2928
- const rootForLink = resolution.workspaceRoot;
2929
- if (!existsSync8(source)) {
3277
+ const rootForLink = resolution.type === "linked" && resolution.linkPath ? resolve5(resolution.linkPath, "..") : resolution.workspaceRoot;
3278
+ if (!existsSync7(source)) {
2930
3279
  return {
2931
3280
  ok: false,
2932
3281
  from: source,
@@ -2936,18 +3285,39 @@ async function migrateWorkspace(rootPath, options) {
2936
3285
  };
2937
3286
  }
2938
3287
  if (resolution.type === "linked") {
2939
- return {
2940
- ok: false,
2941
- from: source,
2942
- to: source,
2943
- cleaned: false,
2944
- message: "Workspace is already externalized (linked). Nothing to migrate."
2945
- };
3288
+ if (!options?.clean) {
3289
+ return {
3290
+ ok: false,
3291
+ from: join7(rootForLink, ".letra"),
3292
+ to: source,
3293
+ cleaned: false,
3294
+ message: "Workspace is already externalized. Use --clean to inspect and remove a reconciled legacy .letra copy."
3295
+ };
3296
+ }
3297
+ const legacyProjectCopy = join7(rootForLink, ".letra");
3298
+ const nestedProjection2 = join7(source, ".letra");
3299
+ const results = [];
3300
+ if (existsSync7(legacyProjectCopy)) {
3301
+ const result = cleanupLegacyDirectory(legacyProjectCopy, source, "project-legacy", Boolean(options.dryRun));
3302
+ results.push(result);
3303
+ if (!result.ok || options.dryRun) return result;
3304
+ }
3305
+ if (existsSync7(nestedProjection2)) {
3306
+ const result = cleanupLegacyDirectory(nestedProjection2, source, "workspace-projection", Boolean(options.dryRun));
3307
+ results.push(result);
3308
+ if (!result.ok || options.dryRun) return result;
3309
+ }
3310
+ if (results.length === 0) return { ok: true, from: legacyProjectCopy, to: source, cleaned: false, message: "No legacy .letra directory remains." };
3311
+ return { ok: true, from: legacyProjectCopy, to: source, cleaned: true, message: results.map((result) => result.message).join("\n") };
3312
+ }
3313
+ const nestedProjection = join7(source, ".letra");
3314
+ if (resolution.type === "direct" && options?.clean && existsSync7(nestedProjection)) {
3315
+ return cleanupLegacyDirectory(nestedProjection, source, "workspace-projection", Boolean(options.dryRun));
2946
3316
  }
2947
3317
  const name = workspaceName(rootForLink);
2948
3318
  const slug2 = slugifyWorkspaceName(name);
2949
- const target = options?.to ? isAbsolute(options.to) ? options.to : resolve4(cwd, options.to) : join7(EXTERNAL_ROOT, slug2);
2950
- if (existsSync8(target) && existsSync8(join7(target, "workflow.json"))) {
3319
+ const target = options?.to ? isAbsolute(options.to) ? options.to : resolve5(cwd, options.to) : join7(EXTERNAL_ROOT, slug2);
3320
+ if (existsSync7(target) && existsSync7(join7(target, "workflow.json"))) {
2951
3321
  return {
2952
3322
  ok: false,
2953
3323
  from: source,
@@ -2965,16 +3335,16 @@ async function migrateWorkspace(rootPath, options) {
2965
3335
  message: `[dry-run] Would copy ${source} -> ${target} and write ${LINK_FILE} at ${rootForLink}`
2966
3336
  };
2967
3337
  }
2968
- mkdirSync3(target, { recursive: true });
3338
+ mkdirSync2(target, { recursive: true });
2969
3339
  copyDirectoryContents(source, target);
2970
3340
  ensureExternalWorkspaceLayout(target);
2971
3341
  const migrationId = `migration-${Date.now().toString(36)}`;
2972
3342
  const evidenceDir = join7(target, "operations", "migrations");
2973
- mkdirSync3(evidenceDir, { recursive: true });
3343
+ mkdirSync2(evidenceDir, { recursive: true });
2974
3344
  const rollbackDir = join7(target, "operations", "rollbacks", migrationId);
2975
3345
  const rollbackSnapshotDir = join7(rollbackDir, "legacy-letra");
2976
3346
  copyDirectoryContents(source, rollbackSnapshotDir);
2977
- writeFileSync4(
3347
+ writeFileSync3(
2978
3348
  join7(rollbackDir, "rollback.json"),
2979
3349
  JSON.stringify(
2980
3350
  {
@@ -2990,7 +3360,7 @@ async function migrateWorkspace(rootPath, options) {
2990
3360
  ),
2991
3361
  "utf-8"
2992
3362
  );
2993
- writeFileSync4(join7(rootForLink, LINK_FILE), `${target}
3363
+ writeFileSync3(join7(rootForLink, LINK_FILE), `${target}
2994
3364
  `, "utf-8");
2995
3365
  clearWorkspaceCache();
2996
3366
  let cleaned = false;
@@ -2998,7 +3368,7 @@ async function migrateWorkspace(rootPath, options) {
2998
3368
  rmSync2(source, { recursive: true, force: true });
2999
3369
  cleaned = true;
3000
3370
  }
3001
- writeFileSync4(
3371
+ writeFileSync3(
3002
3372
  join7(evidenceDir, `${migrationId}.json`),
3003
3373
  JSON.stringify(
3004
3374
  {
@@ -3026,16 +3396,14 @@ async function migrateWorkspace(rootPath, options) {
3026
3396
  };
3027
3397
  }
3028
3398
  function migrateCommand() {
3029
- const cmd = new Command2("migrate").description(
3030
- "Externalize a workspace's .letra directory to ~/.letra/workspaces/{slug}/ and leave a link"
3031
- ).argument("[root]", "workspace root (defaults to cwd)").option("--to <path>", "target data directory (overrides default)").option("--clean", "remove the original .letra directory after migrating").option("--dry-run", "print what would happen without writing").action(
3399
+ const cmd = new Command3("migrate").description("Externalize workspace data or safely reconcile and clean a legacy .letra copy").argument("[root]", "workspace root (defaults to cwd)").option("--to <path>", "target data directory (overrides default)").option("--clean", "remove the original .letra directory after migrating").option("--dry-run", "print what would happen without writing").action(
3032
3400
  async (root, opts) => {
3033
3401
  const result = await migrateWorkspace(root ?? ".", opts);
3034
3402
  if (!result.ok) {
3035
- console.log(chalk2.red(`\u2717 ${result.message}`));
3403
+ console.log(chalk3.red(`\u2717 ${result.message}`));
3036
3404
  process.exitCode = 1;
3037
3405
  } else {
3038
- console.log(chalk2.green(`\u2713 ${result.message}`));
3406
+ console.log(chalk3.green(`\u2713 ${result.message}`));
3039
3407
  console.log(` from: ${result.from}`);
3040
3408
  console.log(` to: ${result.to}`);
3041
3409
  }
@@ -3051,12 +3419,12 @@ function sendBodyError6(error, res) {
3051
3419
  }
3052
3420
  function resolveUserPath(path, fallback = process.cwd()) {
3053
3421
  const input = path.trim();
3054
- if (!input) return resolve5(fallback);
3422
+ if (!input) return resolve6(fallback);
3055
3423
  if (input === "~") return homedir();
3056
3424
  if (input.startsWith("~/") || input.startsWith("~\\")) {
3057
- return resolve5(homedir(), input.slice(2));
3425
+ return resolve6(homedir(), input.slice(2));
3058
3426
  }
3059
- return resolve5(input);
3427
+ return resolve6(input);
3060
3428
  }
3061
3429
  function templates(harness) {
3062
3430
  if (!harness) return [];
@@ -3084,7 +3452,7 @@ function createWorkspaceRoutes(dependencies) {
3084
3452
  try {
3085
3453
  const registered = dependencies.listWorkspaces();
3086
3454
  const active = workspaceRoot;
3087
- const hasActive = typeof active === "string" && active.length > 0 && existsSync9(join8(getLetraDir2(active), "workflow.json"));
3455
+ const hasActive = typeof active === "string" && active.length > 0 && existsSync8(join8(getLetraDir2(active), "workflow.json"));
3088
3456
  const workspaces = hasActive ? registered.some((w) => String(w.root ?? "") === active) ? registered : [
3089
3457
  {
3090
3458
  id: "ws-active",
@@ -3103,7 +3471,7 @@ function createWorkspaceRoutes(dependencies) {
3103
3471
  const dataDir = root ? getLetraDir2(root) : null;
3104
3472
  const wfPath = dataDir ? join8(dataDir, "workflow.json") : null;
3105
3473
  let wf = null;
3106
- if (wfPath && existsSync9(wfPath)) {
3474
+ if (wfPath && existsSync8(wfPath)) {
3107
3475
  try {
3108
3476
  wf = JSON.parse(readFileSync8(wfPath, "utf-8"));
3109
3477
  } catch {
@@ -3131,7 +3499,7 @@ function createWorkspaceRoutes(dependencies) {
3131
3499
  try {
3132
3500
  const data = await readJson(req);
3133
3501
  const root = data.root || data.workspaceRoot || data.projectRoot;
3134
- if (root) dependencies.switchWorkspace(resolve5(root));
3502
+ if (root) dependencies.switchWorkspace(resolve6(root));
3135
3503
  const activeRoot = dependencies.activeWorkspaceRoot();
3136
3504
  const activeResolution = resolveWorkspaceRoot(activeRoot);
3137
3505
  sendJson(res, 200, {
@@ -3334,108 +3702,18 @@ function createWorkspaceRoutes(dependencies) {
3334
3702
  }
3335
3703
 
3336
3704
  // src/flow-serve/routes/adapter-routes.ts
3337
- import { existsSync as existsSync11, statSync as statSync2 } from "fs";
3338
- import { join as join10 } from "path";
3339
-
3340
- // src/commands/sync.ts
3341
- import { existsSync as existsSync10 } from "fs";
3342
- import { resolve as resolve6, join as join9 } from "path";
3343
- import { Command as Command3 } from "commander";
3344
- import chalk3 from "chalk";
3345
- async function validateFocus(focusSpec, items, stages) {
3346
- const warnings = [];
3347
- const doneIds = new Set(stages.filter((s) => s.id === "done").map((s) => s.id));
3348
- const matchingItems = items.filter((i) => i.spec === focusSpec);
3349
- if (matchingItems.length === 0) {
3350
- warnings.push(`Focus spec "${focusSpec}" does not match any item's spec in workflow`);
3351
- } else {
3352
- for (const item of matchingItems) {
3353
- if (doneIds.has(item.stage)) {
3354
- warnings.push(
3355
- `Focus spec "${focusSpec}" matches ${item.id} which is in "done" stage`
3356
- );
3357
- }
3358
- }
3359
- }
3360
- return warnings;
3361
- }
3362
- async function syncNow(rootPath, options) {
3363
- const workflowFile = join9(getLetraDir2(rootPath), "workflow.json");
3364
- if (!existsSync10(workflowFile)) {
3365
- return {
3366
- ok: false,
3367
- filesUpdated: [],
3368
- warnings: [],
3369
- error: "No workflow found at .letra/workflow.json"
3370
- };
3371
- }
3372
- const workflow = loadWorkflow(rootPath);
3373
- if (!workflow) {
3374
- return { ok: false, filesUpdated: [], warnings: [], error: "Failed to load workflow" };
3375
- }
3376
- const warnings = [];
3377
- const focus = readFocusFile(rootPath);
3378
- if (focus?.specName) {
3379
- const focusWarnings = await validateFocus(focus.specName, workflow.items, workflow.stages);
3380
- warnings.push(...focusWarnings);
3381
- }
3382
- if (options?.dryRun) {
3383
- const filesUpdated = [
3384
- ".letra/workflow.json",
3385
- ...(workflow.tools || []).map((t) => t),
3386
- ".letra/context.md"
3387
- ];
3388
- return { ok: true, filesUpdated, warnings, error: void 0 };
3389
- }
3390
- const result = await writeWorkflow(rootPath, {
3391
- workflow,
3392
- source: "flow-edit",
3393
- skipSitrep: options?.skipSitrep ?? false
3394
- });
3395
- return { ...result, warnings };
3396
- }
3397
- function sync_default() {
3398
- const cmd = new Command3("sync").description("Sync workflow state to all adapters");
3399
- cmd.option("--dry-run", "Show what would be done without writing").option("--fix", "Apply reconciliation (default behavior)").action(async (opts) => {
3400
- const root = resolve6(process.cwd());
3401
- const isDryRun = !!opts.dryRun;
3402
- const result = await syncNow(root, { dryRun: isDryRun });
3403
- if (!result.ok) {
3404
- console.log(chalk3.red(`\u2717 Sync failed: ${result.error ?? "unknown error"}`));
3405
- process.exit(1);
3406
- }
3407
- if (result.warnings.length > 0) {
3408
- for (const w of result.warnings) {
3409
- console.log(chalk3.yellow(` \u26A0 ${w}`));
3410
- }
3411
- }
3412
- if (isDryRun) {
3413
- console.log(chalk3.bold("\n\u{1F4CB} Simula\xE7\xE3o \u2014 dry-run\n"));
3414
- console.log(chalk3.gray(" Seriam regenerados:"));
3415
- for (const f of result.filesUpdated) {
3416
- console.log(` ${chalk3.gray("\u2192")} ${f}`);
3417
- }
3418
- return;
3419
- }
3420
- console.log(chalk3.green("\u2713 Workflow synced"));
3421
- for (const f of result.filesUpdated) {
3422
- console.log(` ${chalk3.gray("\u2192")} ${f}`);
3423
- }
3424
- });
3425
- return cmd;
3426
- }
3427
-
3428
- // src/flow-serve/routes/adapter-routes.ts
3705
+ import { existsSync as existsSync9, statSync as statSync3 } from "fs";
3706
+ import { join as join9 } from "path";
3429
3707
  function getAdapterStatus(workspaceRoot) {
3430
3708
  return Object.values(ADAPTER_REGISTRY).map((adapter) => {
3431
- const paths = adapter.detectionPaths.map((p) => join10(workspaceRoot, p));
3709
+ const paths = adapter.detectionPaths.map((p) => join9(workspaceRoot, p));
3432
3710
  const artifacts = paths.map((fullPath) => {
3433
3711
  let exists = false;
3434
3712
  let modifiedAt = null;
3435
3713
  try {
3436
- exists = existsSync11(fullPath);
3714
+ exists = existsSync9(fullPath);
3437
3715
  if (exists) {
3438
- modifiedAt = statSync2(fullPath).mtime.toISOString();
3716
+ modifiedAt = statSync3(fullPath).mtime.toISOString();
3439
3717
  }
3440
3718
  } catch {
3441
3719
  }
@@ -3446,8 +3724,8 @@ function getAdapterStatus(workspaceRoot) {
3446
3724
  };
3447
3725
  });
3448
3726
  const detected = artifacts.some((a) => a.exists);
3449
- const wf = join10(getLetraDir2(workspaceRoot), "workflow.json");
3450
- const wfMtime = existsSync11(wf) ? statSync2(wf).mtime.getTime() : 0;
3727
+ const wf = join9(getLetraDir2(workspaceRoot), "workflow.json");
3728
+ const wfMtime = existsSync9(wf) ? statSync3(wf).mtime.getTime() : 0;
3451
3729
  const newestArtifact = artifacts.filter((a) => a.exists && a.modifiedAt).sort(
3452
3730
  (a, b) => new Date(b.modifiedAt).getTime() - new Date(a.modifiedAt).getTime()
3453
3731
  )[0];
@@ -3531,7 +3809,9 @@ function createAgentRoutes(dependencies) {
3531
3809
  const root = context.workspaceRoot;
3532
3810
  try {
3533
3811
  if (context.path === "/api/agents" && context.method === "GET") {
3534
- sendJson(context.res, 200, listAgents(root, dependencies.loadWorkflow(root)));
3812
+ const workflow = dependencies.loadWorkflow(root);
3813
+ const registry = dependencies.loadRuntimeRegistry?.(root, workflow);
3814
+ sendJson(context.res, 200, projectAgentPresence(registry ?? listAgents(root, workflow), workflow, dependencies.getExecutors?.() ?? []));
3535
3815
  return true;
3536
3816
  }
3537
3817
  if (context.path === "/api/agents" && context.method === "POST") {
@@ -3580,9 +3860,93 @@ function createAgentRoutes(dependencies) {
3580
3860
  };
3581
3861
  }
3582
3862
 
3863
+ // src/flow-serve/routes/security-review-routes.ts
3864
+ import { readFileSync as readFileSync9, existsSync as existsSync10 } from "fs";
3865
+ function sendSecurityError(res, status, reasonCode, reason, evidence = []) {
3866
+ sendJson(res, status, { outcome: "rejected", auditId: "http-error", beforeRevision: "", afterRevision: "", reasonCode, reason, evidence });
3867
+ }
3868
+ function createSecurityReviewRoutes() {
3869
+ return async ({ method, path, req, res, workspaceRoot }) => {
3870
+ const itemId = routeParam(path, "/api/items/:id/security-review");
3871
+ if (itemId === null) return false;
3872
+ const workflow = loadWorkflow(workspaceRoot);
3873
+ const item = workflow?.items.find((candidate) => candidate.id === itemId);
3874
+ if (!item) {
3875
+ sendSecurityError(res, 404, "ITEM_NOT_FOUND", "Item not found");
3876
+ return true;
3877
+ }
3878
+ if (method === "GET") {
3879
+ const pathToReport = securityReportPath(workspaceRoot, itemId);
3880
+ let report = item.securityReview;
3881
+ if (!report && existsSync10(pathToReport)) {
3882
+ try {
3883
+ report = JSON.parse(readFileSync9(pathToReport, "utf8"));
3884
+ } catch {
3885
+ report = void 0;
3886
+ }
3887
+ }
3888
+ sendJson(res, 200, report ?? { reasonCode: "SECURITY_REVIEW_REQUIRED", itemId });
3889
+ return true;
3890
+ }
3891
+ if (method !== "POST") {
3892
+ sendSecurityError(res, 405, "SECURITY_METHOD_NOT_ALLOWED", "Method not allowed");
3893
+ return true;
3894
+ }
3895
+ try {
3896
+ const data = await readJson(req);
3897
+ const result = await runSecurityReviewOperation(workspaceRoot, {
3898
+ itemId,
3899
+ executorId: data.executorId ?? "opencode",
3900
+ expectedRevision: data.expectedRevision ?? directionForOperation(workspaceRoot, { itemId }).revision,
3901
+ reason: data.reason?.trim() || "Revis\xE3o de Security solicitada pela UI.",
3902
+ actor: data.actor ?? "security",
3903
+ idempotencyKey: data.idempotencyKey
3904
+ });
3905
+ if (result.outcome === "rejected") {
3906
+ const evidence = result.securityReview?.findings.flatMap((finding) => finding.evidence) ?? [];
3907
+ sendJson(res, result.reasonCode === "DIRECTION_STALE" ? 409 : 422, { ...result, evidence });
3908
+ return true;
3909
+ }
3910
+ sendJson(res, 200, result);
3911
+ } catch (error) {
3912
+ if (error instanceof HttpBodyError) sendSecurityError(res, error.status, "SECURITY_REQUEST_INVALID", error.message);
3913
+ else sendSecurityError(res, 400, "SECURITY_REQUEST_INVALID", error.message);
3914
+ }
3915
+ return true;
3916
+ };
3917
+ }
3918
+
3919
+ // src/flow-serve/routes/autopilot-routes.ts
3920
+ function sendBodyError7(error, res) {
3921
+ if (error instanceof HttpBodyError) sendError(res, error.status, error.message);
3922
+ else sendError(res, 400, error instanceof Error ? error.message : String(error));
3923
+ }
3924
+ function createAutopilotRoutes(dependencies) {
3925
+ return async ({ method, path, req, res, workspaceRoot }) => {
3926
+ if (path !== "/api/autopilot") return false;
3927
+ if (method === "GET") {
3928
+ sendJson(res, 200, dependencies.getStatus(workspaceRoot));
3929
+ return true;
3930
+ }
3931
+ if (method === "POST") {
3932
+ try {
3933
+ const data = await readJson(req);
3934
+ if (typeof data.enabled !== "boolean") {
3935
+ throw new HttpBodyError("The 'enabled' field must be a boolean", 400);
3936
+ }
3937
+ sendJson(res, 200, dependencies.setEnabled(workspaceRoot, data.enabled));
3938
+ } catch (error) {
3939
+ sendBodyError7(error, res);
3940
+ }
3941
+ return true;
3942
+ }
3943
+ return false;
3944
+ };
3945
+ }
3946
+
3583
3947
  // src/flow-serve/client-assets.ts
3584
- import { existsSync as existsSync12, readFileSync as readFileSync10 } from "fs";
3585
- import { dirname, extname, join as join11 } from "path";
3948
+ import { existsSync as existsSync11, readFileSync as readFileSync10 } from "fs";
3949
+ import { dirname, extname, join as join10 } from "path";
3586
3950
  import { fileURLToPath } from "url";
3587
3951
  var ClientAssets = class {
3588
3952
  constructor(root) {
@@ -3594,18 +3958,18 @@ var ClientAssets = class {
3594
3958
  if (!this.clientDir) {
3595
3959
  const moduleDir = dirname(fileURLToPath(import.meta.url));
3596
3960
  const candidates = [
3597
- join11(moduleDir, "client"),
3598
- join11(this.root, "packages", "client", "dist"),
3599
- join11(moduleDir, "..", "..", "..", "client", "dist")
3961
+ join10(moduleDir, "client"),
3962
+ join10(this.root, "packages", "client", "dist"),
3963
+ join10(moduleDir, "..", "..", "..", "client", "dist")
3600
3964
  ];
3601
- this.clientDir = candidates.find((directory) => existsSync12(join11(directory, "index.html"))) ?? null;
3965
+ this.clientDir = candidates.find((directory) => existsSync11(join10(directory, "index.html"))) ?? null;
3602
3966
  }
3603
3967
  if (!this.clientDir) {
3604
3968
  this.proxyToVite(req, res);
3605
3969
  return;
3606
3970
  }
3607
- let filePath = join11(this.clientDir, path === "/" ? "index.html" : path);
3608
- if (!existsSync12(filePath)) filePath = join11(this.clientDir, "index.html");
3971
+ let filePath = join10(this.clientDir, path === "/" ? "index.html" : path);
3972
+ if (!existsSync11(filePath)) filePath = join10(this.clientDir, "index.html");
3609
3973
  const mime = {
3610
3974
  ".html": "text/html; charset=utf-8",
3611
3975
  ".js": "application/javascript; charset=utf-8",
@@ -3641,8 +4005,8 @@ var ClientAssets = class {
3641
4005
  };
3642
4006
 
3643
4007
  // src/flow-serve/automation-runtime.ts
3644
- import { existsSync as existsSync13, watch } from "fs";
3645
- import { join as join12 } from "path";
4008
+ import { existsSync as existsSync12, watch } from "fs";
4009
+ import { join as join11 } from "path";
3646
4010
  var AutomationRuntime = class {
3647
4011
  constructor(dependencies) {
3648
4012
  this.dependencies = dependencies;
@@ -3674,8 +4038,8 @@ var AutomationRuntime = class {
3674
4038
  this.binding = void 0;
3675
4039
  }
3676
4040
  armWatchers(binding) {
3677
- const workflowPath = join12(binding.workspaceDir, "workflow.json");
3678
- const pathExists = this.dependencies.pathExists ?? existsSync13;
4041
+ const workflowPath = join11(binding.workspaceDir, "workflow.json");
4042
+ const pathExists = this.dependencies.pathExists ?? existsSync12;
3679
4043
  const watchPath = this.dependencies.watchPath ?? ((path, options, listener) => watch(path, options, listener));
3680
4044
  if (pathExists(workflowPath)) {
3681
4045
  try {
@@ -3692,7 +4056,7 @@ var AutomationRuntime = class {
3692
4056
  } catch {
3693
4057
  }
3694
4058
  }
3695
- const specsPath = join12(binding.workspaceDir, "specs");
4059
+ const specsPath = join11(binding.workspaceDir, "specs");
3696
4060
  if (pathExists(specsPath)) {
3697
4061
  try {
3698
4062
  this.safeLogAction(binding.workspaceRoot, "specs-watch", "armed", {
@@ -3770,14 +4134,149 @@ var AutomationRuntime = class {
3770
4134
 
3771
4135
  // src/orchestrator/orchestrator.ts
3772
4136
  import {
3773
- existsSync as existsSync14,
3774
- mkdirSync as mkdirSync4,
4137
+ existsSync as existsSync13,
4138
+ mkdirSync as mkdirSync3,
3775
4139
  readFileSync as readFileSync11,
3776
- writeFileSync as writeFileSync5,
4140
+ writeFileSync as writeFileSync4,
3777
4141
  unlinkSync as unlinkSync2,
3778
4142
  readdirSync as readdirSync6
3779
4143
  } from "fs";
3780
- import { join as join13 } from "path";
4144
+ import { join as join12 } from "path";
4145
+
4146
+ // src/domain-operations/orchestrator-gateway.ts
4147
+ async function persist(root, options) {
4148
+ try {
4149
+ await writeWorkflow(root, options);
4150
+ return { ok: true };
4151
+ } catch (error) {
4152
+ return { ok: false, reason: error instanceof Error ? error.message : String(error) };
4153
+ }
4154
+ }
4155
+ var CanonicalOrchestratorGateway = class {
4156
+ async emitHandoff(root, payload) {
4157
+ const workflow = loadWorkflow(root);
4158
+ const item = workflow?.items.find((entry) => entry.id === payload.itemId);
4159
+ if (!workflow || !item) return { ok: false, reason: `Item ${payload.itemId} not found` };
4160
+ item.handoff = {
4161
+ from: payload.from,
4162
+ to: payload.to,
4163
+ summary: payload.summary,
4164
+ evidence: payload.evidence,
4165
+ timestamp: payload.timestamp,
4166
+ expiresAt: payload.expiresAt,
4167
+ executorId: payload.executorId
4168
+ };
4169
+ workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
4170
+ const persisted = await persist(root, {
4171
+ workflow,
4172
+ source: "orchestrator-gateway",
4173
+ primaryItemId: item.id,
4174
+ skipSitrep: true,
4175
+ skipLog: true,
4176
+ quiet: true,
4177
+ confineAdapterWrites: true
4178
+ });
4179
+ if (!persisted.ok) return persisted;
4180
+ logEntry(root, "handoff_emitted", `Handoff emitted to ${payload.to}`, {
4181
+ itemId: payload.itemId,
4182
+ from: payload.from,
4183
+ to: payload.to,
4184
+ summary: payload.summary,
4185
+ evidence: payload.evidence
4186
+ });
4187
+ return { ok: true };
4188
+ }
4189
+ async claim(root, input) {
4190
+ const workflow = loadWorkflow(root);
4191
+ const item = workflow?.items.find((entry) => entry.id === input.itemId);
4192
+ if (!workflow || !item) return { ok: false, reason: `Item ${input.itemId} not found` };
4193
+ const handoff = item.handoff && item.handoff.to === input.agentId ? { ...item.handoff } : null;
4194
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4195
+ item.claimedBy = input.executorId;
4196
+ item.claimedAt = now;
4197
+ if (handoff) item.handoff = void 0;
4198
+ workflow.updatedAt = now;
4199
+ const persisted = await persist(root, {
4200
+ workflow,
4201
+ source: "orchestrator-gateway",
4202
+ primaryItemId: input.itemId,
4203
+ skipSitrep: true,
4204
+ skipLog: true,
4205
+ quiet: true,
4206
+ confineAdapterWrites: true
4207
+ });
4208
+ if (!persisted.ok) return persisted;
4209
+ logEntry(root, "item_claim", `Claimed by ${input.executorId}`, {
4210
+ itemId: input.itemId,
4211
+ executorId: input.executorId,
4212
+ agentId: input.agentId
4213
+ });
4214
+ return { ok: true };
4215
+ }
4216
+ async reclaim(root, itemIds) {
4217
+ if (itemIds.length === 0) return { ok: true };
4218
+ const workflow = loadWorkflow(root);
4219
+ if (!workflow) return { ok: false, reason: "No workflow found" };
4220
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4221
+ for (const itemId of itemIds) {
4222
+ const item = workflow.items.find((entry) => entry.id === itemId);
4223
+ if (!item) continue;
4224
+ item.claimedBy = void 0;
4225
+ item.claimedAt = void 0;
4226
+ item.claimExpiresAt = void 0;
4227
+ item.claimExecutorId = void 0;
4228
+ item.claimCapability = void 0;
4229
+ item.claimRevision = void 0;
4230
+ item.claimTtlMinutes = void 0;
4231
+ logEntry(root, "item_reclaim", "Item reclaimed after persisted lease expiry", { itemId });
4232
+ }
4233
+ workflow.updatedAt = now;
4234
+ const persisted = await persist(root, {
4235
+ workflow,
4236
+ source: "orchestrator-gateway",
4237
+ skipSitrep: true,
4238
+ skipLog: true,
4239
+ quiet: true,
4240
+ confineAdapterWrites: true
4241
+ });
4242
+ if (!persisted.ok) return persisted;
4243
+ return { ok: true };
4244
+ }
4245
+ async retry(root, input) {
4246
+ const workflow = loadWorkflow(root);
4247
+ const item = workflow?.items.find((entry) => entry.id === input.itemId);
4248
+ if (!workflow || !item) return { ok: false, reason: `Item ${input.itemId} not found` };
4249
+ item.handoff = {
4250
+ from: input.handoff.from,
4251
+ to: input.handoff.to,
4252
+ summary: input.handoff.summary,
4253
+ evidence: input.handoff.evidence,
4254
+ timestamp: input.handoff.timestamp,
4255
+ expiresAt: input.handoff.expiresAt,
4256
+ executorId: input.handoff.executorId
4257
+ };
4258
+ item.retryCount = input.retryCount;
4259
+ if (input.lastOperationKey) item.lastOperationKey = input.lastOperationKey;
4260
+ workflow.updatedAt = input.handoff.timestamp;
4261
+ const persisted = await persist(root, {
4262
+ workflow,
4263
+ source: "orchestrator-gateway",
4264
+ primaryItemId: input.itemId,
4265
+ skipSitrep: true,
4266
+ skipLog: true,
4267
+ quiet: true,
4268
+ confineAdapterWrites: true
4269
+ });
4270
+ if (!persisted.ok) return persisted;
4271
+ logEntry(root, "handoff_emitted", input.deadLetter ? "Retry dead-lettered to human" : "Handoff re-emitted after retry", {
4272
+ itemId: input.itemId,
4273
+ details: { retry: true, deadLetter: Boolean(input.deadLetter), executorId: input.handoff.executorId }
4274
+ });
4275
+ return { ok: true };
4276
+ }
4277
+ };
4278
+
4279
+ // src/orchestrator/orchestrator.ts
3781
4280
  var DEFAULT_HEARTBEAT_TIMEOUT = 6e4;
3782
4281
  var DEFAULT_MAX_EXECUTION_TIME = 18e5;
3783
4282
  var RECLAIM_INTERVAL = 6e4;
@@ -3789,12 +4288,14 @@ var Orchestrator = class {
3789
4288
  heartbeats = /* @__PURE__ */ new Map();
3790
4289
  stageExecutorPreferences = /* @__PURE__ */ new Map();
3791
4290
  onHandoffEvent;
4291
+ gateway;
3792
4292
  reclaimTimer = null;
3793
4293
  constructor(config) {
3794
4294
  this.root = config.root;
3795
4295
  this.manifest = loadHarness(resolveHarnessRoot(config.root, DEFAULT_HARNESS_VERSION));
3796
4296
  this.gateChecker = new GateChecker(config.root, this.manifest ?? void 0);
3797
4297
  this.onHandoffEvent = config.onHandoffEvent;
4298
+ this.gateway = config.gateway ?? new CanonicalOrchestratorGateway();
3798
4299
  }
3799
4300
  registerExecutor(executor) {
3800
4301
  this.executors.set(executor.id, executor);
@@ -3851,7 +4352,7 @@ var Orchestrator = class {
3851
4352
  }
3852
4353
  return null;
3853
4354
  }
3854
- emitHandoff(payload) {
4355
+ async emitHandoff(payload) {
3855
4356
  const workflow = loadWorkflow(this.root);
3856
4357
  if (!workflow) {
3857
4358
  return { success: false, reason: "No workflow found" };
@@ -3871,30 +4372,9 @@ var Orchestrator = class {
3871
4372
  return { success: false, reason: gateResult.reason };
3872
4373
  }
3873
4374
  }
3874
- item.handoff = {
3875
- from: payload.from,
3876
- to: payload.to,
3877
- summary: payload.summary,
3878
- evidence: payload.evidence,
3879
- timestamp: payload.timestamp,
3880
- expiresAt: payload.expiresAt,
3881
- executorId: payload.executorId
3882
- };
3883
- workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
3884
- writeWorkflow(this.root, {
3885
- workflow,
3886
- source: "orchestrator",
3887
- primaryItemId: item.id,
3888
- skipSitrep: true
3889
- });
3890
- this.writeHandoffFile(item);
3891
- logEntry(this.root, "handoff_emitted", `Handoff emitted to ${payload.to}`, {
3892
- itemId: payload.itemId,
3893
- from: payload.from,
3894
- to: payload.to,
3895
- summary: payload.summary,
3896
- evidence: payload.evidence
3897
- });
4375
+ const persisted = await this.gateway.emitHandoff(this.root, payload);
4376
+ if (!persisted.ok) return { success: false, reason: persisted.reason };
4377
+ this.writeHandoffFile({ ...item, handoff: payload });
3898
4378
  if (this.onHandoffEvent) {
3899
4379
  this.onHandoffEvent({
3900
4380
  itemId: payload.itemId,
@@ -3910,7 +4390,7 @@ var Orchestrator = class {
3910
4390
  }
3911
4391
  return { success: true };
3912
4392
  }
3913
- autoClaim(itemId, executorId, agentId) {
4393
+ async autoClaim(itemId, executorId, agentId) {
3914
4394
  const workflow = loadWorkflow(this.root);
3915
4395
  if (!workflow) {
3916
4396
  return { success: false, reason: "No workflow found" };
@@ -3935,25 +4415,10 @@ var Orchestrator = class {
3935
4415
  };
3936
4416
  }
3937
4417
  this.writeFileLock(itemId, { executor: executorId, claimedAt: Date.now() });
3938
- item.claimedBy = executorId;
3939
- item.claimedAt = (/* @__PURE__ */ new Date()).toISOString();
3940
4418
  const handoffData = item.handoff && item.handoff.to === agentId ? { ...item.handoff } : null;
3941
- if (item.handoff && item.handoff.to === agentId) {
3942
- item.handoff = void 0;
3943
- this.removeHandoffFile(itemId);
3944
- }
3945
- workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
3946
- writeWorkflow(this.root, {
3947
- workflow,
3948
- source: "orchestrator",
3949
- primaryItemId: itemId,
3950
- skipSitrep: true
3951
- });
3952
- logEntry(this.root, "item_claim", `Claimed by ${executorId}`, {
3953
- itemId,
3954
- executorId,
3955
- agentId
3956
- });
4419
+ const persisted = await this.gateway.claim(this.root, { itemId, executorId, agentId });
4420
+ if (!persisted.ok) return { success: false, reason: persisted.reason };
4421
+ if (handoffData) this.removeHandoffFile(itemId);
3957
4422
  if (this.onHandoffEvent && handoffData) {
3958
4423
  this.onHandoffEvent({
3959
4424
  itemId,
@@ -3974,11 +4439,11 @@ var Orchestrator = class {
3974
4439
  if (!workflow) return null;
3975
4440
  const item = workflow.items.find((i) => i.id === itemId);
3976
4441
  if (!item) return null;
3977
- const snapshot = resolveAgentDirection(this.root);
4442
+ const snapshot = resolveDirection(this.root, { itemId });
3978
4443
  let specContent = null;
3979
4444
  if (item.spec) {
3980
- const specPath = join13(this.root, ".letra", "specs", item.spec, "spec.md");
3981
- if (existsSync14(specPath)) {
4445
+ const specPath = join12(getLetraDir2(this.root), "specs", item.spec, "spec.md");
4446
+ if (existsSync13(specPath)) {
3982
4447
  specContent = readFileSync11(specPath, "utf-8");
3983
4448
  }
3984
4449
  }
@@ -4021,29 +4486,19 @@ var Orchestrator = class {
4021
4486
  isOnline: true
4022
4487
  });
4023
4488
  }
4024
- reclaimStaleItems() {
4489
+ async reclaimStaleItems() {
4025
4490
  const workflow = loadWorkflow(this.root);
4026
4491
  if (!workflow) return [];
4027
4492
  const reclaimed = [];
4028
4493
  const now = Date.now();
4029
4494
  const lockFiles = this.listLockFiles();
4030
4495
  for (const [itemId, lock] of lockFiles) {
4031
- const executorConfig = this.executors.get(lock.executor);
4032
- const maxExecTime = executorConfig?.maxExecutionTime ? executorConfig.maxExecutionTime * 1e3 : DEFAULT_MAX_EXECUTION_TIME;
4033
- const age = now - lock.claimedAt;
4034
- if (age > maxExecTime) {
4035
- const item = workflow.items.find((i) => i.id === itemId);
4036
- if (item) {
4037
- item.claimedBy = void 0;
4038
- item.claimedAt = void 0;
4039
- reclaimed.push(itemId);
4040
- logEntry(this.root, "item_reclaim", `Item reclaimed (timeout ${age}ms)`, {
4041
- itemId,
4042
- executorId: lock.executor
4043
- });
4044
- }
4045
- this.deleteFileLock(itemId);
4496
+ const item = workflow.items.find((i) => i.id === itemId);
4497
+ const expiry = item?.claimExpiresAt ? Date.parse(item.claimExpiresAt) : lock.claimedAt + DEFAULT_MAX_EXECUTION_TIME;
4498
+ if (item && Number.isFinite(expiry) && now >= expiry) {
4499
+ reclaimed.push(itemId);
4046
4500
  }
4501
+ if (!item || Number.isFinite(expiry) && now >= expiry) this.deleteFileLock(itemId);
4047
4502
  }
4048
4503
  for (const [executorId, heartbeat] of this.heartbeats) {
4049
4504
  const executor = this.executors.get(executorId);
@@ -4059,19 +4514,15 @@ var Orchestrator = class {
4059
4514
  }
4060
4515
  }
4061
4516
  if (reclaimed.length > 0) {
4062
- workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
4063
- writeWorkflow(this.root, {
4064
- workflow,
4065
- source: "orchestrator-reclaim",
4066
- skipSitrep: true
4067
- });
4517
+ const persisted = await this.gateway.reclaim(this.root, reclaimed);
4518
+ if (!persisted.ok) return [];
4068
4519
  }
4069
4520
  return reclaimed;
4070
4521
  }
4071
4522
  startReclaimTimer() {
4072
4523
  if (this.reclaimTimer) return;
4073
4524
  this.reclaimTimer = setInterval(() => {
4074
- this.reclaimStaleItems();
4525
+ void this.reclaimStaleItems().catch(() => void 0);
4075
4526
  }, RECLAIM_INTERVAL);
4076
4527
  }
4077
4528
  stopReclaimTimer() {
@@ -4087,11 +4538,11 @@ var Orchestrator = class {
4087
4538
  return Array.from(this.heartbeats.values());
4088
4539
  }
4089
4540
  getLocksDir() {
4090
- return join13(this.root, ".letra", "locks");
4541
+ return join12(this.root, ".letra", "locks");
4091
4542
  }
4092
4543
  readFileLock(itemId) {
4093
- const lockPath = join13(this.getLocksDir(), `${itemId}.lock`);
4094
- if (!existsSync14(lockPath)) return null;
4544
+ const lockPath = join12(this.getLocksDir(), `${itemId}.lock`);
4545
+ if (!existsSync13(lockPath)) return null;
4095
4546
  try {
4096
4547
  const data = JSON.parse(readFileSync11(lockPath, "utf-8"));
4097
4548
  return { executor: data.executor, claimedAt: data.claimedAt };
@@ -4101,19 +4552,19 @@ var Orchestrator = class {
4101
4552
  }
4102
4553
  writeFileLock(itemId, lock) {
4103
4554
  const dir = this.getLocksDir();
4104
- mkdirSync4(dir, { recursive: true });
4105
- const lockPath = join13(dir, `${itemId}.lock`);
4106
- writeFileSync5(lockPath, JSON.stringify(lock, null, 2));
4555
+ mkdirSync3(dir, { recursive: true });
4556
+ const lockPath = join12(dir, `${itemId}.lock`);
4557
+ writeFileSync4(lockPath, JSON.stringify(lock, null, 2));
4107
4558
  }
4108
4559
  deleteFileLock(itemId) {
4109
- const lockPath = join13(this.getLocksDir(), `${itemId}.lock`);
4110
- if (existsSync14(lockPath)) {
4560
+ const lockPath = join12(this.getLocksDir(), `${itemId}.lock`);
4561
+ if (existsSync13(lockPath)) {
4111
4562
  unlinkSync2(lockPath);
4112
4563
  }
4113
4564
  }
4114
4565
  listLockFiles() {
4115
4566
  const dir = this.getLocksDir();
4116
- if (!existsSync14(dir)) return /* @__PURE__ */ new Map();
4567
+ if (!existsSync13(dir)) return /* @__PURE__ */ new Map();
4117
4568
  const files = readdirSync6(dir).filter((f) => f.endsWith(".lock"));
4118
4569
  const locks = /* @__PURE__ */ new Map();
4119
4570
  for (const file of files) {
@@ -4124,14 +4575,14 @@ var Orchestrator = class {
4124
4575
  return locks;
4125
4576
  }
4126
4577
  getHandoffsDir() {
4127
- return join13(this.root, ".letra", "handoffs");
4578
+ return join12(this.root, ".letra", "handoffs");
4128
4579
  }
4129
4580
  writeHandoffFile(item) {
4130
4581
  if (!item.handoff) return;
4131
4582
  const dir = this.getHandoffsDir();
4132
- mkdirSync4(dir, { recursive: true });
4133
- const filePath = join13(dir, `${item.id}.json`);
4134
- writeFileSync5(
4583
+ mkdirSync3(dir, { recursive: true });
4584
+ const filePath = join12(dir, `${item.id}.json`);
4585
+ writeFileSync4(
4135
4586
  filePath,
4136
4587
  JSON.stringify(
4137
4588
  {
@@ -4150,12 +4601,12 @@ var Orchestrator = class {
4150
4601
  );
4151
4602
  }
4152
4603
  removeHandoffFile(itemId) {
4153
- const filePath = join13(this.getHandoffsDir(), `${itemId}.json`);
4154
- if (existsSync14(filePath)) {
4604
+ const filePath = join12(this.getHandoffsDir(), `${itemId}.json`);
4605
+ if (existsSync13(filePath)) {
4155
4606
  unlinkSync2(filePath);
4156
4607
  }
4157
4608
  }
4158
- retryHandoff(itemId) {
4609
+ async retryHandoff(itemId) {
4159
4610
  const workflow = loadWorkflow(this.root);
4160
4611
  if (!workflow) {
4161
4612
  return { success: false, reason: "No workflow found" };
@@ -4170,6 +4621,23 @@ var Orchestrator = class {
4170
4621
  if (new Date(item.handoff.expiresAt) >= /* @__PURE__ */ new Date()) {
4171
4622
  return { success: false, reason: `Handoff for ${itemId} has not expired yet` };
4172
4623
  }
4624
+ const retryCount = item.retryCount ?? 0;
4625
+ if (retryCount >= 3) {
4626
+ const now2 = /* @__PURE__ */ new Date();
4627
+ const deadLetter = {
4628
+ itemId,
4629
+ from: item.handoff.from,
4630
+ to: "human",
4631
+ summary: `Retry limit exceeded for ${itemId}; human recovery required.`,
4632
+ evidence: item.handoff.evidence,
4633
+ timestamp: now2.toISOString(),
4634
+ expiresAt: new Date(now2.getTime() + 24 * 60 * 6e4).toISOString()
4635
+ };
4636
+ const persisted2 = await this.gateway.retry(this.root, { itemId, deadLetter: true, handoff: deadLetter, retryCount });
4637
+ if (!persisted2.ok) return { success: false, reason: persisted2.reason };
4638
+ this.writeHandoffFile({ ...item, handoff: deadLetter });
4639
+ return { success: true, reEmittedTo: "human" };
4640
+ }
4173
4641
  const previousTo = item.handoff.to;
4174
4642
  const previousFrom = item.handoff.from;
4175
4643
  const summary = item.handoff.summary;
@@ -4191,7 +4659,8 @@ var Orchestrator = class {
4191
4659
  const ttlMinutes = 30;
4192
4660
  const now = /* @__PURE__ */ new Date();
4193
4661
  const expiresAt = new Date(now.getTime() + ttlMinutes * 60 * 1e3);
4194
- item.handoff = {
4662
+ const nextHandoff2 = {
4663
+ itemId,
4195
4664
  from: previousFrom,
4196
4665
  to: previousTo,
4197
4666
  summary,
@@ -4200,26 +4669,14 @@ var Orchestrator = class {
4200
4669
  expiresAt: expiresAt.toISOString(),
4201
4670
  executorId: nextExecutor.id
4202
4671
  };
4203
- workflow.updatedAt = now.toISOString();
4204
- writeWorkflow(this.root, {
4205
- workflow,
4206
- source: "orchestrator-retry",
4207
- primaryItemId: itemId,
4208
- skipSitrep: true
4672
+ const persisted = await this.gateway.retry(this.root, {
4673
+ itemId,
4674
+ handoff: nextHandoff2,
4675
+ retryCount: retryCount + 1,
4676
+ lastOperationKey: `retry:${itemId}:${retryCount + 1}:${nextExecutor.id}`
4209
4677
  });
4210
- this.writeHandoffFile(item);
4211
- logEntry(
4212
- this.root,
4213
- "handoff_emitted",
4214
- `Handoff re-emitted to ${previousTo} (retry via ${nextExecutor.id})`,
4215
- {
4216
- itemId,
4217
- from: previousFrom,
4218
- to: previousTo,
4219
- executorId: nextExecutor.id,
4220
- retry: true
4221
- }
4222
- );
4678
+ if (!persisted.ok) return { success: false, reason: persisted.reason };
4679
+ this.writeHandoffFile({ ...item, handoff: nextHandoff2 });
4223
4680
  if (this.onHandoffEvent) {
4224
4681
  this.onHandoffEvent({
4225
4682
  itemId,
@@ -4237,13 +4694,12 @@ var Orchestrator = class {
4237
4694
  }
4238
4695
  getPendingHandoffFiles() {
4239
4696
  const dir = this.getHandoffsDir();
4240
- if (!existsSync14(dir)) return [];
4241
- const { readdirSync: readdirSync7 } = __require("fs");
4242
- const files = readdirSync7(dir).filter((f) => f.endsWith(".json"));
4697
+ if (!existsSync13(dir)) return [];
4698
+ const files = readdirSync6(dir).filter((f) => f.endsWith(".json"));
4243
4699
  const now = /* @__PURE__ */ new Date();
4244
4700
  return files.flatMap((file) => {
4245
4701
  try {
4246
- const data = JSON.parse(readFileSync11(join13(dir, file), "utf-8"));
4702
+ const data = JSON.parse(readFileSync11(join12(dir, file), "utf-8"));
4247
4703
  if (new Date(data.expiresAt) < now) return [];
4248
4704
  return [{ itemId: data.itemId, to: data.to, expiresAt: data.expiresAt }];
4249
4705
  } catch {
@@ -4254,6 +4710,29 @@ var Orchestrator = class {
4254
4710
  };
4255
4711
 
4256
4712
  // src/orchestrator/dispatcher.ts
4713
+ var SecurityReviewOperationError = class extends Error {
4714
+ constructor(operation) {
4715
+ super(operation.reason);
4716
+ this.operation = operation;
4717
+ this.name = "SecurityReviewOperationError";
4718
+ }
4719
+ operation;
4720
+ };
4721
+ function evidenceKind(value) {
4722
+ const trimmed = value.trim();
4723
+ const absolute = /^[A-Za-z]:[\\/]/.test(trimmed) || trimmed.startsWith("/") || trimmed.startsWith("\\");
4724
+ const traversal = /(?:^|[\\/])\.\.(?:[\\/]|$)/.test(trimmed);
4725
+ return absolute || traversal || trimmed.includes("/") && !/\s/.test(trimmed) ? "file" : "command";
4726
+ }
4727
+ async function withFreshRevision(getDirection, itemId, operation) {
4728
+ let expectedRevision = getDirection(itemId).revision;
4729
+ for (let attempt = 0; attempt < 3; attempt += 1) {
4730
+ const result = await operation(expectedRevision);
4731
+ if (result.reasonCode !== "DIRECTION_STALE") return result;
4732
+ expectedRevision = getDirection(itemId).revision;
4733
+ }
4734
+ return operation(expectedRevision);
4735
+ }
4257
4736
  var PersistentDispatcher = class {
4258
4737
  constructor(store, executors, intervalMs = 3e4, options = {}) {
4259
4738
  this.store = store;
@@ -4282,82 +4761,176 @@ var PersistentDispatcher = class {
4282
4761
  try {
4283
4762
  const workflow = this.store.loadWorkflow();
4284
4763
  const results = [];
4764
+ if (this.store.operations.reclaimExpired) {
4765
+ const recovery = await withFreshRevision(
4766
+ this.store.operations.getDirection,
4767
+ "",
4768
+ (expectedRevision) => this.store.operations.reclaimExpired({ actor: "system:dispatcher", expectedRevision, reason: "Recuperar claims expirados ao iniciar ciclo do dispatcher.", idempotencyKey: `reclaim:${(/* @__PURE__ */ new Date()).toISOString().slice(0, 16)}` })
4769
+ );
4770
+ if (recovery.outcome !== "accepted" && recovery.reasonCode !== "ITEM_NOT_CURRENT") {
4771
+ this.options.onResult?.({ itemId: "workspace", status: "failed", reason: recovery.reason });
4772
+ }
4773
+ }
4285
4774
  for (const item of workflow.items) {
4286
4775
  if (!item.handoff || item.claimedBy) continue;
4287
4776
  const stage = workflow.stages.find((entry) => entry.id === item.stage);
4288
4777
  if (!stage) continue;
4289
- if (item.handoff.to === "human" || item.handoff.to.startsWith("human:")) {
4290
- const result = { itemId: item.id, status: "waiting-human", reason: "aguardando decis\xE3o humana" };
4778
+ const targetsHuman = item.handoff.to === "human" || item.handoff.to.startsWith("human:");
4779
+ const blockedByHumanGate = this.options.blocksHandoff?.(stage, item) === true;
4780
+ if (blockedByHumanGate) {
4781
+ const result = { itemId: item.id, status: "waiting-human", reason: "gate humano bloqueante" };
4291
4782
  results.push(result);
4292
4783
  this.options.onResult?.(result);
4293
4784
  continue;
4294
4785
  }
4295
- if (this.options.blocksHandoff?.(stage, item)) {
4296
- const result = { itemId: item.id, status: "waiting-human", reason: "gate humano bloqueante" };
4786
+ if (targetsHuman) {
4787
+ const result = {
4788
+ itemId: item.id,
4789
+ status: "failed",
4790
+ reason: "HUMAN_HANDOFF_REQUIRES_BLOCKING_GATE: handoff humano sem gate humano bloqueante"
4791
+ };
4297
4792
  results.push(result);
4298
4793
  this.options.onResult?.(result);
4299
4794
  continue;
4300
4795
  }
4301
- const capability = stage.id;
4302
- const online = this.executors().filter((entry) => entry.status !== "offline");
4303
- const executor = online.find((entry) => entry.capabilities.includes(capability)) ?? online[0];
4796
+ const executionWorkspace = this.options.resolveExecutionWorkspace?.(stage, item);
4797
+ if (executionWorkspace && !executionWorkspace.ok) {
4798
+ const result = { itemId: item.id, status: "failed", reason: `${executionWorkspace.reasonCode}: ${executionWorkspace.reason}` };
4799
+ results.push(result);
4800
+ this.options.onResult?.(result);
4801
+ continue;
4802
+ }
4803
+ const capability = this.options.stageCapability?.(stage, item) ?? stage.id;
4804
+ const actor = item.handoff.to;
4805
+ const attempt = item.lastFailure?.at ?? "first";
4806
+ const operationKey = `dispatch:${item.id}:${item.handoff.timestamp}:${attempt}`;
4807
+ const allExecutors = this.executors();
4808
+ const resolvedBinding = this.options.resolveBinding?.(stage, item, actor, capability, allExecutors);
4809
+ const online = allExecutors.filter((entry) => entry.status !== "offline");
4810
+ const compatible = online.filter((entry) => entry.capabilities.includes(capability));
4811
+ const preference = this.options.executorPreference?.(stage, item) ?? [];
4812
+ const executor = resolvedBinding ? resolvedBinding.ok ? resolvedBinding.executor : void 0 : compatible.sort((a, b) => {
4813
+ const ai = preference.indexOf(a.id);
4814
+ const bi = preference.indexOf(b.id);
4815
+ if (ai >= 0 || bi >= 0) return (ai < 0 ? Number.MAX_SAFE_INTEGER : ai) - (bi < 0 ? Number.MAX_SAFE_INTEGER : bi);
4816
+ return a.id.localeCompare(b.id);
4817
+ })[0];
4304
4818
  if (!executor) {
4305
- results.push({ itemId: item.id, status: "offline", reason: "nenhum executor online" });
4819
+ const result = {
4820
+ itemId: item.id,
4821
+ status: "offline",
4822
+ reasonCode: resolvedBinding?.reasonCode ?? "NO_COMPATIBLE_EXECUTOR",
4823
+ reason: `${resolvedBinding?.reasonCode ?? "NO_COMPATIBLE_EXECUTOR"}: ${resolvedBinding?.reason ?? "nenhum executor registrado \xE9 compat\xEDvel"}`
4824
+ };
4825
+ results.push(result);
4826
+ this.options.onResult?.(result);
4306
4827
  continue;
4307
4828
  }
4308
- const claimed = {
4309
- ...item,
4310
- claimedBy: item.handoff.to,
4311
- claimedAt: (/* @__PURE__ */ new Date()).toISOString(),
4312
- claimExecutorId: executor.id,
4313
- activityStatus: "started",
4314
- activityStartedAt: (/* @__PURE__ */ new Date()).toISOString(),
4315
- lastHeartbeatAt: (/* @__PURE__ */ new Date()).toISOString()
4316
- };
4317
- if (this.store.claim) {
4318
- const accepted = await this.store.claim(item.id, executor.id, item.handoff.to);
4319
- if (!accepted) continue;
4320
- } else {
4321
- const nextWorkflow = { ...workflow, items: workflow.items.map((entry) => entry.id === item.id ? claimed : entry) };
4322
- await this.store.writeWorkflow(nextWorkflow);
4829
+ const claim = await withFreshRevision(
4830
+ this.store.operations.getDirection,
4831
+ item.id,
4832
+ (expectedRevision) => this.store.operations.claim({ itemId: item.id, executorId: executor.id, capability, actor, expectedRevision, reason: "Dispatcher aut\xF4nomo iniciou a execu\xE7\xE3o.", idempotencyKey: `${operationKey}:claim` })
4833
+ );
4834
+ if (claim.outcome !== "accepted") {
4835
+ const result = { itemId: item.id, status: "failed", reason: claim.reason };
4836
+ results.push(result);
4837
+ this.options.onResult?.(result);
4838
+ continue;
4839
+ }
4840
+ const started = await withFreshRevision(
4841
+ this.store.operations.getDirection,
4842
+ item.id,
4843
+ (expectedRevision) => this.store.operations.event({ itemId: item.id, executorId: executor.id, actor, status: "started", expectedRevision, reason: "Registrar in\xEDcio da execu\xE7\xE3o aut\xF4noma.", idempotencyKey: `${operationKey}:started` })
4844
+ );
4845
+ if (started.outcome !== "accepted") {
4846
+ const released = await withFreshRevision(
4847
+ this.store.operations.getDirection,
4848
+ item.id,
4849
+ (expectedRevision) => this.store.operations.release({ itemId: item.id, actor, expectedRevision, reason: "Liberar claim ap\xF3s falha ao registrar in\xEDcio.", idempotencyKey: `${operationKey}:release-start` })
4850
+ );
4851
+ const result = { itemId: item.id, status: "failed", reason: started.reason };
4852
+ results.push(result);
4853
+ this.options.onResult?.(result);
4854
+ if (released.outcome !== "accepted") this.options.onResult?.({ ...result, reason: `${result.reason}; libera\xE7\xE3o do claim: ${released.reason}` });
4855
+ continue;
4323
4856
  }
4857
+ const claimed = started.nextDirection.item ?? { ...item, claimedBy: actor, claimExecutorId: executor.id };
4324
4858
  try {
4325
4859
  if (typeof executor.heartbeat === "function") {
4326
4860
  await executor.heartbeat();
4327
4861
  }
4328
- const execution = await executor.execute({ itemId: claimed.id, item: claimed, agent: item.handoff.to, stage: item.stage, spec: claimed.spec ?? null, diff: null, snapshot: { stages: workflow.stages.map((entry) => ({ ...entry, agents: this.options.stageActors?.(entry.id) ?? entry.agents })) }, sessionLog: [], commands: [], prohibitions: [] });
4329
- const current = this.store.loadWorkflow();
4330
- const updated = current.items.map((entry) => {
4331
- if (entry.id !== item.id) return entry;
4332
- const next = { ...entry, claimedBy: void 0, claimedAt: void 0, claimExecutorId: void 0, activityStatus: execution.success ? "succeeded" : "failed", lastHeartbeatAt: (/* @__PURE__ */ new Date()).toISOString() };
4333
- if (execution.success && execution.handoff) {
4334
- const targetStage = workflow.stages.find(
4335
- (candidate) => (this.options.stageActors?.(candidate.id) ?? candidate.agents ?? []).includes(execution.handoff.to)
4862
+ let execution;
4863
+ const heartbeatTimer = setInterval(() => {
4864
+ const revision = this.store.operations.getDirection(item.id).revision;
4865
+ void this.store.operations.event({ itemId: item.id, executorId: executor.id, actor, status: "heartbeat", expectedRevision: revision, reason: "Renovar lease durante execu\xE7\xE3o longa.", idempotencyKey: `${operationKey}:heartbeat:${Date.now()}` }).catch(() => void 0);
4866
+ }, Math.max(5e3, Math.min(3e4, this.intervalMs)));
4867
+ try {
4868
+ execution = await executor.execute({ itemId: claimed.id, item: claimed, agent: resolvedBinding?.identity?.displayName ?? actor, stage: item.stage, spec: claimed.spec ?? null, diff: null, snapshot: { stages: workflow.stages.map((entry) => ({ ...entry, agents: this.options.stageActors?.(entry.id) ?? entry.agents, transitions: this.options.stageTransitions?.(entry.id) ?? entry.transitions })), executionWorkspace: executionWorkspace?.ok ? executionWorkspace.root : void 0, persona: resolvedBinding?.identity ? { id: resolvedBinding.identity.id, displayName: resolvedBinding.identity.displayName, role: resolvedBinding.binding?.roleId, skills: resolvedBinding.identity.skills, adapterHints: resolvedBinding.identity.adapterHints, stageBindings: resolvedBinding.identity.stageBindings, binding: resolvedBinding.binding } : void 0 }, sessionLog: [], commands: [], prohibitions: [], promptTemplate: resolvedBinding?.binding?.promptTemplate ?? null });
4869
+ } finally {
4870
+ clearInterval(heartbeatTimer);
4871
+ }
4872
+ let latest = this.store.operations.getDirection(item.id);
4873
+ if (execution.success) {
4874
+ if (item.stage === "security" && this.store.operations.securityReview) {
4875
+ const securityReview = await withFreshRevision(
4876
+ this.store.operations.getDirection,
4877
+ item.id,
4878
+ (expectedRevision) => this.store.operations.securityReview({ itemId: item.id, executorId: executor.id, actor, expectedRevision, reason: "Dispatcher executou a revis\xE3o de Security escopada antes do handoff.", idempotencyKey: `${operationKey}:security-review` })
4336
4879
  );
4337
- if (targetStage) next.stage = targetStage.id;
4338
- next.handoff = {
4339
- from: execution.handoff.from,
4340
- to: execution.handoff.to,
4341
- summary: execution.handoff.summary,
4342
- evidence: execution.handoff.evidence ?? execution.evidences ?? [],
4343
- timestamp: execution.handoff.timestamp,
4344
- expiresAt: new Date(Date.now() + 30 * 6e4).toISOString(),
4345
- executorId: executor.id
4346
- };
4880
+ if (securityReview.outcome === "rejected") throw new SecurityReviewOperationError(securityReview);
4347
4881
  }
4348
- if (!execution.success) next.lastFailure = { code: "EXECUTOR_FAILED", message: execution.error ?? execution.output, recovery: "retry", at: (/* @__PURE__ */ new Date()).toISOString() };
4349
- return next;
4350
- });
4351
- await this.store.writeWorkflow({ ...current, items: updated, updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
4882
+ const evidences = execution.evidences ?? [];
4883
+ if (evidences.length > 0) {
4884
+ const evidenceResult = await withFreshRevision(this.store.operations.getDirection, item.id, (expectedRevision) => this.store.operations.evidence({ itemId: item.id, executorId: executor.id, actor, expectedRevision, reason: "Registrar evid\xEAncias da execu\xE7\xE3o aut\xF4noma.", evidence: evidences.map((value) => ({ kind: evidenceKind(value), value, source: "executor" })), idempotencyKey: `${operationKey}:evidence` }));
4885
+ if (evidenceResult.outcome !== "accepted") throw new Error(evidenceResult.reason);
4886
+ latest = evidenceResult.nextDirection;
4887
+ }
4888
+ const completed = await withFreshRevision(
4889
+ this.store.operations.getDirection,
4890
+ item.id,
4891
+ (expectedRevision) => this.store.operations.event({ itemId: item.id, executorId: executor.id, actor, status: "succeeded", expectedRevision, reason: "Registrar conclus\xE3o da execu\xE7\xE3o aut\xF4noma.", idempotencyKey: `${operationKey}:succeeded` })
4892
+ );
4893
+ if (completed.outcome !== "accepted") throw new Error(completed.reason);
4894
+ latest = completed.nextDirection;
4895
+ const handoff = execution.handoff;
4896
+ if (handoff) {
4897
+ const targetStage = workflow.stages.find((candidate) => candidate.id === item.stage && (this.options.stageActors?.(candidate.id) ?? candidate.agents ?? []).includes(actor));
4898
+ if (targetStage && handoff.to !== actor) {
4899
+ const validation = await withFreshRevision(this.store.operations.getDirection, "", (expectedRevision) => this.store.operations.validate({ actor, expectedRevision, reason: "Dispatcher executou a valida\xE7\xE3o automatizada antes da transi\xE7\xE3o." }));
4900
+ if (validation.outcome !== "accepted") {
4901
+ const failed = await withFreshRevision(this.store.operations.getDirection, item.id, (expectedRevision) => this.store.operations.event({ itemId: item.id, executorId: executor.id, actor, status: "failed", expectedRevision, reason: "Valida\xE7\xE3o automatizada bloqueou a transi\xE7\xE3o.", message: validation.reason, errorCode: validation.reasonCode, recovery: "retry", idempotencyKey: `${operationKey}:validation-failed` }));
4902
+ if (failed.outcome === "accepted") await withFreshRevision(this.store.operations.getDirection, item.id, (expectedRevision) => this.store.operations.release({ itemId: item.id, actor, expectedRevision, reason: "Liberar claim ap\xF3s falha de valida\xE7\xE3o.", idempotencyKey: `${operationKey}:release-validation` }));
4903
+ const result2 = { itemId: item.id, status: "failed", reason: validation.reason };
4904
+ results.push(result2);
4905
+ this.options.onResult?.(result2);
4906
+ continue;
4907
+ }
4908
+ latest = validation.nextDirection;
4909
+ }
4910
+ const handoffResult = await withFreshRevision(this.store.operations.getDirection, item.id, (expectedRevision) => this.store.operations.passage({ itemId: item.id, ...targetStage && handoff.to === actor ? { targetStageId: targetStage.id } : {}, to: handoff.to, executorId: executor.id, actor, summary: handoff.summary, evidence: handoff.evidence ?? evidences ?? [], expectedRevision, reason: "Dispatcher concluiu a passagem can\xF4nica pelo workflow.", idempotencyKey: `${operationKey}:passage` }));
4911
+ if (handoffResult.outcome !== "accepted") {
4912
+ const result2 = { itemId: item.id, status: "failed", reason: handoffResult.reason, outcome: handoffResult.outcome, reasonCode: handoffResult.reasonCode };
4913
+ results.push(result2);
4914
+ this.options.onResult?.(result2);
4915
+ continue;
4916
+ }
4917
+ latest = handoffResult.nextDirection;
4918
+ }
4919
+ } else {
4920
+ const failed = await withFreshRevision(this.store.operations.getDirection, item.id, (expectedRevision) => this.store.operations.event({ itemId: item.id, executorId: executor.id, actor, status: "failed", expectedRevision, reason: "Registrar falha da execu\xE7\xE3o aut\xF4noma.", message: execution.error ?? execution.output, errorCode: "EXECUTOR_FAILED", recovery: "release", idempotencyKey: `${operationKey}:failed` }));
4921
+ if (failed.outcome === "accepted") {
4922
+ await withFreshRevision(this.store.operations.getDirection, item.id, (expectedRevision) => this.store.operations.release({ itemId: item.id, actor, expectedRevision, reason: "Liberar claim ap\xF3s falha do executor; o handoff continua dispon\xEDvel para retry.", idempotencyKey: `${operationKey}:release-failed` }));
4923
+ }
4924
+ }
4352
4925
  const result = execution.success ? { itemId: item.id, status: "dispatched" } : { itemId: item.id, status: "failed", reason: execution.error ?? execution.output };
4353
4926
  results.push(result);
4354
4927
  this.options.onResult?.(result);
4355
4928
  } catch (error) {
4356
- const current = this.store.loadWorkflow();
4357
4929
  const message = error instanceof Error ? error.message : String(error);
4358
- const recoveredItems = current.items.map((entry) => entry.id === item.id ? { ...entry, claimedBy: void 0, claimedAt: void 0, claimExecutorId: void 0, activityStatus: "failed", lastFailure: { code: "EXECUTOR_EXCEPTION", message, recovery: "retry", at: (/* @__PURE__ */ new Date()).toISOString() } } : entry);
4359
- await this.store.writeWorkflow({ ...current, items: recoveredItems, updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
4360
- const result = { itemId: item.id, status: "failed", reason: error instanceof Error ? error.message : String(error) };
4930
+ const failed = await withFreshRevision(this.store.operations.getDirection, item.id, (expectedRevision) => this.store.operations.event({ itemId: item.id, executorId: executor.id, actor, status: "failed", expectedRevision, reason: "Registrar exce\xE7\xE3o do executor aut\xF4nomo.", message, errorCode: "EXECUTOR_EXCEPTION", recovery: "retry", idempotencyKey: `${operationKey}:exception` }));
4931
+ if (failed.outcome === "accepted") await withFreshRevision(this.store.operations.getDirection, item.id, (expectedRevision) => this.store.operations.release({ itemId: item.id, actor, expectedRevision, reason: "Liberar claim ap\xF3s exce\xE7\xE3o do executor.", idempotencyKey: `${operationKey}:release-exception` }));
4932
+ const operation = error instanceof SecurityReviewOperationError ? error.operation : void 0;
4933
+ const result = operation ? { itemId: item.id, status: "failed", reason: operation.reason, outcome: operation.outcome, reasonCode: operation.reasonCode, securityReview: operation.securityReview } : { itemId: item.id, status: "failed", reason: error instanceof Error ? error.message : String(error) };
4361
4934
  results.push(result);
4362
4935
  this.options.onResult?.(result);
4363
4936
  }
@@ -4369,39 +4942,209 @@ var PersistentDispatcher = class {
4369
4942
  }
4370
4943
  };
4371
4944
 
4372
- // src/orchestrator/simulated-executor.ts
4373
- function createSimulatedExecutor(id, capabilities = ["design", "code", "review", "security"]) {
4945
+ // src/orchestrator/codex-executor.ts
4946
+ import { execFileSync, spawn } from "child_process";
4947
+ import { existsSync as existsSync14 } from "fs";
4948
+ import { homedir as homedir2 } from "os";
4949
+ import { join as join13 } from "path";
4950
+ function nextHandoff(context, executorId, evidence) {
4951
+ const stages = Array.isArray(context.snapshot?.stages) ? context.snapshot.stages : [];
4952
+ const current = stages.find((stage) => stage.id === context.stage);
4953
+ const next = current ? stages.filter((stage) => stage.order > current.order).sort((a, b) => a.order - b.order)[0] : void 0;
4954
+ const target = next?.agents?.[0] ?? "human";
4955
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
4956
+ return {
4957
+ type: "handoff",
4958
+ itemId: context.itemId,
4959
+ from: executorId,
4960
+ to: target,
4961
+ summary: `Codex concluiu ${context.stage}; aguardando ${target}.`,
4962
+ evidence,
4963
+ timestamp
4964
+ };
4965
+ }
4966
+ function parseCodexOutput(stdout) {
4967
+ const messages = [];
4968
+ for (const line of stdout.split(/\r?\n/)) {
4969
+ const trimmed = line.trim();
4970
+ if (!trimmed) continue;
4971
+ try {
4972
+ const event = JSON.parse(trimmed);
4973
+ const text = event.item?.text ?? event.text;
4974
+ if (text && (event.item?.type === "agent_message" || event.type === "agent_message" || event.type === "turn.completed")) messages.push(text);
4975
+ } catch {
4976
+ }
4977
+ }
4978
+ return { output: messages.join("\n\n").trim() || stdout.trim(), evidences: [] };
4979
+ }
4980
+ function collectWorkspaceEvidence(root) {
4981
+ try {
4982
+ const files = execFileSync("git", ["diff", "--name-only"], { cwd: root, encoding: "utf8" }).split(/\r?\n/).map((file) => file.trim()).filter(Boolean);
4983
+ const untracked = execFileSync("git", ["status", "--porcelain", "--untracked-files=all"], { cwd: root, encoding: "utf8" }).split(/\r?\n/).map((line) => line.slice(3).trim()).filter(Boolean);
4984
+ return [.../* @__PURE__ */ new Set([...files, ...untracked])];
4985
+ } catch {
4986
+ return [];
4987
+ }
4988
+ }
4989
+ function runCodex(root, command, model, prompt, timeoutMs) {
4990
+ return new Promise((resolve8, reject) => {
4991
+ const baseArgs = ["-C", root, "exec", "--skip-git-repo-check", "--json", "--ephemeral", "--model", model, "--sandbox", "workspace-write", "-"];
4992
+ const npmCodex = join13(process.env.APPDATA ?? join13(homedir2(), "AppData", "Roaming"), "npm", "node_modules", "@openai", "codex", "bin", "codex.js");
4993
+ const useNodeEntrypoint = process.platform === "win32" && command === "codex" && existsSync14(npmCodex);
4994
+ const executable = useNodeEntrypoint ? process.execPath : process.platform === "win32" && command === "codex" ? "codex.cmd" : command;
4995
+ const args = useNodeEntrypoint ? [npmCodex, ...baseArgs] : baseArgs;
4996
+ const child = spawn(executable, args, {
4997
+ cwd: root,
4998
+ stdio: ["pipe", "pipe", "pipe"],
4999
+ shell: !useNodeEntrypoint && process.platform === "win32",
5000
+ windowsHide: true
5001
+ });
5002
+ let stdout = "";
5003
+ let stderr = "";
5004
+ let settled = false;
5005
+ const finish = (result) => {
5006
+ if (settled) return;
5007
+ settled = true;
5008
+ resolve8(result);
5009
+ };
5010
+ const timer = setTimeout(() => {
5011
+ if (settled) return;
5012
+ child.kill();
5013
+ finish({ code: 124, stdout, stderr: `${stderr}
5014
+ Codex executor timed out after ${timeoutMs}ms.`.trim() });
5015
+ }, timeoutMs);
5016
+ child.stdout.on("data", (chunk) => {
5017
+ stdout += chunk.toString();
5018
+ });
5019
+ child.stderr.on("data", (chunk) => {
5020
+ stderr += chunk.toString();
5021
+ });
5022
+ child.on("error", (error) => {
5023
+ clearTimeout(timer);
5024
+ if (!settled) reject(error);
5025
+ });
5026
+ child.on("close", (code) => {
5027
+ clearTimeout(timer);
5028
+ finish({ code: code ?? 1, stdout, stderr });
5029
+ });
5030
+ child.stdin.end(prompt);
5031
+ });
5032
+ }
5033
+ function createCodexExecutor(options) {
5034
+ const id = "codex";
5035
+ const command = options.command ?? "codex";
5036
+ const model = options.model ?? "gpt-5.5";
5037
+ const timeoutMs = options.timeoutMs ?? 30 * 60 * 1e3;
5038
+ const available = command === "codex" || existsSync14(command);
4374
5039
  return {
4375
5040
  id,
4376
- label: `Simulated ${id}`,
4377
- capabilities,
4378
- status: "online",
5041
+ label: "Codex CLI",
5042
+ capabilities: options.capabilities,
5043
+ status: available ? "online" : "offline",
4379
5044
  heartbeat: async () => void 0,
4380
5045
  async execute(context) {
4381
- const stages = Array.isArray(context.snapshot?.stages) ? context.snapshot.stages : [];
4382
- const current = stages.find((stage) => stage.id === context.stage);
4383
- const next = current ? stages.filter((stage) => stage.order > current.order).sort((a, b) => a.order - b.order)[0] : void 0;
4384
- const target = next?.agents?.[0] ?? "human";
4385
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
4386
- return {
4387
- success: true,
4388
- output: `Simulated execution completed for ${context.itemId} at ${context.stage}`,
4389
- artifacts: [],
4390
- evidences: [`simulated:${context.stage}:${context.itemId}`],
4391
- handoff: {
4392
- type: "handoff",
4393
- itemId: context.itemId,
4394
- from: id,
4395
- to: target,
4396
- summary: `Simulated ${context.stage} completed; awaiting ${target}.`,
4397
- evidence: [`simulated:${context.stage}:${context.itemId}`],
4398
- timestamp
4399
- }
4400
- };
5046
+ const executionRoot = typeof context.snapshot.executionWorkspace === "string" ? context.snapshot.executionWorkspace : options.root;
5047
+ const persona = context.snapshot.persona;
5048
+ const personaContext = persona ? [
5049
+ `Persona: ${persona.displayName ?? context.agent}`,
5050
+ `Papel: ${persona.role ?? "n\xE3o informado"}`,
5051
+ `Skills relevantes: ${(persona.skills ?? []).map((skill) => `${skill.label} (${skill.level})`).join(", ") || "nenhuma"}`,
5052
+ `Est\xE1gios permitidos: ${(persona.stageBindings ?? []).join(", ") || "nenhum"}`,
5053
+ `Restri\xE7\xF5es da persona: ${Object.values(persona.adapterHints ?? {}).join("; ") || "seguir o harness"}`
5054
+ ].join("\n") : `Persona/actor: ${context.agent}`;
5055
+ const prompt = [
5056
+ "Voc\xEA \xE9 o executor externo Codex operando sob o protocolo do Letra.",
5057
+ `Item: ${context.itemId}`,
5058
+ `Est\xE1gio: ${context.stage}`,
5059
+ personaContext,
5060
+ `Spec: ${context.spec ?? "nenhuma"}`,
5061
+ context.promptTemplate ? `Template do papel: ${context.promptTemplate}` : "",
5062
+ "Leia a dire\xE7\xE3o vigente com 'letra direction --json' antes de agir.",
5063
+ "Implemente o trabalho real do est\xE1gio no workspace atual, respeitando a spec, a constitui\xE7\xE3o e os ACs.",
5064
+ "Voc\xEA pode editar arquivos do projeto e executar testes. N\xE3o edite .letra/workflow.json manualmente, n\xE3o altere o harness e n\xE3o aprove gates humanos.",
5065
+ "Ao terminar, deixe os arquivos e testes reais prontos e responda com um resumo objetivo."
5066
+ ].join("\n");
5067
+ try {
5068
+ const result = await runCodex(executionRoot, command, model, prompt, timeoutMs);
5069
+ const parsed = parseCodexOutput(result.stdout);
5070
+ if (result.code !== 0) return { success: false, output: parsed.output, artifacts: [], evidences: [], error: result.stderr || parsed.output || `Codex terminou com c\xF3digo ${result.code}.` };
5071
+ const evidence = collectWorkspaceEvidence(executionRoot);
5072
+ return { success: true, output: parsed.output, artifacts: [], evidences: evidence, handoff: nextHandoff(context, id, evidence) };
5073
+ } catch (error) {
5074
+ return { success: false, output: "", artifacts: [], evidences: [], error: error instanceof Error ? error.message : String(error) };
5075
+ }
4401
5076
  }
4402
5077
  };
4403
5078
  }
4404
5079
 
5080
+ // src/flow-serve/human-session.ts
5081
+ import { createHmac, randomBytes, timingSafeEqual } from "crypto";
5082
+ import { userInfo } from "os";
5083
+ var COOKIE_NAME = "letra_human_session";
5084
+ var SESSION_TTL_MS = 8 * 60 * 60 * 1e3;
5085
+ function cookieValue(req, name) {
5086
+ for (const part of (req.headers.cookie ?? "").split(";")) {
5087
+ const [key, ...value] = part.trim().split("=");
5088
+ if (key === name) return value.join("=") || null;
5089
+ }
5090
+ return null;
5091
+ }
5092
+ function sameOrigin(req) {
5093
+ const origin = req.headers.origin;
5094
+ const host = req.headers.host;
5095
+ if (!origin || !host) return false;
5096
+ try {
5097
+ return new URL(origin).host === host;
5098
+ } catch {
5099
+ return false;
5100
+ }
5101
+ }
5102
+ var HumanSessionGateway = class {
5103
+ secret = randomBytes(32);
5104
+ sessions = /* @__PURE__ */ new Map();
5105
+ workspaceRoot;
5106
+ constructor(workspaceRoot) {
5107
+ this.workspaceRoot = workspaceRoot;
5108
+ }
5109
+ establishNavigationSession(req, res) {
5110
+ if (req.method !== "GET" || req.url?.startsWith("/api/")) return;
5111
+ if (this.sessionFor(cookieValue(req, COOKIE_NAME))) return;
5112
+ const sessionId = randomBytes(32).toString("base64url");
5113
+ const username = userInfo().username.trim();
5114
+ if (!username) return;
5115
+ this.sessions.set(sessionId, { actor: resolveLocalIdentity(this.workspaceRoot).id, expiresAt: Date.now() + SESSION_TTL_MS });
5116
+ const signature = this.sign(sessionId);
5117
+ res.setHeader("Set-Cookie", `${COOKIE_NAME}=${sessionId}.${signature}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${SESSION_TTL_MS / 1e3}`);
5118
+ }
5119
+ resolveHumanActor(req) {
5120
+ if (!sameOrigin(req)) return null;
5121
+ return this.sessionFor(cookieValue(req, COOKIE_NAME))?.actor ?? null;
5122
+ }
5123
+ /** The live session this server issued for the token, if any. */
5124
+ sessionFor(token) {
5125
+ if (!token) return null;
5126
+ const separator = token.lastIndexOf(".");
5127
+ if (separator < 1) return null;
5128
+ const sessionId = token.slice(0, separator);
5129
+ const signature = token.slice(separator + 1);
5130
+ if (!this.validSignature(sessionId, signature)) return null;
5131
+ const session = this.sessions.get(sessionId);
5132
+ if (!session || session.expiresAt <= Date.now()) {
5133
+ this.sessions.delete(sessionId);
5134
+ return null;
5135
+ }
5136
+ return session;
5137
+ }
5138
+ sign(sessionId) {
5139
+ return createHmac("sha256", this.secret).update(sessionId).digest("base64url");
5140
+ }
5141
+ validSignature(sessionId, signature) {
5142
+ const expected = Buffer.from(this.sign(sessionId));
5143
+ const actual = Buffer.from(signature);
5144
+ return expected.length === actual.length && timingSafeEqual(expected, actual);
5145
+ }
5146
+ };
5147
+
4405
5148
  // src/commands/flow-serve.ts
4406
5149
  var DEFAULT_PORT = 3e3;
4407
5150
  function resolveHarnessWithShared(root) {
@@ -4413,6 +5156,7 @@ var FlowServer = class {
4413
5156
  server;
4414
5157
  events = new FlowServerEvents();
4415
5158
  router = new FlowServerRouter();
5159
+ humanSessions;
4416
5160
  clientAssets;
4417
5161
  automationRuntime;
4418
5162
  orchestrator;
@@ -4423,13 +5167,18 @@ var FlowServer = class {
4423
5167
  activeWorkspaceRoot;
4424
5168
  activeDirectory = null;
4425
5169
  dispatcher;
5170
+ runtimeExecutors = [];
5171
+ autopilotEnabled;
5172
+ autopilotUpdatedAt = null;
4426
5173
  options;
4427
5174
  constructor(root, port = DEFAULT_PORT, options = {}) {
4428
5175
  this.options = options;
5176
+ this.autopilotEnabled = options.autopilot === true;
4429
5177
  this.clientAssets = new ClientAssets(root);
4430
5178
  this.port = port;
4431
5179
  this.resolution = resolveWorkspaceRoot(root);
4432
- this.activeWorkspaceRoot = this.resolution.workspaceRoot;
5180
+ this.activeWorkspaceRoot = this.resolution.errorCode === "WORKSPACE_LINK_INVALID" ? this.resolution.locationPath : this.resolution.workspaceRoot;
5181
+ this.humanSessions = new HumanSessionGateway(this.activeWorkspaceRoot);
4433
5182
  this.loadWorkflow = (overrideRoot) => loadWorkflow(overrideRoot ?? this.activeWorkspaceRoot);
4434
5183
  this.engine = new DiagnosticEngine(this.activeWorkspaceRoot);
4435
5184
  this.automationRuntime = new AutomationRuntime({
@@ -4450,7 +5199,7 @@ var FlowServer = class {
4450
5199
  onHandoffEvent: (payload) => this.events.broadcastHandoff(payload)
4451
5200
  });
4452
5201
  this.orchestrator.registerFromManifest();
4453
- if (options.autopilot) this.dispatcher = this.createDispatcher();
5202
+ if (this.autopilotEnabled) this.dispatcher = this.createDispatcher();
4454
5203
  this.router.register((context) => {
4455
5204
  if (context.path !== "/events") return false;
4456
5205
  this.events.handleSse(context.req, context.res);
@@ -4463,6 +5212,18 @@ var FlowServer = class {
4463
5212
  writeFocusFile: writeFocusWithRecommendations,
4464
5213
  logEntry,
4465
5214
  resolveActiveFlow: resolveActiveFlowFor,
5215
+ decideGateOperation: (root2, input) => decideGateOperation(root2, input),
5216
+ claimOperation: (root2, input) => claimOperation(root2, input),
5217
+ releaseClaimOperation: (root2, input) => releaseClaimOperation(root2, input),
5218
+ requestTransitionOperation: (root2, input) => requestTransitionOperation(root2, input),
5219
+ requestPassageOperation: (root2, input) => requestPassageOperation(root2, input),
5220
+ activateWorkOperation: (root2, input) => activateWorkOperation(root2, input),
5221
+ requestReworkOperation: (root2, input) => requestReworkOperation(root2, input),
5222
+ createItemOperation: (root2, input) => createItemOperation(root2, input),
5223
+ updateItemOperation: (root2, input) => updateItemOperation(root2, input),
5224
+ deleteItemOperation: (root2, input) => deleteItemOperation(root2, input),
5225
+ runValidationOperation: (root2, input) => runValidationOperation(root2, input),
5226
+ resolveHumanActor: (req) => this.humanSessions.resolveHumanActor(req),
4466
5227
  broadcast: () => this.broadcast(),
4467
5228
  fireWebhooks: (workspaceRoot, event, payload) => this.fireWebhooks(workspaceRoot, event, payload)
4468
5229
  })
@@ -4488,7 +5249,8 @@ var FlowServer = class {
4488
5249
  getSummary,
4489
5250
  getActiveEntries,
4490
5251
  broadcast: () => this.broadcast(),
4491
- broadcastDiagnostics: (output) => this.broadcastDiagnostics(output)
5252
+ broadcastDiagnostics: (output) => this.broadcastDiagnostics(output),
5253
+ inspectWorkspaceIntegrity
4492
5254
  })
4493
5255
  );
4494
5256
  this.router.register(
@@ -4517,6 +5279,9 @@ var FlowServer = class {
4517
5279
  detectWorkspaceName: detectProjectName,
4518
5280
  loadHarness: (workspaceRoot) => loadHarness(resolveHarnessWithShared(workspaceRoot)),
4519
5281
  createFromTemplate: createWorkflowFromTemplate,
5282
+ // Publish/rollback is a human-confirmed action. Do not derive this
5283
+ // identity from request bodies or a permissive default.
5284
+ resolveHumanActor: (req) => this.humanSessions.resolveHumanActor(req),
4520
5285
  broadcast: () => this.broadcast()
4521
5286
  })
4522
5287
  );
@@ -4571,11 +5336,89 @@ var FlowServer = class {
4571
5336
  }
4572
5337
  })
4573
5338
  );
4574
- this.router.register(createAgentRoutes({ loadWorkflow: (root2) => this.loadWorkflow(root2), broadcast: () => this.broadcast() }));
5339
+ this.router.register(createSecurityReviewRoutes());
5340
+ this.router.register(createAgentRoutes({
5341
+ loadWorkflow: (root2) => this.loadWorkflow(root2),
5342
+ loadRuntimeRegistry: (root2, workflow) => loadRuntimeAgentRegistry(root2, workflow),
5343
+ getExecutors: () => this.runtimeExecutors,
5344
+ broadcast: () => this.broadcast()
5345
+ }));
5346
+ this.router.register((context) => {
5347
+ if (context.path !== "/api/runs" || context.method !== "GET") return false;
5348
+ try {
5349
+ const runs = readExecutionRuns(context.workspaceRoot).runs;
5350
+ context.res.writeHead(200, { "Content-Type": "application/json" });
5351
+ context.res.end(JSON.stringify(runs));
5352
+ } catch (error) {
5353
+ context.res.writeHead(500, { "Content-Type": "application/json" });
5354
+ context.res.end(JSON.stringify({ error: error instanceof Error ? error.message : "RUN_STORE_UNAVAILABLE" }));
5355
+ }
5356
+ return true;
5357
+ });
5358
+ this.router.register(
5359
+ createAutopilotRoutes({
5360
+ getStatus: (workspaceRoot) => this.getAutopilotStatus(workspaceRoot),
5361
+ setEnabled: (workspaceRoot, enabled) => this.setAutopilotEnabled(workspaceRoot, enabled)
5362
+ })
5363
+ );
5364
+ }
5365
+ getAutopilotStatus(workspaceRoot) {
5366
+ const workflow = this.loadWorkflow(workspaceRoot);
5367
+ const items = workflow?.items ?? [];
5368
+ return {
5369
+ enabled: this.autopilotEnabled,
5370
+ activeItems: items.filter((item) => hasLiveClaim(item)).length,
5371
+ waitingHuman: items.filter(
5372
+ (item) => item.handoff?.to === "human" || item.handoff?.to?.startsWith("human:")
5373
+ ).length,
5374
+ updatedAt: this.autopilotUpdatedAt
5375
+ };
5376
+ }
5377
+ setAutopilotEnabled(workspaceRoot, enabled) {
5378
+ if (workspaceRoot !== this.activeWorkspaceRoot) {
5379
+ throw new Error("Autopilot can only be controlled for the active workspace.");
5380
+ }
5381
+ if (enabled === this.autopilotEnabled) return this.getAutopilotStatus(workspaceRoot);
5382
+ this.autopilotEnabled = enabled;
5383
+ this.autopilotUpdatedAt = (/* @__PURE__ */ new Date()).toISOString();
5384
+ if (enabled) {
5385
+ this.dispatcher ??= this.createDispatcher();
5386
+ this.dispatcher.start();
5387
+ } else {
5388
+ this.dispatcher?.stop();
5389
+ }
5390
+ logEntry(
5391
+ workspaceRoot,
5392
+ "system",
5393
+ `Autopilot ${enabled ? "enabled" : "paused"} via UI`,
5394
+ { details: { enabled, source: "web-ui", timestamp: this.autopilotUpdatedAt } }
5395
+ );
5396
+ this.broadcast();
5397
+ return this.getAutopilotStatus(workspaceRoot);
4575
5398
  }
4576
5399
  createDispatcher() {
4577
- const simulated = createSimulatedExecutor("letra-simulated");
4578
5400
  const manifest = this.orchestrator.getManifest();
5401
+ const harnessCapabilities = manifest ? Object.values(manifest.roles).flatMap((role) => role.capabilities) : [];
5402
+ const capabilities = harnessCapabilities.length > 0 ? [...new Set(harnessCapabilities)] : [
5403
+ "read_code",
5404
+ "write_spec",
5405
+ "generate_doc",
5406
+ "write_code",
5407
+ "run_tests",
5408
+ "review_code",
5409
+ "security_scan",
5410
+ "dependency_audit"
5411
+ ];
5412
+ const executionWorkspace = resolveExecutionWorkspace({
5413
+ workflow: this.loadWorkflow() ?? { version: "1", name: "empty", createdAt: "", updatedAt: "", stages: [], items: [], tools: [] },
5414
+ workspaceRoot: this.activeWorkspaceRoot,
5415
+ selectedDirectory: this.activeDirectory
5416
+ });
5417
+ const executors = this.options.executorFactory ? this.options.executorFactory(this.activeWorkspaceRoot, capabilities) : [createCodexExecutor({
5418
+ root: executionWorkspace.ok ? executionWorkspace.root : this.activeWorkspaceRoot,
5419
+ capabilities
5420
+ })];
5421
+ this.runtimeExecutors = executors;
4579
5422
  return new PersistentDispatcher(
4580
5423
  {
4581
5424
  loadWorkflow: () => {
@@ -4583,37 +5426,70 @@ var FlowServer = class {
4583
5426
  if (!workflow) throw new Error("No workflow found for dispatcher");
4584
5427
  return workflow;
4585
5428
  },
4586
- writeWorkflow: async (workflow) => {
4587
- writeWorkflow(this.activeWorkspaceRoot, {
4588
- workflow,
4589
- source: "orchestrator",
4590
- primaryItemId: workflow.primaryItemId,
4591
- skipSitrep: true
4592
- });
4593
- this.broadcast();
4594
- },
4595
- advance: () => void 0,
4596
- claim: (itemId, executorId, agentId) => this.orchestrator.autoClaim(itemId, executorId, agentId).success
5429
+ operations: {
5430
+ // Must be the direction the operations compare: it accounts for
5431
+ // the item's active Run. resolveDirection(root, { itemId }) does
5432
+ // not, so with a Run active every retry stayed DIRECTION_STALE.
5433
+ getDirection: (itemId) => directionForOperation(this.activeWorkspaceRoot, itemId ? { itemId } : {}),
5434
+ claim: (input) => claimOperation(this.activeWorkspaceRoot, { ...input, ttlMinutes: 30 }),
5435
+ event: (input) => recordExecutionEvent(this.activeWorkspaceRoot, input),
5436
+ evidence: (input) => submitEvidenceOperation(this.activeWorkspaceRoot, input),
5437
+ validate: (input) => runValidationOperation(this.activeWorkspaceRoot, input),
5438
+ securityReview: (input) => runSecurityReviewOperation(this.activeWorkspaceRoot, input),
5439
+ transition: (input) => requestTransitionOperation(this.activeWorkspaceRoot, input),
5440
+ handoff: (input) => requestHandoffOperation(this.activeWorkspaceRoot, input),
5441
+ passage: async (input) => requestPassageOperation(this.activeWorkspaceRoot, input),
5442
+ release: (input) => releaseClaimOperation(this.activeWorkspaceRoot, input),
5443
+ reclaimExpired: (input) => reclaimExpiredClaimsOperation(this.activeWorkspaceRoot, input)
5444
+ }
4597
5445
  },
4598
- () => [simulated],
5446
+ () => executors,
4599
5447
  this.options.dispatcherIntervalMs ?? 3e4,
4600
5448
  {
4601
5449
  stageActors: (stageId) => {
4602
5450
  const templateId = this.loadWorkflow()?.template ?? "flow-main";
4603
5451
  return manifest?.flows[templateId]?.stages.find((stage) => stage.id === stageId)?.agents ?? [];
4604
5452
  },
5453
+ stageTransitions: (stageId) => {
5454
+ const templateId = this.loadWorkflow()?.template ?? "flow-main";
5455
+ return manifest?.flows[templateId]?.stages.find((stage) => stage.id === stageId)?.transitions;
5456
+ },
5457
+ stageCapability: (stage) => {
5458
+ const templateId = this.loadWorkflow()?.template ?? "flow-main";
5459
+ const stageDef = manifest?.flows[templateId]?.stages.find((entry) => entry.id === stage.id);
5460
+ const roleId = stageDef?.agents?.[0];
5461
+ return manifest?.roles[roleId ?? ""]?.capabilities?.find((capability) => capability !== "read_code") ?? stage.id;
5462
+ },
5463
+ executorPreference: (stage) => {
5464
+ const templateId = this.loadWorkflow()?.template ?? "flow-main";
5465
+ const roleId = manifest?.flows[templateId]?.stages.find((entry) => entry.id === stage.id)?.agents?.[0];
5466
+ const configured = manifest?.executors?.stageExecutorPreferences?.[roleId ?? stage.id];
5467
+ if (configured?.length) return configured;
5468
+ const preferred = stage.preferredExecutor;
5469
+ return preferred ? [preferred] : [];
5470
+ },
5471
+ resolveExecutionWorkspace: (_stage, _item) => {
5472
+ const workflow = this.loadWorkflow();
5473
+ if (!workflow) return { ok: false, reasonCode: "EXECUTION_WORKSPACE_UNAVAILABLE", reason: "Workflow indispon\xEDvel para resolver o local de execu\xE7\xE3o." };
5474
+ return resolveExecutionWorkspace({ workflow, workspaceRoot: this.activeWorkspaceRoot, selectedDirectory: this.activeDirectory });
5475
+ },
5476
+ resolveBinding: (stage, item, actor, capability, runtimeExecutors) => {
5477
+ const workflow = this.loadWorkflow();
5478
+ if (!workflow) return { ok: false, reasonCode: "NO_COMPATIBLE_BINDING", reason: "Workflow indispon\xEDvel para resolver v\xEDnculo operacional." };
5479
+ const active = resolveActiveFlowFor(this.activeWorkspaceRoot, workflow);
5480
+ const registry = loadRuntimeAgentRegistry(this.activeWorkspaceRoot, workflow);
5481
+ return resolveRuntimeBinding({ registry, workflow, manifest: active.harness ?? manifest, stageId: stage.id, actor, capability, executors: runtimeExecutors });
5482
+ },
4605
5483
  blocksHandoff: (stage, item) => {
4606
5484
  const gate = stage.gate ? manifest?.gates[stage.gate] : void 0;
4607
5485
  const currentActor = (manifest?.flows[this.loadWorkflow()?.template ?? "flow-main"]?.stages.find((entry) => entry.id === stage.id)?.agents ?? stage.agents)?.[0];
4608
- return gate?.type === "human" && gate.blocksHandoff === true && item.handoff?.to !== currentActor;
5486
+ return gate?.type === "human" && gate.blocking === true && gate.blocksHandoff === true && item.handoff?.to !== currentActor;
4609
5487
  },
4610
5488
  onResult: (result) => {
4611
- if (result.status === "dispatched" || result.status === "failed") {
4612
- logEntry(this.activeWorkspaceRoot, "agent_execution_event", `Autonomous dispatcher: ${result.status}`, {
4613
- itemId: result.itemId,
4614
- details: { status: result.status, reason: result.reason ?? null }
4615
- });
4616
- }
5489
+ logEntry(this.activeWorkspaceRoot, "agent_execution_event", `Autonomous dispatcher: ${result.status}`, {
5490
+ itemId: result.itemId,
5491
+ details: { status: result.status, reason: result.reason ?? null }
5492
+ });
4617
5493
  this.broadcast();
4618
5494
  }
4619
5495
  }
@@ -4622,6 +5498,7 @@ var FlowServer = class {
4622
5498
  switchWorkspace(workspaceRoot) {
4623
5499
  this.activeWorkspaceRoot = workspaceRoot;
4624
5500
  this.activeDirectory = null;
5501
+ this.runtimeExecutors = [];
4625
5502
  this.resolution = resolveWorkspaceRoot(workspaceRoot);
4626
5503
  this.loadWorkflow = (overrideRoot) => loadWorkflow(overrideRoot ?? this.activeWorkspaceRoot);
4627
5504
  this.engine = new DiagnosticEngine(this.activeWorkspaceRoot);
@@ -4631,12 +5508,11 @@ var FlowServer = class {
4631
5508
  onHandoffEvent: (payload) => this.events.broadcastHandoff(payload)
4632
5509
  });
4633
5510
  this.orchestrator.registerFromManifest();
4634
- if (this.options.autopilot) {
5511
+ if (this.autopilotEnabled) {
4635
5512
  this.dispatcher?.stop();
4636
5513
  this.dispatcher = this.createDispatcher();
4637
5514
  this.dispatcher.start();
4638
5515
  }
4639
- this.orchestrator.startReclaimTimer();
4640
5516
  this.broadcast();
4641
5517
  }
4642
5518
  switchDirectory(directory) {
@@ -4657,6 +5533,7 @@ var FlowServer = class {
4657
5533
  };
4658
5534
  }
4659
5535
  handleRequest = async (req, res) => {
5536
+ this.humanSessions.establishNavigationSession(req, res);
4660
5537
  const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
4661
5538
  const path = url.pathname;
4662
5539
  const requestRoot = this.workspaceRootFor(url);
@@ -4717,7 +5594,6 @@ var FlowServer = class {
4717
5594
  this.server = createServer(this.handleRequest);
4718
5595
  this.server.listen(this.port, () => {
4719
5596
  this.automationRuntime.start(this.automationBinding());
4720
- this.orchestrator.startReclaimTimer();
4721
5597
  this.dispatcher?.start();
4722
5598
  resolve8();
4723
5599
  });
@@ -4727,7 +5603,6 @@ var FlowServer = class {
4727
5603
  stop() {
4728
5604
  this.automationRuntime.stop();
4729
5605
  this.dispatcher?.stop();
4730
- this.orchestrator.stopReclaimTimer();
4731
5606
  if (this.server) this.server.close();
4732
5607
  this.events.close();
4733
5608
  }
@@ -4772,10 +5647,9 @@ async function flowServeAction(targetPath, options) {
4772
5647
 
4773
5648
  export {
4774
5649
  pulse_default,
4775
- validateSpecStructure,
5650
+ sitrep_default,
4776
5651
  buildActivityContext,
4777
5652
  migrateCommand,
4778
- sync_default,
4779
5653
  FlowServer,
4780
5654
  flowServeAction
4781
5655
  };