@letra-ai/cli 0.6.2 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/chunk-2GRNAFBQ.js +5305 -0
  2. package/dist/{chunk-MJ2QXNH6.js → chunk-42RST74I.js} +1 -1
  3. package/dist/chunk-HC24XMPZ.js +269 -0
  4. package/dist/chunk-LUPN3TRC.js +554 -0
  5. package/dist/{chunk-URUC6ZZP.js → chunk-MUCIMQAU.js} +1735 -861
  6. package/dist/chunk-POGWTSEA.js +125 -0
  7. package/dist/chunk-TNF7XTFG.js +6178 -0
  8. package/dist/{chunk-BKAUN5QH.js → chunk-UMC5PDL2.js} +227 -33
  9. package/dist/{chunk-6HSUVCTR.js → chunk-YAQ2TKSK.js} +82 -30
  10. package/dist/client/assets/index-C-6kWNFi.js +232 -0
  11. package/dist/client/assets/index-QV-zN0V8.css +1 -0
  12. package/dist/client/index.html +2 -2
  13. package/dist/fallback-CXCCKHBA.js +56 -0
  14. package/dist/flow-serve-LFILD3EV.js +19 -0
  15. package/dist/{generate-UPFERQMD.js → generate-3R7POT7L.js} +4 -5
  16. package/dist/harness/default/v0.1.0/gates/all-acs-passing.yaml +1 -0
  17. package/dist/harness/default/v0.1.0/gates/has-spec-file.yaml +1 -0
  18. package/dist/harness/default/v0.1.1/gates/all-acs-passing.yaml +1 -0
  19. package/dist/harness/default/v0.1.1/gates/has-spec-file.yaml +1 -0
  20. package/dist/harness/default/v0.1.2/gates/all-acs-passing.yaml +1 -0
  21. package/dist/harness/default/v0.1.2/gates/has-spec-file.yaml +1 -0
  22. package/dist/harness/default/v0.1.3/gates/all-acs-passing.yaml +1 -0
  23. package/dist/harness/default/v0.1.3/gates/has-spec-file.yaml +1 -0
  24. package/dist/harness/default/v0.2.0/executors/registry.yaml +17 -0
  25. package/dist/harness/default/v0.2.0/flows/flow-main.yaml +81 -3
  26. package/dist/harness/default/v0.2.0/gates/code-reviewed.yaml +1 -0
  27. package/dist/harness/default/v0.2.0/gates/human-approved.yaml +1 -0
  28. package/dist/harness/default/v0.2.0/gates/security-clear.yaml +1 -0
  29. package/dist/{health-record-YDVXEVLR.js → health-record-JO2ZTIMR.js} +2 -2
  30. package/dist/index.js +2284 -1168
  31. package/dist/{push-VJRSQGUD.js → push-2ZCQSOHF.js} +37 -49
  32. package/dist/server-WUYVNSH7.js +677 -0
  33. package/dist/service-SVEAXQBX.js +28 -0
  34. package/dist/service-TOBY3OHO.js +22 -0
  35. package/dist/service-USTAY5E3.js +62 -0
  36. package/dist/{session-log-WTQ5JBEN.js → session-log-X2Q4XKQN.js} +6 -2
  37. package/dist/specs-CQRB7LPA.js +21 -0
  38. package/dist/sync-LIVPQXEW.js +21 -0
  39. package/package.json +1 -1
  40. package/dist/chunk-DMOLJWWW.js +0 -3321
  41. package/dist/chunk-EDD55PWL.js +0 -119
  42. package/dist/chunk-H64RC3YS.js +0 -254
  43. package/dist/chunk-L6YKDTAQ.js +0 -275
  44. package/dist/chunk-OIHMDOIN.js +0 -1326
  45. package/dist/client/assets/index-EyRsq1SH.css +0 -1
  46. package/dist/client/assets/index-WfKR7Xp6.js +0 -232
  47. package/dist/fallback-MQLGS4KL.js +0 -46
  48. package/dist/flow-serve-G5MSSB3G.js +0 -18
  49. package/dist/focus-sync-3D3XWCTI.js +0 -17
  50. package/dist/server-P6GKRWDX.js +0 -423
  51. package/dist/service-2JN2KI4D.js +0 -29
  52. package/dist/sitrep-OKNZJICV.js +0 -16
