@letra-ai/cli 0.6.1 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-2GRNAFBQ.js +5305 -0
- package/dist/{chunk-MJ2QXNH6.js → chunk-42RST74I.js} +1 -1
- package/dist/chunk-HC24XMPZ.js +269 -0
- package/dist/chunk-LUPN3TRC.js +554 -0
- package/dist/{chunk-KGQLHMGZ.js → chunk-MUCIMQAU.js} +1918 -757
- package/dist/chunk-POGWTSEA.js +125 -0
- package/dist/chunk-TNF7XTFG.js +6178 -0
- package/dist/{chunk-BKAUN5QH.js → chunk-UMC5PDL2.js} +227 -33
- package/dist/{chunk-6HSUVCTR.js → chunk-YAQ2TKSK.js} +82 -30
- package/dist/client/assets/index-C-6kWNFi.js +232 -0
- package/dist/client/assets/index-QV-zN0V8.css +1 -0
- package/dist/client/index.html +2 -2
- package/dist/fallback-CXCCKHBA.js +56 -0
- package/dist/flow-serve-LFILD3EV.js +19 -0
- package/dist/{generate-N22QOXUF.js → generate-3R7POT7L.js} +4 -5
- package/dist/harness/default/v0.1.0/gates/all-acs-passing.yaml +1 -0
- package/dist/harness/default/v0.1.0/gates/has-spec-file.yaml +1 -0
- package/dist/harness/default/v0.1.1/gates/all-acs-passing.yaml +1 -0
- package/dist/harness/default/v0.1.1/gates/has-spec-file.yaml +1 -0
- package/dist/harness/default/v0.1.2/gates/all-acs-passing.yaml +1 -0
- package/dist/harness/default/v0.1.2/gates/has-spec-file.yaml +1 -0
- package/dist/harness/default/v0.1.3/gates/all-acs-passing.yaml +1 -0
- package/dist/harness/default/v0.1.3/gates/has-spec-file.yaml +1 -0
- package/dist/harness/default/v0.2.0/executors/registry.yaml +17 -0
- package/dist/harness/default/v0.2.0/flows/flow-main.yaml +84 -4
- package/dist/harness/default/v0.2.0/gates/code-reviewed.yaml +1 -0
- package/dist/harness/default/v0.2.0/gates/human-approved.yaml +4 -3
- package/dist/harness/default/v0.2.0/gates/security-clear.yaml +1 -0
- package/dist/harness/default/v0.2.0/gates/spec-approved.yaml +3 -3
- package/dist/{health-record-YDVXEVLR.js → health-record-JO2ZTIMR.js} +2 -2
- package/dist/index.js +2237 -1104
- package/dist/{push-5JEYSXBY.js → push-2ZCQSOHF.js} +37 -49
- package/dist/server-WUYVNSH7.js +677 -0
- package/dist/service-SVEAXQBX.js +28 -0
- package/dist/service-TOBY3OHO.js +22 -0
- package/dist/service-USTAY5E3.js +62 -0
- package/dist/{session-log-WTQ5JBEN.js → session-log-X2Q4XKQN.js} +6 -2
- package/dist/specs-CQRB7LPA.js +21 -0
- package/dist/sync-LIVPQXEW.js +21 -0
- package/package.json +1 -1
- package/dist/chunk-4QDEU6KP.js +0 -2765
- package/dist/chunk-BTPFUKHG.js +0 -275
- package/dist/chunk-EDD55PWL.js +0 -119
- package/dist/chunk-ELBTIPYN.js +0 -256
- package/dist/chunk-IEFSLCJL.js +0 -837
- package/dist/chunk-MSF44WWE.js +0 -443
- package/dist/chunk-QIVKP3EY.js +0 -362
- package/dist/client/assets/index-BuABgOyz.js +0 -232
- package/dist/client/assets/index-CpseCZh9.css +0 -1
- package/dist/fallback-UXSZ4LNR.js +0 -47
- package/dist/flow-serve-MTB6KZMR.js +0 -19
- package/dist/focus-sync-3D3XWCTI.js +0 -17
- package/dist/server-FUP3APZA.js +0 -415
- package/dist/service-OGF7BMCQ.js +0 -21
- package/dist/sitrep-DJXTP3JO.js +0 -16
|
@@ -1,46 +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-
|
|
7
|
-
import {
|
|
8
|
-
resolveActiveFlow,
|
|
9
|
-
resolveActiveFlowFor,
|
|
10
|
-
resolveAgentDirection
|
|
11
|
-
} from "./chunk-MSF44WWE.js";
|
|
12
|
-
import {
|
|
13
|
-
sitrep
|
|
14
|
-
} from "./chunk-BTPFUKHG.js";
|
|
37
|
+
} from "./chunk-TNF7XTFG.js";
|
|
15
38
|
import {
|
|
16
39
|
DEFAULT_HARNESS_VERSION,
|
|
17
40
|
DiagnosticEngine,
|
|
41
|
+
clearFocusFile,
|
|
42
|
+
createAgent,
|
|
43
|
+
createWorkflowDefinition,
|
|
44
|
+
createWorkflowDraft,
|
|
45
|
+
deleteAgent,
|
|
18
46
|
detectExistingTools,
|
|
19
47
|
detectProjectName,
|
|
20
48
|
ensureSharedHarness,
|
|
21
49
|
generateAdapters,
|
|
50
|
+
getActiveWorkflowVersion,
|
|
51
|
+
getWorkflowDraft,
|
|
52
|
+
getWorkflowVersion,
|
|
53
|
+
inspectWorkspaceIntegrity,
|
|
54
|
+
listAgents,
|
|
55
|
+
listWorkflowDefinitions,
|
|
56
|
+
listWorkflowDraftRevisions,
|
|
57
|
+
listWorkflowVersions,
|
|
22
58
|
loadHarness,
|
|
59
|
+
loadRuntimeAgentRegistry,
|
|
23
60
|
loadWorkflow,
|
|
61
|
+
projectAgentPresence,
|
|
62
|
+
publishWorkflowDraft,
|
|
63
|
+
readExecutionRuns,
|
|
64
|
+
readFocusFile,
|
|
24
65
|
renderAdapterFiles,
|
|
66
|
+
resolveActiveFlowFor,
|
|
67
|
+
resolveDirection,
|
|
25
68
|
resolveHarnessRoot,
|
|
69
|
+
resolveLocalIdentity,
|
|
70
|
+
resolveRuntimeBinding,
|
|
71
|
+
rollbackWorkflowVersion,
|
|
72
|
+
signLocalOperation,
|
|
26
73
|
stageFromTemplateStage,
|
|
74
|
+
syncFocus,
|
|
75
|
+
updateAgent,
|
|
76
|
+
updateWorkflowDraft,
|
|
77
|
+
validateWorkflowContent,
|
|
27
78
|
writeWorkflow
|
|
28
|
-
} from "./chunk-
|
|
29
|
-
import {
|
|
30
|
-
loadSessionLog,
|
|
31
|
-
logEntry,
|
|
32
|
-
queryLog,
|
|
33
|
-
queryLogWithMeta
|
|
34
|
-
} from "./chunk-BKAUN5QH.js";
|
|
79
|
+
} from "./chunk-2GRNAFBQ.js";
|
|
35
80
|
import {
|
|
36
81
|
ADAPTER_REGISTRY,
|
|
37
82
|
supportedAdapterTools
|
|
38
83
|
} from "./chunk-JMIC5NKB.js";
|
|
39
|
-
import {
|
|
40
|
-
clearFocusFile,
|
|
41
|
-
readFocusFile,
|
|
42
|
-
syncFocus
|
|
43
|
-
} from "./chunk-EDD55PWL.js";
|
|
44
84
|
import {
|
|
45
85
|
ackEntry,
|
|
46
86
|
dismissEntry,
|
|
@@ -49,7 +89,16 @@ import {
|
|
|
49
89
|
loadHealthRecord,
|
|
50
90
|
mergeScanResults,
|
|
51
91
|
saveHealthRecord
|
|
52
|
-
} from "./chunk-
|
|
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";
|
|
53
102
|
import {
|
|
54
103
|
LINK_FILE,
|
|
55
104
|
clearWorkspaceCache,
|
|
@@ -60,10 +109,7 @@ import {
|
|
|
60
109
|
listWorkspaces,
|
|
61
110
|
resolveWorkspaceRoot,
|
|
62
111
|
slugifyWorkspaceName
|
|
63
|
-
} from "./chunk-
|
|
64
|
-
import {
|
|
65
|
-
__require
|
|
66
|
-
} from "./chunk-PDX44BCA.js";
|
|
112
|
+
} from "./chunk-YAQ2TKSK.js";
|
|
67
113
|
|
|
68
114
|
// src/commands/flow-serve.ts
|
|
69
115
|
import { createServer } from "http";
|
|
@@ -116,17 +162,9 @@ function countSpecACs(stateDir, specName) {
|
|
|
116
162
|
if (!existsSync(specFile)) return { pending: 0, done: 0, total: 0 };
|
|
117
163
|
try {
|
|
118
164
|
const content = readFileSync(specFile, "utf-8");
|
|
119
|
-
const
|
|
120
|
-
const
|
|
121
|
-
|
|
122
|
-
return {
|
|
123
|
-
pending: boldPending.length,
|
|
124
|
-
done: boldDone.length,
|
|
125
|
-
total: boldPending.length + boldDone.length
|
|
126
|
-
};
|
|
127
|
-
}
|
|
128
|
-
const genericPending = content.match(/^- \[ \]\s+AC[-]?\d+/gm) || [];
|
|
129
|
-
const genericDone = content.match(/^- \[[xX]\]\s+AC[-]?\d+/gm) || [];
|
|
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));
|
|
130
168
|
return {
|
|
131
169
|
pending: genericPending.length,
|
|
132
170
|
done: genericDone.length,
|
|
@@ -280,7 +318,7 @@ ${chalk.bold("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
|
|
|
280
318
|
);
|
|
281
319
|
}
|
|
282
320
|
if (ci.spec) {
|
|
283
|
-
const specReference = statePath ? pathToFileURL(join(statePath, "specs", ci.spec, "spec.md")).href :
|
|
321
|
+
const specReference = statePath ? pathToFileURL(join(statePath, "specs", ci.spec, "spec.md")).href : `specs/${ci.spec}/spec.md`;
|
|
284
322
|
console.log(` ${chalk.gray(`Spec: ${specReference}`)}`);
|
|
285
323
|
} else {
|
|
286
324
|
console.log(` ${chalk.yellow("\u26A0 sem spec associada")}`);
|
|
@@ -377,6 +415,148 @@ function pulse_default() {
|
|
|
377
415
|
return cmd;
|
|
378
416
|
}
|
|
379
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
|
+
|
|
380
560
|
// src/flow-serve/events.ts
|
|
381
561
|
var FlowServerEvents = class {
|
|
382
562
|
clients = /* @__PURE__ */ new Set();
|
|
@@ -443,106 +623,8 @@ async function runDiagnosticsAndSyncHealth(engine, root) {
|
|
|
443
623
|
return output;
|
|
444
624
|
}
|
|
445
625
|
|
|
446
|
-
// src/flow-serve/specs.ts
|
|
447
|
-
import { existsSync as existsSync3, mkdirSync, readFileSync as readFileSync3, readdirSync, writeFileSync } from "fs";
|
|
448
|
-
import { join as join2 } from "path";
|
|
449
|
-
|
|
450
|
-
// src/validation/structure.ts
|
|
451
|
-
import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
|
|
452
|
-
var REQUIRED_SECTIONS = [
|
|
453
|
-
"## Outcome",
|
|
454
|
-
"## Constraints",
|
|
455
|
-
"## Exclusions",
|
|
456
|
-
"## Acceptance Criteria",
|
|
457
|
-
"## Context"
|
|
458
|
-
];
|
|
459
|
-
function checkRequiredSections(content) {
|
|
460
|
-
return REQUIRED_SECTIONS.filter((section) => !content.includes(section));
|
|
461
|
-
}
|
|
462
|
-
function checkSpecLength(content, maxChars = 3e3) {
|
|
463
|
-
return content.length > maxChars ? `Spec exceeds ${maxChars} chars (should be thin \u2014 max 1 page)` : null;
|
|
464
|
-
}
|
|
465
|
-
function checkChecklist(content) {
|
|
466
|
-
const hasChecklist = /-\s*\[[ x]\]\s*\*\*/i.test(content);
|
|
467
|
-
if (!hasChecklist && content.includes("## Acceptance Criteria")) {
|
|
468
|
-
return "Acceptance Criteria section exists but has no checklist items";
|
|
469
|
-
}
|
|
470
|
-
return null;
|
|
471
|
-
}
|
|
472
|
-
function validateSpecStructure(specFile) {
|
|
473
|
-
const errors = [];
|
|
474
|
-
const warnings = [];
|
|
475
|
-
if (!existsSync2(specFile)) {
|
|
476
|
-
errors.push("Missing spec.md");
|
|
477
|
-
return { errors, warnings };
|
|
478
|
-
}
|
|
479
|
-
const content = readFileSync2(specFile, "utf-8");
|
|
480
|
-
const missingSections = checkRequiredSections(content);
|
|
481
|
-
errors.push(...missingSections.map((s) => `Missing section: ${s}`));
|
|
482
|
-
const lengthWarning = checkSpecLength(content);
|
|
483
|
-
if (lengthWarning) warnings.push(lengthWarning);
|
|
484
|
-
const checklistError = checkChecklist(content);
|
|
485
|
-
if (checklistError) errors.push(checklistError);
|
|
486
|
-
return { errors, warnings };
|
|
487
|
-
}
|
|
488
|
-
|
|
489
|
-
// src/flow-serve/specs.ts
|
|
490
|
-
function loadResolvedSpecs(root, workflow) {
|
|
491
|
-
const result = [];
|
|
492
|
-
if (workflow?.specLinks) {
|
|
493
|
-
for (const [id, link] of Object.entries(workflow.specLinks)) {
|
|
494
|
-
const filePath = join2(root, link.path);
|
|
495
|
-
if (existsSync3(filePath)) {
|
|
496
|
-
result.push({ id, content: readFileSync3(filePath, "utf-8") });
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
}
|
|
500
|
-
const specsDir = join2(getLetraDir2(root), "specs");
|
|
501
|
-
const registered = new Set(result.map((entry) => entry.id));
|
|
502
|
-
if (!existsSync3(specsDir)) return result;
|
|
503
|
-
for (const entry of readdirSync(specsDir, { withFileTypes: true })) {
|
|
504
|
-
if (!entry.isDirectory() || registered.has(entry.name)) continue;
|
|
505
|
-
const specPath = join2(specsDir, entry.name, "spec.md");
|
|
506
|
-
if (!existsSync3(specPath)) continue;
|
|
507
|
-
result.push({ id: entry.name, content: readFileSync3(specPath, "utf-8") });
|
|
508
|
-
}
|
|
509
|
-
return result;
|
|
510
|
-
}
|
|
511
|
-
function readAllowedContextFile(workspaceDir, file) {
|
|
512
|
-
const allowedFiles = /* @__PURE__ */ new Set(["context.md", "constitution.md", "glossary.md"]);
|
|
513
|
-
if (!allowedFiles.has(file)) return null;
|
|
514
|
-
const filePath = join2(workspaceDir, file);
|
|
515
|
-
if (!existsSync3(filePath)) return null;
|
|
516
|
-
return readFileSync3(filePath, "utf-8");
|
|
517
|
-
}
|
|
518
|
-
function writeSpec(workspaceDir, id, content) {
|
|
519
|
-
const specDir = join2(workspaceDir, "specs", id);
|
|
520
|
-
if (!existsSync3(specDir)) mkdirSync(specDir, { recursive: true });
|
|
521
|
-
writeFileSync(join2(specDir, "spec.md"), content, "utf-8");
|
|
522
|
-
}
|
|
523
|
-
function clearSpec(workspaceDir, id) {
|
|
524
|
-
const specFile = join2(workspaceDir, "specs", id, "spec.md");
|
|
525
|
-
if (existsSync3(specFile)) writeFileSync(specFile, "", "utf-8");
|
|
526
|
-
}
|
|
527
|
-
function validateSpec(workspaceDir, id) {
|
|
528
|
-
const specFile = join2(workspaceDir, "specs", id, "spec.md");
|
|
529
|
-
if (!existsSync3(specFile)) {
|
|
530
|
-
return {
|
|
531
|
-
id,
|
|
532
|
-
issues: [{ type: "error", msg: "spec.md not found" }],
|
|
533
|
-
valid: false
|
|
534
|
-
};
|
|
535
|
-
}
|
|
536
|
-
const { errors, warnings } = validateSpecStructure(specFile);
|
|
537
|
-
const issues = [
|
|
538
|
-
...errors.map((msg) => ({ type: "error", msg })),
|
|
539
|
-
...warnings.map((msg) => ({ type: "warning", msg }))
|
|
540
|
-
];
|
|
541
|
-
return { id, issues, valid: errors.length === 0 };
|
|
542
|
-
}
|
|
543
|
-
|
|
544
626
|
// src/flow-serve/context.ts
|
|
545
|
-
import { existsSync as
|
|
627
|
+
import { existsSync as existsSync4, readFileSync as readFileSync4, readdirSync as readdirSync2 } from "fs";
|
|
546
628
|
import { join as join4 } from "path";
|
|
547
629
|
|
|
548
630
|
// src/activity-context/compatibility.ts
|
|
@@ -560,10 +642,10 @@ var MUST_NOT_DO = {
|
|
|
560
642
|
],
|
|
561
643
|
implement: [
|
|
562
644
|
"N\xE3o editar `workflow.json` manualmente.",
|
|
563
|
-
"N\xE3o implementar fora do escopo da
|
|
645
|
+
"N\xE3o implementar fora do escopo da dire\xE7\xE3o atribu\xEDda."
|
|
564
646
|
],
|
|
565
647
|
review: [
|
|
566
|
-
"N\xE3o focar em novas features fora do diff/
|
|
648
|
+
"N\xE3o focar em novas features fora do diff/dire\xE7\xE3o analisada.",
|
|
567
649
|
"N\xE3o aprovar sem checar riscos, ACs e sinais ativos."
|
|
568
650
|
],
|
|
569
651
|
diagnose: [
|
|
@@ -577,15 +659,17 @@ var MUST_NOT_DO = {
|
|
|
577
659
|
};
|
|
578
660
|
function compatibilityReferences(activity, context) {
|
|
579
661
|
const references = [
|
|
580
|
-
{ path: ".letra/context.md", reason: "Contexto operacional do workspace" },
|
|
581
662
|
{ path: ".letra/constitution.md", reason: "Regras n\xE3o negoci\xE1veis do Letra" }
|
|
582
663
|
];
|
|
583
|
-
if (
|
|
584
|
-
references.push({
|
|
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
|
+
});
|
|
585
669
|
}
|
|
586
670
|
if (context.specName) {
|
|
587
671
|
references.push({
|
|
588
|
-
path:
|
|
672
|
+
path: `specs/${context.specName}/spec.md`,
|
|
589
673
|
reason: "Spec e crit\xE9rios do trabalho atual"
|
|
590
674
|
});
|
|
591
675
|
}
|
|
@@ -601,12 +685,6 @@ function compatibilityReferences(activity, context) {
|
|
|
601
685
|
reason: "Estado persistente dos alertas ativos"
|
|
602
686
|
});
|
|
603
687
|
}
|
|
604
|
-
if (!context.hasCurrentItem) {
|
|
605
|
-
references.push({
|
|
606
|
-
path: ".letra/workflow.json",
|
|
607
|
-
reason: "Fonte de verdade para triagem e escolha do pr\xF3ximo item"
|
|
608
|
-
});
|
|
609
|
-
}
|
|
610
688
|
return references;
|
|
611
689
|
}
|
|
612
690
|
function currentItemActions(activity, context) {
|
|
@@ -630,7 +708,7 @@ function currentItemActions(activity, context) {
|
|
|
630
708
|
case "implement":
|
|
631
709
|
return [
|
|
632
710
|
{
|
|
633
|
-
label: "Executar item
|
|
711
|
+
label: "Executar item atribu\xEDdo",
|
|
634
712
|
description: `Implementar o pr\xF3ximo passo observando os ACs da ${specRef}.`
|
|
635
713
|
},
|
|
636
714
|
{
|
|
@@ -700,8 +778,8 @@ function getCompatibilityActivityIntent(activity, context) {
|
|
|
700
778
|
description: "Escolher ou criar um item ativo antes de aprofundar a execu\xE7\xE3o."
|
|
701
779
|
},
|
|
702
780
|
{
|
|
703
|
-
label: "Confirmar
|
|
704
|
-
description: "
|
|
781
|
+
label: "Confirmar atribui\xE7\xE3o",
|
|
782
|
+
description: "Aguardar atribui\xE7\xE3o ou solicitar sele\xE7\xE3o expl\xEDcita de execu\xE7\xE3o."
|
|
705
783
|
}
|
|
706
784
|
]
|
|
707
785
|
};
|
|
@@ -840,27 +918,11 @@ function resolveActivityIntent(activity, sources) {
|
|
|
840
918
|
}
|
|
841
919
|
|
|
842
920
|
// src/activity-context/sources.ts
|
|
843
|
-
import { existsSync as
|
|
921
|
+
import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
|
|
844
922
|
import { join as join3 } from "path";
|
|
845
|
-
function
|
|
923
|
+
function getStageName3(workflow, stageId) {
|
|
846
924
|
return workflow.stages.find((stage) => stage.id === stageId)?.name ?? stageId;
|
|
847
925
|
}
|
|
848
|
-
function findCurrentItem2(workflow) {
|
|
849
|
-
const activeStages = workflow.stages.filter(
|
|
850
|
-
(stage) => stage.zone === "doing" || !stage.zone && stage.order > 0 && stage.order < workflow.stages.length - 1
|
|
851
|
-
).map((stage) => stage.id);
|
|
852
|
-
const stageSet = new Set(activeStages);
|
|
853
|
-
if (stageSet.size === 0) {
|
|
854
|
-
const middle = Math.floor(workflow.stages.length / 2);
|
|
855
|
-
const stage = workflow.stages[middle];
|
|
856
|
-
if (stage) stageSet.add(stage.id);
|
|
857
|
-
}
|
|
858
|
-
const items = workflow.items.filter((item) => stageSet.has(item.stage));
|
|
859
|
-
if (items.length === 0) return null;
|
|
860
|
-
return items.reduce(
|
|
861
|
-
(left, right) => new Date(left.createdAt) > new Date(right.createdAt) ? left : right
|
|
862
|
-
);
|
|
863
|
-
}
|
|
864
926
|
function extractOutcome(content) {
|
|
865
927
|
const match = content.match(/## Outcome\s+([\s\S]*?)(?=\n## |\n*$)/);
|
|
866
928
|
return match ? match[1].trim() : null;
|
|
@@ -886,36 +948,40 @@ function countSpecACs2(content) {
|
|
|
886
948
|
function loadSpecMeta(root, specName) {
|
|
887
949
|
if (!specName) return null;
|
|
888
950
|
const specPath = join3(getLetraDir2(root), "specs", specName, "spec.md");
|
|
889
|
-
if (!
|
|
951
|
+
if (!existsSync3(specPath)) {
|
|
890
952
|
return {
|
|
891
953
|
name: specName,
|
|
892
|
-
path:
|
|
954
|
+
path: `specs/${specName}/spec.md`,
|
|
893
955
|
outcome: null,
|
|
894
956
|
acs: { pending: 0, done: 0, total: 0 }
|
|
895
957
|
};
|
|
896
958
|
}
|
|
897
|
-
const content =
|
|
959
|
+
const content = readFileSync3(specPath, "utf-8");
|
|
898
960
|
return {
|
|
899
961
|
name: specName,
|
|
900
|
-
path:
|
|
962
|
+
path: `specs/${specName}/spec.md`,
|
|
901
963
|
outcome: extractOutcome(content),
|
|
902
964
|
acs: countSpecACs2(content)
|
|
903
965
|
};
|
|
904
966
|
}
|
|
905
|
-
function loadActivityContextSources(root) {
|
|
967
|
+
function loadActivityContextSources(root, itemId, runId) {
|
|
906
968
|
const workflow = loadWorkflow(root);
|
|
907
|
-
const
|
|
908
|
-
const
|
|
909
|
-
|
|
910
|
-
|
|
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;
|
|
911
977
|
const currentPhase = currentItem?.currentPhase ?? null;
|
|
912
978
|
const activeFlowStage = currentItem ? flowResolution.flow?.stages.find((stage) => stage.id === currentItem.stage) ?? null : null;
|
|
913
979
|
const activePhaseDef = currentPhase && activeFlowStage?.phases?.states?.[currentPhase] ? activeFlowStage.phases.states[currentPhase] : null;
|
|
914
980
|
const activePhaseHarness = activePhaseDef?.harness ?? null;
|
|
915
981
|
const activeReviewExpectation = activePhaseHarness?.activity?.review ?? activePhaseHarness?.review ?? activeFlowStage?.activity?.review ?? null;
|
|
916
982
|
const activeGateExpectation = activePhaseHarness?.activity?.gate ?? activePhaseHarness?.gate ?? activeFlowStage?.activity?.gate ?? null;
|
|
917
|
-
const focusDiverged =
|
|
918
|
-
const specName =
|
|
983
|
+
const focusDiverged = false;
|
|
984
|
+
const specName = currentItem?.spec ?? null;
|
|
919
985
|
const spec = loadSpecMeta(root, specName);
|
|
920
986
|
const activeAlerts = getActiveEntries(loadHealthRecord(root));
|
|
921
987
|
const lastActions = queryLog(root, { all: false, limit: 5 });
|
|
@@ -943,14 +1009,14 @@ function buildSignals(activity, intentSignal, focusDiverged, alertCount, highSev
|
|
|
943
1009
|
signals.push({
|
|
944
1010
|
level: "warning",
|
|
945
1011
|
code: "no-current-item",
|
|
946
|
-
message: "
|
|
1012
|
+
message: "Nenhuma execu\xE7\xE3o atribu\xEDda. Aguarde uma atribui\xE7\xE3o ou selecione uma execu\xE7\xE3o explicitamente."
|
|
947
1013
|
});
|
|
948
1014
|
}
|
|
949
1015
|
if (focusDiverged) {
|
|
950
1016
|
signals.push({
|
|
951
1017
|
level: "error",
|
|
952
1018
|
code: "focus-diverged",
|
|
953
|
-
message: "
|
|
1019
|
+
message: "O foco visual diverge da execu\xE7\xE3o. A dire\xE7\xE3o da execu\xE7\xE3o permanece can\xF4nica."
|
|
954
1020
|
});
|
|
955
1021
|
}
|
|
956
1022
|
if (alertCount > 0) {
|
|
@@ -996,22 +1062,34 @@ function buildRisks(activity, alertCount, highSeverityCount, pendingAcs) {
|
|
|
996
1062
|
}
|
|
997
1063
|
function buildActivityContext(options) {
|
|
998
1064
|
const { activity, workspaceRoot } = options;
|
|
999
|
-
const
|
|
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);
|
|
1000
1073
|
const intent = resolveActivityIntent(activity, sources);
|
|
1001
|
-
const 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
|
+
}
|
|
1002
1080
|
const currentItemContext = currentItem ? {
|
|
1003
1081
|
id: currentItem.id,
|
|
1004
1082
|
description: currentItem.description,
|
|
1005
1083
|
stage: currentItem.stage,
|
|
1006
|
-
stageName: sources.activeFlowStage?.name ?? (sources.workflow ?
|
|
1084
|
+
stageName: sources.activeFlowStage?.name ?? (sources.workflow ? getStageName3(sources.workflow, currentItem.stage) : currentItem.stage),
|
|
1007
1085
|
currentPhase: sources.currentPhase ?? void 0,
|
|
1008
1086
|
spec: currentItem.spec ?? null,
|
|
1009
|
-
outcome: sources.spec?.outcome ??
|
|
1087
|
+
outcome: sources.spec?.outcome ?? null,
|
|
1010
1088
|
acs: sources.spec?.acs ?? { pending: 0, done: 0, total: 0 }
|
|
1011
1089
|
} : null;
|
|
1012
1090
|
const stage = currentItem ? {
|
|
1013
1091
|
id: currentItem.stage,
|
|
1014
|
-
name: sources.activeFlowStage?.name ?? (sources.workflow ?
|
|
1092
|
+
name: sources.activeFlowStage?.name ?? (sources.workflow ? getStageName3(sources.workflow, currentItem.stage) : currentItem.stage)
|
|
1015
1093
|
} : null;
|
|
1016
1094
|
const highSeverityCount = sources.activeAlerts.filter(
|
|
1017
1095
|
(entry) => entry.severity === "alta"
|
|
@@ -1019,6 +1097,8 @@ function buildActivityContext(options) {
|
|
|
1019
1097
|
const pendingAcs = sources.spec?.acs.pending ?? 0;
|
|
1020
1098
|
return {
|
|
1021
1099
|
activity,
|
|
1100
|
+
assignment: direction.assignment,
|
|
1101
|
+
directionRevision: direction.revision,
|
|
1022
1102
|
objective: intent.objective,
|
|
1023
1103
|
currentItem: currentItemContext,
|
|
1024
1104
|
stage,
|
|
@@ -1042,16 +1122,19 @@ function buildActivityContext(options) {
|
|
|
1042
1122
|
function resolveRequestedActivity(value) {
|
|
1043
1123
|
return value === "design" || value === "implement" || value === "review" || value === "diagnose" || value === "gate" ? value : "implement";
|
|
1044
1124
|
}
|
|
1045
|
-
function buildRequestedActivityContext(workspaceRoot, activityParam) {
|
|
1125
|
+
function buildRequestedActivityContext(workspaceRoot, activityParam, runId, executorId, itemId) {
|
|
1046
1126
|
return buildActivityContext({
|
|
1047
1127
|
activity: resolveRequestedActivity(activityParam),
|
|
1048
|
-
workspaceRoot
|
|
1128
|
+
workspaceRoot,
|
|
1129
|
+
runId: runId ?? void 0,
|
|
1130
|
+
executorId: executorId ?? void 0,
|
|
1131
|
+
itemId: itemId ?? void 0
|
|
1049
1132
|
});
|
|
1050
1133
|
}
|
|
1051
1134
|
function readFocusState(workspaceDir) {
|
|
1052
1135
|
const focusFile = join4(workspaceDir, "focus.md");
|
|
1053
|
-
if (!
|
|
1054
|
-
const lines =
|
|
1136
|
+
if (!existsSync4(focusFile)) return { active: false };
|
|
1137
|
+
const lines = readFileSync4(focusFile, "utf-8").split(/\r?\n/);
|
|
1055
1138
|
const itemLine = lines.find((line) => line.startsWith("**Item**: "));
|
|
1056
1139
|
return {
|
|
1057
1140
|
active: true,
|
|
@@ -1061,33 +1144,33 @@ function readFocusState(workspaceDir) {
|
|
|
1061
1144
|
}
|
|
1062
1145
|
function readFocusDocument(workspaceDir) {
|
|
1063
1146
|
const focusFile = join4(workspaceDir, "focus.md");
|
|
1064
|
-
return
|
|
1147
|
+
return existsSync4(focusFile) ? readFileSync4(focusFile, "utf-8") : null;
|
|
1065
1148
|
}
|
|
1066
1149
|
function readDecisions(workspaceDir) {
|
|
1067
1150
|
const decisionsDir = join4(workspaceDir, "decisions");
|
|
1068
|
-
if (!
|
|
1151
|
+
if (!existsSync4(decisionsDir)) return [];
|
|
1069
1152
|
return readdirSync2(decisionsDir).filter((name) => name.endsWith(".md")).sort().reverse().map((name) => ({
|
|
1070
1153
|
name,
|
|
1071
|
-
content:
|
|
1154
|
+
content: readFileSync4(join4(decisionsDir, name), "utf-8")
|
|
1072
1155
|
}));
|
|
1073
1156
|
}
|
|
1074
1157
|
function contextFileExists(workspaceDir, file) {
|
|
1075
|
-
return
|
|
1158
|
+
return existsSync4(join4(workspaceDir, file));
|
|
1076
1159
|
}
|
|
1077
1160
|
|
|
1078
1161
|
// src/flow-serve/workspace.ts
|
|
1079
1162
|
import {
|
|
1080
1163
|
accessSync,
|
|
1081
1164
|
constants,
|
|
1082
|
-
existsSync as
|
|
1083
|
-
mkdirSync
|
|
1165
|
+
existsSync as existsSync5,
|
|
1166
|
+
mkdirSync,
|
|
1084
1167
|
rmSync,
|
|
1085
|
-
readFileSync as
|
|
1168
|
+
readFileSync as readFileSync5,
|
|
1086
1169
|
readdirSync as readdirSync3,
|
|
1087
|
-
statSync,
|
|
1088
|
-
writeFileSync
|
|
1170
|
+
statSync as statSync2,
|
|
1171
|
+
writeFileSync
|
|
1089
1172
|
} from "fs";
|
|
1090
|
-
import { basename, join as join5, resolve as
|
|
1173
|
+
import { basename, join as join5, resolve as resolve3 } from "path";
|
|
1091
1174
|
var LEGACY_BOOTSTRAP_TEMPLATES = {
|
|
1092
1175
|
padrao: {
|
|
1093
1176
|
name: "Padr\xE3o",
|
|
@@ -1129,17 +1212,17 @@ var TARGET_MARKERS = [
|
|
|
1129
1212
|
"build.gradle.kts"
|
|
1130
1213
|
];
|
|
1131
1214
|
function hasTargetMarker(path) {
|
|
1132
|
-
return TARGET_MARKERS.some((marker) =>
|
|
1215
|
+
return TARGET_MARKERS.some((marker) => existsSync5(join5(path, marker))) || existsSync5(join5(path, ".git"));
|
|
1133
1216
|
}
|
|
1134
1217
|
function detectStack(path) {
|
|
1135
1218
|
const stack = /* @__PURE__ */ new Set();
|
|
1136
1219
|
const evidence = [];
|
|
1137
1220
|
const packagePath = join5(path, "package.json");
|
|
1138
|
-
if (
|
|
1221
|
+
if (existsSync5(packagePath)) {
|
|
1139
1222
|
stack.add("Node.js");
|
|
1140
1223
|
evidence.push("package.json");
|
|
1141
1224
|
try {
|
|
1142
|
-
const pkg = JSON.parse(
|
|
1225
|
+
const pkg = JSON.parse(readFileSync5(packagePath, "utf-8"));
|
|
1143
1226
|
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
1144
1227
|
if (deps.react) stack.add("React");
|
|
1145
1228
|
if (deps.vite) stack.add("Vite");
|
|
@@ -1149,17 +1232,17 @@ function detectStack(path) {
|
|
|
1149
1232
|
evidence.push("package.json inv\xE1lido");
|
|
1150
1233
|
}
|
|
1151
1234
|
}
|
|
1152
|
-
if (
|
|
1235
|
+
if (existsSync5(join5(path, "pyproject.toml")) || existsSync5(join5(path, "requirements.txt"))) {
|
|
1153
1236
|
stack.add("Python");
|
|
1154
1237
|
evidence.push(
|
|
1155
|
-
|
|
1238
|
+
existsSync5(join5(path, "pyproject.toml")) ? "pyproject.toml" : "requirements.txt"
|
|
1156
1239
|
);
|
|
1157
1240
|
}
|
|
1158
|
-
if (
|
|
1241
|
+
if (existsSync5(join5(path, "go.mod"))) {
|
|
1159
1242
|
stack.add("Go");
|
|
1160
1243
|
evidence.push("go.mod");
|
|
1161
1244
|
}
|
|
1162
|
-
if (
|
|
1245
|
+
if (existsSync5(join5(path, "Cargo.toml"))) {
|
|
1163
1246
|
stack.add("Rust");
|
|
1164
1247
|
evidence.push("Cargo.toml");
|
|
1165
1248
|
}
|
|
@@ -1170,9 +1253,9 @@ function detectStack(path) {
|
|
|
1170
1253
|
}
|
|
1171
1254
|
} catch {
|
|
1172
1255
|
}
|
|
1173
|
-
if (
|
|
1256
|
+
if (existsSync5(join5(path, "Dockerfile")) || existsSync5(join5(path, "docker-compose.yml"))) {
|
|
1174
1257
|
stack.add("Docker");
|
|
1175
|
-
evidence.push(
|
|
1258
|
+
evidence.push(existsSync5(join5(path, "Dockerfile")) ? "Dockerfile" : "docker-compose.yml");
|
|
1176
1259
|
}
|
|
1177
1260
|
return { stack: [...stack], evidence };
|
|
1178
1261
|
}
|
|
@@ -1208,8 +1291,8 @@ function discoverTargetPaths(root) {
|
|
|
1208
1291
|
return [...candidates].slice(0, 100);
|
|
1209
1292
|
}
|
|
1210
1293
|
function analyzeWorkspaceSetup(input) {
|
|
1211
|
-
const root =
|
|
1212
|
-
if (!
|
|
1294
|
+
const root = resolve3(input.root);
|
|
1295
|
+
if (!existsSync5(root) || !statSync2(root).isDirectory()) {
|
|
1213
1296
|
throw new Error("A pasta inicial n\xE3o existe ou n\xE3o \xE9 um diret\xF3rio.");
|
|
1214
1297
|
}
|
|
1215
1298
|
try {
|
|
@@ -1236,7 +1319,7 @@ function analyzeWorkspaceSetup(input) {
|
|
|
1236
1319
|
state: isDetected ? "detected" : "available",
|
|
1237
1320
|
selected: isDetected,
|
|
1238
1321
|
evidence: isDetected ? tool.detectionPaths.filter(
|
|
1239
|
-
(adapterPath) =>
|
|
1322
|
+
(adapterPath) => existsSync5(join5(path, adapterPath))
|
|
1240
1323
|
) : []
|
|
1241
1324
|
};
|
|
1242
1325
|
})
|
|
@@ -1278,7 +1361,7 @@ function buildLineDiff(before, after) {
|
|
|
1278
1361
|
return lines.length > limit ? [...lines.slice(0, limit), ` ... ${lines.length - limit} linha(s) omitida(s)`].join("\n") : lines.join("\n");
|
|
1279
1362
|
}
|
|
1280
1363
|
function operationFor(path, context, after) {
|
|
1281
|
-
if (!
|
|
1364
|
+
if (!existsSync5(path)) {
|
|
1282
1365
|
return {
|
|
1283
1366
|
kind: "create",
|
|
1284
1367
|
path: path.replace(/\\/g, "/"),
|
|
@@ -1288,7 +1371,7 @@ function operationFor(path, context, after) {
|
|
|
1288
1371
|
diff: buildLineDiff("", after)
|
|
1289
1372
|
};
|
|
1290
1373
|
}
|
|
1291
|
-
const current =
|
|
1374
|
+
const current = readFileSync5(path, "utf-8");
|
|
1292
1375
|
const generated = /(?:Generated by letra|Gerado (?:por|by) letra)/i.test(current.slice(0, 500));
|
|
1293
1376
|
const managedSection = context.artifactId === "codex-project-config";
|
|
1294
1377
|
return {
|
|
@@ -1302,11 +1385,11 @@ function operationFor(path, context, after) {
|
|
|
1302
1385
|
};
|
|
1303
1386
|
}
|
|
1304
1387
|
function planWorkspaceSetup(input) {
|
|
1305
|
-
const workspaceRoot =
|
|
1388
|
+
const workspaceRoot = resolve3(input.workspaceRoot);
|
|
1306
1389
|
const normalizedRoot = workspaceRoot.replace(/\\/g, "/");
|
|
1307
1390
|
const operations = [];
|
|
1308
1391
|
const workflowPath = join5(workspaceRoot, "workflow.json");
|
|
1309
|
-
const workflowBefore =
|
|
1392
|
+
const workflowBefore = existsSync5(workflowPath) ? readFileSync5(workflowPath, "utf-8") : void 0;
|
|
1310
1393
|
const workflowAfter = input.workflow ? JSON.stringify(input.workflow, null, 2) : void 0;
|
|
1311
1394
|
operations.push({
|
|
1312
1395
|
kind: workflowBefore ? "conflict" : "create",
|
|
@@ -1317,12 +1400,12 @@ function planWorkspaceSetup(input) {
|
|
|
1317
1400
|
diff: workflowAfter ? buildLineDiff(workflowBefore || "", workflowAfter) : void 0
|
|
1318
1401
|
});
|
|
1319
1402
|
for (const target of input.targets) {
|
|
1320
|
-
const resolvedTarget =
|
|
1321
|
-
if (!
|
|
1403
|
+
const resolvedTarget = resolve3(target.path);
|
|
1404
|
+
if (!existsSync5(resolvedTarget) || !statSync2(resolvedTarget).isDirectory()) {
|
|
1322
1405
|
throw new Error(`O projeto "${target.label}" n\xE3o existe ou n\xE3o \xE9 um diret\xF3rio.`);
|
|
1323
1406
|
}
|
|
1324
1407
|
const linkPath = join5(resolvedTarget, ".letra-link");
|
|
1325
|
-
const linkBefore =
|
|
1408
|
+
const linkBefore = existsSync5(linkPath) ? readFileSync5(linkPath, "utf-8") : void 0;
|
|
1326
1409
|
const linkAfter = `${normalizedRoot}
|
|
1327
1410
|
`;
|
|
1328
1411
|
const linkMatches = linkBefore?.trim().replace(/\\/g, "/") === normalizedRoot;
|
|
@@ -1399,11 +1482,11 @@ function createWorkflowFromTemplate(root, templateId, options, harness) {
|
|
|
1399
1482
|
function registerWorkspaceSetup(input) {
|
|
1400
1483
|
const name = input.name.trim();
|
|
1401
1484
|
const description = input.description.trim();
|
|
1402
|
-
const workspaceRoot = input.workspacePath ?
|
|
1403
|
-
|
|
1485
|
+
const workspaceRoot = input.workspacePath ? resolve3(input.workspacePath) : resolve3(process.cwd());
|
|
1486
|
+
mkdirSync(workspaceRoot, { recursive: true });
|
|
1404
1487
|
const slug2 = name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 64);
|
|
1405
1488
|
const registryDir = join5(getLetraDir(), "workspaces", slug2);
|
|
1406
|
-
|
|
1489
|
+
mkdirSync(registryDir, { recursive: true });
|
|
1407
1490
|
const workspaceId = `ws_${Date.now().toString(36)}`;
|
|
1408
1491
|
const createdAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1409
1492
|
const workspace = {
|
|
@@ -1418,18 +1501,18 @@ function registerWorkspaceSetup(input) {
|
|
|
1418
1501
|
template: input.template
|
|
1419
1502
|
};
|
|
1420
1503
|
const registryFile = join5(registryDir, "workspace.json");
|
|
1421
|
-
if (
|
|
1504
|
+
if (existsSync5(registryFile)) {
|
|
1422
1505
|
throw new Error("J\xE1 existe um workspace registrado com este nome.");
|
|
1423
1506
|
}
|
|
1424
|
-
|
|
1507
|
+
writeFileSync(registryFile, JSON.stringify(workspace, null, 2), "utf-8");
|
|
1425
1508
|
return { workspace, workspaceRoot, registryFile };
|
|
1426
1509
|
}
|
|
1427
1510
|
function writeWorkspaceTargetAdapters(workspaceRoot, targets, workflow) {
|
|
1428
1511
|
const workspaceRootNormalized = workspaceRoot.replace(/\\/g, "/");
|
|
1429
1512
|
for (const target of targets) {
|
|
1430
|
-
const targetPath =
|
|
1431
|
-
if (!
|
|
1432
|
-
|
|
1513
|
+
const targetPath = resolve3(target.path);
|
|
1514
|
+
if (!existsSync5(targetPath)) continue;
|
|
1515
|
+
writeFileSync(join5(targetPath, ".letra-link"), `${workspaceRootNormalized}
|
|
1433
1516
|
`, "utf-8");
|
|
1434
1517
|
generateAdapters(targetPath, target.adapters, {
|
|
1435
1518
|
source: "init",
|
|
@@ -1445,10 +1528,10 @@ function writeWorkspaceTargetAdapters(workspaceRoot, targets, workflow) {
|
|
|
1445
1528
|
}
|
|
1446
1529
|
}
|
|
1447
1530
|
function writeExternalWorkspaceSetup(workspaceRoot, workflow, workspace) {
|
|
1448
|
-
const root =
|
|
1531
|
+
const root = resolve3(workspaceRoot);
|
|
1449
1532
|
ensureExternalWorkspaceLayout(root, { workflow, workspace });
|
|
1450
|
-
|
|
1451
|
-
|
|
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");
|
|
1452
1535
|
}
|
|
1453
1536
|
function workflowLocations(targets, workspaceRoot) {
|
|
1454
1537
|
return targets.map((target) => ({
|
|
@@ -1457,31 +1540,31 @@ function workflowLocations(targets, workspaceRoot) {
|
|
|
1457
1540
|
label: target.label,
|
|
1458
1541
|
adapters: [...target.adapters]
|
|
1459
1542
|
})).filter(
|
|
1460
|
-
(target) =>
|
|
1543
|
+
(target) => resolve3(target.path) !== resolve3(workspaceRoot) || target.adapters.length > 0
|
|
1461
1544
|
);
|
|
1462
1545
|
}
|
|
1463
1546
|
function captureWorkspaceSetup(plan) {
|
|
1464
1547
|
return plan.operations.filter((operation) => operation.kind === "create" || operation.kind === "update").map((operation) => ({
|
|
1465
1548
|
path: operation.path,
|
|
1466
|
-
existed:
|
|
1467
|
-
contentBase64:
|
|
1549
|
+
existed: existsSync5(operation.path),
|
|
1550
|
+
contentBase64: existsSync5(operation.path) ? Buffer.from(readFileSync5(operation.path)).toString("base64") : void 0
|
|
1468
1551
|
}));
|
|
1469
1552
|
}
|
|
1470
1553
|
function restoreWorkspaceSetup(snapshots) {
|
|
1471
1554
|
for (const snapshot of [...snapshots].reverse()) {
|
|
1472
1555
|
if (snapshot.existed) {
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
} else if (
|
|
1556
|
+
mkdirSync(join5(snapshot.path, ".."), { recursive: true });
|
|
1557
|
+
writeFileSync(snapshot.path, Buffer.from(snapshot.contentBase64 || "", "base64"));
|
|
1558
|
+
} else if (existsSync5(snapshot.path)) {
|
|
1476
1559
|
rmSync(snapshot.path, { force: true });
|
|
1477
1560
|
}
|
|
1478
1561
|
}
|
|
1479
1562
|
}
|
|
1480
1563
|
function saveWorkspaceSetupManifest(workspaceRoot, proposalId, operations, snapshots) {
|
|
1481
1564
|
const manifestId = `setup-${Date.now().toString(36)}`;
|
|
1482
|
-
const manifestDir = join5(
|
|
1483
|
-
|
|
1484
|
-
|
|
1565
|
+
const manifestDir = join5(resolve3(workspaceRoot), "operations", "setup-manifests");
|
|
1566
|
+
mkdirSync(manifestDir, { recursive: true });
|
|
1567
|
+
writeFileSync(
|
|
1485
1568
|
join5(manifestDir, `${manifestId}.json`),
|
|
1486
1569
|
JSON.stringify(
|
|
1487
1570
|
{
|
|
@@ -1500,14 +1583,14 @@ function saveWorkspaceSetupManifest(workspaceRoot, proposalId, operations, snaps
|
|
|
1500
1583
|
}
|
|
1501
1584
|
function rollbackWorkspaceSetup(workspaceRoot, manifestId) {
|
|
1502
1585
|
if (!/^setup-[a-z0-9]+$/i.test(manifestId)) throw new Error("Manifest de rollback inv\xE1lido.");
|
|
1503
|
-
const root =
|
|
1504
|
-
const manifestPath =
|
|
1586
|
+
const root = resolve3(workspaceRoot);
|
|
1587
|
+
const manifestPath = existsSync5(
|
|
1505
1588
|
join5(root, "operations", "setup-manifests", `${manifestId}.json`)
|
|
1506
1589
|
) ? join5(root, "operations", "setup-manifests", `${manifestId}.json`) : join5(root, ".letra", "setup-manifests", `${manifestId}.json`);
|
|
1507
|
-
if (!
|
|
1508
|
-
const manifest = JSON.parse(
|
|
1590
|
+
if (!existsSync5(manifestPath)) throw new Error("Manifest de rollback n\xE3o encontrado.");
|
|
1591
|
+
const manifest = JSON.parse(readFileSync5(manifestPath, "utf-8"));
|
|
1509
1592
|
restoreWorkspaceSetup(Array.isArray(manifest.snapshots) ? manifest.snapshots : []);
|
|
1510
|
-
|
|
1593
|
+
writeFileSync(
|
|
1511
1594
|
join5(manifestPath, "..", `${manifestId}.rollback.json`),
|
|
1512
1595
|
JSON.stringify({ manifestId, rolledBackAt: (/* @__PURE__ */ new Date()).toISOString() }, null, 2),
|
|
1513
1596
|
"utf-8"
|
|
@@ -1529,7 +1612,7 @@ var RECURRING_SYSTEM_ACTIONS = [
|
|
|
1529
1612
|
label: "Specs watcher",
|
|
1530
1613
|
trigger: "watch",
|
|
1531
1614
|
cadence: "sob mudan\xE7a de arquivo",
|
|
1532
|
-
cause: "Mudan\xE7a em
|
|
1615
|
+
cause: "Mudan\xE7a em `specs/**` no diret\xF3rio de dados do workspace",
|
|
1533
1616
|
effect: "Atualiza a vis\xE3o derivada de specs e emite `workflow-updated`"
|
|
1534
1617
|
},
|
|
1535
1618
|
{
|
|
@@ -1643,6 +1726,16 @@ function sendJson(res, status, payload) {
|
|
|
1643
1726
|
function sendError(res, status, message) {
|
|
1644
1727
|
sendJson(res, status, { error: message });
|
|
1645
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
|
+
}
|
|
1646
1739
|
function routeParam(path, pattern) {
|
|
1647
1740
|
const pathSegments = path.split("/").filter(Boolean);
|
|
1648
1741
|
const patternSegments = pattern.split("/").filter(Boolean);
|
|
@@ -1661,14 +1754,6 @@ function routeParam(path, pattern) {
|
|
|
1661
1754
|
}
|
|
1662
1755
|
|
|
1663
1756
|
// src/flow-serve/routes/item-routes.ts
|
|
1664
|
-
function resolveDecisionTarget(flow, currentStageId, target) {
|
|
1665
|
-
const currentIndex = flow.stages.findIndex((stage) => stage.id === currentStageId);
|
|
1666
|
-
if (currentIndex === -1) return null;
|
|
1667
|
-
if (target === "next") return flow.stages[currentIndex + 1]?.id ?? null;
|
|
1668
|
-
if (target === "previous") return flow.stages[currentIndex - 1]?.id ?? null;
|
|
1669
|
-
if (target === "first") return flow.stages[0]?.id ?? null;
|
|
1670
|
-
return flow.stages.some((stage) => stage.id === target) ? target : null;
|
|
1671
|
-
}
|
|
1672
1757
|
function sendBodyError(error, res) {
|
|
1673
1758
|
if (error instanceof HttpBodyError) {
|
|
1674
1759
|
sendError(res, error.status, error.message);
|
|
@@ -1679,6 +1764,87 @@ function sendBodyError(error, res) {
|
|
|
1679
1764
|
function createItemRoutes(dependencies) {
|
|
1680
1765
|
return async (context) => {
|
|
1681
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
|
+
}
|
|
1682
1848
|
if (path === "/api/items/alerts" && method === "GET") {
|
|
1683
1849
|
const record = dependencies.loadHealthRecord(workspaceRoot);
|
|
1684
1850
|
const itemAlerts = {};
|
|
@@ -1699,34 +1865,38 @@ function createItemRoutes(dependencies) {
|
|
|
1699
1865
|
sendError(res, 400, "id, description, and stage required");
|
|
1700
1866
|
return true;
|
|
1701
1867
|
}
|
|
1702
|
-
if (!
|
|
1703
|
-
sendError(res,
|
|
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);
|
|
1704
1887
|
return true;
|
|
1705
1888
|
}
|
|
1706
|
-
const item = {
|
|
1707
|
-
id: data.id,
|
|
1708
|
-
description: data.description,
|
|
1709
|
-
stage: data.stage,
|
|
1710
|
-
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1711
|
-
tasks: []
|
|
1712
|
-
};
|
|
1713
|
-
workflow.items.push(item);
|
|
1714
|
-
workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1715
|
-
dependencies.writeWorkflow(workspaceRoot, {
|
|
1716
|
-
workflow,
|
|
1717
|
-
source: "web-ui",
|
|
1718
|
-
primaryItemId: item.id,
|
|
1719
|
-
skipSitrep: true,
|
|
1720
|
-
quiet: true
|
|
1721
|
-
});
|
|
1722
1889
|
dependencies.broadcast();
|
|
1723
|
-
sendJson(res, 200,
|
|
1890
|
+
sendJson(res, 200, operation);
|
|
1724
1891
|
} catch (error) {
|
|
1725
1892
|
sendBodyError(error, res);
|
|
1726
1893
|
}
|
|
1727
1894
|
return true;
|
|
1728
1895
|
}
|
|
1729
|
-
const gateDecisionItemId = routeParam(
|
|
1896
|
+
const gateDecisionItemId = routeParam(
|
|
1897
|
+
path,
|
|
1898
|
+
"/api/items/:id/gate-decisions"
|
|
1899
|
+
);
|
|
1730
1900
|
if (gateDecisionItemId !== null && method === "POST") {
|
|
1731
1901
|
try {
|
|
1732
1902
|
const data = await readJson(req);
|
|
@@ -1735,97 +1905,133 @@ function createItemRoutes(dependencies) {
|
|
|
1735
1905
|
return true;
|
|
1736
1906
|
}
|
|
1737
1907
|
if (!data.decision || !["approve", "request-changes", "reject"].includes(data.decision)) {
|
|
1738
|
-
sendError(
|
|
1908
|
+
sendError(
|
|
1909
|
+
res,
|
|
1910
|
+
400,
|
|
1911
|
+
"decision must be approve, request-changes, or reject"
|
|
1912
|
+
);
|
|
1739
1913
|
return true;
|
|
1740
1914
|
}
|
|
1741
1915
|
const reason = data.reason?.trim();
|
|
1742
1916
|
if (data.decision !== "approve" && !reason) {
|
|
1743
|
-
sendError(res, 400, "reason is required for request-changes and reject");
|
|
1744
|
-
return true;
|
|
1745
|
-
}
|
|
1746
|
-
const item = workflow.items.find(
|
|
1747
|
-
(candidate) => candidate.id === gateDecisionItemId
|
|
1748
|
-
);
|
|
1749
|
-
if (!item) {
|
|
1750
|
-
sendError(res, 404, "Item not found");
|
|
1751
|
-
return true;
|
|
1752
|
-
}
|
|
1753
|
-
const resolved = dependencies.resolveActiveFlow(workspaceRoot, workflow);
|
|
1754
|
-
const flow = resolved.flow;
|
|
1755
|
-
const currentStage = flow?.stages.find((stage) => stage.id === item.stage);
|
|
1756
|
-
const gate = currentStage?.gate;
|
|
1757
|
-
if (!flow || gate?.type !== "human" || !gate.blocking) {
|
|
1758
|
-
sendError(res, 422, "Item is not waiting at a blocking human gate");
|
|
1759
|
-
return true;
|
|
1760
|
-
}
|
|
1761
|
-
const targetRule = gate.decisions?.[data.decision];
|
|
1762
|
-
if (!targetRule) {
|
|
1763
1917
|
sendError(
|
|
1764
1918
|
res,
|
|
1765
|
-
|
|
1766
|
-
|
|
1919
|
+
400,
|
|
1920
|
+
"reason is required for request-changes and reject"
|
|
1767
1921
|
);
|
|
1768
1922
|
return true;
|
|
1769
1923
|
}
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1924
|
+
if (!dependencies.decideGateOperation) {
|
|
1925
|
+
sendError(res, 503, "Canonical gate decision operation unavailable");
|
|
1926
|
+
return true;
|
|
1927
|
+
}
|
|
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
|
+
}
|
|
1776
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);
|
|
1777
1965
|
return true;
|
|
1778
1966
|
}
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
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(
|
|
1790
1981
|
workspaceRoot,
|
|
1791
|
-
"decision",
|
|
1792
|
-
`Gate ${gate.name}: ${data.decision} (${item.id})`,
|
|
1793
1982
|
{
|
|
1794
|
-
itemId:
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
reason: reason ?? null,
|
|
1800
|
-
from: sourceStage,
|
|
1801
|
-
to: targetStage,
|
|
1802
|
-
by: "human:web-ui",
|
|
1803
|
-
outcome: "completed"
|
|
1804
|
-
}
|
|
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."
|
|
1805
1988
|
}
|
|
1806
1989
|
);
|
|
1807
|
-
if (
|
|
1808
|
-
|
|
1990
|
+
if (operation.outcome !== "accepted") {
|
|
1991
|
+
sendRefusal(res, operation.reasonCode === "DIRECTION_STALE" ? 409 : 422, operation);
|
|
1992
|
+
return true;
|
|
1809
1993
|
}
|
|
1810
1994
|
dependencies.broadcast();
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
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
|
|
1827
2027
|
}
|
|
1828
|
-
|
|
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);
|
|
1829
2035
|
} catch (error) {
|
|
1830
2036
|
sendBodyError(error, res);
|
|
1831
2037
|
}
|
|
@@ -1848,154 +2054,142 @@ function createItemRoutes(dependencies) {
|
|
|
1848
2054
|
if (itemId !== null && method === "PATCH") {
|
|
1849
2055
|
try {
|
|
1850
2056
|
const data = await readJson(req);
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
const item = workflow.items.find((candidate) => candidate.id === itemId);
|
|
1856
|
-
if (!item) {
|
|
2057
|
+
const item = workflow?.items.find(
|
|
2058
|
+
(candidate) => candidate.id === itemId
|
|
2059
|
+
);
|
|
2060
|
+
if (!workflow || !item) {
|
|
1857
2061
|
sendError(res, 404, "Item not found");
|
|
1858
2062
|
return true;
|
|
1859
2063
|
}
|
|
1860
2064
|
const oldStage = item.stage;
|
|
1861
2065
|
if (data.stage !== void 0 && data.stage !== oldStage) {
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
`Gate bloqueante: ${sourceStage.gate.name}. Use uma decis\xE3o humana expl\xEDcita para sair de "${sourceStage.name}".`
|
|
1871
|
-
);
|
|
1872
|
-
return true;
|
|
1873
|
-
}
|
|
1874
|
-
const targetStage = resolved.flow?.stages.find(
|
|
1875
|
-
(stage) => stage.id === data.stage
|
|
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"
|
|
1876
2074
|
);
|
|
1877
|
-
|
|
1878
|
-
if (gate?.type === "human" && gate.blocking) {
|
|
1879
|
-
sendError(
|
|
1880
|
-
res,
|
|
1881
|
-
422,
|
|
1882
|
-
`Gate bloqueante: ${gate.name}. Aprova\xE7\xE3o humana necess\xE1ria para entrar em "${targetStage?.name ?? data.stage}".`
|
|
1883
|
-
);
|
|
1884
|
-
return true;
|
|
1885
|
-
}
|
|
1886
|
-
item.stage = data.stage;
|
|
2075
|
+
return true;
|
|
1887
2076
|
}
|
|
1888
|
-
if (
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
dependencies.logEntry(
|
|
1903
|
-
workspaceRoot,
|
|
1904
|
-
"focus_sync",
|
|
1905
|
-
`Focus synced to ${item.spec} via item move (${item.id})`,
|
|
1906
|
-
{ itemId: item.id, spec: item.spec }
|
|
1907
|
-
);
|
|
1908
|
-
console.log(` [focus] Synced to ${item.spec} via drag`);
|
|
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
|
|
1909
2091
|
}
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
targetStage: data.stage
|
|
1915
|
-
});
|
|
2092
|
+
);
|
|
2093
|
+
if (operation.outcome !== "accepted") {
|
|
2094
|
+
sendRefusal(res, operation.reasonCode === "DIRECTION_STALE" ? 409 : 422, operation);
|
|
2095
|
+
return true;
|
|
1916
2096
|
}
|
|
1917
|
-
|
|
2097
|
+
dependencies.broadcast();
|
|
2098
|
+
sendJson(res, 200, operation);
|
|
1918
2099
|
} catch (error) {
|
|
1919
2100
|
sendBodyError(error, res);
|
|
1920
2101
|
}
|
|
1921
2102
|
return true;
|
|
1922
2103
|
}
|
|
1923
2104
|
if (itemId !== null && method === "DELETE") {
|
|
1924
|
-
if (!
|
|
1925
|
-
sendError(res,
|
|
2105
|
+
if (!dependencies.deleteItemOperation) {
|
|
2106
|
+
sendError(res, 503, "Canonical item deletion operation unavailable");
|
|
1926
2107
|
return true;
|
|
1927
2108
|
}
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
2109
|
+
let data = {};
|
|
2110
|
+
try {
|
|
2111
|
+
data = await readJson(req);
|
|
2112
|
+
} catch {
|
|
1932
2113
|
}
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
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
|
|
1940
2120
|
});
|
|
2121
|
+
if (operation.outcome !== "accepted") {
|
|
2122
|
+
sendRefusal(res, operation.reasonCode === "DIRECTION_STALE" ? 409 : 422, operation);
|
|
2123
|
+
return true;
|
|
2124
|
+
}
|
|
1941
2125
|
dependencies.broadcast();
|
|
1942
|
-
sendJson(res, 200,
|
|
2126
|
+
sendJson(res, 200, operation);
|
|
1943
2127
|
return true;
|
|
1944
2128
|
}
|
|
1945
2129
|
const claimId = routeParam(path, "/api/items/:id/claim");
|
|
1946
2130
|
if (claimId !== null && method === "POST") {
|
|
1947
|
-
if (!
|
|
1948
|
-
sendError(res,
|
|
1949
|
-
return true;
|
|
1950
|
-
}
|
|
1951
|
-
const item = workflow.items.find((candidate) => candidate.id === claimId);
|
|
1952
|
-
if (!item) {
|
|
1953
|
-
sendError(res, 404, "Item not found");
|
|
2131
|
+
if (!dependencies.claimOperation) {
|
|
2132
|
+
sendError(res, 503, "Canonical claim operation unavailable");
|
|
1954
2133
|
return true;
|
|
1955
2134
|
}
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
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);
|
|
1962
2163
|
}
|
|
1963
|
-
item.claimedBy = "web-ui";
|
|
1964
|
-
item.claimedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1965
|
-
workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1966
|
-
dependencies.writeWorkflow(workspaceRoot, {
|
|
1967
|
-
workflow,
|
|
1968
|
-
source: "web-ui",
|
|
1969
|
-
primaryItemId: item.id,
|
|
1970
|
-
skipSitrep: true,
|
|
1971
|
-
quiet: true
|
|
1972
|
-
});
|
|
1973
|
-
dependencies.broadcast();
|
|
1974
|
-
sendJson(res, 200, item);
|
|
1975
2164
|
return true;
|
|
1976
2165
|
}
|
|
1977
2166
|
const releaseId = routeParam(path, "/api/items/:id/release");
|
|
1978
2167
|
if (releaseId !== null && method === "POST") {
|
|
1979
|
-
if (!
|
|
1980
|
-
sendError(res,
|
|
2168
|
+
if (!dependencies.releaseClaimOperation) {
|
|
2169
|
+
sendError(res, 503, "Canonical release operation unavailable");
|
|
1981
2170
|
return true;
|
|
1982
2171
|
}
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
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);
|
|
1987
2192
|
}
|
|
1988
|
-
item.claimedBy = void 0;
|
|
1989
|
-
item.claimedAt = void 0;
|
|
1990
|
-
workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1991
|
-
dependencies.writeWorkflow(workspaceRoot, {
|
|
1992
|
-
workflow,
|
|
1993
|
-
source: "web-ui",
|
|
1994
|
-
skipSitrep: true,
|
|
1995
|
-
quiet: true
|
|
1996
|
-
});
|
|
1997
|
-
dependencies.broadcast();
|
|
1998
|
-
sendJson(res, 200, item);
|
|
1999
2193
|
return true;
|
|
2000
2194
|
}
|
|
2001
2195
|
const focusId = routeParam(path, "/api/items/:id/focus");
|
|
@@ -2011,9 +2205,14 @@ function createItemRoutes(dependencies) {
|
|
|
2011
2205
|
}
|
|
2012
2206
|
const specName = item.spec || focusId;
|
|
2013
2207
|
dependencies.writeFocusFile(workspaceRoot, specName, item.id);
|
|
2014
|
-
dependencies.logEntry(
|
|
2015
|
-
|
|
2016
|
-
|
|
2208
|
+
dependencies.logEntry(
|
|
2209
|
+
workspaceRoot,
|
|
2210
|
+
"focus_set",
|
|
2211
|
+
`Focus set via UI: ${specName}`,
|
|
2212
|
+
{
|
|
2213
|
+
itemId: focusId
|
|
2214
|
+
}
|
|
2215
|
+
);
|
|
2017
2216
|
dependencies.broadcast();
|
|
2018
2217
|
sendJson(res, 200, { itemId: focusId, spec: specName });
|
|
2019
2218
|
return true;
|
|
@@ -2035,6 +2234,14 @@ function sendBodyError2(error, res) {
|
|
|
2035
2234
|
}
|
|
2036
2235
|
function createSpecRoutes(dependencies) {
|
|
2037
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
|
+
}
|
|
2038
2245
|
if (path === "/api/specs" && method === "GET") {
|
|
2039
2246
|
try {
|
|
2040
2247
|
sendJson(res, 200, dependencies.loadResolvedSpecs(workspaceRoot, workflow));
|
|
@@ -2053,7 +2260,7 @@ function createSpecRoutes(dependencies) {
|
|
|
2053
2260
|
dependencies.writeSpec(workspaceDir, id, content);
|
|
2054
2261
|
if (workflow) {
|
|
2055
2262
|
workflow.specLinks ??= {};
|
|
2056
|
-
workflow.specLinks[id] = { path:
|
|
2263
|
+
workflow.specLinks[id] = { path: `specs/${id}/spec.md` };
|
|
2057
2264
|
workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
2058
2265
|
dependencies.writeWorkflow(workspaceRoot, {
|
|
2059
2266
|
workflow,
|
|
@@ -2134,6 +2341,10 @@ function sendBodyError3(error, res) {
|
|
|
2134
2341
|
function createDiagnosticsRoutes(dependencies) {
|
|
2135
2342
|
return async ({ method, path, req, res, url, workspaceRoot }) => {
|
|
2136
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
|
+
}
|
|
2137
2348
|
if (path === "/api/diagnostics" && method === "GET") {
|
|
2138
2349
|
sendJson(res, 200, engine.getLastOutput());
|
|
2139
2350
|
return true;
|
|
@@ -2447,6 +2658,7 @@ function createContextRoutes(dependencies) {
|
|
|
2447
2658
|
const result = dependencies.queryLogWithMeta(workspaceRoot, {
|
|
2448
2659
|
all: url.searchParams.get("all") === "true",
|
|
2449
2660
|
itemId: url.searchParams.get("item") ?? void 0,
|
|
2661
|
+
runId: url.searchParams.get("run") ?? void 0,
|
|
2450
2662
|
action: url.searchParams.get("action") ?? void 0,
|
|
2451
2663
|
since: url.searchParams.get("since") ?? void 0,
|
|
2452
2664
|
q: url.searchParams.get("q") ?? void 0,
|
|
@@ -2476,9 +2688,9 @@ function createContextRoutes(dependencies) {
|
|
|
2476
2688
|
var readFile = readFile2;
|
|
2477
2689
|
const { existsSync: existsSync16, readFileSync: readFileSync12 } = await import("fs");
|
|
2478
2690
|
const { join: join14 } = await import("path");
|
|
2479
|
-
const {
|
|
2480
|
-
const {
|
|
2481
|
-
const {
|
|
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");
|
|
2482
2694
|
const l1Files = [
|
|
2483
2695
|
"constitution.md",
|
|
2484
2696
|
"context.md",
|
|
@@ -2487,14 +2699,14 @@ function createContextRoutes(dependencies) {
|
|
|
2487
2699
|
];
|
|
2488
2700
|
const l1 = l1Files.map((f) => ({
|
|
2489
2701
|
path: `.letra/${f}`,
|
|
2490
|
-
content: readFile2(f)
|
|
2702
|
+
content: f === "context.md" ? stripSitrepSnapshots(readFile2(f)) : readFile2(f)
|
|
2491
2703
|
}));
|
|
2492
|
-
const
|
|
2493
|
-
const
|
|
2494
|
-
const specContent =
|
|
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`) : "";
|
|
2495
2707
|
const l2 = {
|
|
2496
|
-
|
|
2497
|
-
spec: specContent ? { path:
|
|
2708
|
+
direction,
|
|
2709
|
+
spec: specContent ? { path: `specs/${specName}/spec.md`, content: specContent } : null
|
|
2498
2710
|
};
|
|
2499
2711
|
const healthRecord = loadHealthRecord2(workspaceRoot);
|
|
2500
2712
|
const alerts = getActiveEntries2(healthRecord);
|
|
@@ -2519,10 +2731,10 @@ function createContextRoutes(dependencies) {
|
|
|
2519
2731
|
return true;
|
|
2520
2732
|
}
|
|
2521
2733
|
if (path === "/api/sitrep" && method === "POST") {
|
|
2522
|
-
|
|
2523
|
-
|
|
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."
|
|
2524
2737
|
});
|
|
2525
|
-
sendJson(res, 200, { ok: true });
|
|
2526
2738
|
return true;
|
|
2527
2739
|
}
|
|
2528
2740
|
if (path === "/api/pulse" && method === "GET") {
|
|
@@ -2530,10 +2742,13 @@ function createContextRoutes(dependencies) {
|
|
|
2530
2742
|
return true;
|
|
2531
2743
|
}
|
|
2532
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");
|
|
2533
2748
|
sendJson(
|
|
2534
2749
|
res,
|
|
2535
2750
|
200,
|
|
2536
|
-
dependencies.buildActivityContext(workspaceRoot, url.searchParams.get("activity"))
|
|
2751
|
+
dependencies.buildActivityContext(workspaceRoot, url.searchParams.get("activity"), runId, executorId, itemId)
|
|
2537
2752
|
);
|
|
2538
2753
|
return true;
|
|
2539
2754
|
}
|
|
@@ -2542,8 +2757,8 @@ function createContextRoutes(dependencies) {
|
|
|
2542
2757
|
}
|
|
2543
2758
|
|
|
2544
2759
|
// src/flow-serve/routes/workflow-routes.ts
|
|
2545
|
-
import { existsSync as
|
|
2546
|
-
import { join as join6, resolve as
|
|
2760
|
+
import { existsSync as existsSync6, readFileSync as readFileSync6, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
|
|
2761
|
+
import { join as join6, resolve as resolve4 } from "path";
|
|
2547
2762
|
function sendBodyError5(error, res) {
|
|
2548
2763
|
if (error instanceof HttpBodyError) sendError(res, error.status, error.message);
|
|
2549
2764
|
else sendError(res, 400, error.message);
|
|
@@ -2565,21 +2780,21 @@ function labelFromPath(path, fallback = "Projeto") {
|
|
|
2565
2780
|
return normalizedPath(path).split("/").filter(Boolean).pop() || fallback;
|
|
2566
2781
|
}
|
|
2567
2782
|
function assertProjectDirectory(path) {
|
|
2568
|
-
const resolved =
|
|
2569
|
-
if (!
|
|
2783
|
+
const resolved = resolve4(path);
|
|
2784
|
+
if (!existsSync6(resolved)) throw new Error("A pasta de projeto n\xE3o existe.");
|
|
2570
2785
|
return resolved;
|
|
2571
2786
|
}
|
|
2572
2787
|
function linkPathFor(locationPath) {
|
|
2573
|
-
return join6(
|
|
2788
|
+
return join6(resolve4(locationPath), ".letra-link");
|
|
2574
2789
|
}
|
|
2575
2790
|
function readLink(locationPath) {
|
|
2576
2791
|
const path = linkPathFor(locationPath);
|
|
2577
|
-
if (!
|
|
2578
|
-
return
|
|
2792
|
+
if (!existsSync6(path)) return null;
|
|
2793
|
+
return readFileSync6(path, "utf-8").trim();
|
|
2579
2794
|
}
|
|
2580
2795
|
function writeLocationLink(locationPath, dataDir) {
|
|
2581
2796
|
const resolved = assertProjectDirectory(locationPath);
|
|
2582
|
-
|
|
2797
|
+
writeFileSync2(join6(resolved, ".letra-link"), `${dataDir}
|
|
2583
2798
|
`, "utf-8");
|
|
2584
2799
|
}
|
|
2585
2800
|
function removeLocationLinkIfOwned(locationPath, dataDir) {
|
|
@@ -2591,6 +2806,78 @@ function removeLocationLinkIfOwned(locationPath, dataDir) {
|
|
|
2591
2806
|
}
|
|
2592
2807
|
function createWorkflowRoutes(dependencies) {
|
|
2593
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
|
+
}
|
|
2594
2881
|
if (path === "/api/workflow" && method === "GET") {
|
|
2595
2882
|
sendJson(res, 200, workflow ?? { error: "No workflow found" });
|
|
2596
2883
|
return true;
|
|
@@ -2885,32 +3172,110 @@ function createWorkflowRoutes(dependencies) {
|
|
|
2885
3172
|
}
|
|
2886
3173
|
|
|
2887
3174
|
// src/flow-serve/routes/workspace-routes.ts
|
|
2888
|
-
import { readdirSync as readdirSync5, existsSync as
|
|
2889
|
-
import { join as join8, resolve as
|
|
3175
|
+
import { readdirSync as readdirSync5, existsSync as existsSync8, readFileSync as readFileSync8 } from "fs";
|
|
3176
|
+
import { join as join8, resolve as resolve6 } from "path";
|
|
2890
3177
|
import { homedir } from "os";
|
|
2891
3178
|
|
|
2892
3179
|
// src/commands/migrate.ts
|
|
2893
|
-
import { existsSync as
|
|
2894
|
-
import {
|
|
2895
|
-
import {
|
|
2896
|
-
import
|
|
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";
|
|
2897
3185
|
var EXTERNAL_ROOT = getWorkspacesDir();
|
|
2898
3186
|
function workspaceName(root) {
|
|
2899
3187
|
const wf = loadWorkflow(root);
|
|
2900
3188
|
return wf?.name || slugifyWorkspaceName(root);
|
|
2901
3189
|
}
|
|
2902
3190
|
function copyDirectoryContents(source, target) {
|
|
2903
|
-
|
|
3191
|
+
mkdirSync2(target, { recursive: true });
|
|
2904
3192
|
for (const entry of readdirSync4(source)) {
|
|
2905
3193
|
cpSync(join7(source, entry), join7(target, entry), { recursive: true, force: true });
|
|
2906
3194
|
}
|
|
2907
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
|
+
}
|
|
2908
3273
|
async function migrateWorkspace(rootPath, options) {
|
|
2909
|
-
const cwd = rootPath ?
|
|
3274
|
+
const cwd = rootPath ? resolve5(process.cwd(), rootPath) : process.cwd();
|
|
2910
3275
|
const resolution = resolveWorkspaceRoot(cwd);
|
|
2911
3276
|
const source = resolution.workspaceDir;
|
|
2912
|
-
const rootForLink = resolution.workspaceRoot;
|
|
2913
|
-
if (!
|
|
3277
|
+
const rootForLink = resolution.type === "linked" && resolution.linkPath ? resolve5(resolution.linkPath, "..") : resolution.workspaceRoot;
|
|
3278
|
+
if (!existsSync7(source)) {
|
|
2914
3279
|
return {
|
|
2915
3280
|
ok: false,
|
|
2916
3281
|
from: source,
|
|
@@ -2920,18 +3285,39 @@ async function migrateWorkspace(rootPath, options) {
|
|
|
2920
3285
|
};
|
|
2921
3286
|
}
|
|
2922
3287
|
if (resolution.type === "linked") {
|
|
2923
|
-
|
|
2924
|
-
|
|
2925
|
-
|
|
2926
|
-
|
|
2927
|
-
|
|
2928
|
-
|
|
2929
|
-
|
|
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));
|
|
2930
3316
|
}
|
|
2931
3317
|
const name = workspaceName(rootForLink);
|
|
2932
3318
|
const slug2 = slugifyWorkspaceName(name);
|
|
2933
|
-
const target = options?.to ? isAbsolute(options.to) ? options.to :
|
|
2934
|
-
if (
|
|
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"))) {
|
|
2935
3321
|
return {
|
|
2936
3322
|
ok: false,
|
|
2937
3323
|
from: source,
|
|
@@ -2949,16 +3335,16 @@ async function migrateWorkspace(rootPath, options) {
|
|
|
2949
3335
|
message: `[dry-run] Would copy ${source} -> ${target} and write ${LINK_FILE} at ${rootForLink}`
|
|
2950
3336
|
};
|
|
2951
3337
|
}
|
|
2952
|
-
|
|
3338
|
+
mkdirSync2(target, { recursive: true });
|
|
2953
3339
|
copyDirectoryContents(source, target);
|
|
2954
3340
|
ensureExternalWorkspaceLayout(target);
|
|
2955
3341
|
const migrationId = `migration-${Date.now().toString(36)}`;
|
|
2956
3342
|
const evidenceDir = join7(target, "operations", "migrations");
|
|
2957
|
-
|
|
3343
|
+
mkdirSync2(evidenceDir, { recursive: true });
|
|
2958
3344
|
const rollbackDir = join7(target, "operations", "rollbacks", migrationId);
|
|
2959
3345
|
const rollbackSnapshotDir = join7(rollbackDir, "legacy-letra");
|
|
2960
3346
|
copyDirectoryContents(source, rollbackSnapshotDir);
|
|
2961
|
-
|
|
3347
|
+
writeFileSync3(
|
|
2962
3348
|
join7(rollbackDir, "rollback.json"),
|
|
2963
3349
|
JSON.stringify(
|
|
2964
3350
|
{
|
|
@@ -2974,7 +3360,7 @@ async function migrateWorkspace(rootPath, options) {
|
|
|
2974
3360
|
),
|
|
2975
3361
|
"utf-8"
|
|
2976
3362
|
);
|
|
2977
|
-
|
|
3363
|
+
writeFileSync3(join7(rootForLink, LINK_FILE), `${target}
|
|
2978
3364
|
`, "utf-8");
|
|
2979
3365
|
clearWorkspaceCache();
|
|
2980
3366
|
let cleaned = false;
|
|
@@ -2982,7 +3368,7 @@ async function migrateWorkspace(rootPath, options) {
|
|
|
2982
3368
|
rmSync2(source, { recursive: true, force: true });
|
|
2983
3369
|
cleaned = true;
|
|
2984
3370
|
}
|
|
2985
|
-
|
|
3371
|
+
writeFileSync3(
|
|
2986
3372
|
join7(evidenceDir, `${migrationId}.json`),
|
|
2987
3373
|
JSON.stringify(
|
|
2988
3374
|
{
|
|
@@ -3010,16 +3396,14 @@ async function migrateWorkspace(rootPath, options) {
|
|
|
3010
3396
|
};
|
|
3011
3397
|
}
|
|
3012
3398
|
function migrateCommand() {
|
|
3013
|
-
const cmd = new
|
|
3014
|
-
"Externalize a workspace's .letra directory to ~/.letra/workspaces/{slug}/ and leave a link"
|
|
3015
|
-
).argument("[root]", "workspace root (defaults to cwd)").option("--to <path>", "target data directory (overrides default)").option("--clean", "remove the original .letra directory after migrating").option("--dry-run", "print what would happen without writing").action(
|
|
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(
|
|
3016
3400
|
async (root, opts) => {
|
|
3017
3401
|
const result = await migrateWorkspace(root ?? ".", opts);
|
|
3018
3402
|
if (!result.ok) {
|
|
3019
|
-
console.log(
|
|
3403
|
+
console.log(chalk3.red(`\u2717 ${result.message}`));
|
|
3020
3404
|
process.exitCode = 1;
|
|
3021
3405
|
} else {
|
|
3022
|
-
console.log(
|
|
3406
|
+
console.log(chalk3.green(`\u2713 ${result.message}`));
|
|
3023
3407
|
console.log(` from: ${result.from}`);
|
|
3024
3408
|
console.log(` to: ${result.to}`);
|
|
3025
3409
|
}
|
|
@@ -3035,12 +3419,12 @@ function sendBodyError6(error, res) {
|
|
|
3035
3419
|
}
|
|
3036
3420
|
function resolveUserPath(path, fallback = process.cwd()) {
|
|
3037
3421
|
const input = path.trim();
|
|
3038
|
-
if (!input) return
|
|
3422
|
+
if (!input) return resolve6(fallback);
|
|
3039
3423
|
if (input === "~") return homedir();
|
|
3040
3424
|
if (input.startsWith("~/") || input.startsWith("~\\")) {
|
|
3041
|
-
return
|
|
3425
|
+
return resolve6(homedir(), input.slice(2));
|
|
3042
3426
|
}
|
|
3043
|
-
return
|
|
3427
|
+
return resolve6(input);
|
|
3044
3428
|
}
|
|
3045
3429
|
function templates(harness) {
|
|
3046
3430
|
if (!harness) return [];
|
|
@@ -3068,7 +3452,7 @@ function createWorkspaceRoutes(dependencies) {
|
|
|
3068
3452
|
try {
|
|
3069
3453
|
const registered = dependencies.listWorkspaces();
|
|
3070
3454
|
const active = workspaceRoot;
|
|
3071
|
-
const hasActive = typeof active === "string" && active.length > 0 &&
|
|
3455
|
+
const hasActive = typeof active === "string" && active.length > 0 && existsSync8(join8(getLetraDir2(active), "workflow.json"));
|
|
3072
3456
|
const workspaces = hasActive ? registered.some((w) => String(w.root ?? "") === active) ? registered : [
|
|
3073
3457
|
{
|
|
3074
3458
|
id: "ws-active",
|
|
@@ -3087,7 +3471,7 @@ function createWorkspaceRoutes(dependencies) {
|
|
|
3087
3471
|
const dataDir = root ? getLetraDir2(root) : null;
|
|
3088
3472
|
const wfPath = dataDir ? join8(dataDir, "workflow.json") : null;
|
|
3089
3473
|
let wf = null;
|
|
3090
|
-
if (wfPath &&
|
|
3474
|
+
if (wfPath && existsSync8(wfPath)) {
|
|
3091
3475
|
try {
|
|
3092
3476
|
wf = JSON.parse(readFileSync8(wfPath, "utf-8"));
|
|
3093
3477
|
} catch {
|
|
@@ -3115,7 +3499,7 @@ function createWorkspaceRoutes(dependencies) {
|
|
|
3115
3499
|
try {
|
|
3116
3500
|
const data = await readJson(req);
|
|
3117
3501
|
const root = data.root || data.workspaceRoot || data.projectRoot;
|
|
3118
|
-
if (root) dependencies.switchWorkspace(
|
|
3502
|
+
if (root) dependencies.switchWorkspace(resolve6(root));
|
|
3119
3503
|
const activeRoot = dependencies.activeWorkspaceRoot();
|
|
3120
3504
|
const activeResolution = resolveWorkspaceRoot(activeRoot);
|
|
3121
3505
|
sendJson(res, 200, {
|
|
@@ -3318,108 +3702,18 @@ function createWorkspaceRoutes(dependencies) {
|
|
|
3318
3702
|
}
|
|
3319
3703
|
|
|
3320
3704
|
// src/flow-serve/routes/adapter-routes.ts
|
|
3321
|
-
import { existsSync as
|
|
3322
|
-
import { join as
|
|
3323
|
-
|
|
3324
|
-
// src/commands/sync.ts
|
|
3325
|
-
import { existsSync as existsSync10 } from "fs";
|
|
3326
|
-
import { resolve as resolve6, join as join9 } from "path";
|
|
3327
|
-
import { Command as Command3 } from "commander";
|
|
3328
|
-
import chalk3 from "chalk";
|
|
3329
|
-
async function validateFocus(focusSpec, items, stages) {
|
|
3330
|
-
const warnings = [];
|
|
3331
|
-
const doneIds = new Set(stages.filter((s) => s.id === "done").map((s) => s.id));
|
|
3332
|
-
const matchingItems = items.filter((i) => i.spec === focusSpec);
|
|
3333
|
-
if (matchingItems.length === 0) {
|
|
3334
|
-
warnings.push(`Focus spec "${focusSpec}" does not match any item's spec in workflow`);
|
|
3335
|
-
} else {
|
|
3336
|
-
for (const item of matchingItems) {
|
|
3337
|
-
if (doneIds.has(item.stage)) {
|
|
3338
|
-
warnings.push(
|
|
3339
|
-
`Focus spec "${focusSpec}" matches ${item.id} which is in "done" stage`
|
|
3340
|
-
);
|
|
3341
|
-
}
|
|
3342
|
-
}
|
|
3343
|
-
}
|
|
3344
|
-
return warnings;
|
|
3345
|
-
}
|
|
3346
|
-
async function syncNow(rootPath, options) {
|
|
3347
|
-
const workflowFile = join9(getLetraDir2(rootPath), "workflow.json");
|
|
3348
|
-
if (!existsSync10(workflowFile)) {
|
|
3349
|
-
return {
|
|
3350
|
-
ok: false,
|
|
3351
|
-
filesUpdated: [],
|
|
3352
|
-
warnings: [],
|
|
3353
|
-
error: "No workflow found at .letra/workflow.json"
|
|
3354
|
-
};
|
|
3355
|
-
}
|
|
3356
|
-
const workflow = loadWorkflow(rootPath);
|
|
3357
|
-
if (!workflow) {
|
|
3358
|
-
return { ok: false, filesUpdated: [], warnings: [], error: "Failed to load workflow" };
|
|
3359
|
-
}
|
|
3360
|
-
const warnings = [];
|
|
3361
|
-
const focus = readFocusFile(rootPath);
|
|
3362
|
-
if (focus?.specName) {
|
|
3363
|
-
const focusWarnings = await validateFocus(focus.specName, workflow.items, workflow.stages);
|
|
3364
|
-
warnings.push(...focusWarnings);
|
|
3365
|
-
}
|
|
3366
|
-
if (options?.dryRun) {
|
|
3367
|
-
const filesUpdated = [
|
|
3368
|
-
".letra/workflow.json",
|
|
3369
|
-
...(workflow.tools || []).map((t) => t),
|
|
3370
|
-
".letra/context.md"
|
|
3371
|
-
];
|
|
3372
|
-
return { ok: true, filesUpdated, warnings, error: void 0 };
|
|
3373
|
-
}
|
|
3374
|
-
const result = await writeWorkflow(rootPath, {
|
|
3375
|
-
workflow,
|
|
3376
|
-
source: "flow-edit",
|
|
3377
|
-
skipSitrep: options?.skipSitrep ?? false
|
|
3378
|
-
});
|
|
3379
|
-
return { ...result, warnings };
|
|
3380
|
-
}
|
|
3381
|
-
function sync_default() {
|
|
3382
|
-
const cmd = new Command3("sync").description("Sync workflow state to all adapters");
|
|
3383
|
-
cmd.option("--dry-run", "Show what would be done without writing").option("--fix", "Apply reconciliation (default behavior)").action(async (opts) => {
|
|
3384
|
-
const root = resolve6(process.cwd());
|
|
3385
|
-
const isDryRun = !!opts.dryRun;
|
|
3386
|
-
const result = await syncNow(root, { dryRun: isDryRun });
|
|
3387
|
-
if (!result.ok) {
|
|
3388
|
-
console.log(chalk3.red(`\u2717 Sync failed: ${result.error ?? "unknown error"}`));
|
|
3389
|
-
process.exit(1);
|
|
3390
|
-
}
|
|
3391
|
-
if (result.warnings.length > 0) {
|
|
3392
|
-
for (const w of result.warnings) {
|
|
3393
|
-
console.log(chalk3.yellow(` \u26A0 ${w}`));
|
|
3394
|
-
}
|
|
3395
|
-
}
|
|
3396
|
-
if (isDryRun) {
|
|
3397
|
-
console.log(chalk3.bold("\n\u{1F4CB} Simula\xE7\xE3o \u2014 dry-run\n"));
|
|
3398
|
-
console.log(chalk3.gray(" Seriam regenerados:"));
|
|
3399
|
-
for (const f of result.filesUpdated) {
|
|
3400
|
-
console.log(` ${chalk3.gray("\u2192")} ${f}`);
|
|
3401
|
-
}
|
|
3402
|
-
return;
|
|
3403
|
-
}
|
|
3404
|
-
console.log(chalk3.green("\u2713 Workflow synced"));
|
|
3405
|
-
for (const f of result.filesUpdated) {
|
|
3406
|
-
console.log(` ${chalk3.gray("\u2192")} ${f}`);
|
|
3407
|
-
}
|
|
3408
|
-
});
|
|
3409
|
-
return cmd;
|
|
3410
|
-
}
|
|
3411
|
-
|
|
3412
|
-
// src/flow-serve/routes/adapter-routes.ts
|
|
3705
|
+
import { existsSync as existsSync9, statSync as statSync3 } from "fs";
|
|
3706
|
+
import { join as join9 } from "path";
|
|
3413
3707
|
function getAdapterStatus(workspaceRoot) {
|
|
3414
3708
|
return Object.values(ADAPTER_REGISTRY).map((adapter) => {
|
|
3415
|
-
const paths = adapter.detectionPaths.map((p) =>
|
|
3709
|
+
const paths = adapter.detectionPaths.map((p) => join9(workspaceRoot, p));
|
|
3416
3710
|
const artifacts = paths.map((fullPath) => {
|
|
3417
3711
|
let exists = false;
|
|
3418
3712
|
let modifiedAt = null;
|
|
3419
3713
|
try {
|
|
3420
|
-
exists =
|
|
3714
|
+
exists = existsSync9(fullPath);
|
|
3421
3715
|
if (exists) {
|
|
3422
|
-
modifiedAt =
|
|
3716
|
+
modifiedAt = statSync3(fullPath).mtime.toISOString();
|
|
3423
3717
|
}
|
|
3424
3718
|
} catch {
|
|
3425
3719
|
}
|
|
@@ -3430,8 +3724,8 @@ function getAdapterStatus(workspaceRoot) {
|
|
|
3430
3724
|
};
|
|
3431
3725
|
});
|
|
3432
3726
|
const detected = artifacts.some((a) => a.exists);
|
|
3433
|
-
const wf =
|
|
3434
|
-
const wfMtime =
|
|
3727
|
+
const wf = join9(getLetraDir2(workspaceRoot), "workflow.json");
|
|
3728
|
+
const wfMtime = existsSync9(wf) ? statSync3(wf).mtime.getTime() : 0;
|
|
3435
3729
|
const newestArtifact = artifacts.filter((a) => a.exists && a.modifiedAt).sort(
|
|
3436
3730
|
(a, b) => new Date(b.modifiedAt).getTime() - new Date(a.modifiedAt).getTime()
|
|
3437
3731
|
)[0];
|
|
@@ -3500,9 +3794,159 @@ function createHandoffRoutes(dependencies) {
|
|
|
3500
3794
|
};
|
|
3501
3795
|
}
|
|
3502
3796
|
|
|
3797
|
+
// src/flow-serve/routes/agent-routes.ts
|
|
3798
|
+
var agentMutation = false;
|
|
3799
|
+
async function acquireAgentMutation() {
|
|
3800
|
+
while (agentMutation) await new Promise((resolve8) => setTimeout(resolve8, 0));
|
|
3801
|
+
agentMutation = true;
|
|
3802
|
+
return () => {
|
|
3803
|
+
agentMutation = false;
|
|
3804
|
+
};
|
|
3805
|
+
}
|
|
3806
|
+
function createAgentRoutes(dependencies) {
|
|
3807
|
+
return async (context) => {
|
|
3808
|
+
if (!context.path.startsWith("/api/agents")) return false;
|
|
3809
|
+
const root = context.workspaceRoot;
|
|
3810
|
+
try {
|
|
3811
|
+
if (context.path === "/api/agents" && context.method === "GET") {
|
|
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?.() ?? []));
|
|
3815
|
+
return true;
|
|
3816
|
+
}
|
|
3817
|
+
if (context.path === "/api/agents" && context.method === "POST") {
|
|
3818
|
+
const release = await acquireAgentMutation();
|
|
3819
|
+
try {
|
|
3820
|
+
const agent = await readJson(context.req);
|
|
3821
|
+
const result = createAgent(root, agent, dependencies.loadWorkflow(root));
|
|
3822
|
+
dependencies.broadcast?.();
|
|
3823
|
+
sendJson(context.res, 201, result);
|
|
3824
|
+
return true;
|
|
3825
|
+
} finally {
|
|
3826
|
+
release();
|
|
3827
|
+
}
|
|
3828
|
+
}
|
|
3829
|
+
const match = context.path.match(/^\/api\/agents\/([^/]+)$/);
|
|
3830
|
+
if (!match) return false;
|
|
3831
|
+
const id = decodeURIComponent(match[1]);
|
|
3832
|
+
if (context.method === "PATCH") {
|
|
3833
|
+
const release = await acquireAgentMutation();
|
|
3834
|
+
try {
|
|
3835
|
+
const patch = await readJson(context.req);
|
|
3836
|
+
const result = updateAgent(root, id, patch, dependencies.loadWorkflow(root));
|
|
3837
|
+
dependencies.broadcast?.();
|
|
3838
|
+
sendJson(context.res, 200, result);
|
|
3839
|
+
return true;
|
|
3840
|
+
} finally {
|
|
3841
|
+
release();
|
|
3842
|
+
}
|
|
3843
|
+
}
|
|
3844
|
+
if (context.method === "DELETE") {
|
|
3845
|
+
const release = await acquireAgentMutation();
|
|
3846
|
+
try {
|
|
3847
|
+
deleteAgent(root, id, dependencies.loadWorkflow(root));
|
|
3848
|
+
dependencies.broadcast?.();
|
|
3849
|
+
sendJson(context.res, 200, { ok: true });
|
|
3850
|
+
return true;
|
|
3851
|
+
} finally {
|
|
3852
|
+
release();
|
|
3853
|
+
}
|
|
3854
|
+
}
|
|
3855
|
+
return false;
|
|
3856
|
+
} catch (error) {
|
|
3857
|
+
sendError(context.res, 400, error.message);
|
|
3858
|
+
return true;
|
|
3859
|
+
}
|
|
3860
|
+
};
|
|
3861
|
+
}
|
|
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
|
+
|
|
3503
3947
|
// src/flow-serve/client-assets.ts
|
|
3504
|
-
import { existsSync as
|
|
3505
|
-
import { dirname, extname, join as
|
|
3948
|
+
import { existsSync as existsSync11, readFileSync as readFileSync10 } from "fs";
|
|
3949
|
+
import { dirname, extname, join as join10 } from "path";
|
|
3506
3950
|
import { fileURLToPath } from "url";
|
|
3507
3951
|
var ClientAssets = class {
|
|
3508
3952
|
constructor(root) {
|
|
@@ -3514,18 +3958,18 @@ var ClientAssets = class {
|
|
|
3514
3958
|
if (!this.clientDir) {
|
|
3515
3959
|
const moduleDir = dirname(fileURLToPath(import.meta.url));
|
|
3516
3960
|
const candidates = [
|
|
3517
|
-
|
|
3518
|
-
|
|
3519
|
-
|
|
3961
|
+
join10(moduleDir, "client"),
|
|
3962
|
+
join10(this.root, "packages", "client", "dist"),
|
|
3963
|
+
join10(moduleDir, "..", "..", "..", "client", "dist")
|
|
3520
3964
|
];
|
|
3521
|
-
this.clientDir = candidates.find((directory) =>
|
|
3965
|
+
this.clientDir = candidates.find((directory) => existsSync11(join10(directory, "index.html"))) ?? null;
|
|
3522
3966
|
}
|
|
3523
3967
|
if (!this.clientDir) {
|
|
3524
3968
|
this.proxyToVite(req, res);
|
|
3525
3969
|
return;
|
|
3526
3970
|
}
|
|
3527
|
-
let filePath =
|
|
3528
|
-
if (!
|
|
3971
|
+
let filePath = join10(this.clientDir, path === "/" ? "index.html" : path);
|
|
3972
|
+
if (!existsSync11(filePath)) filePath = join10(this.clientDir, "index.html");
|
|
3529
3973
|
const mime = {
|
|
3530
3974
|
".html": "text/html; charset=utf-8",
|
|
3531
3975
|
".js": "application/javascript; charset=utf-8",
|
|
@@ -3561,8 +4005,8 @@ var ClientAssets = class {
|
|
|
3561
4005
|
};
|
|
3562
4006
|
|
|
3563
4007
|
// src/flow-serve/automation-runtime.ts
|
|
3564
|
-
import { existsSync as
|
|
3565
|
-
import { join as
|
|
4008
|
+
import { existsSync as existsSync12, watch } from "fs";
|
|
4009
|
+
import { join as join11 } from "path";
|
|
3566
4010
|
var AutomationRuntime = class {
|
|
3567
4011
|
constructor(dependencies) {
|
|
3568
4012
|
this.dependencies = dependencies;
|
|
@@ -3594,8 +4038,8 @@ var AutomationRuntime = class {
|
|
|
3594
4038
|
this.binding = void 0;
|
|
3595
4039
|
}
|
|
3596
4040
|
armWatchers(binding) {
|
|
3597
|
-
const workflowPath =
|
|
3598
|
-
const pathExists = this.dependencies.pathExists ??
|
|
4041
|
+
const workflowPath = join11(binding.workspaceDir, "workflow.json");
|
|
4042
|
+
const pathExists = this.dependencies.pathExists ?? existsSync12;
|
|
3599
4043
|
const watchPath = this.dependencies.watchPath ?? ((path, options, listener) => watch(path, options, listener));
|
|
3600
4044
|
if (pathExists(workflowPath)) {
|
|
3601
4045
|
try {
|
|
@@ -3612,7 +4056,7 @@ var AutomationRuntime = class {
|
|
|
3612
4056
|
} catch {
|
|
3613
4057
|
}
|
|
3614
4058
|
}
|
|
3615
|
-
const specsPath =
|
|
4059
|
+
const specsPath = join11(binding.workspaceDir, "specs");
|
|
3616
4060
|
if (pathExists(specsPath)) {
|
|
3617
4061
|
try {
|
|
3618
4062
|
this.safeLogAction(binding.workspaceRoot, "specs-watch", "armed", {
|
|
@@ -3690,14 +4134,149 @@ var AutomationRuntime = class {
|
|
|
3690
4134
|
|
|
3691
4135
|
// src/orchestrator/orchestrator.ts
|
|
3692
4136
|
import {
|
|
3693
|
-
existsSync as
|
|
3694
|
-
mkdirSync as
|
|
4137
|
+
existsSync as existsSync13,
|
|
4138
|
+
mkdirSync as mkdirSync3,
|
|
3695
4139
|
readFileSync as readFileSync11,
|
|
3696
|
-
writeFileSync as
|
|
4140
|
+
writeFileSync as writeFileSync4,
|
|
3697
4141
|
unlinkSync as unlinkSync2,
|
|
3698
4142
|
readdirSync as readdirSync6
|
|
3699
4143
|
} from "fs";
|
|
3700
|
-
import { join as
|
|
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
|
|
3701
4280
|
var DEFAULT_HEARTBEAT_TIMEOUT = 6e4;
|
|
3702
4281
|
var DEFAULT_MAX_EXECUTION_TIME = 18e5;
|
|
3703
4282
|
var RECLAIM_INTERVAL = 6e4;
|
|
@@ -3709,12 +4288,14 @@ var Orchestrator = class {
|
|
|
3709
4288
|
heartbeats = /* @__PURE__ */ new Map();
|
|
3710
4289
|
stageExecutorPreferences = /* @__PURE__ */ new Map();
|
|
3711
4290
|
onHandoffEvent;
|
|
4291
|
+
gateway;
|
|
3712
4292
|
reclaimTimer = null;
|
|
3713
4293
|
constructor(config) {
|
|
3714
4294
|
this.root = config.root;
|
|
3715
4295
|
this.manifest = loadHarness(resolveHarnessRoot(config.root, DEFAULT_HARNESS_VERSION));
|
|
3716
4296
|
this.gateChecker = new GateChecker(config.root, this.manifest ?? void 0);
|
|
3717
4297
|
this.onHandoffEvent = config.onHandoffEvent;
|
|
4298
|
+
this.gateway = config.gateway ?? new CanonicalOrchestratorGateway();
|
|
3718
4299
|
}
|
|
3719
4300
|
registerExecutor(executor) {
|
|
3720
4301
|
this.executors.set(executor.id, executor);
|
|
@@ -3771,7 +4352,7 @@ var Orchestrator = class {
|
|
|
3771
4352
|
}
|
|
3772
4353
|
return null;
|
|
3773
4354
|
}
|
|
3774
|
-
emitHandoff(payload) {
|
|
4355
|
+
async emitHandoff(payload) {
|
|
3775
4356
|
const workflow = loadWorkflow(this.root);
|
|
3776
4357
|
if (!workflow) {
|
|
3777
4358
|
return { success: false, reason: "No workflow found" };
|
|
@@ -3791,30 +4372,9 @@ var Orchestrator = class {
|
|
|
3791
4372
|
return { success: false, reason: gateResult.reason };
|
|
3792
4373
|
}
|
|
3793
4374
|
}
|
|
3794
|
-
|
|
3795
|
-
|
|
3796
|
-
|
|
3797
|
-
summary: payload.summary,
|
|
3798
|
-
evidence: payload.evidence,
|
|
3799
|
-
timestamp: payload.timestamp,
|
|
3800
|
-
expiresAt: payload.expiresAt,
|
|
3801
|
-
executorId: payload.executorId
|
|
3802
|
-
};
|
|
3803
|
-
workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
3804
|
-
writeWorkflow(this.root, {
|
|
3805
|
-
workflow,
|
|
3806
|
-
source: "orchestrator",
|
|
3807
|
-
primaryItemId: item.id,
|
|
3808
|
-
skipSitrep: true
|
|
3809
|
-
});
|
|
3810
|
-
this.writeHandoffFile(item);
|
|
3811
|
-
logEntry(this.root, "handoff_emitted", `Handoff emitted to ${payload.to}`, {
|
|
3812
|
-
itemId: payload.itemId,
|
|
3813
|
-
from: payload.from,
|
|
3814
|
-
to: payload.to,
|
|
3815
|
-
summary: payload.summary,
|
|
3816
|
-
evidence: payload.evidence
|
|
3817
|
-
});
|
|
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 });
|
|
3818
4378
|
if (this.onHandoffEvent) {
|
|
3819
4379
|
this.onHandoffEvent({
|
|
3820
4380
|
itemId: payload.itemId,
|
|
@@ -3830,7 +4390,7 @@ var Orchestrator = class {
|
|
|
3830
4390
|
}
|
|
3831
4391
|
return { success: true };
|
|
3832
4392
|
}
|
|
3833
|
-
autoClaim(itemId, executorId, agentId) {
|
|
4393
|
+
async autoClaim(itemId, executorId, agentId) {
|
|
3834
4394
|
const workflow = loadWorkflow(this.root);
|
|
3835
4395
|
if (!workflow) {
|
|
3836
4396
|
return { success: false, reason: "No workflow found" };
|
|
@@ -3855,25 +4415,10 @@ var Orchestrator = class {
|
|
|
3855
4415
|
};
|
|
3856
4416
|
}
|
|
3857
4417
|
this.writeFileLock(itemId, { executor: executorId, claimedAt: Date.now() });
|
|
3858
|
-
item.claimedBy = executorId;
|
|
3859
|
-
item.claimedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
3860
4418
|
const handoffData = item.handoff && item.handoff.to === agentId ? { ...item.handoff } : null;
|
|
3861
|
-
|
|
3862
|
-
|
|
3863
|
-
|
|
3864
|
-
}
|
|
3865
|
-
workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
3866
|
-
writeWorkflow(this.root, {
|
|
3867
|
-
workflow,
|
|
3868
|
-
source: "orchestrator",
|
|
3869
|
-
primaryItemId: itemId,
|
|
3870
|
-
skipSitrep: true
|
|
3871
|
-
});
|
|
3872
|
-
logEntry(this.root, "item_claim", `Claimed by ${executorId}`, {
|
|
3873
|
-
itemId,
|
|
3874
|
-
executorId,
|
|
3875
|
-
agentId
|
|
3876
|
-
});
|
|
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);
|
|
3877
4422
|
if (this.onHandoffEvent && handoffData) {
|
|
3878
4423
|
this.onHandoffEvent({
|
|
3879
4424
|
itemId,
|
|
@@ -3894,11 +4439,11 @@ var Orchestrator = class {
|
|
|
3894
4439
|
if (!workflow) return null;
|
|
3895
4440
|
const item = workflow.items.find((i) => i.id === itemId);
|
|
3896
4441
|
if (!item) return null;
|
|
3897
|
-
const snapshot =
|
|
4442
|
+
const snapshot = resolveDirection(this.root, { itemId });
|
|
3898
4443
|
let specContent = null;
|
|
3899
4444
|
if (item.spec) {
|
|
3900
|
-
const specPath =
|
|
3901
|
-
if (
|
|
4445
|
+
const specPath = join12(getLetraDir2(this.root), "specs", item.spec, "spec.md");
|
|
4446
|
+
if (existsSync13(specPath)) {
|
|
3902
4447
|
specContent = readFileSync11(specPath, "utf-8");
|
|
3903
4448
|
}
|
|
3904
4449
|
}
|
|
@@ -3941,29 +4486,19 @@ var Orchestrator = class {
|
|
|
3941
4486
|
isOnline: true
|
|
3942
4487
|
});
|
|
3943
4488
|
}
|
|
3944
|
-
reclaimStaleItems() {
|
|
4489
|
+
async reclaimStaleItems() {
|
|
3945
4490
|
const workflow = loadWorkflow(this.root);
|
|
3946
4491
|
if (!workflow) return [];
|
|
3947
4492
|
const reclaimed = [];
|
|
3948
4493
|
const now = Date.now();
|
|
3949
4494
|
const lockFiles = this.listLockFiles();
|
|
3950
4495
|
for (const [itemId, lock] of lockFiles) {
|
|
3951
|
-
const
|
|
3952
|
-
const
|
|
3953
|
-
|
|
3954
|
-
|
|
3955
|
-
const item = workflow.items.find((i) => i.id === itemId);
|
|
3956
|
-
if (item) {
|
|
3957
|
-
item.claimedBy = void 0;
|
|
3958
|
-
item.claimedAt = void 0;
|
|
3959
|
-
reclaimed.push(itemId);
|
|
3960
|
-
logEntry(this.root, "item_reclaim", `Item reclaimed (timeout ${age}ms)`, {
|
|
3961
|
-
itemId,
|
|
3962
|
-
executorId: lock.executor
|
|
3963
|
-
});
|
|
3964
|
-
}
|
|
3965
|
-
this.deleteFileLock(itemId);
|
|
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);
|
|
3966
4500
|
}
|
|
4501
|
+
if (!item || Number.isFinite(expiry) && now >= expiry) this.deleteFileLock(itemId);
|
|
3967
4502
|
}
|
|
3968
4503
|
for (const [executorId, heartbeat] of this.heartbeats) {
|
|
3969
4504
|
const executor = this.executors.get(executorId);
|
|
@@ -3979,19 +4514,15 @@ var Orchestrator = class {
|
|
|
3979
4514
|
}
|
|
3980
4515
|
}
|
|
3981
4516
|
if (reclaimed.length > 0) {
|
|
3982
|
-
|
|
3983
|
-
|
|
3984
|
-
workflow,
|
|
3985
|
-
source: "orchestrator-reclaim",
|
|
3986
|
-
skipSitrep: true
|
|
3987
|
-
});
|
|
4517
|
+
const persisted = await this.gateway.reclaim(this.root, reclaimed);
|
|
4518
|
+
if (!persisted.ok) return [];
|
|
3988
4519
|
}
|
|
3989
4520
|
return reclaimed;
|
|
3990
4521
|
}
|
|
3991
4522
|
startReclaimTimer() {
|
|
3992
4523
|
if (this.reclaimTimer) return;
|
|
3993
4524
|
this.reclaimTimer = setInterval(() => {
|
|
3994
|
-
this.reclaimStaleItems();
|
|
4525
|
+
void this.reclaimStaleItems().catch(() => void 0);
|
|
3995
4526
|
}, RECLAIM_INTERVAL);
|
|
3996
4527
|
}
|
|
3997
4528
|
stopReclaimTimer() {
|
|
@@ -4007,11 +4538,11 @@ var Orchestrator = class {
|
|
|
4007
4538
|
return Array.from(this.heartbeats.values());
|
|
4008
4539
|
}
|
|
4009
4540
|
getLocksDir() {
|
|
4010
|
-
return
|
|
4541
|
+
return join12(this.root, ".letra", "locks");
|
|
4011
4542
|
}
|
|
4012
4543
|
readFileLock(itemId) {
|
|
4013
|
-
const lockPath =
|
|
4014
|
-
if (!
|
|
4544
|
+
const lockPath = join12(this.getLocksDir(), `${itemId}.lock`);
|
|
4545
|
+
if (!existsSync13(lockPath)) return null;
|
|
4015
4546
|
try {
|
|
4016
4547
|
const data = JSON.parse(readFileSync11(lockPath, "utf-8"));
|
|
4017
4548
|
return { executor: data.executor, claimedAt: data.claimedAt };
|
|
@@ -4021,19 +4552,19 @@ var Orchestrator = class {
|
|
|
4021
4552
|
}
|
|
4022
4553
|
writeFileLock(itemId, lock) {
|
|
4023
4554
|
const dir = this.getLocksDir();
|
|
4024
|
-
|
|
4025
|
-
const lockPath =
|
|
4026
|
-
|
|
4555
|
+
mkdirSync3(dir, { recursive: true });
|
|
4556
|
+
const lockPath = join12(dir, `${itemId}.lock`);
|
|
4557
|
+
writeFileSync4(lockPath, JSON.stringify(lock, null, 2));
|
|
4027
4558
|
}
|
|
4028
4559
|
deleteFileLock(itemId) {
|
|
4029
|
-
const lockPath =
|
|
4030
|
-
if (
|
|
4560
|
+
const lockPath = join12(this.getLocksDir(), `${itemId}.lock`);
|
|
4561
|
+
if (existsSync13(lockPath)) {
|
|
4031
4562
|
unlinkSync2(lockPath);
|
|
4032
4563
|
}
|
|
4033
4564
|
}
|
|
4034
4565
|
listLockFiles() {
|
|
4035
4566
|
const dir = this.getLocksDir();
|
|
4036
|
-
if (!
|
|
4567
|
+
if (!existsSync13(dir)) return /* @__PURE__ */ new Map();
|
|
4037
4568
|
const files = readdirSync6(dir).filter((f) => f.endsWith(".lock"));
|
|
4038
4569
|
const locks = /* @__PURE__ */ new Map();
|
|
4039
4570
|
for (const file of files) {
|
|
@@ -4044,14 +4575,14 @@ var Orchestrator = class {
|
|
|
4044
4575
|
return locks;
|
|
4045
4576
|
}
|
|
4046
4577
|
getHandoffsDir() {
|
|
4047
|
-
return
|
|
4578
|
+
return join12(this.root, ".letra", "handoffs");
|
|
4048
4579
|
}
|
|
4049
4580
|
writeHandoffFile(item) {
|
|
4050
4581
|
if (!item.handoff) return;
|
|
4051
4582
|
const dir = this.getHandoffsDir();
|
|
4052
|
-
|
|
4053
|
-
const filePath =
|
|
4054
|
-
|
|
4583
|
+
mkdirSync3(dir, { recursive: true });
|
|
4584
|
+
const filePath = join12(dir, `${item.id}.json`);
|
|
4585
|
+
writeFileSync4(
|
|
4055
4586
|
filePath,
|
|
4056
4587
|
JSON.stringify(
|
|
4057
4588
|
{
|
|
@@ -4070,12 +4601,12 @@ var Orchestrator = class {
|
|
|
4070
4601
|
);
|
|
4071
4602
|
}
|
|
4072
4603
|
removeHandoffFile(itemId) {
|
|
4073
|
-
const filePath =
|
|
4074
|
-
if (
|
|
4604
|
+
const filePath = join12(this.getHandoffsDir(), `${itemId}.json`);
|
|
4605
|
+
if (existsSync13(filePath)) {
|
|
4075
4606
|
unlinkSync2(filePath);
|
|
4076
4607
|
}
|
|
4077
4608
|
}
|
|
4078
|
-
retryHandoff(itemId) {
|
|
4609
|
+
async retryHandoff(itemId) {
|
|
4079
4610
|
const workflow = loadWorkflow(this.root);
|
|
4080
4611
|
if (!workflow) {
|
|
4081
4612
|
return { success: false, reason: "No workflow found" };
|
|
@@ -4090,6 +4621,23 @@ var Orchestrator = class {
|
|
|
4090
4621
|
if (new Date(item.handoff.expiresAt) >= /* @__PURE__ */ new Date()) {
|
|
4091
4622
|
return { success: false, reason: `Handoff for ${itemId} has not expired yet` };
|
|
4092
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
|
+
}
|
|
4093
4641
|
const previousTo = item.handoff.to;
|
|
4094
4642
|
const previousFrom = item.handoff.from;
|
|
4095
4643
|
const summary = item.handoff.summary;
|
|
@@ -4111,7 +4659,8 @@ var Orchestrator = class {
|
|
|
4111
4659
|
const ttlMinutes = 30;
|
|
4112
4660
|
const now = /* @__PURE__ */ new Date();
|
|
4113
4661
|
const expiresAt = new Date(now.getTime() + ttlMinutes * 60 * 1e3);
|
|
4114
|
-
|
|
4662
|
+
const nextHandoff2 = {
|
|
4663
|
+
itemId,
|
|
4115
4664
|
from: previousFrom,
|
|
4116
4665
|
to: previousTo,
|
|
4117
4666
|
summary,
|
|
@@ -4120,26 +4669,14 @@ var Orchestrator = class {
|
|
|
4120
4669
|
expiresAt: expiresAt.toISOString(),
|
|
4121
4670
|
executorId: nextExecutor.id
|
|
4122
4671
|
};
|
|
4123
|
-
|
|
4124
|
-
|
|
4125
|
-
|
|
4126
|
-
|
|
4127
|
-
|
|
4128
|
-
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}`
|
|
4129
4677
|
});
|
|
4130
|
-
|
|
4131
|
-
|
|
4132
|
-
this.root,
|
|
4133
|
-
"handoff_emitted",
|
|
4134
|
-
`Handoff re-emitted to ${previousTo} (retry via ${nextExecutor.id})`,
|
|
4135
|
-
{
|
|
4136
|
-
itemId,
|
|
4137
|
-
from: previousFrom,
|
|
4138
|
-
to: previousTo,
|
|
4139
|
-
executorId: nextExecutor.id,
|
|
4140
|
-
retry: true
|
|
4141
|
-
}
|
|
4142
|
-
);
|
|
4678
|
+
if (!persisted.ok) return { success: false, reason: persisted.reason };
|
|
4679
|
+
this.writeHandoffFile({ ...item, handoff: nextHandoff2 });
|
|
4143
4680
|
if (this.onHandoffEvent) {
|
|
4144
4681
|
this.onHandoffEvent({
|
|
4145
4682
|
itemId,
|
|
@@ -4157,13 +4694,12 @@ var Orchestrator = class {
|
|
|
4157
4694
|
}
|
|
4158
4695
|
getPendingHandoffFiles() {
|
|
4159
4696
|
const dir = this.getHandoffsDir();
|
|
4160
|
-
if (!
|
|
4161
|
-
const
|
|
4162
|
-
const files = readdirSync7(dir).filter((f) => f.endsWith(".json"));
|
|
4697
|
+
if (!existsSync13(dir)) return [];
|
|
4698
|
+
const files = readdirSync6(dir).filter((f) => f.endsWith(".json"));
|
|
4163
4699
|
const now = /* @__PURE__ */ new Date();
|
|
4164
4700
|
return files.flatMap((file) => {
|
|
4165
4701
|
try {
|
|
4166
|
-
const data = JSON.parse(readFileSync11(
|
|
4702
|
+
const data = JSON.parse(readFileSync11(join12(dir, file), "utf-8"));
|
|
4167
4703
|
if (new Date(data.expiresAt) < now) return [];
|
|
4168
4704
|
return [{ itemId: data.itemId, to: data.to, expiresAt: data.expiresAt }];
|
|
4169
4705
|
} catch {
|
|
@@ -4173,6 +4709,442 @@ var Orchestrator = class {
|
|
|
4173
4709
|
}
|
|
4174
4710
|
};
|
|
4175
4711
|
|
|
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
|
+
}
|
|
4736
|
+
var PersistentDispatcher = class {
|
|
4737
|
+
constructor(store, executors, intervalMs = 3e4, options = {}) {
|
|
4738
|
+
this.store = store;
|
|
4739
|
+
this.executors = executors;
|
|
4740
|
+
this.intervalMs = intervalMs;
|
|
4741
|
+
this.options = options;
|
|
4742
|
+
}
|
|
4743
|
+
store;
|
|
4744
|
+
executors;
|
|
4745
|
+
intervalMs;
|
|
4746
|
+
options;
|
|
4747
|
+
timer;
|
|
4748
|
+
running = false;
|
|
4749
|
+
start() {
|
|
4750
|
+
if (this.timer) return;
|
|
4751
|
+
void this.dispatch();
|
|
4752
|
+
this.timer = setInterval(() => void this.dispatch(), this.intervalMs);
|
|
4753
|
+
}
|
|
4754
|
+
stop() {
|
|
4755
|
+
if (this.timer) clearInterval(this.timer);
|
|
4756
|
+
this.timer = void 0;
|
|
4757
|
+
}
|
|
4758
|
+
async dispatch() {
|
|
4759
|
+
if (this.running) return [];
|
|
4760
|
+
this.running = true;
|
|
4761
|
+
try {
|
|
4762
|
+
const workflow = this.store.loadWorkflow();
|
|
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
|
+
}
|
|
4774
|
+
for (const item of workflow.items) {
|
|
4775
|
+
if (!item.handoff || item.claimedBy) continue;
|
|
4776
|
+
const stage = workflow.stages.find((entry) => entry.id === item.stage);
|
|
4777
|
+
if (!stage) continue;
|
|
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" };
|
|
4782
|
+
results.push(result);
|
|
4783
|
+
this.options.onResult?.(result);
|
|
4784
|
+
continue;
|
|
4785
|
+
}
|
|
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
|
+
};
|
|
4792
|
+
results.push(result);
|
|
4793
|
+
this.options.onResult?.(result);
|
|
4794
|
+
continue;
|
|
4795
|
+
}
|
|
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];
|
|
4818
|
+
if (!executor) {
|
|
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);
|
|
4827
|
+
continue;
|
|
4828
|
+
}
|
|
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;
|
|
4856
|
+
}
|
|
4857
|
+
const claimed = started.nextDirection.item ?? { ...item, claimedBy: actor, claimExecutorId: executor.id };
|
|
4858
|
+
try {
|
|
4859
|
+
if (typeof executor.heartbeat === "function") {
|
|
4860
|
+
await executor.heartbeat();
|
|
4861
|
+
}
|
|
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` })
|
|
4879
|
+
);
|
|
4880
|
+
if (securityReview.outcome === "rejected") throw new SecurityReviewOperationError(securityReview);
|
|
4881
|
+
}
|
|
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
|
+
}
|
|
4925
|
+
const result = execution.success ? { itemId: item.id, status: "dispatched" } : { itemId: item.id, status: "failed", reason: execution.error ?? execution.output };
|
|
4926
|
+
results.push(result);
|
|
4927
|
+
this.options.onResult?.(result);
|
|
4928
|
+
} catch (error) {
|
|
4929
|
+
const message = 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) };
|
|
4934
|
+
results.push(result);
|
|
4935
|
+
this.options.onResult?.(result);
|
|
4936
|
+
}
|
|
4937
|
+
}
|
|
4938
|
+
return results;
|
|
4939
|
+
} finally {
|
|
4940
|
+
this.running = false;
|
|
4941
|
+
}
|
|
4942
|
+
}
|
|
4943
|
+
};
|
|
4944
|
+
|
|
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);
|
|
5039
|
+
return {
|
|
5040
|
+
id,
|
|
5041
|
+
label: "Codex CLI",
|
|
5042
|
+
capabilities: options.capabilities,
|
|
5043
|
+
status: available ? "online" : "offline",
|
|
5044
|
+
heartbeat: async () => void 0,
|
|
5045
|
+
async execute(context) {
|
|
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
|
+
}
|
|
5076
|
+
}
|
|
5077
|
+
};
|
|
5078
|
+
}
|
|
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
|
+
|
|
4176
5148
|
// src/commands/flow-serve.ts
|
|
4177
5149
|
var DEFAULT_PORT = 3e3;
|
|
4178
5150
|
function resolveHarnessWithShared(root) {
|
|
@@ -4184,6 +5156,7 @@ var FlowServer = class {
|
|
|
4184
5156
|
server;
|
|
4185
5157
|
events = new FlowServerEvents();
|
|
4186
5158
|
router = new FlowServerRouter();
|
|
5159
|
+
humanSessions;
|
|
4187
5160
|
clientAssets;
|
|
4188
5161
|
automationRuntime;
|
|
4189
5162
|
orchestrator;
|
|
@@ -4193,22 +5166,30 @@ var FlowServer = class {
|
|
|
4193
5166
|
resolution;
|
|
4194
5167
|
activeWorkspaceRoot;
|
|
4195
5168
|
activeDirectory = null;
|
|
4196
|
-
|
|
5169
|
+
dispatcher;
|
|
5170
|
+
runtimeExecutors = [];
|
|
5171
|
+
autopilotEnabled;
|
|
5172
|
+
autopilotUpdatedAt = null;
|
|
5173
|
+
options;
|
|
5174
|
+
constructor(root, port = DEFAULT_PORT, options = {}) {
|
|
5175
|
+
this.options = options;
|
|
5176
|
+
this.autopilotEnabled = options.autopilot === true;
|
|
4197
5177
|
this.clientAssets = new ClientAssets(root);
|
|
4198
5178
|
this.port = port;
|
|
4199
5179
|
this.resolution = resolveWorkspaceRoot(root);
|
|
4200
|
-
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);
|
|
4201
5182
|
this.loadWorkflow = (overrideRoot) => loadWorkflow(overrideRoot ?? this.activeWorkspaceRoot);
|
|
4202
5183
|
this.engine = new DiagnosticEngine(this.activeWorkspaceRoot);
|
|
4203
5184
|
this.automationRuntime = new AutomationRuntime({
|
|
4204
5185
|
runDiagnostics: runDiagnosticsAndSyncHealth,
|
|
4205
5186
|
broadcastWorkflow: () => this.broadcast(),
|
|
4206
5187
|
broadcastDiagnostics: (output) => this.broadcastDiagnostics(output),
|
|
4207
|
-
logAction: (workspaceRoot, actionId, outcome,
|
|
5188
|
+
logAction: (workspaceRoot, actionId, outcome, options2) => {
|
|
4208
5189
|
logSystemAction(workspaceRoot, actionId, {
|
|
4209
5190
|
outcome,
|
|
4210
|
-
error:
|
|
4211
|
-
details:
|
|
5191
|
+
error: options2?.error,
|
|
5192
|
+
details: options2?.details
|
|
4212
5193
|
});
|
|
4213
5194
|
this.events.broadcastSystemActionUpdated({ actionId, outcome });
|
|
4214
5195
|
}
|
|
@@ -4218,6 +5199,7 @@ var FlowServer = class {
|
|
|
4218
5199
|
onHandoffEvent: (payload) => this.events.broadcastHandoff(payload)
|
|
4219
5200
|
});
|
|
4220
5201
|
this.orchestrator.registerFromManifest();
|
|
5202
|
+
if (this.autopilotEnabled) this.dispatcher = this.createDispatcher();
|
|
4221
5203
|
this.router.register((context) => {
|
|
4222
5204
|
if (context.path !== "/events") return false;
|
|
4223
5205
|
this.events.handleSse(context.req, context.res);
|
|
@@ -4230,6 +5212,18 @@ var FlowServer = class {
|
|
|
4230
5212
|
writeFocusFile: writeFocusWithRecommendations,
|
|
4231
5213
|
logEntry,
|
|
4232
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),
|
|
4233
5227
|
broadcast: () => this.broadcast(),
|
|
4234
5228
|
fireWebhooks: (workspaceRoot, event, payload) => this.fireWebhooks(workspaceRoot, event, payload)
|
|
4235
5229
|
})
|
|
@@ -4255,7 +5249,8 @@ var FlowServer = class {
|
|
|
4255
5249
|
getSummary,
|
|
4256
5250
|
getActiveEntries,
|
|
4257
5251
|
broadcast: () => this.broadcast(),
|
|
4258
|
-
broadcastDiagnostics: (output) => this.broadcastDiagnostics(output)
|
|
5252
|
+
broadcastDiagnostics: (output) => this.broadcastDiagnostics(output),
|
|
5253
|
+
inspectWorkspaceIntegrity
|
|
4259
5254
|
})
|
|
4260
5255
|
);
|
|
4261
5256
|
this.router.register(
|
|
@@ -4284,6 +5279,9 @@ var FlowServer = class {
|
|
|
4284
5279
|
detectWorkspaceName: detectProjectName,
|
|
4285
5280
|
loadHarness: (workspaceRoot) => loadHarness(resolveHarnessWithShared(workspaceRoot)),
|
|
4286
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),
|
|
4287
5285
|
broadcast: () => this.broadcast()
|
|
4288
5286
|
})
|
|
4289
5287
|
);
|
|
@@ -4338,10 +5336,169 @@ var FlowServer = class {
|
|
|
4338
5336
|
}
|
|
4339
5337
|
})
|
|
4340
5338
|
);
|
|
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);
|
|
5398
|
+
}
|
|
5399
|
+
createDispatcher() {
|
|
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;
|
|
5422
|
+
return new PersistentDispatcher(
|
|
5423
|
+
{
|
|
5424
|
+
loadWorkflow: () => {
|
|
5425
|
+
const workflow = this.loadWorkflow();
|
|
5426
|
+
if (!workflow) throw new Error("No workflow found for dispatcher");
|
|
5427
|
+
return workflow;
|
|
5428
|
+
},
|
|
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
|
+
}
|
|
5445
|
+
},
|
|
5446
|
+
() => executors,
|
|
5447
|
+
this.options.dispatcherIntervalMs ?? 3e4,
|
|
5448
|
+
{
|
|
5449
|
+
stageActors: (stageId) => {
|
|
5450
|
+
const templateId = this.loadWorkflow()?.template ?? "flow-main";
|
|
5451
|
+
return manifest?.flows[templateId]?.stages.find((stage) => stage.id === stageId)?.agents ?? [];
|
|
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
|
+
},
|
|
5483
|
+
blocksHandoff: (stage, item) => {
|
|
5484
|
+
const gate = stage.gate ? manifest?.gates[stage.gate] : void 0;
|
|
5485
|
+
const currentActor = (manifest?.flows[this.loadWorkflow()?.template ?? "flow-main"]?.stages.find((entry) => entry.id === stage.id)?.agents ?? stage.agents)?.[0];
|
|
5486
|
+
return gate?.type === "human" && gate.blocking === true && gate.blocksHandoff === true && item.handoff?.to !== currentActor;
|
|
5487
|
+
},
|
|
5488
|
+
onResult: (result) => {
|
|
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
|
+
});
|
|
5493
|
+
this.broadcast();
|
|
5494
|
+
}
|
|
5495
|
+
}
|
|
5496
|
+
);
|
|
4341
5497
|
}
|
|
4342
5498
|
switchWorkspace(workspaceRoot) {
|
|
4343
5499
|
this.activeWorkspaceRoot = workspaceRoot;
|
|
4344
5500
|
this.activeDirectory = null;
|
|
5501
|
+
this.runtimeExecutors = [];
|
|
4345
5502
|
this.resolution = resolveWorkspaceRoot(workspaceRoot);
|
|
4346
5503
|
this.loadWorkflow = (overrideRoot) => loadWorkflow(overrideRoot ?? this.activeWorkspaceRoot);
|
|
4347
5504
|
this.engine = new DiagnosticEngine(this.activeWorkspaceRoot);
|
|
@@ -4351,7 +5508,11 @@ var FlowServer = class {
|
|
|
4351
5508
|
onHandoffEvent: (payload) => this.events.broadcastHandoff(payload)
|
|
4352
5509
|
});
|
|
4353
5510
|
this.orchestrator.registerFromManifest();
|
|
4354
|
-
this.
|
|
5511
|
+
if (this.autopilotEnabled) {
|
|
5512
|
+
this.dispatcher?.stop();
|
|
5513
|
+
this.dispatcher = this.createDispatcher();
|
|
5514
|
+
this.dispatcher.start();
|
|
5515
|
+
}
|
|
4355
5516
|
this.broadcast();
|
|
4356
5517
|
}
|
|
4357
5518
|
switchDirectory(directory) {
|
|
@@ -4372,6 +5533,7 @@ var FlowServer = class {
|
|
|
4372
5533
|
};
|
|
4373
5534
|
}
|
|
4374
5535
|
handleRequest = async (req, res) => {
|
|
5536
|
+
this.humanSessions.establishNavigationSession(req, res);
|
|
4375
5537
|
const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
|
|
4376
5538
|
const path = url.pathname;
|
|
4377
5539
|
const requestRoot = this.workspaceRootFor(url);
|
|
@@ -4432,7 +5594,7 @@ var FlowServer = class {
|
|
|
4432
5594
|
this.server = createServer(this.handleRequest);
|
|
4433
5595
|
this.server.listen(this.port, () => {
|
|
4434
5596
|
this.automationRuntime.start(this.automationBinding());
|
|
4435
|
-
this.
|
|
5597
|
+
this.dispatcher?.start();
|
|
4436
5598
|
resolve8();
|
|
4437
5599
|
});
|
|
4438
5600
|
this.server.on("error", reject);
|
|
@@ -4440,7 +5602,7 @@ var FlowServer = class {
|
|
|
4440
5602
|
}
|
|
4441
5603
|
stop() {
|
|
4442
5604
|
this.automationRuntime.stop();
|
|
4443
|
-
this.
|
|
5605
|
+
this.dispatcher?.stop();
|
|
4444
5606
|
if (this.server) this.server.close();
|
|
4445
5607
|
this.events.close();
|
|
4446
5608
|
}
|
|
@@ -4456,7 +5618,7 @@ async function flowServeAction(targetPath, options) {
|
|
|
4456
5618
|
console.log("No workflow found. Run 'letra flow init --quick' first");
|
|
4457
5619
|
return;
|
|
4458
5620
|
}
|
|
4459
|
-
const server = new FlowServer(root, port);
|
|
5621
|
+
const server = new FlowServer(root, port, { autopilot: options?.autopilot });
|
|
4460
5622
|
try {
|
|
4461
5623
|
await server.start();
|
|
4462
5624
|
console.log(`
|
|
@@ -4485,10 +5647,9 @@ async function flowServeAction(targetPath, options) {
|
|
|
4485
5647
|
|
|
4486
5648
|
export {
|
|
4487
5649
|
pulse_default,
|
|
4488
|
-
|
|
5650
|
+
sitrep_default,
|
|
4489
5651
|
buildActivityContext,
|
|
4490
5652
|
migrateCommand,
|
|
4491
|
-
sync_default,
|
|
4492
5653
|
FlowServer,
|
|
4493
5654
|
flowServeAction
|
|
4494
5655
|
};
|