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