@@ -0,0 +1,677 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ activityOperation,
4
+ claimOperation,
5
+ completeAcOperation,
6
+ createItemOperation,
7
+ linkItemSpecOperation,
8
+ migrateRunWorkflowOperation,
9
+ recordExecutionEvent,
10
+ requestHandoffOperation,
11
+ requestPassageOperation,
12
+ requestReworkOperation,
13
+ requestTransitionOperation,
14
+ runSecurityReviewOperation,
15
+ runValidationOperation,
16
+ submitEvidenceOperation
17
+ } from "./chunk-TNF7XTFG.js";
18
+ import {
19
+ assertOperationLevel,
20
+ createWorkflowDefinition,
21
+ createWorkflowDraft,
22
+ createWorkspaceBoundary,
23
+ getActiveWorkflowVersion,
24
+ getWorkflowDraft,
25
+ getWorkflowVersion,
26
+ invalidWorkspaceDiagnostic,
27
+ listWorkflowDefinitions,
28
+ listWorkflowVersions,
29
+ loadHarnessForWorkflow,
30
+ loadWorkflow,
31
+ publishWorkflowDraft,
32
+ resolveActiveFlowFor,
33
+ resolveAgentDirection,
34
+ resolveDirection,
35
+ rollbackWorkflowVersion,
36
+ signLocalOperation,
37
+ updateWorkflowDraft,
38
+ validateWorkflowContent
39
+ } from "./chunk-2GRNAFBQ.js";
40
+ import "./chunk-JMIC5NKB.js";
41
+ import {
42
+ getActiveEntries,
43
+ loadHealthRecord
44
+ } from "./chunk-42RST74I.js";
45
+ import {
46
+ readSpecCatalog
47
+ } from "./chunk-LUPN3TRC.js";
48
+ import {
49
+ logEntry
50
+ } from "./chunk-UMC5PDL2.js";
51
+ import {
52
+ getLetraDir2 as getLetraDir,
53
+ resolveWorkspaceRoot
54
+ } from "./chunk-YAQ2TKSK.js";
55
+ import "./chunk-PDX44BCA.js";
56
+
57
+ // src/mcp/server.ts
58
+ import { existsSync, readFileSync } from "fs";
59
+ import { createHash } from "crypto";
60
+ import { join, resolve } from "path";
61
+ import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
62
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
63
+ import { z } from "zod";
64
+ function jsonText(value) {
65
+ return {
66
+ content: [{ type: "text", text: JSON.stringify(value, null, 2) }]
67
+ };
68
+ }
69
+ function safeActiveSpec(root, boundary, direction = resolveDirection(root)) {
70
+ const name = direction.item?.spec ?? null;
71
+ if (!name || !/^[a-zA-Z0-9._-]+$/.test(name)) {
72
+ return { name, path: null, content: null };
73
+ }
74
+ const workspace = resolveWorkspaceRoot(root);
75
+ const candidateRoots = [resolve(workspace.dataDir, "specs"), resolve(workspace.workspaceRoot, "specs"), resolve(getLetraDir(root), "specs")];
76
+ const specsRoot = candidateRoots.find((candidate) => existsSync(resolve(candidate, name, "spec.md")) || existsSync(resolve(candidate, name, "acceptance.md"))) ?? candidateRoots[0];
77
+ const specDir = resolve(specsRoot, name);
78
+ if (specDir !== specsRoot && !specDir.startsWith(`${specsRoot}\\`) && !specDir.startsWith(`${specsRoot}/`)) {
79
+ return { name, path: null, content: null };
80
+ }
81
+ const specPath = join(specDir, "spec.md");
82
+ const acceptancePath = join(specDir, "acceptance.md");
83
+ const selectedPath = existsSync(acceptancePath) ? existsSync(specPath) ? specPath : acceptancePath : existsSync(specPath) ? specPath : null;
84
+ return {
85
+ name,
86
+ path: selectedPath ? boundary.assertPath(selectedPath).replace(/\\/g, "/") : null,
87
+ content: selectedPath ? readFileSync(boundary.assertPath(selectedPath), "utf-8") : null
88
+ };
89
+ }
90
+ function gateIdFromRef(gateRef) {
91
+ return gateRef.replace(/^.*[\\/]/, "").replace(/\.ya?ml$/, "");
92
+ }
93
+ function loadHarnessManifest(root) {
94
+ return loadHarnessForWorkflow(root, loadWorkflow(root));
95
+ }
96
+ function collectGates(root) {
97
+ const harness = loadHarnessManifest(root);
98
+ return harness ? Object.values(harness.gates) : [];
99
+ }
100
+ function collectRoles(root) {
101
+ const resolution = resolveActiveFlowFor(root);
102
+ return [...resolution.flow?.roles ?? []];
103
+ }
104
+ function healthPayload(root) {
105
+ const workspace = invalidWorkspaceDiagnostic(root);
106
+ if (workspace) return { reasonCode: workspace.code, workspace };
107
+ const record = loadHealthRecord(root);
108
+ return {
109
+ scannedAt: record.lastScanAt ?? null,
110
+ active: getActiveEntries(record)
111
+ };
112
+ }
113
+ function resourceText(uri, text, mimeType = "application/json") {
114
+ return {
115
+ contents: [{ uri, mimeType, text }]
116
+ };
117
+ }
118
+ function createLetraMcpServer(root, options = {}) {
119
+ const resolution = resolveWorkspaceRoot(root);
120
+ const workspaceDir = resolution.workspaceDir;
121
+ const boundary = createWorkspaceBoundary(
122
+ resolution.errorCode === "WORKSPACE_LINK_INVALID" ? resolution.locationPath : workspaceDir
123
+ );
124
+ const workspaceRoot = resolution.errorCode === "WORKSPACE_LINK_INVALID" ? resolution.locationPath : boundary.root;
125
+ const operationRoot = workspaceRoot;
126
+ const mcpActor = () => {
127
+ const client = server.server.getClientVersion();
128
+ return client?.name ? `mcp:${client.name}` : "mcp:unknown";
129
+ };
130
+ const requireHumanActor = () => {
131
+ const actor = options.resolveBoundHumanActor?.();
132
+ if (!actor?.startsWith("human:") || !existsSync(join(getLetraDir(workspaceRoot), "identity", "local.json"))) throw new Error("HUMAN_SESSION_REQUIRED");
133
+ assertOperationLevel(workspaceRoot, actor, "local");
134
+ return actor;
135
+ };
136
+ const auditedReads = /* @__PURE__ */ new Set();
137
+ const server = new McpServer({
138
+ name: "letra",
139
+ version: "0.6.2"
140
+ });
141
+ const readOnlyAnnotations = {
142
+ readOnlyHint: true,
143
+ destructiveHint: false,
144
+ idempotentHint: true,
145
+ openWorldHint: false
146
+ };
147
+ const verificationAnnotations = {
148
+ readOnlyHint: false,
149
+ destructiveHint: false,
150
+ idempotentHint: false,
151
+ openWorldHint: false
152
+ };
153
+ const mutationAnnotations = {
154
+ readOnlyHint: false,
155
+ destructiveHint: true,
156
+ idempotentHint: false,
157
+ openWorldHint: false
158
+ };
159
+ const expectedRevision = z.string().regex(/^sha256:[a-f0-9]{64}$/);
160
+ const reason = z.string().trim().min(1).max(500);
161
+ const auditActor = mcpActor;
162
+ const auditRead = (resource, direction = resolveAgentDirection(workspaceRoot)) => {
163
+ if (invalidWorkspaceDiagnostic(workspaceRoot)) return direction;
164
+ const key = `${resource}:${direction.revision}`;
165
+ if (auditedReads.has(key)) return direction;
166
+ const client = auditActor();
167
+ try {
168
+ logEntry(workspaceRoot, "agent_direction_read", `MCP read: ${resource}`, {
169
+ itemId: direction.item?.id,
170
+ acId: direction.pendingAC?.id,
171
+ details: {
172
+ adapter: "codex",
173
+ by: client,
174
+ resource,
175
+ revision: direction.revision,
176
+ reason: "Consulta de contexto pelo transporte MCP.",
177
+ outcome: "accepted"
178
+ }
179
+ });
180
+ auditedReads.add(key);
181
+ } catch {
182
+ direction.mode = "degraded";
183
+ direction.warnings = [
184
+ ...direction.warnings ?? [],
185
+ { code: "AUDIT_DEGRADED", message: "Auditoria indispon\xEDvel; dire\xE7\xE3o retornada sem registro." }
186
+ ];
187
+ }
188
+ return direction;
189
+ };
190
+ const blockedRead = () => {
191
+ const workspace = invalidWorkspaceDiagnostic(workspaceRoot);
192
+ return workspace ? { reasonCode: workspace.code, workspace } : null;
193
+ };
194
+ server.registerTool(
195
+ "get_direction",
196
+ {
197
+ description: "Retorna a dire\xE7\xE3o vigente e versionada do harness para o workspace atual.",
198
+ inputSchema: {
199
+ runId: z.string().optional(),
200
+ executorId: z.string().optional(),
201
+ itemId: z.string().optional()
202
+ },
203
+ annotations: readOnlyAnnotations
204
+ },
205
+ async (args) => {
206
+ const blocked = blockedRead();
207
+ if (blocked) return jsonText(blocked);
208
+ try {
209
+ return jsonText(auditRead("direction", resolveDirection(workspaceRoot, args)));
210
+ } catch (error) {
211
+ const message = error instanceof Error ? error.message : String(error);
212
+ return jsonText({ reasonCode: message.split(":")[0], message });
213
+ }
214
+ }
215
+ );
216
+ server.registerTool(
217
+ "get_active_spec",
218
+ {
219
+ description: "Retorna a spec ativa e seus crit\xE9rios de aceita\xE7\xE3o.",
220
+ inputSchema: { runId: z.string().optional(), executorId: z.string().optional(), itemId: z.string().optional() },
221
+ annotations: readOnlyAnnotations
222
+ },
223
+ async (args) => {
224
+ const blocked = blockedRead();
225
+ if (blocked) return jsonText(blocked);
226
+ try {
227
+ const direction = resolveDirection(workspaceRoot, args);
228
+ auditRead("active-spec", direction);
229
+ return jsonText(safeActiveSpec(workspaceRoot, boundary, direction));
230
+ } catch (error) {
231
+ const message = error instanceof Error ? error.message : String(error);
232
+ return jsonText({ reasonCode: message.split(":")[0], message });
233
+ }
234
+ }
235
+ );
236
+ server.registerTool(
237
+ "get_health",
238
+ {
239
+ description: "Retorna alertas operacionais ativos do workspace.",
240
+ annotations: readOnlyAnnotations
241
+ },
242
+ async () => {
243
+ const blocked = blockedRead();
244
+ if (blocked) return jsonText(blocked);
245
+ auditRead("health");
246
+ return jsonText(healthPayload(workspaceRoot));
247
+ }
248
+ );
249
+ server.registerTool(
250
+ "validate",
251
+ {
252
+ description: "Valida o workspace pela implementa\xE7\xE3o can\xF4nica e registra o resultado.",
253
+ inputSchema: {
254
+ itemId: z.string().regex(/^ITEM-\d+$/i).optional(),
255
+ runId: z.string().trim().min(1).optional(),
256
+ executorId: z.string().trim().min(1).optional(),
257
+ expectedRevision,
258
+ reason,
259
+ idempotencyKey: z.string().trim().min(1).max(200).optional()
260
+ },
261
+ annotations: verificationAnnotations
262
+ },
263
+ async (input) => jsonText(
264
+ await runValidationOperation(operationRoot, {
265
+ ...input,
266
+ actor: mcpActor()
267
+ })
268
+ )
269
+ );
270
+ server.registerTool(
271
+ "complete_ac",
272
+ {
273
+ description: "Conclui o AC vigente ap\xF3s validar revis\xE3o e evid\xEAncia de regress\xE3o.",
274
+ inputSchema: {
275
+ itemId: z.string().regex(/^ITEM-\d+$/i),
276
+ acId: z.string().regex(/^AC\d+(?:\.\d+)*$/i),
277
+ executorId: z.string().trim().min(1).optional(),
278
+ runId: z.string().trim().min(1).optional(),
279
+ expectedRevision,
280
+ evidence: z.array(z.string().trim().min(1).max(500)).max(20),
281
+ reason,
282
+ idempotencyKey: z.string().trim().min(1).max(200).optional()
283
+ },
284
+ annotations: mutationAnnotations
285
+ },
286
+ async (input) => jsonText(
287
+ completeAcOperation(operationRoot, {
288
+ ...input,
289
+ actor: mcpActor()
290
+ })
291
+ )
292
+ );
293
+ server.registerTool(
294
+ "request_transition",
295
+ {
296
+ description: "Solicita transi\xE7\xE3o do item vigente sem contornar ACs, pap\xE9is ou gates.",
297
+ inputSchema: {
298
+ itemId: z.string().regex(/^ITEM-\d+$/i),
299
+ targetStageId: z.string().regex(/^[a-zA-Z0-9._-]+$/),
300
+ expectedRevision,
301
+ reason,
302
+ idempotencyKey: z.string().trim().min(1).max(200).optional()
303
+ },
304
+ annotations: mutationAnnotations
305
+ },
306
+ async (input) => jsonText(
307
+ await requestTransitionOperation(operationRoot, {
308
+ ...input,
309
+ actor: mcpActor()
310
+ })
311
+ )
312
+ );
313
+ server.registerTool("get_context", { description: "Retorna contexto operacional can\xF4nico completo.", annotations: readOnlyAnnotations }, async () => {
314
+ const blocked = blockedRead();
315
+ if (blocked) return jsonText(blocked);
316
+ const direction = auditRead("context");
317
+ return jsonText({
318
+ direction,
319
+ spec: safeActiveSpec(workspaceRoot, boundary),
320
+ health: healthPayload(workspaceRoot),
321
+ workflow: loadWorkflow(workspaceRoot)
322
+ });
323
+ });
324
+ server.registerTool("get_activity", { description: "Retorna atividade operacional vigente.", inputSchema: { itemId: z.string().optional() }, annotations: readOnlyAnnotations }, async ({ itemId }) => {
325
+ const blocked = blockedRead();
326
+ if (blocked) return jsonText(blocked);
327
+ return jsonText(activityOperation(workspaceRoot, itemId));
328
+ });
329
+ server.registerTool("get_spec_catalog", { description: "Retorna a matriz can\xF4nica de specs, disposi\xE7\xF5es e refer\xEAncias.", annotations: readOnlyAnnotations }, async () => {
330
+ const blocked = blockedRead();
331
+ if (blocked) return jsonText(blocked);
332
+ auditRead("spec-catalog");
333
+ return jsonText(readSpecCatalog(workspaceRoot));
334
+ });
335
+ server.registerTool("load_reference", { description: "Carrega uma refer\xEAncia da dire\xE7\xE3o e verifica seu hash SHA-256 atual.", inputSchema: { id: z.string(), runId: z.string().optional(), executorId: z.string().optional(), itemId: z.string().optional(), expectedSha256: z.string().regex(/^[a-f0-9]{64}$/).optional() }, annotations: readOnlyAnnotations }, async ({ id, runId, executorId, itemId, expectedSha256 }) => {
336
+ const blocked = blockedRead();
337
+ if (blocked) return jsonText(blocked);
338
+ let direction;
339
+ try {
340
+ direction = resolveDirection(workspaceRoot, { runId, executorId, itemId });
341
+ } catch (error) {
342
+ const message = error instanceof Error ? error.message : String(error);
343
+ return jsonText({ reasonCode: message.split(":")[0], message });
344
+ }
345
+ const reference = direction.references?.find((entry) => entry.id === id);
346
+ if (!reference) return jsonText({ reasonCode: "REFERENCE_NOT_FOUND", id });
347
+ const path = boundary.assertPath(join(getLetraDir(workspaceRoot), reference.path));
348
+ if (!reference.available || !existsSync(path)) return jsonText({ status: "unavailable", reasonCode: "REFERENCE_UNAVAILABLE", id, path: reference.path });
349
+ const content = readFileSync(path, "utf8");
350
+ const sha256 = createHash("sha256").update(content).digest("hex");
351
+ const expected = expectedSha256 ?? reference.sha256;
352
+ const verified = expected === sha256;
353
+ return jsonText({ id, path: reference.path, status: verified ? "current" : "stale", reasonCode: verified ? null : "REFERENCE_STALE", expectedSha256: expected, sha256, verified, content });
354
+ });
355
+ server.registerTool("claim", { description: "Solicita claim exclusivo.", inputSchema: { itemId: z.string(), executorId: z.string(), capability: z.string(), expectedRevision, reason, ttlMinutes: z.number().optional(), idempotencyKey: z.string().trim().min(1).max(200).optional() }, annotations: mutationAnnotations }, async (input) => jsonText(await claimOperation(operationRoot, { ...input, actor: mcpActor() })));
356
+ server.registerTool("create_item", { description: "Cria item no primeiro est\xE1gio usando a opera\xE7\xE3o can\xF4nica. O ID incremental \xE9 padr\xE3o; itemId permite escolher ITEM-N.", inputSchema: { description: z.string().trim().min(1).max(4e3), itemId: z.string().trim().optional(), spec: z.string().trim().optional(), runId: z.string(), executorId: z.string(), expectedRevision, reason, idempotencyKey: z.string().trim().min(1).max(200).optional() }, annotations: mutationAnnotations }, async ({ description, itemId, spec, runId, executorId, expectedRevision: revision, reason: why, idempotencyKey }) => jsonText(await createItemOperation(operationRoot, { id: itemId, description, spec, runId, executorId, expectedRevision: revision, reason: why, idempotencyKey, actor: mcpActor() })));
357
+ server.registerTool("link_item_spec", { description: "Vincula uma spec existente e seus ACs ao item pela opera\xE7\xE3o can\xF4nica revision-aware.", inputSchema: { itemId: z.string(), specId: z.string().trim().min(1), runId: z.string(), executorId: z.string(), expectedRevision, reason, idempotencyKey: z.string().trim().min(1).max(200).optional() }, annotations: mutationAnnotations }, async (input) => jsonText(await linkItemSpecOperation(operationRoot, { ...input, actor: mcpActor() })));
358
+ server.registerTool("execution_event", { description: "Registra started, heartbeat, succeeded ou failed.", inputSchema: { itemId: z.string(), status: z.enum(["started", "heartbeat", "succeeded", "failed"]), executorId: z.string(), expectedRevision, reason, message: z.string().optional(), recovery: z.enum(["retry", "release", "handoff", "human"]).optional(), errorCode: z.string().optional(), idempotencyKey: z.string().trim().min(1).max(200).optional() }, annotations: mutationAnnotations }, async (input) => jsonText(await recordExecutionEvent(operationRoot, { ...input, actor: mcpActor() })));
359
+ server.registerTool("submit_evidence", { description: "Registra evid\xEAncia estruturada confinada.", inputSchema: { itemId: z.string(), executorId: z.string(), expectedRevision, reason, evidence: z.array(z.object({ kind: z.enum(["diff", "file", "command", "test", "artifact"]), value: z.string(), source: z.string(), observedAt: z.string().optional(), sha256: z.string().optional(), exitCode: z.number().optional() })), idempotencyKey: z.string().trim().min(1).max(200).optional() }, annotations: mutationAnnotations }, async (input) => jsonText(await submitEvidenceOperation(operationRoot, { ...input, actor: mcpActor() })));
360
+ server.registerTool("security_review", { description: "Executa a revis\xE3o de Security escopada ao item, usando baseline e pol\xEDtica do harness.", inputSchema: { itemId: z.string(), executorId: z.string(), expectedRevision, reason, idempotencyKey: z.string().trim().min(1).max(200).optional() }, annotations: mutationAnnotations }, async (input) => jsonText(await runSecurityReviewOperation(operationRoot, { ...input, actor: mcpActor() })));
361
+ server.registerTool("request_handoff", { description: "Solicita handoff at\xF4mico.", inputSchema: { itemId: z.string(), to: z.string(), executorId: z.string(), summary: z.string(), evidence: z.array(z.string()), expectedRevision, reason, idempotencyKey: z.string().trim().min(1).max(200).optional() }, annotations: mutationAnnotations }, async (input) => jsonText(await requestHandoffOperation(operationRoot, { ...input, actor: mcpActor() })));
362
+ server.registerTool("request_passage", { description: "Valida e comita transi\xE7\xE3o, handoff e Run pela opera\xE7\xE3o can\xF4nica.", inputSchema: { itemId: z.string(), targetStageId: z.string(), to: z.string(), executorId: z.string(), runId: z.string().trim().min(1).optional(), summary: z.string(), evidence: z.array(z.string()), expectedRevision, reason, idempotencyKey: z.string().trim().min(1).max(200).optional() }, annotations: mutationAnnotations }, async (input) => jsonText(await requestPassageOperation(operationRoot, { ...input, actor: mcpActor() })));
363
+ server.registerTool("request_rework", { description: "Solicita retrabalho conforme a configura\xE7\xE3o declarativa do est\xE1gio.", inputSchema: { itemId: z.string(), expectedRevision, reason, acceptanceCriteria: z.array(z.object({ id: z.string().optional(), description: z.string().min(1) })).default([]) }, annotations: mutationAnnotations }, async (input) => jsonText(await requestReworkOperation(operationRoot, { ...input, actor: mcpActor() })));
364
+ server.registerResource(
365
+ "direction",
366
+ "letra://direction",
367
+ { title: "Dire\xE7\xE3o vigente do harness", mimeType: "application/json" },
368
+ async () => {
369
+ const blocked = blockedRead();
370
+ if (blocked) return resourceText("letra://direction", JSON.stringify(blocked, null, 2), "application/json");
371
+ return resourceText("letra://direction", JSON.stringify(auditRead("direction"), null, 2), "application/json");
372
+ }
373
+ );
374
+ server.registerResource(
375
+ "active-spec",
376
+ "letra://spec/active",
377
+ { title: "Spec ativa", mimeType: "text/markdown" },
378
+ async () => {
379
+ const blocked = blockedRead();
380
+ if (blocked) return resourceText("letra://spec/active", JSON.stringify(blocked, null, 2), "application/json");
381
+ auditRead("active-spec");
382
+ return resourceText("letra://spec/active", safeActiveSpec(workspaceRoot, boundary).content ?? "", "text/markdown");
383
+ }
384
+ );
385
+ server.registerResource(
386
+ "spec-catalog",
387
+ "letra://spec-catalog",
388
+ { title: "Cat\xE1logo can\xF4nico de specs", mimeType: "application/json" },
389
+ async () => {
390
+ const blocked = blockedRead();
391
+ if (blocked) return resourceText("letra://spec-catalog", JSON.stringify(blocked, null, 2), "application/json");
392
+ auditRead("spec-catalog");
393
+ return resourceText("letra://spec-catalog", JSON.stringify(readSpecCatalog(workspaceRoot), null, 2), "application/json");
394
+ }
395
+ );
396
+ server.registerResource(
397
+ "constitution",
398
+ "letra://constitution",
399
+ { title: "Constitui\xE7\xE3o do workspace", mimeType: "text/markdown" },
400
+ async () => {
401
+ const blocked = blockedRead();
402
+ if (blocked) return resourceText("letra://constitution", JSON.stringify(blocked, null, 2), "application/json");
403
+ auditRead("constitution");
404
+ const path = boundary.assertPath(join(getLetraDir(workspaceRoot), "constitution.md"));
405
+ const content = existsSync(path) ? readFileSync(path, "utf-8") : "";
406
+ logEntry(workspaceRoot, "constitution_read", "Constitution read via MCP", {
407
+ details: {
408
+ adapter: "mcp",
409
+ by: "mcp:constitution-resource",
410
+ available: existsSync(path),
411
+ version: content.match(/\*\*Version:\*\*\s*(.+)/)?.[1]?.trim() ?? null
412
+ }
413
+ });
414
+ return resourceText("letra://constitution", content, "text/markdown");
415
+ }
416
+ );
417
+ server.registerResource(
418
+ "health",
419
+ "letra://health",
420
+ { title: "Sa\xFAde operacional", mimeType: "application/json" },
421
+ async () => {
422
+ const blocked = blockedRead();
423
+ if (blocked) return resourceText("letra://health", JSON.stringify(blocked, null, 2));
424
+ auditRead("health");
425
+ return resourceText("letra://health", JSON.stringify(healthPayload(workspaceRoot), null, 2));
426
+ }
427
+ );
428
+ const auditHarnessRead = (resource) => {
429
+ if (blockedRead()) return false;
430
+ const direction = resolveAgentDirection(workspaceRoot);
431
+ const key = `harness:${resource}:${direction.revision}`;
432
+ if (auditedReads.has(key)) return;
433
+ auditedReads.add(key);
434
+ const client = auditActor();
435
+ logEntry(workspaceRoot, "agent_harness_read", `MCP harness read: ${resource}`, {
436
+ itemId: direction.item?.id,
437
+ acId: direction.pendingAC?.id,
438
+ details: {
439
+ adapter: "codex",
440
+ by: client,
441
+ resource,
442
+ revision: direction.revision,
443
+ outcome: "accepted"
444
+ }
445
+ });
446
+ };
447
+ server.registerResource(
448
+ "harness-templates",
449
+ "letra://harness/templates",
450
+ { title: "Templates dispon\xEDveis no harness", mimeType: "application/json" },
451
+ async () => {
452
+ const blocked = blockedRead();
453
+ if (blocked) return resourceText("letra://harness/templates", JSON.stringify(blocked, null, 2));
454
+ auditHarnessRead("templates");
455
+ const workflow = loadWorkflow(workspaceRoot);
456
+ const harness = loadHarnessForWorkflow(workspaceRoot, workflow);
457
+ const templateIds = harness ? Object.keys(harness.flows).sort() : [];
458
+ return resourceText("letra://harness/templates", JSON.stringify(templateIds, null, 2));
459
+ }
460
+ );
461
+ server.resource(
462
+ "harness-template",
463
+ new ResourceTemplate("letra://harness/templates/{flowId}", { list: void 0 }),
464
+ async (uri, variables) => {
465
+ const blocked = blockedRead();
466
+ if (blocked) return resourceText(uri.href, JSON.stringify(blocked, null, 2));
467
+ const flowId = variables.flowId;
468
+ auditHarnessRead(`templates/${flowId}`);
469
+ const workflow = loadWorkflow(workspaceRoot);
470
+ const harness = loadHarnessForWorkflow(workspaceRoot, workflow);
471
+ if (!harness) {
472
+ return resourceText(uri.href, JSON.stringify({ error: "Harness not available" }));
473
+ }
474
+ const template = harness.flows[flowId];
475
+ if (!template) {
476
+ return resourceText(
477
+ uri.href,
478
+ JSON.stringify({ error: `Template "${flowId}" not found` })
479
+ );
480
+ }
481
+ const resolvedStages = template.stages.map((stage) => {
482
+ const gateId = stage.gate ? gateIdFromRef(stage.gate) : null;
483
+ return {
484
+ id: stage.id,
485
+ name: stage.name,
486
+ order: stage.order,
487
+ zone: stage.zone,
488
+ description: stage.description,
489
+ gate: gateId && harness.gates[gateId] ? harness.gates[gateId] : null,
490
+ roles: stage.agents.map((roleId) => harness.roles[roleId]).filter(Boolean),
491
+ phases: stage.phases,
492
+ activity: stage.activity
493
+ };
494
+ });
495
+ const policyId = template.defaultPolicy ? template.defaultPolicy.replace(/^.*[\\/]/, "").replace(/\.json$/, "") : null;
496
+ return resourceText(
497
+ uri.href,
498
+ JSON.stringify(
499
+ {
500
+ id: template.id,
501
+ version: template.version,
502
+ name: template.name,
503
+ description: template.description,
504
+ defaultPolicy: template.defaultPolicy,
505
+ stages: resolvedStages,
506
+ gates: Object.values(harness.gates),
507
+ roles: Object.values(harness.roles),
508
+ policy: policyId && harness.policies[policyId] ? harness.policies[policyId] : null
509
+ },
510
+ null,
511
+ 2
512
+ )
513
+ );
514
+ }
515
+ );
516
+ server.registerResource(
517
+ "harness-gates",
518
+ "letra://harness/gates",
519
+ { title: "Gates do harness", mimeType: "application/json" },
520
+ async () => {
521
+ const blocked = blockedRead();
522
+ if (blocked) return resourceText("letra://harness/gates", JSON.stringify(blocked, null, 2));
523
+ auditHarnessRead("gates");
524
+ return resourceText(
525
+ "letra://harness/gates",
526
+ JSON.stringify(collectGates(workspaceRoot), null, 2)
527
+ );
528
+ }
529
+ );
530
+ server.registerResource(
531
+ "harness-roles",
532
+ "letra://harness/roles",
533
+ { title: "Roles do harness", mimeType: "application/json" },
534
+ async () => {
535
+ const blocked = blockedRead();
536
+ if (blocked) return resourceText("letra://harness/roles", JSON.stringify(blocked, null, 2));
537
+ auditHarnessRead("roles");
538
+ return resourceText(
539
+ "letra://harness/roles",
540
+ JSON.stringify(collectRoles(workspaceRoot), null, 2)
541
+ );
542
+ }
543
+ );
544
+ server.registerTool(
545
+ "list_gates",
546
+ {
547
+ description: "Lista todos os gates do template ativo do harness.",
548
+ annotations: readOnlyAnnotations
549
+ },
550
+ async () => {
551
+ const blocked = blockedRead();
552
+ if (blocked) return jsonText(blocked);
553
+ auditHarnessRead("gates");
554
+ return jsonText(collectGates(workspaceRoot));
555
+ }
556
+ );
557
+ server.registerTool(
558
+ "list_roles",
559
+ {
560
+ description: "Lista todos os roles do template ativo do harness.",
561
+ annotations: readOnlyAnnotations
562
+ },
563
+ async () => {
564
+ const blocked = blockedRead();
565
+ if (blocked) return jsonText(blocked);
566
+ auditHarnessRead("roles");
567
+ return jsonText(collectRoles(workspaceRoot));
568
+ }
569
+ );
570
+ server.registerTool(
571
+ "workflow_list_definitions",
572
+ { description: "Lista todas as defini\xE7\xF5es de workflow do workspace.", annotations: readOnlyAnnotations },
573
+ async () => jsonText(listWorkflowDefinitions(workspaceRoot))
574
+ );
575
+ server.registerTool(
576
+ "workflow_list_versions",
577
+ { description: "Lista todas as vers\xF5es publicadas de um workflow.", inputSchema: { workflowId: z.string() }, annotations: readOnlyAnnotations },
578
+ async ({ workflowId }) => jsonText(listWorkflowVersions(workspaceRoot, workflowId))
579
+ );
580
+ server.registerTool(
581
+ "workflow_get_version",
582
+ { description: "Obt\xE9m uma vers\xE3o espec\xEDfica de um workflow.", inputSchema: { workflowId: z.string(), versionNumber: z.number() }, annotations: readOnlyAnnotations },
583
+ async ({ workflowId, versionNumber }) => jsonText(getWorkflowVersion(workspaceRoot, workflowId, versionNumber))
584
+ );
585
+ server.registerTool(
586
+ "workflow_get_active",
587
+ { description: "Obt\xE9m a vers\xE3o ativa de um workflow.", inputSchema: { workflowId: z.string() }, annotations: readOnlyAnnotations },
588
+ async ({ workflowId }) => jsonText(getActiveWorkflowVersion(workspaceRoot, workflowId))
589
+ );
590
+ server.registerTool(
591
+ "workflow_get_draft",
592
+ { description: "Obt\xE9m o rascunho atual de um workflow.", inputSchema: { workflowId: z.string() }, annotations: readOnlyAnnotations },
593
+ async ({ workflowId }) => jsonText(getWorkflowDraft(workspaceRoot, workflowId))
594
+ );
595
+ server.registerTool(
596
+ "run_migrate_workflow",
597
+ {
598
+ description: "Migra uma Run para uma vers\xE3o publicada de workflow com autoriza\xE7\xE3o humana assinada.",
599
+ inputSchema: { runId: z.string(), toWorkflowVersionId: z.string(), toStageId: z.string(), expectedRunRevision: z.number().int().positive(), expectedRevision, reason },
600
+ annotations: mutationAnnotations
601
+ },
602
+ async (input) => {
603
+ const actor = requireHumanActor();
604
+ const details = { runId: input.runId, toWorkflowVersionId: input.toWorkflowVersionId, toStageId: input.toStageId, expectedRunRevision: input.expectedRunRevision, expectedDirectionRevision: input.expectedRevision, reason: input.reason };
605
+ const proof = signLocalOperation(workspaceRoot, actor, "run.workflow.migrate", details);
606
+ return jsonText(migrateRunWorkflowOperation(operationRoot, { ...input, actor, proof }));
607
+ }
608
+ );
609
+ server.registerTool(
610
+ "workflow_create_definition",
611
+ {
612
+ description: "Cria uma nova defini\xE7\xE3o de workflow.",
613
+ inputSchema: { name: z.string(), description: z.string().optional() },
614
+ annotations: mutationAnnotations
615
+ },
616
+ async (input) => jsonText(createWorkflowDefinition(workspaceRoot, { ...input, actor: requireHumanActor() }))
617
+ );
618
+ server.registerTool(
619
+ "workflow_create_draft",
620
+ {
621
+ description: "Cria um rascunho para edi\xE7\xE3o de um workflow.",
622
+ inputSchema: { workflowId: z.string(), basedOnVersionNumber: z.number().optional() },
623
+ annotations: mutationAnnotations
624
+ },
625
+ async ({ workflowId, basedOnVersionNumber }) => jsonText(createWorkflowDraft(workspaceRoot, workflowId, requireHumanActor(), basedOnVersionNumber))
626
+ );
627
+ server.registerTool(
628
+ "workflow_update_draft",
629
+ {
630
+ description: "Atualiza o conte\xFAdo de um rascunho.",
631
+ inputSchema: {
632
+ workflowId: z.string(),
633
+ expectedRevision: z.number(),
634
+ content: z.record(z.unknown()),
635
+ changeSummary: z.string().optional()
636
+ },
637
+ annotations: mutationAnnotations
638
+ },
639
+ async (input) => jsonText(updateWorkflowDraft(workspaceRoot, input.workflowId, { actor: requireHumanActor(), expectedRevision: input.expectedRevision, content: input.content, changeSummary: input.changeSummary }))
640
+ );
641
+ server.registerTool(
642
+ "workflow_validate_draft",
643
+ { description: "Valida o conte\xFAdo do rascunho atual.", inputSchema: { workflowId: z.string() }, annotations: verificationAnnotations },
644
+ async ({ workflowId }) => jsonText(validateWorkflowContent(getWorkflowDraft(workspaceRoot, workflowId).content))
645
+ );
646
+ server.registerTool(
647
+ "workflow_publish",
648
+ {
649
+ description: "Publica o rascunho como nova vers\xE3o.",
650
+ inputSchema: { workflowId: z.string(), expectedRevision: z.number(), reason },
651
+ annotations: mutationAnnotations
652
+ },
653
+ async (input) => jsonText(publishWorkflowDraft(workspaceRoot, input.workflowId, { expectedRevision: input.expectedRevision, actor: requireHumanActor(), reason: input.reason }))
654
+ );
655
+ server.registerTool(
656
+ "workflow_rollback",
657
+ {
658
+ description: "Faz rollback para uma vers\xE3o anterior (publica nova vers\xE3o derivada).",
659
+ inputSchema: { workflowId: z.string(), versionNumber: z.number(), reason },
660
+ annotations: mutationAnnotations
661
+ },
662
+ async (input) => {
663
+ const actor = requireHumanActor();
664
+ const proof = signLocalOperation(workspaceRoot, actor, "workflow.rollback", { workflowId: input.workflowId, versionNumber: input.versionNumber, reason: input.reason });
665
+ return jsonText(rollbackWorkflowVersion(workspaceRoot, input.workflowId, { versionNumber: input.versionNumber, actor, reason: input.reason, proof }));
666
+ }
667
+ );
668
+ return server;
669
+ }
670
+ async function startLetraMcpServer(root) {
671
+ const server = createLetraMcpServer(root);
672
+ await server.connect(new StdioServerTransport());
673
+ }
674
+ export {
675
+ createLetraMcpServer,
676
+ startLetraMcpServer
677
+ };