@letra-ai/cli 0.5.3 → 0.6.2
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-6HSUVCTR.js +363 -0
- package/dist/chunk-BKAUN5QH.js +300 -0
- package/dist/chunk-DMOLJWWW.js +3321 -0
- package/dist/chunk-EDD55PWL.js +119 -0
- package/dist/chunk-H64RC3YS.js +254 -0
- package/dist/chunk-JMIC5NKB.js +235 -0
- package/dist/chunk-L6YKDTAQ.js +275 -0
- package/dist/chunk-MJ2QXNH6.js +130 -0
- package/dist/chunk-OIHMDOIN.js +1326 -0
- package/dist/chunk-PDX44BCA.js +11 -0
- package/dist/chunk-URUC6ZZP.js +4781 -0
- package/dist/client/assets/index-EyRsq1SH.css +1 -0
- package/dist/client/assets/index-WfKR7Xp6.js +232 -0
- package/dist/client/favicon.svg +16 -4
- package/dist/client/index.html +25 -20
- package/dist/fallback-MQLGS4KL.js +46 -0
- package/dist/flow-serve-G5MSSB3G.js +18 -0
- package/dist/focus-sync-3D3XWCTI.js +17 -0
- package/dist/generate-UPFERQMD.js +20 -0
- package/dist/harness/default/v0.1.0/flows/sdlc.yaml +179 -0
- package/dist/harness/default/v0.1.0/gates/all-acs-passing.yaml +8 -0
- package/dist/harness/default/v0.1.0/gates/has-spec-file.yaml +7 -0
- package/dist/harness/default/v0.1.0/gates/human-approved-code.yaml +8 -0
- package/dist/harness/default/v0.1.0/gates/human-approved-spec.yaml +8 -0
- package/dist/harness/default/v0.1.0/gates/security-clear.yaml +8 -0
- package/dist/harness/default/v0.1.0/policies/sdlc-default.json +20 -0
- package/dist/harness/default/v0.1.0/roles/analyst.yaml +9 -0
- package/dist/harness/default/v0.1.0/roles/builder.yaml +9 -0
- package/dist/harness/default/v0.1.0/roles/pr-bot.yaml +8 -0
- package/dist/harness/default/v0.1.0/roles/reviewer.yaml +10 -0
- package/dist/harness/default/v0.1.0/roles/security.yaml +8 -0
- package/dist/harness/default/v0.1.1/flows/flow-main.yaml +61 -0
- package/dist/harness/default/v0.1.1/flows/sdlc.yaml +179 -0
- package/dist/harness/default/v0.1.1/gates/all-acs-passing.yaml +8 -0
- package/dist/harness/default/v0.1.1/gates/has-spec-file.yaml +7 -0
- package/dist/harness/default/v0.1.1/gates/human-approved-code.yaml +8 -0
- package/dist/harness/default/v0.1.1/gates/human-approved-spec.yaml +8 -0
- package/dist/harness/default/v0.1.1/gates/security-clear.yaml +8 -0
- package/dist/harness/default/v0.1.1/policies/sdlc-default.json +20 -0
- package/dist/harness/default/v0.1.1/roles/analyst.yaml +9 -0
- package/dist/harness/default/v0.1.1/roles/builder.yaml +9 -0
- package/dist/harness/default/v0.1.1/roles/pr-bot.yaml +8 -0
- package/dist/harness/default/v0.1.1/roles/reviewer.yaml +10 -0
- package/dist/harness/default/v0.1.1/roles/security.yaml +8 -0
- package/dist/harness/default/v0.1.2/flows/flow-main.yaml +86 -0
- package/dist/harness/default/v0.1.2/flows/sdlc.yaml +179 -0
- package/dist/harness/default/v0.1.2/gates/all-acs-passing.yaml +8 -0
- package/dist/harness/default/v0.1.2/gates/has-spec-file.yaml +7 -0
- package/dist/harness/default/v0.1.2/gates/human-approved-code.yaml +8 -0
- package/dist/harness/default/v0.1.2/gates/human-approved-spec.yaml +8 -0
- package/dist/harness/default/v0.1.2/gates/security-clear.yaml +8 -0
- package/dist/harness/default/v0.1.2/policies/sdlc-default.json +20 -0
- package/dist/harness/default/v0.1.2/roles/analyst.yaml +9 -0
- package/dist/harness/default/v0.1.2/roles/builder.yaml +9 -0
- package/dist/harness/default/v0.1.2/roles/pr-bot.yaml +8 -0
- package/dist/harness/default/v0.1.2/roles/reviewer.yaml +10 -0
- package/dist/harness/default/v0.1.2/roles/security.yaml +8 -0
- package/dist/harness/default/v0.1.3/flows/flow-main.yaml +90 -0
- package/dist/harness/default/v0.1.3/flows/sdlc.yaml +179 -0
- package/dist/harness/default/v0.1.3/gates/all-acs-passing.yaml +8 -0
- package/dist/harness/default/v0.1.3/gates/has-spec-file.yaml +7 -0
- package/dist/harness/default/v0.1.3/gates/human-approved-code.yaml +9 -0
- package/dist/harness/default/v0.1.3/gates/human-approved-spec.yaml +9 -0
- package/dist/harness/default/v0.1.3/gates/security-clear.yaml +8 -0
- package/dist/harness/default/v0.1.3/policies/sdlc-default.json +20 -0
- package/dist/harness/default/v0.1.3/roles/analyst.yaml +9 -0
- package/dist/harness/default/v0.1.3/roles/builder.yaml +9 -0
- package/dist/harness/default/v0.1.3/roles/pr-bot.yaml +8 -0
- package/dist/harness/default/v0.1.3/roles/reviewer.yaml +10 -0
- package/dist/harness/default/v0.1.3/roles/security.yaml +8 -0
- package/dist/harness/default/v0.2.0/executors/registry.yaml +51 -0
- package/dist/harness/default/v0.2.0/flows/flow-main.yaml +249 -0
- package/dist/harness/default/v0.2.0/gates/code-reviewed.yaml +7 -0
- package/dist/harness/default/v0.2.0/gates/human-approved.yaml +10 -0
- package/dist/harness/default/v0.2.0/gates/security-clear.yaml +7 -0
- package/dist/harness/default/v0.2.0/gates/spec-approved.yaml +10 -0
- package/dist/harness/default/v0.2.0/policies/sdlc-default.json +20 -0
- package/dist/harness/default/v0.2.0/roles/analyst.yaml +16 -0
- package/dist/harness/default/v0.2.0/roles/implementer.yaml +17 -0
- package/dist/harness/default/v0.2.0/roles/reviewer.yaml +17 -0
- package/dist/harness/default/v0.2.0/roles/security.yaml +17 -0
- package/dist/health-record-YDVXEVLR.js +21 -0
- package/dist/index.js +1951 -2530
- package/dist/init-wizard-NODBBNKO.js +178 -0
- package/dist/push-VJRSQGUD.js +116 -0
- package/dist/registry-6VPIA3EG.js +18 -0
- package/dist/server-P6GKRWDX.js +423 -0
- package/dist/service-2JN2KI4D.js +29 -0
- package/dist/session-log-WTQ5JBEN.js +21 -0
- package/dist/sitrep-OKNZJICV.js +16 -0
- package/package.json +37 -28
- package/dist/chunk-56GTTLC4.js +0 -1322
- package/dist/chunk-QWT5M4XU.js +0 -643
- package/dist/client/assets/index-CuLfFw4K.js +0 -85
- package/dist/client/assets/index-iyLqZcWx.css +0 -1
- package/dist/generate-BF5R5GGA.js +0 -7
- package/dist/sitrep-SI6ZFIAM.js +0 -10
- package/tsup.config.ts +0 -11
|
@@ -0,0 +1,1326 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
GateChecker,
|
|
4
|
+
writeFocusWithRecommendations
|
|
5
|
+
} from "./chunk-H64RC3YS.js";
|
|
6
|
+
import {
|
|
7
|
+
createWorkspaceBoundary,
|
|
8
|
+
generateAdapters,
|
|
9
|
+
loadWorkflow,
|
|
10
|
+
resolveActiveFlow,
|
|
11
|
+
resolveAgentDirection,
|
|
12
|
+
writeWorkflow
|
|
13
|
+
} from "./chunk-DMOLJWWW.js";
|
|
14
|
+
import {
|
|
15
|
+
logEntry
|
|
16
|
+
} from "./chunk-BKAUN5QH.js";
|
|
17
|
+
import {
|
|
18
|
+
getLetraDir2 as getLetraDir,
|
|
19
|
+
resolveWorkspaceRoot
|
|
20
|
+
} from "./chunk-6HSUVCTR.js";
|
|
21
|
+
|
|
22
|
+
// src/domain-operations/service.ts
|
|
23
|
+
import { existsSync as existsSync4, readFileSync as readFileSync4, renameSync, writeFileSync, statSync as statSync2 } from "fs";
|
|
24
|
+
import { createHash } from "crypto";
|
|
25
|
+
import { join as join4, resolve as resolve2 } from "path";
|
|
26
|
+
|
|
27
|
+
// src/commands/validate.ts
|
|
28
|
+
import { existsSync as existsSync3, readFileSync as readFileSync3, readdirSync as readdirSync2, watch } from "fs";
|
|
29
|
+
import { join as join3, resolve, dirname } from "path";
|
|
30
|
+
import chalk from "chalk";
|
|
31
|
+
|
|
32
|
+
// src/config.ts
|
|
33
|
+
import { existsSync, readFileSync } from "fs";
|
|
34
|
+
import { join } from "path";
|
|
35
|
+
var DEFAULT_HEURISTICS = {
|
|
36
|
+
"conteudo-minimo": { severity: "warning", minChars: 50 },
|
|
37
|
+
"consistencia-terminologia": { severity: "warning" },
|
|
38
|
+
"detecao-tom": {
|
|
39
|
+
severity: "warning",
|
|
40
|
+
blacklist: ["tipo", "t\xE1", "pra", "blz", "kkk", "eita", "oi", "oi pessoal"]
|
|
41
|
+
},
|
|
42
|
+
"drift-temporal": { severity: "warning", maxDays: 30 },
|
|
43
|
+
"secoes-vazias": { severity: "warning" },
|
|
44
|
+
"acs-sem-metrica": { severity: "warning" },
|
|
45
|
+
"baixa-confianca": { severity: "warning" },
|
|
46
|
+
"validate-conflict": { severity: "warning" }
|
|
47
|
+
};
|
|
48
|
+
function loadConfig(root) {
|
|
49
|
+
const configPath = join(getLetraDir(root), "config.json");
|
|
50
|
+
const heuristics = {};
|
|
51
|
+
for (const [key, value] of Object.entries(DEFAULT_HEURISTICS)) {
|
|
52
|
+
heuristics[key] = { ...value };
|
|
53
|
+
}
|
|
54
|
+
if (existsSync(configPath)) {
|
|
55
|
+
try {
|
|
56
|
+
const raw = JSON.parse(readFileSync(configPath, "utf-8"));
|
|
57
|
+
if (raw.heuristics && typeof raw.heuristics === "object") {
|
|
58
|
+
for (const [key, value] of Object.entries(raw.heuristics)) {
|
|
59
|
+
if (heuristics[key]) {
|
|
60
|
+
heuristics[key] = {
|
|
61
|
+
...heuristics[key],
|
|
62
|
+
...value
|
|
63
|
+
};
|
|
64
|
+
} else {
|
|
65
|
+
heuristics[key] = value;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
} catch {
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return { heuristics };
|
|
73
|
+
}
|
|
74
|
+
function getHeuristicConfig(config, label) {
|
|
75
|
+
const key = heuristicKey(label);
|
|
76
|
+
return config.heuristics[key] ?? { severity: "warning" };
|
|
77
|
+
}
|
|
78
|
+
function normalize(str) {
|
|
79
|
+
return str.normalize("NFD").replace(/\p{M}/gu, "");
|
|
80
|
+
}
|
|
81
|
+
function heuristicKey(label) {
|
|
82
|
+
const lower = normalize(label.toLowerCase());
|
|
83
|
+
if (lower.includes("conteudo minimo")) return "conteudo-minimo";
|
|
84
|
+
if (lower.includes("terminologia")) return "consistencia-terminologia";
|
|
85
|
+
if (lower.includes("tom")) return "detecao-tom";
|
|
86
|
+
if (lower.includes("drift temporal")) return "drift-temporal";
|
|
87
|
+
if (lower.includes("secoes vazias")) return "secoes-vazias";
|
|
88
|
+
if (lower.includes("acs sem metrica")) return "acs-sem-metrica";
|
|
89
|
+
if (lower.includes("baixa confianca")) return "baixa-confianca";
|
|
90
|
+
if (lower.includes("validate conflict")) return "validate-conflict";
|
|
91
|
+
return lower.replace(/\s+/g, "-");
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// src/validation/content.ts
|
|
95
|
+
import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync2, statSync } from "fs";
|
|
96
|
+
import { join as join2 } from "path";
|
|
97
|
+
var placeholderPatterns = [
|
|
98
|
+
/o que o usu[áa]rio consegue fazer quando isso estiver pronto/i,
|
|
99
|
+
/limitaç[õo]es t[ée]cnicas e de neg[óo]cio/i,
|
|
100
|
+
/o que explicitamente n[ãa]o est[áa] neste escopo/i,
|
|
101
|
+
/descriç[ãa]o bin[áa]ria/i,
|
|
102
|
+
/por que estamos construindo isso/i
|
|
103
|
+
];
|
|
104
|
+
var vagueVerbs = [
|
|
105
|
+
"melhorar",
|
|
106
|
+
"otimizar",
|
|
107
|
+
"facilitar",
|
|
108
|
+
"aumentar",
|
|
109
|
+
"diminuir",
|
|
110
|
+
"agilizar",
|
|
111
|
+
"simplificar",
|
|
112
|
+
"aprimorar"
|
|
113
|
+
];
|
|
114
|
+
var lowConfidenceMarkers = [
|
|
115
|
+
"provavelmente",
|
|
116
|
+
"talvez",
|
|
117
|
+
"tentar",
|
|
118
|
+
"idealmente",
|
|
119
|
+
"possivelmente",
|
|
120
|
+
"quem sabe",
|
|
121
|
+
"de repente",
|
|
122
|
+
"teoricamente"
|
|
123
|
+
];
|
|
124
|
+
function checkSpecContent(specDir, label, description, config) {
|
|
125
|
+
const cfg = config ?? loadConfig(join2(specDir, "..", "..", ".."));
|
|
126
|
+
const specFile = join2(specDir, "spec.md");
|
|
127
|
+
const glossaryFile = join2(specDir, "..", "..", "glossary.md");
|
|
128
|
+
if (!existsSync2(specFile)) return { status: "FAIL", note: "(spec.md not found)" };
|
|
129
|
+
const specContent = readFileSync2(specFile, "utf-8");
|
|
130
|
+
const now = /* @__PURE__ */ new Date();
|
|
131
|
+
if (label.includes("Conte\xFAdo M\xEDnimo")) {
|
|
132
|
+
const outcomeMatch = specContent.match(/## Outcome\s+([\s\S]*?)(?=\n## )/);
|
|
133
|
+
if (!outcomeMatch) return { status: "FAIL", note: "(no Outcome section)" };
|
|
134
|
+
const outcomeContent = outcomeMatch[1].trim();
|
|
135
|
+
const heurConfig = getHeuristicConfig(cfg, label);
|
|
136
|
+
const minChars = heurConfig.minChars ?? 50;
|
|
137
|
+
if (outcomeContent.length >= minChars) {
|
|
138
|
+
return {
|
|
139
|
+
status: "PASS",
|
|
140
|
+
note: `(${outcomeContent.length} chars, need ${minChars})`
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
return {
|
|
144
|
+
status: "FAIL",
|
|
145
|
+
note: `(only ${outcomeContent.length} chars, need ${minChars}+)`
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
if (label.includes("Consist\xEAncia de Terminologia") || label.includes("Terminologia")) {
|
|
149
|
+
if (!existsSync2(glossaryFile)) {
|
|
150
|
+
return {
|
|
151
|
+
status: "PASS",
|
|
152
|
+
note: "(no glossary to check against)"
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
const glossaryContent = readFileSync2(glossaryFile, "utf-8");
|
|
156
|
+
const terms = glossaryContent.match(/\*\*(.+?)\*\*/g) || [];
|
|
157
|
+
const extractedTerms = terms.map((t) => t.replace(/\*\*/g, "").trim()).filter((t) => t.length > 3);
|
|
158
|
+
const missingTerms = extractedTerms.filter(
|
|
159
|
+
(term) => !specContent.toLowerCase().includes(term.toLowerCase())
|
|
160
|
+
);
|
|
161
|
+
if (missingTerms.length === 0) {
|
|
162
|
+
return { status: "PASS", note: "(all glossary terms used)" };
|
|
163
|
+
}
|
|
164
|
+
return {
|
|
165
|
+
status: "FAIL",
|
|
166
|
+
note: `(missing: ${missingTerms.slice(0, 3).join(", ")})`
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
if (label.includes("Detec\xE7\xE3o de Tom") || label.includes("Tom")) {
|
|
170
|
+
const lowerSpec = specContent.toLowerCase();
|
|
171
|
+
const words = lowerSpec.split(/\s+/);
|
|
172
|
+
const heurConfig = getHeuristicConfig(cfg, label);
|
|
173
|
+
const blacklist = heurConfig.blacklist ?? [
|
|
174
|
+
"tipo",
|
|
175
|
+
"t\xE1",
|
|
176
|
+
"pra",
|
|
177
|
+
"blz",
|
|
178
|
+
"kkk",
|
|
179
|
+
"eita",
|
|
180
|
+
"oi",
|
|
181
|
+
"oi pessoal"
|
|
182
|
+
];
|
|
183
|
+
const foundColloquialisms = blacklist.filter((c) => words.includes(c));
|
|
184
|
+
if (foundColloquialisms.length === 0) {
|
|
185
|
+
return { status: "PASS", note: "(formal tone maintained)" };
|
|
186
|
+
}
|
|
187
|
+
return {
|
|
188
|
+
status: "FAIL",
|
|
189
|
+
note: `(colloquialisms: ${foundColloquialisms.join(", ")})`
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
if (label.includes("Drift Temporal") || label.includes("Temporal")) {
|
|
193
|
+
const stat = statSync(specFile);
|
|
194
|
+
const daysOld = Math.floor((now.getTime() - stat.mtimeMs) / (1e3 * 60 * 60 * 24));
|
|
195
|
+
const heurConfig = getHeuristicConfig(cfg, label);
|
|
196
|
+
const maxDays = heurConfig.maxDays ?? 30;
|
|
197
|
+
if (daysOld < maxDays) {
|
|
198
|
+
return { status: "PASS", note: `(${daysOld} days old)` };
|
|
199
|
+
}
|
|
200
|
+
return {
|
|
201
|
+
status: "FAIL",
|
|
202
|
+
note: `(${daysOld} days old, stale >${maxDays}d)`
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
return null;
|
|
206
|
+
}
|
|
207
|
+
function checkEmptySections(specContent) {
|
|
208
|
+
const requiredSections = [
|
|
209
|
+
"## Outcome",
|
|
210
|
+
"## Constraints",
|
|
211
|
+
"## Exclusions",
|
|
212
|
+
"## Acceptance Criteria",
|
|
213
|
+
"## Context"
|
|
214
|
+
];
|
|
215
|
+
const emptyOrPlaceholder = [];
|
|
216
|
+
for (const section of requiredSections) {
|
|
217
|
+
const escaped = section.replace(/[#]/g, "\\$&");
|
|
218
|
+
const pattern = new RegExp(`${escaped}\\s+([\\s\\S]*?)(?=\\n## |\\n*$)`);
|
|
219
|
+
const match = specContent.match(pattern);
|
|
220
|
+
if (!match) {
|
|
221
|
+
emptyOrPlaceholder.push(section.replace("## ", ""));
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
const content = match[1].trim();
|
|
225
|
+
if (content.length < 10) {
|
|
226
|
+
emptyOrPlaceholder.push(section.replace("## ", ""));
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
const hasPlaceholder = placeholderPatterns.some((p) => p.test(content));
|
|
230
|
+
if (hasPlaceholder) {
|
|
231
|
+
emptyOrPlaceholder.push(section.replace("## ", ""));
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
if (emptyOrPlaceholder.length === 0) {
|
|
235
|
+
return {
|
|
236
|
+
status: "PASS",
|
|
237
|
+
note: "(all sections have real content)"
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
return {
|
|
241
|
+
status: "FAIL",
|
|
242
|
+
note: `(empty/placeholder: ${emptyOrPlaceholder.join(", ")})`
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
function checkBinaryCriteria(specContent) {
|
|
246
|
+
const acMatch = specContent.match(/## Acceptance Criteria\s+([\s\S]*?)(?=\n## |\n*$)/);
|
|
247
|
+
if (!acMatch) {
|
|
248
|
+
return {
|
|
249
|
+
status: "FAIL",
|
|
250
|
+
note: "(no Acceptance Criteria section)"
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
const criteriaLines = acMatch[1].match(/- \[[ x]\] .+/g) || [];
|
|
254
|
+
if (criteriaLines.length === 0) {
|
|
255
|
+
return { status: "FAIL", note: "(no criteria items found)" };
|
|
256
|
+
}
|
|
257
|
+
const nonBinary = [];
|
|
258
|
+
for (const line of criteriaLines) {
|
|
259
|
+
const description = line.replace(/- \[[ x]\] \*\*.+?\*\*:\s*/, "");
|
|
260
|
+
const hasMetric = /\d+/.test(description);
|
|
261
|
+
const hasVagueVerb = vagueVerbs.some((v) => description.toLowerCase().includes(v));
|
|
262
|
+
if (!hasMetric && hasVagueVerb) {
|
|
263
|
+
const labelMatch = line.match(/\*\*(.+?)\*\*/);
|
|
264
|
+
if (labelMatch) nonBinary.push(labelMatch[1]);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
if (nonBinary.length === 0) {
|
|
268
|
+
return {
|
|
269
|
+
status: "PASS",
|
|
270
|
+
note: "(all criteria have measurable outcomes)"
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
return {
|
|
274
|
+
status: "FAIL",
|
|
275
|
+
note: `(vague criteria: ${nonBinary.join(", ")})`
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
function checkLowConfidence(specContent) {
|
|
279
|
+
const lower = specContent.toLowerCase();
|
|
280
|
+
const words = lower.split(/\s+/);
|
|
281
|
+
const found = lowConfidenceMarkers.filter((m) => {
|
|
282
|
+
if (m.includes(" ")) {
|
|
283
|
+
return lower.includes(m);
|
|
284
|
+
}
|
|
285
|
+
return words.includes(m);
|
|
286
|
+
});
|
|
287
|
+
if (found.length === 0) {
|
|
288
|
+
return {
|
|
289
|
+
status: "PASS",
|
|
290
|
+
note: "(no low-confidence language detected)"
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
return {
|
|
294
|
+
status: "FAIL",
|
|
295
|
+
note: `(low-confidence: ${found.join(", ")})`
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
var commonWords = [
|
|
299
|
+
"para",
|
|
300
|
+
"com",
|
|
301
|
+
"que",
|
|
302
|
+
"dos",
|
|
303
|
+
"das",
|
|
304
|
+
"uma",
|
|
305
|
+
"como",
|
|
306
|
+
"mais",
|
|
307
|
+
"mas",
|
|
308
|
+
"por",
|
|
309
|
+
"pode",
|
|
310
|
+
"ser",
|
|
311
|
+
"s\xE3o",
|
|
312
|
+
"tem",
|
|
313
|
+
"seu",
|
|
314
|
+
"sua",
|
|
315
|
+
"esta",
|
|
316
|
+
"este",
|
|
317
|
+
"isso",
|
|
318
|
+
"the",
|
|
319
|
+
"and",
|
|
320
|
+
"for",
|
|
321
|
+
"with",
|
|
322
|
+
"that",
|
|
323
|
+
"this",
|
|
324
|
+
"from",
|
|
325
|
+
"are",
|
|
326
|
+
"was"
|
|
327
|
+
];
|
|
328
|
+
function getSignificantWords(text) {
|
|
329
|
+
return text.toLowerCase().split(/\s+/).filter((w) => w.length >= 4 && !commonWords.includes(w));
|
|
330
|
+
}
|
|
331
|
+
function getPrefix(name) {
|
|
332
|
+
const idx = name.indexOf("-");
|
|
333
|
+
return idx === -1 ? name : name.slice(0, idx);
|
|
334
|
+
}
|
|
335
|
+
function isSibling(nameA, nameB) {
|
|
336
|
+
return getPrefix(nameA) === getPrefix(nameB);
|
|
337
|
+
}
|
|
338
|
+
function detectConflict(textA, textB) {
|
|
339
|
+
const lowerA = textA.toLowerCase();
|
|
340
|
+
const lowerB = textB.toLowerCase();
|
|
341
|
+
const aHasNeg = /\bn[ãa]o\b/.test(lowerA) || /\bnot\b/.test(lowerA);
|
|
342
|
+
const bHasNeg = /\bn[ãa]o\b/.test(lowerB) || /\bnot\b/.test(lowerB);
|
|
343
|
+
if (aHasNeg !== bHasNeg) {
|
|
344
|
+
const wordsA = getSignificantWords(lowerA);
|
|
345
|
+
const wordsB = getSignificantWords(lowerB);
|
|
346
|
+
const intersection = wordsA.filter((w) => wordsB.includes(w));
|
|
347
|
+
const maxLen = Math.max(wordsA.length, wordsB.length);
|
|
348
|
+
if (maxLen > 0 && intersection.length / maxLen > 0.6) return true;
|
|
349
|
+
}
|
|
350
|
+
const apenasA = lowerA.match(/(?:apenas|only)\s+(\w+)/);
|
|
351
|
+
const apenasB = lowerB.match(/(?:apenas|only)\s+(\w+)/);
|
|
352
|
+
if (apenasA && !apenasB) {
|
|
353
|
+
const termA = apenasA[1];
|
|
354
|
+
const wordsA = getSignificantWords(lowerA);
|
|
355
|
+
const wordsB = getSignificantWords(lowerB);
|
|
356
|
+
const shared = wordsA.filter((w) => w !== termA && wordsB.includes(w));
|
|
357
|
+
if (shared.length > 0 && !wordsB.includes(termA)) return true;
|
|
358
|
+
}
|
|
359
|
+
if (apenasB && !apenasA) {
|
|
360
|
+
const termB = apenasB[1];
|
|
361
|
+
const wordsA = getSignificantWords(lowerA);
|
|
362
|
+
const wordsB = getSignificantWords(lowerB);
|
|
363
|
+
const shared = wordsB.filter((w) => w !== termB && wordsA.includes(w));
|
|
364
|
+
if (shared.length > 0 && !wordsA.includes(termB)) return true;
|
|
365
|
+
}
|
|
366
|
+
if (apenasA && apenasB && apenasA[1] !== apenasB[1]) {
|
|
367
|
+
const wordsA = getSignificantWords(lowerA);
|
|
368
|
+
const wordsB = getSignificantWords(lowerB);
|
|
369
|
+
const shared = wordsA.filter((w) => wordsB.includes(w));
|
|
370
|
+
if (shared.length > 0) return true;
|
|
371
|
+
}
|
|
372
|
+
return false;
|
|
373
|
+
}
|
|
374
|
+
function checkConflicts(specsDir, config) {
|
|
375
|
+
const results = [];
|
|
376
|
+
const conflictGroups = /* @__PURE__ */ new Map();
|
|
377
|
+
const entries = readdirSync(specsDir, { withFileTypes: true });
|
|
378
|
+
const specDirs = entries.filter((e) => e.isDirectory() && !e.name.startsWith("_")).map((e) => e.name);
|
|
379
|
+
const specs = [];
|
|
380
|
+
for (const dir of specDirs) {
|
|
381
|
+
const acceptanceFile = join2(specsDir, dir, "acceptance.md");
|
|
382
|
+
if (!existsSync2(acceptanceFile)) continue;
|
|
383
|
+
const content = readFileSync2(acceptanceFile, "utf-8");
|
|
384
|
+
const acLines = content.match(/- \[[ x]\] \*\*(.+?)\*\*: (.+)/g) || [];
|
|
385
|
+
const acs = acLines.map((line) => {
|
|
386
|
+
const m = line.match(/- \[[ x]\] \*\*(.+?)\*\*: (.+)/);
|
|
387
|
+
return m ? m[2].trim() : "";
|
|
388
|
+
}).filter(Boolean);
|
|
389
|
+
if (acs.length > 0) specs.push({ name: dir, acs });
|
|
390
|
+
}
|
|
391
|
+
for (let i = 0; i < specs.length; i++) {
|
|
392
|
+
for (let j = i + 1; j < specs.length; j++) {
|
|
393
|
+
const a = specs[i];
|
|
394
|
+
const b = specs[j];
|
|
395
|
+
if (isSibling(a.name, b.name)) continue;
|
|
396
|
+
for (const acA of a.acs) {
|
|
397
|
+
for (const acB of b.acs) {
|
|
398
|
+
if (detectConflict(acA, acB)) {
|
|
399
|
+
const key = `${a.name}\0${b.name}`;
|
|
400
|
+
const group = conflictGroups.get(key) ?? {
|
|
401
|
+
specA: a.name,
|
|
402
|
+
specB: b.name,
|
|
403
|
+
criteriaA: /* @__PURE__ */ new Set(),
|
|
404
|
+
criteriaB: /* @__PURE__ */ new Set(),
|
|
405
|
+
occurrences: 0
|
|
406
|
+
};
|
|
407
|
+
group.criteriaA.add(acA);
|
|
408
|
+
group.criteriaB.add(acB);
|
|
409
|
+
group.occurrences++;
|
|
410
|
+
conflictGroups.set(key, group);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
for (const group of conflictGroups.values()) {
|
|
417
|
+
const occurrenceLabel = group.occurrences === 1 ? "ocorr\xEAncia" : "ocorr\xEAncias";
|
|
418
|
+
const criteriaA = [...group.criteriaA].map((criterion) => `"${criterion}"`).join("; ");
|
|
419
|
+
const criteriaB = [...group.criteriaB].map((criterion) => `"${criterion}"`).join("; ");
|
|
420
|
+
results.push({
|
|
421
|
+
label: "Validate Conflict",
|
|
422
|
+
passed: false,
|
|
423
|
+
message: `Conflito: ${group.occurrences} ${occurrenceLabel} entre "${group.specA}" e "${group.specB}". ACs de "${group.specA}": ${criteriaA}. ACs de "${group.specB}": ${criteriaB}.`
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
if (conflictGroups.size === 0) {
|
|
427
|
+
results.push({
|
|
428
|
+
label: "Validate Conflict",
|
|
429
|
+
passed: true,
|
|
430
|
+
message: "Nenhum conflito detectado entre specs"
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
return results;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// src/commands/validate.ts
|
|
437
|
+
function out(format, level, spec, label, message, note) {
|
|
438
|
+
if (format === "silent") return;
|
|
439
|
+
if (format === "github-annotation") {
|
|
440
|
+
const file = spec ? `.letra/specs/${spec}/spec.md` : "";
|
|
441
|
+
if (level === "fail") {
|
|
442
|
+
console.log(`::error file=${file},title=${label}::${message} ${note}`);
|
|
443
|
+
} else if (level === "warning") {
|
|
444
|
+
console.log(`::warning file=${file},title=${label}::${message} ${note}`);
|
|
445
|
+
} else {
|
|
446
|
+
console.log(`${label}: ${message} ${note}`);
|
|
447
|
+
}
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
if (format === "junit") {
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
const icon = level === "pass" ? chalk.green("\u2713") : level === "fail" ? chalk.red("\u2717") : level === "warning" ? chalk.yellow("\u26A0") : "";
|
|
454
|
+
if (level === "info") {
|
|
455
|
+
console.log(` ${message}`);
|
|
456
|
+
} else {
|
|
457
|
+
console.log(` [${icon}] ${chalk.cyan(label)}: ${message} ${chalk.gray(note)}`);
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
function buildJunitXml(results) {
|
|
461
|
+
let xml = `<?xml version="1.0" encoding="UTF-8"?>
|
|
462
|
+
`;
|
|
463
|
+
xml += `<testsuites name="letra-validate" tests="${results.pass + results.fail + results.warning}" failures="${results.fail}">
|
|
464
|
+
`;
|
|
465
|
+
for (const suite of results.suites) {
|
|
466
|
+
xml += ` <testsuite name="${suite.name}" tests="${suite.pass + suite.fail + suite.warning}" failures="${suite.fail}">
|
|
467
|
+
`;
|
|
468
|
+
xml += " </testsuite>\n";
|
|
469
|
+
}
|
|
470
|
+
xml += "</testsuites>\n";
|
|
471
|
+
return xml;
|
|
472
|
+
}
|
|
473
|
+
function collectResult(results, level, spec, label, message, note) {
|
|
474
|
+
results.push({ level, spec, label, message, note });
|
|
475
|
+
}
|
|
476
|
+
function flushResults(results, format, specGroups, totalPass, totalFail, totalWarning) {
|
|
477
|
+
if (format === "silent") return;
|
|
478
|
+
if (format === "junit") {
|
|
479
|
+
const suites = [];
|
|
480
|
+
for (const [name, counts] of specGroups) {
|
|
481
|
+
suites.push({ name, ...counts });
|
|
482
|
+
}
|
|
483
|
+
console.log(
|
|
484
|
+
buildJunitXml({
|
|
485
|
+
pass: totalPass,
|
|
486
|
+
fail: totalFail,
|
|
487
|
+
warning: totalWarning,
|
|
488
|
+
suites
|
|
489
|
+
})
|
|
490
|
+
);
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
493
|
+
if (format === "github-annotation") {
|
|
494
|
+
for (const r of results) {
|
|
495
|
+
out(format, r.level, r.spec, r.label, r.message, r.note);
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
console.log(
|
|
499
|
+
chalk.gray(
|
|
500
|
+
`
|
|
501
|
+
Results: ${totalPass} passed, ${totalFail} failed${totalWarning > 0 ? `, ${totalWarning} warnings` : ""}`
|
|
502
|
+
)
|
|
503
|
+
);
|
|
504
|
+
}
|
|
505
|
+
async function validate(targetPath, options) {
|
|
506
|
+
const root = resolve(process.cwd(), targetPath || ".");
|
|
507
|
+
let specsDir = join3(getLetraDir(root), "specs");
|
|
508
|
+
const fmt = options?.format || "text";
|
|
509
|
+
if (!existsSync3(specsDir)) {
|
|
510
|
+
let found = false;
|
|
511
|
+
let search = root;
|
|
512
|
+
const fsRoot = resolve("/").replace(/\\/g, "/");
|
|
513
|
+
while (search && search !== fsRoot && search !== dirname(search)) {
|
|
514
|
+
const candidate = join3(search, ".letra", "specs");
|
|
515
|
+
if (existsSync3(candidate)) {
|
|
516
|
+
specsDir = candidate;
|
|
517
|
+
found = true;
|
|
518
|
+
break;
|
|
519
|
+
}
|
|
520
|
+
search = dirname(search);
|
|
521
|
+
}
|
|
522
|
+
if (!found) {
|
|
523
|
+
const msg = "Error: .letra/specs/ not found. Run 'letra init' first.";
|
|
524
|
+
if (options?.exit === false) throw new Error(msg);
|
|
525
|
+
if (fmt === "github-annotation") {
|
|
526
|
+
console.log(`::error file=,title=Init Required::${msg}`);
|
|
527
|
+
} else {
|
|
528
|
+
console.log(chalk.red(msg));
|
|
529
|
+
}
|
|
530
|
+
process.exit(1);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
async function runValidation() {
|
|
534
|
+
const config = loadConfig(root);
|
|
535
|
+
const entries = readdirSync2(specsDir, { withFileTypes: true });
|
|
536
|
+
let totalPass = 0;
|
|
537
|
+
let totalFail = 0;
|
|
538
|
+
let totalWarning = 0;
|
|
539
|
+
const specGroups = /* @__PURE__ */ new Map();
|
|
540
|
+
const allResults = [];
|
|
541
|
+
const cursorRulesFile = join3(root, ".cursorrules");
|
|
542
|
+
const copilotFile = join3(root, ".github", "copilot-instructions.md");
|
|
543
|
+
const vscodeSettingsFile = join3(root, ".vscode", "settings.json");
|
|
544
|
+
if (fmt !== "junit") {
|
|
545
|
+
out(fmt, "info", null, "", "\nLetra Validation\n", "");
|
|
546
|
+
}
|
|
547
|
+
for (const entry of entries) {
|
|
548
|
+
if (!entry.isDirectory() || entry.name.startsWith("_")) continue;
|
|
549
|
+
const acceptanceFile = join3(specsDir, entry.name, "acceptance.md");
|
|
550
|
+
const specFile = join3(specsDir, entry.name, "spec.md");
|
|
551
|
+
let content;
|
|
552
|
+
if (existsSync3(acceptanceFile)) {
|
|
553
|
+
content = readFileSync3(acceptanceFile, "utf-8");
|
|
554
|
+
} else if (existsSync3(specFile)) {
|
|
555
|
+
content = readFileSync3(specFile, "utf-8");
|
|
556
|
+
} else {
|
|
557
|
+
out(
|
|
558
|
+
fmt,
|
|
559
|
+
"info",
|
|
560
|
+
entry.name,
|
|
561
|
+
"",
|
|
562
|
+
`Spec "${entry.name}" \u2014 no acceptance.md or spec.md found`,
|
|
563
|
+
""
|
|
564
|
+
);
|
|
565
|
+
continue;
|
|
566
|
+
}
|
|
567
|
+
const criteriaLines = content.match(/- \[ \] \*\*(.+?)\*\*: (.+)/g) || [];
|
|
568
|
+
const specContent = existsSync3(specFile) ? readFileSync3(specFile, "utf-8") : null;
|
|
569
|
+
out(fmt, "info", entry.name, "", `Spec: ${entry.name}`, "");
|
|
570
|
+
if (criteriaLines.length === 0) {
|
|
571
|
+
out(fmt, "info", entry.name, "", "No criteria found", "");
|
|
572
|
+
}
|
|
573
|
+
let specPass = 0;
|
|
574
|
+
let specFail = 0;
|
|
575
|
+
let specWarning = 0;
|
|
576
|
+
for (const line of criteriaLines) {
|
|
577
|
+
const match = line.match(/- \[ \] \*\*(.+?)\*\*: (.+)/);
|
|
578
|
+
if (match) {
|
|
579
|
+
const [, label, description] = match;
|
|
580
|
+
let status = "FAIL";
|
|
581
|
+
let note = "";
|
|
582
|
+
let intelligenceResult = null;
|
|
583
|
+
try {
|
|
584
|
+
intelligenceResult = checkSpecContent(
|
|
585
|
+
join3(specsDir, entry.name),
|
|
586
|
+
label,
|
|
587
|
+
description,
|
|
588
|
+
config
|
|
589
|
+
);
|
|
590
|
+
if (intelligenceResult) {
|
|
591
|
+
status = intelligenceResult.status;
|
|
592
|
+
note = intelligenceResult.note;
|
|
593
|
+
} else if (label.includes("letra validate")) {
|
|
594
|
+
status = "PASS";
|
|
595
|
+
} else if (label.includes("Workflow Ativo")) {
|
|
596
|
+
status = "PASS";
|
|
597
|
+
} else if (label.includes("Gera\xE7\xE3o de Regras") || label.includes("Gera\xE7\xE3o")) {
|
|
598
|
+
if (existsSync3(cursorRulesFile)) {
|
|
599
|
+
const rulesContent = readFileSync3(cursorRulesFile, "utf-8");
|
|
600
|
+
if (rulesContent.includes(".letra/context.md") && rulesContent.includes(".letra/constitution.md")) {
|
|
601
|
+
status = "PASS";
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
} else if (label.includes("Inje\xE7\xE3o de Contexto")) {
|
|
605
|
+
if (existsSync3(cursorRulesFile)) {
|
|
606
|
+
const rulesContent = readFileSync3(cursorRulesFile, "utf-8");
|
|
607
|
+
if (rulesContent.includes("@.letra/")) status = "PASS";
|
|
608
|
+
} else if (existsSync3(copilotFile)) {
|
|
609
|
+
const copilotContent = readFileSync3(copilotFile, "utf-8");
|
|
610
|
+
if (copilotContent.includes(".letra/")) status = "PASS";
|
|
611
|
+
}
|
|
612
|
+
} else if (label.includes("Acesso a Valida\xE7\xE3o")) {
|
|
613
|
+
if (existsSync3(cursorRulesFile)) {
|
|
614
|
+
const rulesContent = readFileSync3(cursorRulesFile, "utf-8");
|
|
615
|
+
if (rulesContent.includes("letra validate")) status = "PASS";
|
|
616
|
+
}
|
|
617
|
+
} else if (label.includes("N\xE3o-intrusivo")) {
|
|
618
|
+
if (existsSync3(cursorRulesFile) || existsSync3(copilotFile)) {
|
|
619
|
+
status = "PASS";
|
|
620
|
+
}
|
|
621
|
+
} else if (label.includes("Gera\xE7\xE3o de Instru\xE7\xF5es")) {
|
|
622
|
+
if (existsSync3(copilotFile)) {
|
|
623
|
+
const copilotContent = readFileSync3(copilotFile, "utf-8");
|
|
624
|
+
if (copilotContent.includes(".letra/context.md") && copilotContent.includes(".letra/constitution.md")) {
|
|
625
|
+
status = "PASS";
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
} else if (label.includes("Settings do Editor")) {
|
|
629
|
+
if (existsSync3(vscodeSettingsFile)) {
|
|
630
|
+
const settingsContent = readFileSync3(vscodeSettingsFile, "utf-8");
|
|
631
|
+
if (settingsContent.includes("editor.formatOnSave")) {
|
|
632
|
+
status = "PASS";
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
} else if (label.includes("Arquivo de Config")) {
|
|
636
|
+
const configFile = join3(getLetraDir(root), "config.json");
|
|
637
|
+
if (existsSync3(configFile)) {
|
|
638
|
+
const cfgContent = readFileSync3(configFile, "utf-8");
|
|
639
|
+
try {
|
|
640
|
+
const parsed = JSON.parse(cfgContent);
|
|
641
|
+
if (parsed.heuristics) {
|
|
642
|
+
status = "PASS";
|
|
643
|
+
note = "(config.json found with heuristics)";
|
|
644
|
+
} else {
|
|
645
|
+
note = "(config.json missing heuristics key)";
|
|
646
|
+
}
|
|
647
|
+
} catch {
|
|
648
|
+
note = "(config.json is invalid JSON)";
|
|
649
|
+
}
|
|
650
|
+
} else {
|
|
651
|
+
note = "(no config.json found)";
|
|
652
|
+
}
|
|
653
|
+
} else if (label.includes("Backward Compatible")) {
|
|
654
|
+
status = "PASS";
|
|
655
|
+
note = "(all heuristics default to warning)";
|
|
656
|
+
} else {
|
|
657
|
+
note = "(manual check needed)";
|
|
658
|
+
}
|
|
659
|
+
} catch (error) {
|
|
660
|
+
status = "FAIL";
|
|
661
|
+
const err = error;
|
|
662
|
+
note = `(error: ${err.message?.split("\n")[0] || "unknown"})`;
|
|
663
|
+
}
|
|
664
|
+
if (status === "PASS") {
|
|
665
|
+
collectResult(allResults, "pass", entry.name, label, description, note);
|
|
666
|
+
totalPass++;
|
|
667
|
+
specPass++;
|
|
668
|
+
} else if (intelligenceResult) {
|
|
669
|
+
const heurCfg = getHeuristicConfig(config, label);
|
|
670
|
+
if (heurCfg.severity === "warning") {
|
|
671
|
+
collectResult(
|
|
672
|
+
allResults,
|
|
673
|
+
"warning",
|
|
674
|
+
entry.name,
|
|
675
|
+
label,
|
|
676
|
+
description,
|
|
677
|
+
note
|
|
678
|
+
);
|
|
679
|
+
totalWarning++;
|
|
680
|
+
specWarning++;
|
|
681
|
+
} else {
|
|
682
|
+
collectResult(allResults, "fail", entry.name, label, description, note);
|
|
683
|
+
totalFail++;
|
|
684
|
+
specFail++;
|
|
685
|
+
}
|
|
686
|
+
} else if (note.includes("manual check needed")) {
|
|
687
|
+
collectResult(allResults, "warning", entry.name, label, description, note);
|
|
688
|
+
totalWarning++;
|
|
689
|
+
specWarning++;
|
|
690
|
+
} else {
|
|
691
|
+
collectResult(allResults, "fail", entry.name, label, description, note);
|
|
692
|
+
totalFail++;
|
|
693
|
+
specFail++;
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
if (specContent) {
|
|
698
|
+
const emptyCfg = getHeuristicConfig(config, "Se\xE7\xF5es Vazias");
|
|
699
|
+
if (emptyCfg.severity !== "off") {
|
|
700
|
+
const emptyResult = checkEmptySections(specContent);
|
|
701
|
+
if (emptyResult.status === "FAIL") {
|
|
702
|
+
if (emptyCfg.severity === "warning") {
|
|
703
|
+
collectResult(
|
|
704
|
+
allResults,
|
|
705
|
+
"warning",
|
|
706
|
+
entry.name,
|
|
707
|
+
"Se\xE7\xF5es Vazias",
|
|
708
|
+
"Se\xE7\xF5es obrigat\xF3rias com placeholder ou vazias",
|
|
709
|
+
emptyResult.note
|
|
710
|
+
);
|
|
711
|
+
totalWarning++;
|
|
712
|
+
specWarning++;
|
|
713
|
+
} else {
|
|
714
|
+
collectResult(
|
|
715
|
+
allResults,
|
|
716
|
+
"fail",
|
|
717
|
+
entry.name,
|
|
718
|
+
"Se\xE7\xF5es Vazias",
|
|
719
|
+
"Se\xE7\xF5es obrigat\xF3rias com placeholder ou vazias",
|
|
720
|
+
emptyResult.note
|
|
721
|
+
);
|
|
722
|
+
totalFail++;
|
|
723
|
+
specFail++;
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
const binaryCfg = getHeuristicConfig(config, "ACs sem M\xE9trica");
|
|
728
|
+
if (binaryCfg.severity !== "off") {
|
|
729
|
+
const binaryResult = checkBinaryCriteria(specContent);
|
|
730
|
+
if (binaryResult.status === "FAIL") {
|
|
731
|
+
if (binaryCfg.severity === "warning") {
|
|
732
|
+
collectResult(
|
|
733
|
+
allResults,
|
|
734
|
+
"warning",
|
|
735
|
+
entry.name,
|
|
736
|
+
"ACs sem M\xE9trica",
|
|
737
|
+
"Crit\xE9rios com verbos vagos sem m\xE9trica",
|
|
738
|
+
binaryResult.note
|
|
739
|
+
);
|
|
740
|
+
totalWarning++;
|
|
741
|
+
specWarning++;
|
|
742
|
+
} else {
|
|
743
|
+
collectResult(
|
|
744
|
+
allResults,
|
|
745
|
+
"fail",
|
|
746
|
+
entry.name,
|
|
747
|
+
"ACs sem M\xE9trica",
|
|
748
|
+
"Crit\xE9rios com verbos vagos sem m\xE9trica",
|
|
749
|
+
binaryResult.note
|
|
750
|
+
);
|
|
751
|
+
totalFail++;
|
|
752
|
+
specFail++;
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
const lowConfCfg = getHeuristicConfig(config, "Baixa Confian\xE7a");
|
|
757
|
+
if (lowConfCfg.severity !== "off") {
|
|
758
|
+
const lowConfResult = checkLowConfidence(specContent);
|
|
759
|
+
if (lowConfResult.status === "FAIL") {
|
|
760
|
+
if (lowConfCfg.severity === "warning") {
|
|
761
|
+
collectResult(
|
|
762
|
+
allResults,
|
|
763
|
+
"warning",
|
|
764
|
+
entry.name,
|
|
765
|
+
"Baixa Confian\xE7a",
|
|
766
|
+
"Spec cont\xE9m linguagem de baixa confian\xE7a",
|
|
767
|
+
lowConfResult.note
|
|
768
|
+
);
|
|
769
|
+
totalWarning++;
|
|
770
|
+
specWarning++;
|
|
771
|
+
} else {
|
|
772
|
+
collectResult(
|
|
773
|
+
allResults,
|
|
774
|
+
"fail",
|
|
775
|
+
entry.name,
|
|
776
|
+
"Baixa Confian\xE7a",
|
|
777
|
+
"Spec cont\xE9m linguagem de baixa confian\xE7a",
|
|
778
|
+
lowConfResult.note
|
|
779
|
+
);
|
|
780
|
+
totalFail++;
|
|
781
|
+
specFail++;
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
specGroups.set(entry.name, {
|
|
787
|
+
pass: specPass,
|
|
788
|
+
fail: specFail,
|
|
789
|
+
warning: specWarning
|
|
790
|
+
});
|
|
791
|
+
}
|
|
792
|
+
const conflictCfg = getHeuristicConfig(config, "Validate Conflict");
|
|
793
|
+
if (conflictCfg.severity !== "off") {
|
|
794
|
+
const conflictResults = checkConflicts(specsDir, config);
|
|
795
|
+
for (const cr of conflictResults) {
|
|
796
|
+
if (cr.passed) continue;
|
|
797
|
+
const level = conflictCfg.severity === "warning" ? "warning" : "fail";
|
|
798
|
+
collectResult(allResults, level, "(cross-spec)", cr.label, cr.message, "");
|
|
799
|
+
if (level === "warning") {
|
|
800
|
+
totalWarning++;
|
|
801
|
+
} else {
|
|
802
|
+
totalFail++;
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
if (fmt === "text" || fmt === "github-annotation") {
|
|
807
|
+
for (const r of allResults) {
|
|
808
|
+
out(fmt, r.level, r.spec, r.label, r.message, r.note);
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
flushResults(allResults, fmt, specGroups, totalPass, totalFail, totalWarning);
|
|
812
|
+
if (options?.log !== false) {
|
|
813
|
+
logEntry(
|
|
814
|
+
root,
|
|
815
|
+
"validate",
|
|
816
|
+
`Valida\xE7\xE3o executada \u2014 ${totalPass} passed, ${totalFail} failed, ${totalWarning} warnings`,
|
|
817
|
+
{
|
|
818
|
+
details: { passed: totalPass, failed: totalFail, warnings: totalWarning }
|
|
819
|
+
}
|
|
820
|
+
);
|
|
821
|
+
}
|
|
822
|
+
return { passed: totalPass, failed: totalFail, warnings: totalWarning };
|
|
823
|
+
}
|
|
824
|
+
const summary = await runValidation();
|
|
825
|
+
if (options?.watch) {
|
|
826
|
+
let timer = null;
|
|
827
|
+
console.log(chalk.gray("\nWatching for changes... (Ctrl+C to stop)"));
|
|
828
|
+
const watcher = watch(specsDir, { recursive: true });
|
|
829
|
+
watcher.on("change", () => {
|
|
830
|
+
if (timer) clearTimeout(timer);
|
|
831
|
+
timer = setTimeout(async () => {
|
|
832
|
+
console.clear();
|
|
833
|
+
await runValidation();
|
|
834
|
+
console.log(chalk.gray("\nWatching for changes... (Ctrl+C to stop)"));
|
|
835
|
+
}, 300);
|
|
836
|
+
});
|
|
837
|
+
process.on("SIGINT", () => {
|
|
838
|
+
watcher.close();
|
|
839
|
+
process.exit(0);
|
|
840
|
+
});
|
|
841
|
+
process.on("SIGTERM", () => {
|
|
842
|
+
watcher.close();
|
|
843
|
+
process.exit(0);
|
|
844
|
+
});
|
|
845
|
+
await new Promise(() => {
|
|
846
|
+
});
|
|
847
|
+
} else {
|
|
848
|
+
if (options?.exit !== false) process.exit(summary.failed > 0 ? 1 : 0);
|
|
849
|
+
}
|
|
850
|
+
return summary;
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
// src/domain-operations/service.ts
|
|
854
|
+
function activityOperation(root, itemId) {
|
|
855
|
+
const direction = resolveAgentDirection(createWorkspaceBoundary(resolve2(root)).root);
|
|
856
|
+
return direction.item && (!itemId || direction.item.id === itemId) ? direction.item : null;
|
|
857
|
+
}
|
|
858
|
+
async function submitEvidenceOperation(root, input) {
|
|
859
|
+
const workspaceRoot = createWorkspaceBoundary(resolve2(root)).root;
|
|
860
|
+
const before = resolveAgentDirection(workspaceRoot);
|
|
861
|
+
const subject = { itemId: input.itemId, operation: "submit_evidence" };
|
|
862
|
+
const stale = checkRevision(workspaceRoot, before, input, subject);
|
|
863
|
+
if (stale) return stale;
|
|
864
|
+
const item = loadWorkflow(workspaceRoot)?.items.find((candidate) => candidate.id === input.itemId);
|
|
865
|
+
if (!item || item.claimedBy !== input.actor || item.claimExecutorId && item.claimExecutorId !== input.executorId) return rejected(workspaceRoot, before, "CLAIM_REQUIRED", "A evid\xEAncia exige claim vigente.", input, subject);
|
|
866
|
+
const boundary = createWorkspaceBoundary(resolveWorkspaceRoot(root).workspaceDir);
|
|
867
|
+
for (const evidence of input.evidence) {
|
|
868
|
+
if (!evidence.source?.trim() || !evidence.value?.trim()) return rejected(workspaceRoot, before, "EVIDENCE_INVALID", "Evid\xEAncia exige origem e valor.", input, subject);
|
|
869
|
+
if (evidence.kind === "file" || evidence.kind === "diff" || evidence.kind === "artifact") {
|
|
870
|
+
try {
|
|
871
|
+
const path = boundary.assertPath(evidence.value);
|
|
872
|
+
if (existsSync4(path) && statSync2(path).isSymbolicLink()) throw new Error("symlink");
|
|
873
|
+
} catch {
|
|
874
|
+
return rejected(workspaceRoot, before, "EVIDENCE_PATH_OUTSIDE_WORKSPACE", "Path da evid\xEAncia fora do workspace autorizado.", input, subject);
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
const entry = audit(workspaceRoot, "agent_execution_event", before, { outcome: "accepted", reasonCode: "EVIDENCE_ACCEPTED", reason: input.reason, actor: input.actor, itemId: input.itemId, details: { evidence: input.evidence.map((e) => ({ ...e, observedAt: e.observedAt ?? (/* @__PURE__ */ new Date()).toISOString(), sha256: e.sha256 ?? createHash("sha256").update(e.value).digest("hex") })) } });
|
|
879
|
+
return result(before, entry.id, "accepted", "EVIDENCE_ACCEPTED", input.reason, resolveAgentDirection(workspaceRoot));
|
|
880
|
+
}
|
|
881
|
+
async function requestHandoffOperation(root, input) {
|
|
882
|
+
const workspaceRoot = createWorkspaceBoundary(resolve2(root)).root;
|
|
883
|
+
const before = resolveAgentDirection(workspaceRoot);
|
|
884
|
+
const subject = { itemId: input.itemId, operation: "request_handoff" };
|
|
885
|
+
const stale = checkRevision(workspaceRoot, before, input, subject);
|
|
886
|
+
if (stale) return stale;
|
|
887
|
+
const workflow = loadWorkflow(workspaceRoot);
|
|
888
|
+
const item = workflow?.items.find((candidate) => candidate.id === input.itemId);
|
|
889
|
+
if (!workflow || !item || item.claimedBy !== input.actor || item.claimExecutorId && item.claimExecutorId !== input.executorId) return rejected(workspaceRoot, before, "CLAIM_REQUIRED", "Handoff exige claim vigente do executor.", input, subject);
|
|
890
|
+
if (item.handoff) return rejected(workspaceRoot, before, "HANDOFF_CONFLICT", "J\xE1 existe handoff pendente.", input, subject);
|
|
891
|
+
const now = /* @__PURE__ */ new Date();
|
|
892
|
+
item.handoff = { from: input.actor ?? "unknown", to: input.to, summary: input.summary, evidence: input.evidence, timestamp: now.toISOString(), expiresAt: new Date(now.getTime() + (input.ttlMinutes ?? 30) * 6e4).toISOString(), executorId: input.executorId };
|
|
893
|
+
item.claimedBy = void 0;
|
|
894
|
+
item.claimedAt = void 0;
|
|
895
|
+
item.claimExecutorId = void 0;
|
|
896
|
+
item.claimCapability = void 0;
|
|
897
|
+
item.claimRevision = void 0;
|
|
898
|
+
item.claimExpiresAt = void 0;
|
|
899
|
+
item.claimTtlMinutes = void 0;
|
|
900
|
+
workflow.updatedAt = now.toISOString();
|
|
901
|
+
const write = await writeWorkflow(workspaceRoot, { workflow, source: "flow-handoff", primaryItemId: item.id, skipSitrep: true, skipLog: true, quiet: true, confineAdapterWrites: true });
|
|
902
|
+
if (!write.ok) return rejected(workspaceRoot, before, "HANDOFF_WRITE_FAILED", write.error ?? "Falha ao persistir handoff.", input, subject);
|
|
903
|
+
const entry = audit(workspaceRoot, "agent_execution_event", before, { outcome: "accepted", reasonCode: "HANDOFF_ACCEPTED", reason: input.reason, actor: input.actor, itemId: item.id, details: { to: input.to, executorId: input.executorId } });
|
|
904
|
+
return result(before, entry.id, "accepted", "HANDOFF_ACCEPTED", input.reason, resolveAgentDirection(workspaceRoot));
|
|
905
|
+
}
|
|
906
|
+
function audit(root, action, direction, input) {
|
|
907
|
+
return logEntry(root, action, input.reason, {
|
|
908
|
+
itemId: input.itemId,
|
|
909
|
+
acId: input.acId,
|
|
910
|
+
details: {
|
|
911
|
+
adapter: "codex",
|
|
912
|
+
by: input.actor ?? "agent:codex",
|
|
913
|
+
revision: direction.revision,
|
|
914
|
+
outcome: input.outcome,
|
|
915
|
+
reasonCode: input.reasonCode,
|
|
916
|
+
...input.details
|
|
917
|
+
}
|
|
918
|
+
});
|
|
919
|
+
}
|
|
920
|
+
function result(direction, entryId, outcome, reasonCode, reason, nextDirection = direction, extra = {}) {
|
|
921
|
+
return {
|
|
922
|
+
outcome,
|
|
923
|
+
auditId: entryId,
|
|
924
|
+
beforeRevision: direction.revision,
|
|
925
|
+
afterRevision: nextDirection.revision,
|
|
926
|
+
reasonCode,
|
|
927
|
+
reason,
|
|
928
|
+
nextDirection,
|
|
929
|
+
...extra
|
|
930
|
+
};
|
|
931
|
+
}
|
|
932
|
+
function rejected(root, direction, reasonCode, reason, context, subject) {
|
|
933
|
+
const entry = audit(root, "agent_operation_rejected", direction, {
|
|
934
|
+
outcome: "rejected",
|
|
935
|
+
reasonCode,
|
|
936
|
+
reason,
|
|
937
|
+
actor: context.actor,
|
|
938
|
+
itemId: subject.itemId,
|
|
939
|
+
acId: subject.acId,
|
|
940
|
+
details: { operation: subject.operation }
|
|
941
|
+
});
|
|
942
|
+
return result(direction, entry.id, "rejected", reasonCode, reason);
|
|
943
|
+
}
|
|
944
|
+
function checkRevision(root, direction, context, subject) {
|
|
945
|
+
if (context.expectedRevision === direction.revision) return null;
|
|
946
|
+
return rejected(
|
|
947
|
+
root,
|
|
948
|
+
direction,
|
|
949
|
+
"DIRECTION_STALE",
|
|
950
|
+
"A dire\xE7\xE3o mudou desde a \xFAltima consulta. Consulte get_direction e tente novamente.",
|
|
951
|
+
context,
|
|
952
|
+
subject
|
|
953
|
+
);
|
|
954
|
+
}
|
|
955
|
+
function normalizeAcId(value) {
|
|
956
|
+
const match = value.trim().match(/^AC[\s-]?(\d+(?:\.\d+)*)$/i);
|
|
957
|
+
return match ? `AC${match[1]}` : value.trim().toUpperCase();
|
|
958
|
+
}
|
|
959
|
+
async function claimOperation(root, input) {
|
|
960
|
+
const workspaceRoot = createWorkspaceBoundary(resolve2(root)).root;
|
|
961
|
+
const before = resolveAgentDirection(workspaceRoot);
|
|
962
|
+
const subject = { itemId: input.itemId, operation: "claim" };
|
|
963
|
+
const stale = checkRevision(workspaceRoot, before, input, subject);
|
|
964
|
+
if (stale) return stale;
|
|
965
|
+
if (!input.actor?.trim())
|
|
966
|
+
return rejected(workspaceRoot, before, "ACTOR_REQUIRED", "Claim exige identidade do actor.", input, subject);
|
|
967
|
+
if (!before.item || before.item.id !== input.itemId)
|
|
968
|
+
return rejected(workspaceRoot, before, "ITEM_NOT_CURRENT", "O claim exige o item vigente.", input, subject);
|
|
969
|
+
const flow = resolveActiveFlow(workspaceRoot).flow;
|
|
970
|
+
const stage = flow?.stages.find((candidate) => candidate.id === before.item?.stage);
|
|
971
|
+
const capabilities = stage?.roles.flatMap((role) => role.capabilities) ?? [];
|
|
972
|
+
if (capabilities.length > 0 && !capabilities.includes(input.capability))
|
|
973
|
+
return rejected(workspaceRoot, before, "CAPABILITY_INVALID", `Capability n\xE3o permitida: ${input.capability}.`, input, subject);
|
|
974
|
+
const workflow = loadWorkflow(workspaceRoot);
|
|
975
|
+
const item = workflow?.items.find((candidate) => candidate.id === input.itemId);
|
|
976
|
+
if (!workflow || !item) return rejected(workspaceRoot, before, "ITEM_NOT_FOUND", "Item n\xE3o encontrado.", input, subject);
|
|
977
|
+
const claimExpired = item.claimExpiresAt ? Date.now() >= Date.parse(item.claimExpiresAt) : false;
|
|
978
|
+
if (item.claimedBy && !claimExpired && (item.claimedBy !== input.actor || item.claimExecutorId !== input.executorId))
|
|
979
|
+
return rejected(workspaceRoot, before, "CLAIM_CONFLICT", `Item j\xE1 est\xE1 sob responsabilidade de ${item.claimedBy}.`, input, subject);
|
|
980
|
+
const ttl = Math.max(1, Math.min(1440, input.ttlMinutes ?? 30));
|
|
981
|
+
const now = /* @__PURE__ */ new Date();
|
|
982
|
+
item.claimedBy = input.actor.trim();
|
|
983
|
+
item.claimedAt = now.toISOString();
|
|
984
|
+
item.claimExecutorId = input.executorId.trim();
|
|
985
|
+
item.claimCapability = input.capability.trim();
|
|
986
|
+
item.claimRevision = before.revision;
|
|
987
|
+
item.claimTtlMinutes = ttl;
|
|
988
|
+
item.claimExpiresAt = new Date(now.getTime() + ttl * 6e4).toISOString();
|
|
989
|
+
workflow.updatedAt = now.toISOString();
|
|
990
|
+
const writeResult = await writeWorkflow(workspaceRoot, {
|
|
991
|
+
workflow,
|
|
992
|
+
source: "flow-claim",
|
|
993
|
+
primaryItemId: item.id,
|
|
994
|
+
skipSitrep: true,
|
|
995
|
+
skipLog: true,
|
|
996
|
+
quiet: true,
|
|
997
|
+
confineAdapterWrites: true
|
|
998
|
+
});
|
|
999
|
+
if (!writeResult.ok)
|
|
1000
|
+
return rejected(workspaceRoot, before, "CLAIM_WRITE_FAILED", writeResult.error ?? "Falha ao persistir claim.", input, subject);
|
|
1001
|
+
const after = resolveAgentDirection(workspaceRoot);
|
|
1002
|
+
const entry = audit(workspaceRoot, "agent_claim_requested", before, {
|
|
1003
|
+
outcome: "accepted",
|
|
1004
|
+
reasonCode: "CLAIM_ACCEPTED",
|
|
1005
|
+
reason: input.reason,
|
|
1006
|
+
actor: input.actor,
|
|
1007
|
+
itemId: item.id,
|
|
1008
|
+
details: { executorId: input.executorId, capability: input.capability, ttlMinutes: ttl, expiresAt: item.claimExpiresAt }
|
|
1009
|
+
});
|
|
1010
|
+
return result(before, entry.id, "accepted", "CLAIM_ACCEPTED", input.reason, after);
|
|
1011
|
+
}
|
|
1012
|
+
async function recordExecutionEvent(root, input) {
|
|
1013
|
+
const workspaceRoot = createWorkspaceBoundary(resolve2(root)).root;
|
|
1014
|
+
const before = resolveAgentDirection(workspaceRoot);
|
|
1015
|
+
const subject = { itemId: input.itemId, operation: input.status };
|
|
1016
|
+
const stale = checkRevision(workspaceRoot, before, input, subject);
|
|
1017
|
+
if (stale) return stale;
|
|
1018
|
+
if (!input.actor?.trim()) return rejected(workspaceRoot, before, "ACTOR_REQUIRED", "Evento exige identidade do actor.", input, subject);
|
|
1019
|
+
if (!before.item || before.item.id !== input.itemId) return rejected(workspaceRoot, before, "ITEM_NOT_CURRENT", "Evento exige o item vigente.", input, subject);
|
|
1020
|
+
const workflow = loadWorkflow(workspaceRoot);
|
|
1021
|
+
const item = workflow?.items.find((candidate) => candidate.id === input.itemId);
|
|
1022
|
+
if (!workflow || !item) return rejected(workspaceRoot, before, "ITEM_NOT_FOUND", "Item n\xE3o encontrado.", input, subject);
|
|
1023
|
+
const expired = !item.claimExpiresAt || Date.now() >= Date.parse(item.claimExpiresAt);
|
|
1024
|
+
if (item.claimedBy !== input.actor || item.claimExecutorId !== input.executorId) return rejected(workspaceRoot, before, "CLAIM_REQUIRED", "Actor e executor precisam possuir o claim vigente.", input, subject);
|
|
1025
|
+
if (expired) return rejected(workspaceRoot, before, "CLAIM_EXPIRED", "O lease do claim expirou; fa\xE7a um novo claim.", input, subject);
|
|
1026
|
+
const nowDate = /* @__PURE__ */ new Date();
|
|
1027
|
+
const now = nowDate.toISOString();
|
|
1028
|
+
item.activityStatus = input.status;
|
|
1029
|
+
if (input.status === "started") item.activityStartedAt = now;
|
|
1030
|
+
if (input.status === "heartbeat" || input.status === "started") item.lastHeartbeatAt = now;
|
|
1031
|
+
if (input.status === "heartbeat") item.claimExpiresAt = new Date(nowDate.getTime() + (item.claimTtlMinutes ?? 30) * 6e4).toISOString();
|
|
1032
|
+
if (input.status === "failed") item.lastFailure = { code: input.errorCode ?? "EXECUTION_FAILED", message: input.message ?? "Execu\xE7\xE3o falhou.", recovery: input.recovery ?? "human", at: now };
|
|
1033
|
+
workflow.updatedAt = now;
|
|
1034
|
+
const writeResult = await writeWorkflow(workspaceRoot, { workflow, source: "flow-claim", primaryItemId: item.id, skipSitrep: true, skipLog: true, quiet: true, confineAdapterWrites: true });
|
|
1035
|
+
if (!writeResult.ok) return rejected(workspaceRoot, before, "EVENT_WRITE_FAILED", writeResult.error ?? "Falha ao persistir evento.", input, subject);
|
|
1036
|
+
const after = resolveAgentDirection(workspaceRoot);
|
|
1037
|
+
const entry = audit(workspaceRoot, "agent_execution_event", before, { outcome: "accepted", reasonCode: "EVENT_RECORDED", reason: input.reason, actor: input.actor, itemId: item.id, details: { status: input.status, executorId: input.executorId, message: input.message, recovery: input.recovery, errorCode: input.errorCode } });
|
|
1038
|
+
return result(before, entry.id, "accepted", "EVENT_RECORDED", input.reason, after);
|
|
1039
|
+
}
|
|
1040
|
+
function markPendingAc(content, acId) {
|
|
1041
|
+
const lines = content.split("\n");
|
|
1042
|
+
const expected = normalizeAcId(acId);
|
|
1043
|
+
const index = lines.findIndex((line) => {
|
|
1044
|
+
if (!/^\s*-\s*\[ \]\s*\*\*/.test(line)) return false;
|
|
1045
|
+
const label = line.match(/\*\*([^*]+)\*\*/)?.[1] ?? "";
|
|
1046
|
+
const id = label.match(/\bAC[\s-]?(\d+(?:\.\d+)*)\b/i);
|
|
1047
|
+
return id ? `AC${id[1]}` === expected : false;
|
|
1048
|
+
});
|
|
1049
|
+
if (index < 0) return null;
|
|
1050
|
+
lines[index] = lines[index].replace(/\[ \]/, "[x]");
|
|
1051
|
+
return lines.join("\n");
|
|
1052
|
+
}
|
|
1053
|
+
async function runValidationOperation(root, context) {
|
|
1054
|
+
const workspaceRoot = createWorkspaceBoundary(resolve2(root)).root;
|
|
1055
|
+
const before = resolveAgentDirection(workspaceRoot);
|
|
1056
|
+
const stale = checkRevision(workspaceRoot, before, context, { operation: "validate" });
|
|
1057
|
+
if (stale) return stale;
|
|
1058
|
+
const validation = await validate(workspaceRoot, {
|
|
1059
|
+
format: "silent",
|
|
1060
|
+
exit: false,
|
|
1061
|
+
log: false
|
|
1062
|
+
});
|
|
1063
|
+
const after = resolveAgentDirection(workspaceRoot);
|
|
1064
|
+
const entry = audit(workspaceRoot, "agent_validation_run", before, {
|
|
1065
|
+
outcome: validation.failed === 0 ? "accepted" : "rejected",
|
|
1066
|
+
reasonCode: validation.failed === 0 ? "VALIDATION_COMPLETED" : "VALIDATION_FAILED",
|
|
1067
|
+
reason: context.reason,
|
|
1068
|
+
actor: context.actor,
|
|
1069
|
+
itemId: before.item?.id,
|
|
1070
|
+
details: { validation }
|
|
1071
|
+
});
|
|
1072
|
+
return result(
|
|
1073
|
+
before,
|
|
1074
|
+
entry.id,
|
|
1075
|
+
validation.failed === 0 ? "accepted" : "rejected",
|
|
1076
|
+
validation.failed === 0 ? "VALIDATION_COMPLETED" : "VALIDATION_FAILED",
|
|
1077
|
+
context.reason,
|
|
1078
|
+
after,
|
|
1079
|
+
{ validation }
|
|
1080
|
+
);
|
|
1081
|
+
}
|
|
1082
|
+
function completeAcOperation(root, input) {
|
|
1083
|
+
const workspaceRoot = createWorkspaceBoundary(resolve2(root)).root;
|
|
1084
|
+
const boundary = createWorkspaceBoundary(resolveWorkspaceRoot(root).workspaceDir);
|
|
1085
|
+
const before = resolveAgentDirection(workspaceRoot);
|
|
1086
|
+
const subject = { itemId: before.item?.id, acId: input.acId, operation: "complete_ac" };
|
|
1087
|
+
const stale = checkRevision(workspaceRoot, before, input, subject);
|
|
1088
|
+
if (stale) return stale;
|
|
1089
|
+
const evidence = input.evidence.map((item) => item.trim()).filter(Boolean);
|
|
1090
|
+
if (evidence.length === 0) {
|
|
1091
|
+
return rejected(
|
|
1092
|
+
workspaceRoot,
|
|
1093
|
+
before,
|
|
1094
|
+
"REGRESSION_EVIDENCE_REQUIRED",
|
|
1095
|
+
"\xC9 obrigat\xF3ria ao menos uma evid\xEAncia verific\xE1vel de regress\xE3o.",
|
|
1096
|
+
input,
|
|
1097
|
+
subject
|
|
1098
|
+
);
|
|
1099
|
+
}
|
|
1100
|
+
const requestedAc = normalizeAcId(input.acId);
|
|
1101
|
+
if (!before.pendingAC || normalizeAcId(before.pendingAC.id) !== requestedAc) {
|
|
1102
|
+
return rejected(
|
|
1103
|
+
workspaceRoot,
|
|
1104
|
+
before,
|
|
1105
|
+
"AC_NOT_CURRENT",
|
|
1106
|
+
`O AC solicitado n\xE3o \xE9 o crit\xE9rio pendente vigente (${before.pendingAC?.id ?? "nenhum"}).`,
|
|
1107
|
+
input,
|
|
1108
|
+
subject
|
|
1109
|
+
);
|
|
1110
|
+
}
|
|
1111
|
+
const spec = before.item?.spec;
|
|
1112
|
+
if (!spec || !/^[a-zA-Z0-9._-]+$/.test(spec)) {
|
|
1113
|
+
return rejected(
|
|
1114
|
+
workspaceRoot,
|
|
1115
|
+
before,
|
|
1116
|
+
"ACTIVE_SPEC_REQUIRED",
|
|
1117
|
+
"O item vigente n\xE3o possui uma spec v\xE1lida vinculada.",
|
|
1118
|
+
input,
|
|
1119
|
+
subject
|
|
1120
|
+
);
|
|
1121
|
+
}
|
|
1122
|
+
const specDir = join4(getLetraDir(workspaceRoot), "specs", spec);
|
|
1123
|
+
const specPath = boundary.assertPath(join4(specDir, "spec.md"));
|
|
1124
|
+
if (!existsSync4(specPath)) {
|
|
1125
|
+
return rejected(
|
|
1126
|
+
workspaceRoot,
|
|
1127
|
+
before,
|
|
1128
|
+
"ACTIVE_SPEC_REQUIRED",
|
|
1129
|
+
"A spec vigente n\xE3o foi encontrada no workspace.",
|
|
1130
|
+
input,
|
|
1131
|
+
subject
|
|
1132
|
+
);
|
|
1133
|
+
}
|
|
1134
|
+
const updatedSpec = markPendingAc(readFileSync4(specPath, "utf-8"), requestedAc);
|
|
1135
|
+
if (!updatedSpec) {
|
|
1136
|
+
return rejected(
|
|
1137
|
+
workspaceRoot,
|
|
1138
|
+
before,
|
|
1139
|
+
"AC_NOT_PENDING",
|
|
1140
|
+
"O AC solicitado n\xE3o est\xE1 pendente na spec vigente.",
|
|
1141
|
+
input,
|
|
1142
|
+
subject
|
|
1143
|
+
);
|
|
1144
|
+
}
|
|
1145
|
+
const acceptancePath = boundary.assertPath(join4(specDir, "acceptance.md"));
|
|
1146
|
+
const updatedAcceptance = existsSync4(acceptancePath) ? markPendingAc(readFileSync4(acceptancePath, "utf-8"), requestedAc) : null;
|
|
1147
|
+
const specTmp = `${specPath}.tmp`;
|
|
1148
|
+
writeFileSync(specTmp, updatedSpec, "utf-8");
|
|
1149
|
+
renameSync(specTmp, specPath);
|
|
1150
|
+
if (updatedAcceptance) {
|
|
1151
|
+
const acceptanceTmp = `${acceptancePath}.tmp`;
|
|
1152
|
+
writeFileSync(acceptanceTmp, updatedAcceptance, "utf-8");
|
|
1153
|
+
renameSync(acceptanceTmp, acceptancePath);
|
|
1154
|
+
}
|
|
1155
|
+
const workflow = loadWorkflow(workspaceRoot);
|
|
1156
|
+
if (workflow?.tools?.length) {
|
|
1157
|
+
generateAdapters(workspaceRoot, workflow.tools, {
|
|
1158
|
+
source: "flow-ac",
|
|
1159
|
+
quiet: true,
|
|
1160
|
+
confineWrites: true
|
|
1161
|
+
});
|
|
1162
|
+
}
|
|
1163
|
+
const after = resolveAgentDirection(workspaceRoot);
|
|
1164
|
+
const entry = audit(workspaceRoot, "agent_ac_completion_requested", before, {
|
|
1165
|
+
outcome: "accepted",
|
|
1166
|
+
reasonCode: "AC_COMPLETED",
|
|
1167
|
+
reason: input.reason,
|
|
1168
|
+
actor: input.actor,
|
|
1169
|
+
itemId: before.item?.id,
|
|
1170
|
+
acId: requestedAc,
|
|
1171
|
+
details: { spec, evidence, afterRevision: after.revision }
|
|
1172
|
+
});
|
|
1173
|
+
return result(before, entry.id, "accepted", "AC_COMPLETED", input.reason, after);
|
|
1174
|
+
}
|
|
1175
|
+
async function requestTransitionOperation(root, input) {
|
|
1176
|
+
const workspaceRoot = createWorkspaceBoundary(resolve2(root)).root;
|
|
1177
|
+
const before = resolveAgentDirection(workspaceRoot);
|
|
1178
|
+
const subject = { itemId: input.itemId, operation: "request_transition" };
|
|
1179
|
+
const stale = checkRevision(workspaceRoot, before, input, subject);
|
|
1180
|
+
if (stale) return stale;
|
|
1181
|
+
if (!before.item || before.item.id !== input.itemId) {
|
|
1182
|
+
return rejected(
|
|
1183
|
+
workspaceRoot,
|
|
1184
|
+
before,
|
|
1185
|
+
"ITEM_NOT_CURRENT",
|
|
1186
|
+
"A transi\xE7\xE3o somente pode ser solicitada para o item vigente.",
|
|
1187
|
+
input,
|
|
1188
|
+
subject
|
|
1189
|
+
);
|
|
1190
|
+
}
|
|
1191
|
+
if (before.pendingAC) {
|
|
1192
|
+
return rejected(
|
|
1193
|
+
workspaceRoot,
|
|
1194
|
+
before,
|
|
1195
|
+
"PENDING_ACCEPTANCE_CRITERIA",
|
|
1196
|
+
`O item ainda possui o crit\xE9rio pendente ${before.pendingAC.id}.`,
|
|
1197
|
+
input,
|
|
1198
|
+
subject
|
|
1199
|
+
);
|
|
1200
|
+
}
|
|
1201
|
+
const workflow = loadWorkflow(workspaceRoot);
|
|
1202
|
+
const item = workflow?.items.find((candidate) => candidate.id === input.itemId);
|
|
1203
|
+
const target = workflow?.stages.find((stage) => stage.id === input.targetStageId);
|
|
1204
|
+
if (!workflow || !item || !target) {
|
|
1205
|
+
return rejected(
|
|
1206
|
+
workspaceRoot,
|
|
1207
|
+
before,
|
|
1208
|
+
"INVALID_TRANSITION",
|
|
1209
|
+
"O item ou est\xE1gio de destino n\xE3o existe no workflow vigente.",
|
|
1210
|
+
input,
|
|
1211
|
+
subject
|
|
1212
|
+
);
|
|
1213
|
+
}
|
|
1214
|
+
if (item.stage === target.id) {
|
|
1215
|
+
return rejected(
|
|
1216
|
+
workspaceRoot,
|
|
1217
|
+
before,
|
|
1218
|
+
"INVALID_TRANSITION",
|
|
1219
|
+
"O item j\xE1 est\xE1 no est\xE1gio solicitado.",
|
|
1220
|
+
input,
|
|
1221
|
+
subject
|
|
1222
|
+
);
|
|
1223
|
+
}
|
|
1224
|
+
if (before.allowedStageIds.length > 0 && !before.allowedStageIds.includes(target.id)) {
|
|
1225
|
+
return rejected(
|
|
1226
|
+
workspaceRoot,
|
|
1227
|
+
before,
|
|
1228
|
+
"STAGE_NOT_ALLOWED",
|
|
1229
|
+
"O papel vigente n\xE3o permite transi\xE7\xE3o para o est\xE1gio solicitado.",
|
|
1230
|
+
input,
|
|
1231
|
+
subject
|
|
1232
|
+
);
|
|
1233
|
+
}
|
|
1234
|
+
const activeFlow = resolveActiveFlow(workspaceRoot).flow;
|
|
1235
|
+
const sourceDefinition = activeFlow?.stages.find((stage) => stage.id === item.stage);
|
|
1236
|
+
const targetDefinition = activeFlow?.stages.find((stage) => stage.id === target.id);
|
|
1237
|
+
const blockingGate = [sourceDefinition?.gate, targetDefinition?.gate].find(
|
|
1238
|
+
(gate) => gate?.blocking
|
|
1239
|
+
);
|
|
1240
|
+
if (blockingGate) {
|
|
1241
|
+
const checker = new GateChecker(workspaceRoot);
|
|
1242
|
+
const gateResult = checker.check(blockingGate.id, item);
|
|
1243
|
+
if (blockingGate.type === "human") {
|
|
1244
|
+
const gateHint = targetDefinition?.activity?.gate;
|
|
1245
|
+
const reviewHint = targetDefinition?.activity?.review;
|
|
1246
|
+
const enriched = {
|
|
1247
|
+
...before,
|
|
1248
|
+
allowedStageIds: targetDefinition ? [...new Set(targetDefinition.roles.flatMap((role) => role.allowedStages))] : before.allowedStageIds,
|
|
1249
|
+
prohibitions: [...gateHint?.mustNotDo ?? reviewHint?.mustNotDo ?? []],
|
|
1250
|
+
requiredEvidence: gateHint?.evidence ? [gateHint.evidence] : []
|
|
1251
|
+
};
|
|
1252
|
+
enriched.pendingAC = void 0;
|
|
1253
|
+
const entry2 = audit(workspaceRoot, "agent_transition_requested", before, {
|
|
1254
|
+
outcome: "approval-required",
|
|
1255
|
+
reasonCode: "HUMAN_APPROVAL_REQUIRED",
|
|
1256
|
+
reason: `O gate "${blockingGate.name}" exige decis\xE3o humana expl\xEDcita.`,
|
|
1257
|
+
actor: input.actor,
|
|
1258
|
+
itemId: item.id,
|
|
1259
|
+
details: { from: item.stage, to: target.id, gateId: blockingGate.id }
|
|
1260
|
+
});
|
|
1261
|
+
return result(
|
|
1262
|
+
before,
|
|
1263
|
+
entry2.id,
|
|
1264
|
+
"approval-required",
|
|
1265
|
+
"HUMAN_APPROVAL_REQUIRED",
|
|
1266
|
+
`O gate "${blockingGate.name}" exige decis\xE3o humana expl\xEDcita.`,
|
|
1267
|
+
enriched
|
|
1268
|
+
);
|
|
1269
|
+
}
|
|
1270
|
+
if (!gateResult.allowed) {
|
|
1271
|
+
return rejected(
|
|
1272
|
+
workspaceRoot,
|
|
1273
|
+
before,
|
|
1274
|
+
"BLOCKING_GATE",
|
|
1275
|
+
gateResult.reason ?? `O gate "${blockingGate.name}" deve ser satisfeito antes da transi\xE7\xE3o.`,
|
|
1276
|
+
input,
|
|
1277
|
+
subject
|
|
1278
|
+
);
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
const from = item.stage;
|
|
1282
|
+
item.stage = target.id;
|
|
1283
|
+
workflow.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1284
|
+
const writeResult = await writeWorkflow(workspaceRoot, {
|
|
1285
|
+
workflow,
|
|
1286
|
+
source: "flow-move",
|
|
1287
|
+
primaryItemId: item.id,
|
|
1288
|
+
skipSitrep: true,
|
|
1289
|
+
skipLog: true,
|
|
1290
|
+
quiet: true,
|
|
1291
|
+
confineAdapterWrites: true
|
|
1292
|
+
});
|
|
1293
|
+
if (!writeResult.ok) {
|
|
1294
|
+
return rejected(
|
|
1295
|
+
workspaceRoot,
|
|
1296
|
+
before,
|
|
1297
|
+
"TRANSITION_WRITE_FAILED",
|
|
1298
|
+
writeResult.error ?? "A persist\xEAncia da transi\xE7\xE3o falhou.",
|
|
1299
|
+
input,
|
|
1300
|
+
subject
|
|
1301
|
+
);
|
|
1302
|
+
}
|
|
1303
|
+
if (item.spec) writeFocusWithRecommendations(workspaceRoot, item.spec, item.id);
|
|
1304
|
+
const after = resolveAgentDirection(workspaceRoot);
|
|
1305
|
+
const entry = audit(workspaceRoot, "agent_transition_requested", before, {
|
|
1306
|
+
outcome: "accepted",
|
|
1307
|
+
reasonCode: "TRANSITION_COMPLETED",
|
|
1308
|
+
reason: input.reason,
|
|
1309
|
+
actor: input.actor,
|
|
1310
|
+
itemId: item.id,
|
|
1311
|
+
details: { from, to: target.id, afterRevision: after.revision }
|
|
1312
|
+
});
|
|
1313
|
+
return result(before, entry.id, "accepted", "TRANSITION_COMPLETED", input.reason, after);
|
|
1314
|
+
}
|
|
1315
|
+
|
|
1316
|
+
export {
|
|
1317
|
+
validate,
|
|
1318
|
+
activityOperation,
|
|
1319
|
+
submitEvidenceOperation,
|
|
1320
|
+
requestHandoffOperation,
|
|
1321
|
+
claimOperation,
|
|
1322
|
+
recordExecutionEvent,
|
|
1323
|
+
runValidationOperation,
|
|
1324
|
+
completeAcOperation,
|
|
1325
|
+
requestTransitionOperation
|
|
1326
|
+
};
|