@guilhermednobre/agent-kit 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/README.md +102 -47
  3. package/bin/cli.js +79 -38
  4. package/package.json +12 -4
  5. package/src/cli/tools.js +51 -0
  6. package/src/cli/wf.js +400 -0
  7. package/src/core/briefing.js +188 -0
  8. package/src/core/config.js +321 -0
  9. package/src/core/dag.js +103 -0
  10. package/src/core/engine.js +505 -0
  11. package/src/core/policy.js +145 -0
  12. package/src/core/report.js +104 -0
  13. package/src/core/states.js +59 -0
  14. package/src/core/store.js +60 -0
  15. package/src/core/verify.js +54 -0
  16. package/src/detect.js +6 -0
  17. package/src/generate.js +55 -0
  18. package/src/install.js +22 -14
  19. package/src/render.js +5 -7
  20. package/src/runtimes/index.js +24 -0
  21. package/src/runtimes/orca.js +61 -0
  22. package/src/runtimes/t3.js +87 -0
  23. package/src/trackers/index.js +34 -0
  24. package/src/trackers/linear-t3.js +138 -0
  25. package/src/trackers/linear.js +209 -0
  26. package/templates/AGENTS.md +111 -110
  27. package/templates/CLAUDE.md +185 -306
  28. package/templates/agent-kit/hooks/pretooluse.mjs +53 -0
  29. package/templates/agent-kit/hooks/session-context.mjs +41 -0
  30. package/templates/agent-kit/runtime/orca.md +68 -0
  31. package/templates/agent-kit/runtime/t3.md +109 -0
  32. package/templates/claude/commands/analisar-consistencia.md +111 -0
  33. package/templates/claude/commands/avaliar-ideia.md +63 -0
  34. package/templates/claude/commands/configurar-worker.md +116 -0
  35. package/templates/claude/commands/criar-prd.md +16 -1
  36. package/templates/claude/commands/criar-tasks.md +40 -3
  37. package/templates/claude/commands/criar-techspec.md +12 -1
  38. package/templates/claude/commands/executar-bugfix.md +11 -11
  39. package/templates/claude/commands/executar-qa.md +14 -15
  40. package/templates/claude/commands/executar-release.md +20 -0
  41. package/templates/claude/commands/executar-review.md +51 -31
  42. package/templates/claude/commands/executar-task.md +14 -23
  43. package/templates/claude/commands/executar-workflow.md +101 -0
  44. package/templates/claude/commands/fechar-ciclo.md +88 -0
  45. package/templates/claude/commands/replanejar-workflow.md +32 -0
  46. package/templates/claude/commands/retomar-workflow.md +30 -0
  47. package/templates/claude/commands/status-workflow.md +19 -0
  48. package/templates/claude/rules/README.md +2 -2
  49. package/templates/claude/settings.json +25 -0
  50. package/templates/claude/templates/bugs-template.md +2 -2
  51. package/templates/claude/templates/plan-template.json +33 -0
  52. package/templates/claude/templates/prd-template.md +65 -61
  53. package/templates/claude/templates/task-template.md +8 -8
  54. package/templates/claude/templates/tasks-template.md +1 -1
  55. package/templates/claude/templates/techspec-template.md +129 -129
  56. package/templates/claude/templates/worker-brief-template.md +11 -7
  57. package/templates/docs/agents/worker.md +94 -0
package/src/cli/wf.js ADDED
@@ -0,0 +1,400 @@
1
+ import { parseArgs } from "node:util";
2
+ import { readFile } from "node:fs/promises";
3
+ import { join, resolve } from "node:path";
4
+ import { executorId, loadSettings, profileForTask, validateAutonomy, validateConfig, validateWorkflow } from "../core/config.js";
5
+ import * as engine from "../core/engine.js";
6
+ import { buildBrief, buildGateBrief, hashBrief, readContextFiles } from "../core/briefing.js";
7
+ import { parseReport, parseReview } from "../core/report.js";
8
+ import { runChecks, taskChecks } from "../core/verify.js";
9
+ import { listRuns, loadRun, runExists, saveArtifact, saveRun } from "../core/store.js";
10
+ import { getAdapter } from "../runtimes/index.js";
11
+ import { createTracker } from "../trackers/index.js";
12
+ import { acknowledge, bindIssue } from "../trackers/linear-t3.js";
13
+
14
+ const OPTIONS = {
15
+ plan: { type: "string" },
16
+ "from-linear": { type: "string" },
17
+ objective: { type: "string" },
18
+ profile: { type: "string" },
19
+ ref: { type: "string" },
20
+ note: { type: "string" },
21
+ file: { type: "string" },
22
+ text: { type: "string" },
23
+ final: { type: "boolean", default: false },
24
+ cwd: { type: "string" },
25
+ verdict: { type: "string" },
26
+ reviewer: { type: "string" },
27
+ finding: { type: "string", multiple: true },
28
+ gate: { type: "string" },
29
+ key: { type: "string" },
30
+ url: { type: "string" },
31
+ ack: { type: "string" },
32
+ reason: { type: "string" },
33
+ resolution: { type: "string" },
34
+ "no-sync": { type: "boolean", default: false },
35
+ };
36
+
37
+ export const WF_HELP = `
38
+ agent-kit wf — workflow state for the coordinator (JSON output).
39
+
40
+ wf list
41
+ wf new <run> --plan <plan.json> [--objective <text>] create a run (publishes to the tracker)
42
+ wf new <run> --from-linear <ISSUE-ID> create a run from a Linear parent issue
43
+ wf next <run> what to dispatch, verify, review, reconcile
44
+ wf dispatch <run> <task> [--profile <name>] write the brief, start an attempt, print the runtime call
45
+ wf started <run> <task> --ref <runtime-id> [--gate <gate>] bind the runtime id (T3 taskId / Orca handle)
46
+ wf touch <run> <task> --note <text> record progress (resets the stall timer)
47
+ wf report <run> <task> --file <path> | --text <text> record the worker's final message
48
+ wf verify <run> <task> [--cwd <dir>] run the task's checks independently
49
+ wf verify <run> --final [--cwd <dir>] run every project check (nothing may be running)
50
+ wf gate <run> <task> <gate> brief + runtime call for a validation gate (qa, system, ...)
51
+ wf review <run> <task> --gate <gate> --reviewer <id> (--file <review.md> | --verdict approved|rejected [--finding <text>]...)
52
+ wf lost <run> <task> --reason <text> the runtime confirmed the worker is gone
53
+ wf takeover <run> <task> the coordinator implements a failed/blocked task itself
54
+ wf unblock <run> <task> --resolution <text>
55
+ wf cancel <run> <task> --reason <text>
56
+ wf replan <run> --plan <plan.json>
57
+ wf status <run> | wf resume <run> | wf complete <run>
58
+ wf sync <run> [--ack <ids>] push tracker events (with Linear via T3: prints the tool calls; ack after running them)
59
+ wf tracker-bind <run> <task|_parent> --key <KEY> [--url <url>] record an issue created through T3
60
+ `;
61
+
62
+ const now = () => new Date().toISOString();
63
+
64
+ export async function runWorkflowCommand(argv, { root = process.cwd(), out = console.log, env = process.env, fetchImpl } = {}) {
65
+ const { values, positionals } = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true });
66
+ const [command, runId, taskId, extra] = positionals;
67
+ if (!command || command === "help") {
68
+ out(WF_HELP.trim());
69
+ return 0;
70
+ }
71
+ const settings = await loadSettings(root);
72
+ const context = { root, values, settings, env, fetchImpl, runId, taskId, extra };
73
+ const handler = HANDLERS[command];
74
+ if (!handler) throw new Error(`Unknown wf command "${command}"\n${WF_HELP.trim()}`);
75
+ if (command !== "list" && !runId) throw new Error(`wf ${command} needs a run id`);
76
+ const result = await handler(context);
77
+ out(JSON.stringify(result.output, null, 2));
78
+ return result.exitCode || 0;
79
+ }
80
+
81
+ function need(value, flag) {
82
+ if (!value) throw new Error(`Missing ${flag}`);
83
+ return value;
84
+ }
85
+
86
+ function needTask(context) {
87
+ return need(context.taskId, "<task> argument");
88
+ }
89
+
90
+ async function persist(context, run, output, exitCode = 0) {
91
+ await saveRun(context.root, run);
92
+ if (!context.values["no-sync"]) {
93
+ try {
94
+ const tracker = createTracker(context.settings.config, context);
95
+ if (tracker.deferred) {
96
+ const unsynced = run.events.filter((event) => !event.synced).length;
97
+ output.tracker = { via: "t3", unsyncedEvents: unsynced, next: unsynced ? `agent-kit wf sync ${run.id}` : null };
98
+ return { output, exitCode };
99
+ }
100
+ output.tracker = await tracker.sync(run);
101
+ await saveRun(context.root, run);
102
+ } catch (error) {
103
+ output.tracker = { error: error.message, note: "state saved locally; run `agent-kit wf sync` later" };
104
+ }
105
+ }
106
+ return { output, exitCode };
107
+ }
108
+
109
+ async function readPlan(root, path) {
110
+ return JSON.parse(await readFile(resolve(root, path), "utf8"));
111
+ }
112
+
113
+ const HANDLERS = {
114
+ async list({ root }) {
115
+ return { output: await listRuns(root) };
116
+ },
117
+
118
+ async new(context) {
119
+ const { root, values, settings, runId } = context;
120
+ if (runExists(root, runId)) throw new Error(`Run "${runId}" already exists; use wf resume or wf replan`);
121
+ assertSettings(settings);
122
+ let plan;
123
+ let completed = [];
124
+ if (values["from-linear"]) {
125
+ const imported = await createTracker(settings.config, context).importPlan(values["from-linear"]);
126
+ plan = imported.plan;
127
+ completed = imported.completed;
128
+ } else {
129
+ plan = await readPlan(root, need(values.plan, "--plan <file>"));
130
+ }
131
+ const run = engine.createRun({ id: runId, objective: values.objective, plan, runtime: settings.config.runtime, now: now(), completed });
132
+ const output = { run: run.id, state: run.state, waves: run.waves };
133
+ if (!values["from-linear"] && !values["no-sync"]) {
134
+ try {
135
+ output.published = await createTracker(settings.config, context).publishPlan(run);
136
+ } catch (error) {
137
+ output.published = { error: error.message };
138
+ }
139
+ }
140
+ output.next = engine.nextActions(run, settings.autonomy, now());
141
+ if (!output.published?.error) for (const event of run.events) event.synced = true;
142
+ return persist(context, run, output);
143
+ },
144
+
145
+ async next(context) {
146
+ const run = await loadRun(context.root, context.runId);
147
+ const output = engine.nextActions(run, context.settings.autonomy, now());
148
+ output.completion = engine.completionStatus(run, context.settings.autonomy, context.settings.config);
149
+ return persist(context, run, output);
150
+ },
151
+
152
+ async dispatch(context) {
153
+ const { root, values, settings, runId } = context;
154
+ const taskId = needTask(context);
155
+ const run = await loadRun(root, runId);
156
+ const task = engine.getTask(run, taskId);
157
+ const adapter = getAdapter(settings.config.runtime);
158
+ const current = engine.currentAttempt(task);
159
+ if (task.state === "running" && current && !current.runtimeRef) {
160
+ const brief = await readFile(join(root, current.briefPath), "utf8");
161
+ const profile = profileForTask(task, settings.config, current.profile);
162
+ return { output: { redispatch: true, attempt: current.number, call: adapter.dispatch({ run, task, attempt: current, brief, profile, config: settings.config }) } };
163
+ }
164
+ return persist(context, run, await startTask(context, run, task, values.profile || task.fix?.profile));
165
+ },
166
+
167
+ async takeover(context) {
168
+ const run = await loadRun(context.root, context.runId);
169
+ const task = engine.reopenForTakeover(run, needTask(context), now());
170
+ return persist(context, run, await startTask(context, run, task, "coordinator"));
171
+ },
172
+
173
+ async started(context) {
174
+ const run = await loadRun(context.root, context.runId);
175
+ const bound = engine.bindRuntimeRef(run, needTask(context), need(context.values.ref, "--ref"), now(), context.values.gate);
176
+ return persist(context, run, { task: context.taskId, gate: context.values.gate || null, runtimeRef: bound.runtimeRef });
177
+ },
178
+
179
+ async touch(context) {
180
+ const run = await loadRun(context.root, context.runId);
181
+ engine.touch(run, needTask(context), need(context.values.note, "--note"), now());
182
+ return persist(context, run, { task: context.taskId, touched: true });
183
+ },
184
+
185
+ async report(context) {
186
+ const { root, values, settings, runId } = context;
187
+ const taskId = needTask(context);
188
+ const run = await loadRun(root, runId);
189
+ const text = values.file ? await readFile(resolve(root, values.file), "utf8") : need(values.text, "--file or --text");
190
+ const attemptNumber = engine.currentAttempt(engine.getTask(run, taskId))?.number || 0;
191
+ const reportPath = await saveArtifact(root, runId, `reports/${safe(taskId)}.${attemptNumber}.md`, text);
192
+ const parsed = parseReport(text);
193
+ const result = engine.recordReport(run, taskId, parsed, settings.autonomy, now());
194
+ return persist(context, run, { task: taskId, reportPath, valid: parsed.valid, errors: parsed.errors, state: run.tasks[taskId].state, ...result });
195
+ },
196
+
197
+ async verify(context) {
198
+ const { root, values, settings, runId } = context;
199
+ const run = await loadRun(root, runId);
200
+ const cwd = values.cwd ? resolve(root, values.cwd) : root;
201
+ if (values.final) {
202
+ const checks = await runChecks(settings.config.checks || [], { cwd });
203
+ engine.recordFinalChecks(run, checks, now());
204
+ await saveArtifact(root, runId, "checks/final.json", JSON.stringify(checks, null, 2));
205
+ return persist(context, run, { final: true, passed: checks.passed, results: summarize(checks.results) }, checks.passed ? 0 : 3);
206
+ }
207
+ const taskId = needTask(context);
208
+ const task = engine.getTask(run, taskId);
209
+ const checks = await runChecks(taskChecks(task, settings.config), { cwd });
210
+ const attemptNumber = engine.currentAttempt(task)?.number || 0;
211
+ await saveArtifact(root, runId, `checks/${safe(taskId)}.${attemptNumber}.json`, JSON.stringify(checks, null, 2));
212
+ const result = engine.recordChecks(run, taskId, checks, settings.autonomy, now(), settings.workflow);
213
+ return persist(context, run, { task: taskId, passed: checks.passed, skipped: checks.skipped, results: summarize(checks.results), state: task.state, ...result }, checks.passed ? 0 : 3);
214
+ },
215
+
216
+ async gate(context) {
217
+ const { root, settings, runId } = context;
218
+ const taskId = needTask(context);
219
+ const gateId = need(context.extra, "<gate> argument");
220
+ const run = await loadRun(root, runId);
221
+ const task = engine.getTask(run, taskId);
222
+ const attempt = engine.currentAttempt(task);
223
+ const gateConfig = (settings.workflow.gates || []).find((gate) => gate.id === gateId) || { id: gateId, role: "review" };
224
+ const profile = profileForTask({ id: taskId, role: gateConfig.role }, settings.config);
225
+ const adapter = getAdapter(settings.config.runtime);
226
+ const problems = adapter.validateProfile(profile, settings.config);
227
+ if (problems.length) throw new Error(problems.join("\n"));
228
+ const gate = engine.startGate(run, taskId, gateId, { profile: profile.name, executor: executorId(profile), now: now() });
229
+ const brief = buildGateBrief({ run, task, attempt, gate, gateConfig, config: settings.config, completionNote: adapter.completionNote });
230
+ const briefPath = await saveArtifact(root, runId, `briefs/${safe(taskId)}.${attempt.number}.gate-${safe(gateId)}.md`, brief);
231
+ const pseudoTask = { ...task, id: `${task.id}`, title: `gate ${gateId}: ${task.title}`, role: gateConfig.role };
232
+ const pseudoAttempt = { ...attempt, briefPath, clientRequestId: `agent-kit:${run.id}:${task.id}:${attempt.number}:gate-${gateId}` };
233
+ const call = adapter.dispatch({ run, task: pseudoTask, attempt: pseudoAttempt, brief, profile, config: settings.config });
234
+ if (call.then) call.then = `agent-kit wf started ${run.id} ${task.id} --gate ${gateId} --ref <taskId>`;
235
+ return persist(context, run, { task: taskId, gate: gateId, profile: profile.name, reviewer: executorId(profile), briefPath, call });
236
+ },
237
+
238
+ async review(context) {
239
+ const { root, values, settings, runId } = context;
240
+ const run = await loadRun(root, runId);
241
+ const taskId = needTask(context);
242
+ let review;
243
+ if (values.file) {
244
+ const text = await readFile(resolve(root, values.file), "utf8");
245
+ const attemptNumber = engine.currentAttempt(engine.getTask(run, taskId))?.number || 0;
246
+ await saveArtifact(root, runId, `reviews/${safe(taskId)}.${attemptNumber}.${safe(values.gate || "review")}.md`, text);
247
+ const parsed = parseReview(text);
248
+ if (!parsed.valid) throw new Error(`Invalid review: ${parsed.errors.join("; ")}. Ask the validator to resend its agent-kit-review block, or record the verdict with --verdict.`);
249
+ review = parsed.review;
250
+ } else {
251
+ review = { verdict: need(values.verdict, "--verdict or --file"), findings: values.finding || [], criteria: [] };
252
+ }
253
+ const result = engine.recordReview(
254
+ run,
255
+ taskId,
256
+ { gate: values.gate, verdict: review.verdict, reviewer: need(values.reviewer, "--reviewer"), findings: review.findings, criteria: review.criteria },
257
+ settings.autonomy,
258
+ now()
259
+ );
260
+ return persist(context, run, { task: taskId, gate: values.gate || null, verdict: review.verdict, state: run.tasks[taskId].state, ...result });
261
+ },
262
+
263
+ async lost(context) {
264
+ const run = await loadRun(context.root, context.runId);
265
+ const result = engine.markLost(run, needTask(context), need(context.values.reason, "--reason"), context.settings.autonomy, now());
266
+ return persist(context, run, { task: context.taskId, state: run.tasks[context.taskId].state, ...result });
267
+ },
268
+
269
+ async unblock(context) {
270
+ const run = await loadRun(context.root, context.runId);
271
+ engine.unblock(run, needTask(context), need(context.values.resolution, "--resolution"), now());
272
+ return persist(context, run, { task: context.taskId, state: run.tasks[context.taskId].state });
273
+ },
274
+
275
+ async cancel(context) {
276
+ const run = await loadRun(context.root, context.runId);
277
+ const task = engine.getTask(run, needTask(context));
278
+ const attempt = engine.currentAttempt(task);
279
+ const runtimeCall = task.state === "running" && attempt?.runtimeRef ? getAdapter(attempt.runtime).cancel({ attempt, reason: context.values.reason }) : null;
280
+ engine.cancelTask(run, task.id, need(context.values.reason, "--reason"), now());
281
+ return persist(context, run, { task: task.id, state: task.state, runtimeCall });
282
+ },
283
+
284
+ async replan(context) {
285
+ const run = await loadRun(context.root, context.runId);
286
+ engine.replan(run, await readPlan(context.root, need(context.values.plan, "--plan <file>")), now());
287
+ const output = { run: run.id, state: run.state, waves: run.waves };
288
+ if (!context.values["no-sync"]) {
289
+ try {
290
+ output.published = await createTracker(context.settings.config, context).publishPlan(run);
291
+ } catch (error) {
292
+ output.published = { error: error.message };
293
+ }
294
+ }
295
+ output.next = engine.nextActions(run, context.settings.autonomy, now());
296
+ return persist(context, run, output);
297
+ },
298
+
299
+ async status(context) {
300
+ const run = await loadRun(context.root, context.runId);
301
+ const tasks = run.order.map((id) => {
302
+ const task = run.tasks[id];
303
+ const attempt = engine.currentAttempt(task);
304
+ return { id, title: task.title, state: task.state, attempts: task.attempts.length, profile: attempt?.profile || null, runtimeRef: attempt?.runtimeRef || null, tracker: task.tracker?.identifier || null };
305
+ });
306
+ return {
307
+ output: {
308
+ run: run.id,
309
+ objective: run.objective,
310
+ state: run.state,
311
+ runtime: run.runtime,
312
+ tracker: run.tracker?.parent?.identifier || run.tracker?.kind || "local",
313
+ tasks,
314
+ unsyncedEvents: run.events.filter((event) => !event.synced).length,
315
+ completion: engine.completionStatus(run, context.settings.autonomy, context.settings.config),
316
+ },
317
+ };
318
+ },
319
+
320
+ async resume(context) {
321
+ const run = await loadRun(context.root, context.runId);
322
+ const runtime = context.settings.config.runtime;
323
+ const plan = engine.resumePlan(run, context.settings.autonomy, now(), runtime);
324
+ plan.gates = run.order
325
+ .map((id) => run.tasks[id])
326
+ .filter((task) => task.state === "review")
327
+ .flatMap((task) => Object.entries(engine.currentAttempt(task).gates || {})
328
+ .filter(([, gate]) => gate.status === "pending" && gate.dispatchedAt)
329
+ .map(([gate, info]) => ({ id: task.id, gate, runtimeRef: info.runtimeRef, call: info.runtimeRef ? getAdapter(runtime).status({ attempt: { runtimeRef: info.runtimeRef } }) : null })));
330
+ plan.reconcile = plan.reconcile.map((item) => {
331
+ const attempt = engine.currentAttempt(run.tasks[item.id]);
332
+ return { ...item, call: getAdapter(attempt.runtime || runtime).status({ attempt }) };
333
+ });
334
+ return persist(context, run, plan);
335
+ },
336
+
337
+ async complete(context) {
338
+ const run = await loadRun(context.root, context.runId);
339
+ const status = engine.completeRun(run, context.settings.autonomy, context.settings.config, now());
340
+ return persist(context, run, { run: run.id, state: run.state, ...status }, status.complete ? 0 : 3);
341
+ },
342
+
343
+ async sync(context) {
344
+ const run = await loadRun(context.root, context.runId);
345
+ const tracker = createTracker(context.settings.config, context);
346
+ if (context.values.ack) {
347
+ const ids = context.values.ack.split(",").map((id) => Number.parseInt(id, 10)).filter(Number.isInteger);
348
+ const acknowledged = acknowledge(run, ids);
349
+ await saveRun(context.root, run);
350
+ return { output: { acknowledged, unsyncedEvents: run.events.filter((event) => !event.synced).length } };
351
+ }
352
+ if (tracker.deferred) return { output: await tracker.sync(run) };
353
+ const published = await tracker.publishPlan(run);
354
+ const synced = await tracker.sync(run);
355
+ await saveRun(context.root, run);
356
+ return { output: { published, synced } };
357
+ },
358
+
359
+ async "tracker-bind"(context) {
360
+ const run = await loadRun(context.root, context.runId);
361
+ const bound = bindIssue(run, needTask(context), { key: need(context.values.key, "--key"), url: context.values.url || null });
362
+ await saveRun(context.root, run);
363
+ return { output: { target: context.taskId, ...bound } };
364
+ },
365
+ };
366
+
367
+ async function startTask(context, run, task, profileName) {
368
+ const { root, settings } = context;
369
+ const adapter = getAdapter(settings.config.runtime);
370
+ const profile = profileForTask(task, settings.config, profileName);
371
+ const problems = adapter.validateProfile(profile, settings.config);
372
+ if (problems.length) throw new Error(problems.join("\n"));
373
+ const attemptNumber = task.attempts.length + 1;
374
+ const contextFiles = await readContextFiles(root, [task.doc, ...task.context].filter(Boolean));
375
+ const brief = buildBrief({ run, task, attemptNumber, config: settings.config, autonomy: settings.autonomy, contextFiles, completionNote: adapter.completionNote });
376
+ const briefPath = await saveArtifact(root, run.id, `briefs/${safe(task.id)}.${attemptNumber}.md`, brief);
377
+ const attempt = engine.startAttempt(run, task.id, {
378
+ profile: profile.name,
379
+ executor: executorId(profile),
380
+ runtime: adapter.name,
381
+ briefPath,
382
+ briefHash: hashBrief(brief),
383
+ now: now(),
384
+ });
385
+ const call = adapter.dispatch({ run, task, attempt, brief, profile, config: settings.config });
386
+ return { task: task.id, attempt: attempt.number, profile: profile.name, briefPath, call };
387
+ }
388
+
389
+ function assertSettings({ config, autonomy, workflow }) {
390
+ const errors = [...validateConfig(config).errors, ...validateAutonomy(autonomy, config).errors, ...validateWorkflow(workflow, config).errors];
391
+ if (errors.length) throw new Error(`Invalid .agent-kit configuration:\n- ${errors.join("\n- ")}`);
392
+ }
393
+
394
+ function safe(id) {
395
+ return String(id).replace(/[^a-z0-9._-]/gi, "_");
396
+ }
397
+
398
+ function summarize(results) {
399
+ return results.map((result) => ({ name: result.name, passed: result.passed, exitCode: result.exitCode, timedOut: result.timedOut, tail: result.output.slice(-600) }));
400
+ }
@@ -0,0 +1,188 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFile } from "node:fs/promises";
3
+ import { existsSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { reportExample, reviewExample } from "./report.js";
6
+ import { protectedCategories } from "./policy.js";
7
+ import { ACTIVE_TASK_STATES } from "./states.js";
8
+
9
+ const PER_FILE_LIMIT = 24000;
10
+ const TOTAL_LIMIT = 60000;
11
+
12
+ export async function readContextFiles(root, paths) {
13
+ const files = [];
14
+ let budget = TOTAL_LIMIT;
15
+ for (const path of paths) {
16
+ const absolute = join(root, path);
17
+ if (!existsSync(absolute)) {
18
+ files.push({ path, missing: true });
19
+ continue;
20
+ }
21
+ const text = await readFile(absolute, "utf8");
22
+ if (text.length > PER_FILE_LIMIT || text.length > budget) {
23
+ files.push({ path, tooLarge: true, size: text.length });
24
+ continue;
25
+ }
26
+ budget -= text.length;
27
+ files.push({ path, text });
28
+ }
29
+ return files;
30
+ }
31
+
32
+ export function hashBrief(text) {
33
+ return createHash("sha256").update(text).digest("hex");
34
+ }
35
+
36
+ export function buildBrief({ run, task, attemptNumber, config, autonomy, contextFiles = [], completionNote }) {
37
+ const project = config.project || {};
38
+ const otherOwners = Object.values(run.tasks)
39
+ .filter((other) => other.id !== task.id && ACTIVE_TASK_STATES.includes(other.state))
40
+ .flatMap((other) => other.files.map((file) => `${file} (tarefa ${other.id})`));
41
+ const sections = [
42
+ `# Brief — ${run.id} / ${task.id}: ${task.title} (tentativa ${attemptNumber})`,
43
+ "Você é um **worker**. Este brief é todo o contexto que você recebe: não existe conversa anterior. Siga-o à risca.",
44
+ heading("OBJETIVO", [`Entregar a tarefa **${task.id} — ${task.title}**.`, run.objective ? `Objetivo do workflow: ${run.objective}` : null]),
45
+ heading("CONTEXTO DO PROJETO", [
46
+ bullet(`Projeto: ${project.name || "(ver AGENTS.md)"}${project.description ? ` — ${project.description}` : ""}`),
47
+ bullet(`Stack: ${project.stack || "ver AGENTS.md"}`),
48
+ bullet("Leia antes de começar: `AGENTS.md`, `docs/agents/worker.md`, `.claude/rules/README.md` e as regras aplicáveis."),
49
+ checksList(config.checks),
50
+ ]),
51
+ dependencySection(run, task),
52
+ contextSection(contextFiles),
53
+ heading("ESCOPO DE ARQUIVOS", [
54
+ "Pode criar ou alterar **somente**:",
55
+ ...task.files.map((file) => bullet(`\`${file}\``)),
56
+ "",
57
+ "Não pode alterar nenhum outro arquivo. Em especial:",
58
+ ...otherOwners.map((file) => bullet(`\`${file}\` — em uso por outro worker`)),
59
+ ...(autonomy.permissions?.denyWrite || []).map((file) => bullet(`\`${file}\` — protegido`)),
60
+ ]),
61
+ heading("CRITÉRIOS DE ACEITE", task.acceptance.map((item, index) => `${index + 1}. ${item}`)),
62
+ heading("VALIDAÇÃO", validationLines(task)),
63
+ fixSection(task.fix),
64
+ heading("AÇÕES PROIBIDAS", [
65
+ bullet("Commit, stage, push, troca de branch, merge."),
66
+ bullet("Escolher ou trocar linguagem, framework, gerenciador de pacotes ou ferramenta de testes."),
67
+ bullet("Ler, imprimir ou copiar segredos (`.env`, chaves, tokens)."),
68
+ ...protectedCategories(autonomy).map((category) => bullet(`${category.description} (\`${category.id}\`).`)),
69
+ bullet("Inventar saída de comando, caminho, API ou dependência."),
70
+ ]),
71
+ heading("PROTOCOLO DE CONCLUSÃO", [
72
+ "Termine sua resposta final com **exatamente um** bloco `agent-kit-report` em JSON:",
73
+ "",
74
+ reportExample(),
75
+ "",
76
+ bullet("`outcome`: `succeeded` só se todos os critérios de aceite foram atendidos e a validação rodou com sucesso observado por você."),
77
+ bullet("`failed`: tentou e não conseguiu. `blocked`: precisa de uma decisão ou recurso externo — liste em `blockers`. Não faça perguntas interativas."),
78
+ bullet("`checks`: cada comando que você rodou, com o exit code real. Comando que não existe no projeto: diga isso em `notes`."),
79
+ bullet("`filesChanged`: todos os arquivos que você alterou."),
80
+ completionNote ? bullet(completionNote) : null,
81
+ "O coordenador reexecuta a validação e revisa o diff de forma independente: declarar sucesso sem validação é tratado como falha.",
82
+ ]),
83
+ ];
84
+ return `${sections.filter(Boolean).join("\n\n").replace(/\n{3,}/g, "\n\n")}\n`;
85
+ }
86
+
87
+ function heading(title, lines) {
88
+ const body = lines.filter((line) => line !== null && line !== undefined).join("\n");
89
+ return `## ${title}\n\n${body}`;
90
+ }
91
+
92
+ function bullet(text) {
93
+ return `- ${text}`;
94
+ }
95
+
96
+ function checksList(checks = []) {
97
+ if (!checks.length) return bullet("Comandos do projeto: nenhum configurado (ver tabela de comandos em `AGENTS.md`).");
98
+ return [bullet("Comandos do projeto:"), ...checks.map((check) => ` - ${check.name}: \`${check.command}\``)].join("\n");
99
+ }
100
+
101
+ function dependencySection(run, task) {
102
+ if (!task.dependsOn.length) return null;
103
+ const lines = task.dependsOn.map((id) => {
104
+ const dep = run.tasks[id];
105
+ const report = dep.attempts[dep.attempts.length - 1]?.report;
106
+ const files = report?.filesChanged?.length ? ` Arquivos: ${report.filesChanged.map((file) => `\`${file}\``).join(", ")}.` : "";
107
+ return bullet(`**${dep.id} — ${dep.title}** (${dep.state}).${report?.summary ? ` ${report.summary}` : ""}${files}`);
108
+ });
109
+ return heading("DEPENDÊNCIAS JÁ CONCLUÍDAS", lines);
110
+ }
111
+
112
+ function contextSection(files) {
113
+ if (!files.length) return null;
114
+ const lines = files.map((file) => {
115
+ if (file.missing) return `### \`${file.path}\`\n\n(não encontrado no checkout — avise em \`notes\`)`;
116
+ if (file.tooLarge) return `### \`${file.path}\`\n\n(arquivo grande, ${file.size} caracteres — leia do disco)`;
117
+ const fence = file.text.includes("```") ? "````" : "```";
118
+ return `### \`${file.path}\`\n\n${fence}\n${file.text.trimEnd()}\n${fence}`;
119
+ });
120
+ return heading("DOCUMENTOS DA TAREFA", lines);
121
+ }
122
+
123
+ function validationLines(task) {
124
+ if (!task.validation.length) {
125
+ return ["Nenhum comando específico. Rode os testes relacionados ao que você mudou, se existirem, e cite a saída real."];
126
+ }
127
+ return task.validation.map((command, index) => `${index + 1}. \`${command}\``);
128
+ }
129
+
130
+ function fixSection(fix) {
131
+ if (!fix) return null;
132
+ const titles = { checks: "a validação independente falhou", review: "o review reprovou", worker: "a tentativa anterior falhou", lost: "a tentativa anterior se perdeu", blocker: "um bloqueio foi resolvido" };
133
+ const lines = [
134
+ `Esta é uma tentativa de correção: ${titles[fix.kind] || fix.kind} (tentativa ${fix.fromAttempt}).`,
135
+ "",
136
+ fix.details ? `${fix.details}` : null,
137
+ ...(fix.findings || []).map((finding) => bullet(finding)),
138
+ "",
139
+ "Corrija a causa, não o sintoma. O trabalho anterior está no checkout: parta dele.",
140
+ ];
141
+ return heading("CORREÇÃO", lines);
142
+ }
143
+
144
+ const GATE_INSTRUCTIONS = {
145
+ qa: [
146
+ "Rode os testes da tarefa e os comandos de validação; tente casos de borda e entradas inválidas.",
147
+ "Se houver UI e você tiver ferramenta de browser, exercite os fluxos; se não tiver, diga isso em `summary` — não invente.",
148
+ ],
149
+ system: [
150
+ "Confira aderência à techspec, à arquitetura, aos contratos entre módulos e às convenções do repositório.",
151
+ "Procure duplicação, acoplamento indevido e mudanças fora do escopo da tarefa.",
152
+ ],
153
+ uiux: ["Confira estados (vazio, carregando, erro), responsividade, acessibilidade WCAG 2.2 e consistência visual."],
154
+ security: ["Confira autenticação, autorização, validação de entrada, segredos, dados pessoais (PII) e LGPD."],
155
+ "product-owner": ["Avalie **cada** critério de aceite, um por um, com evidência concreta; preencha `criteria` para todos."],
156
+ };
157
+
158
+ export function buildGateBrief({ run, task, attempt, gate, gateConfig, config, completionNote }) {
159
+ const report = attempt.report || {};
160
+ const files = report.filesChanged?.length ? report.filesChanged : task.files;
161
+ const checks = attempt.checks?.results || [];
162
+ const instructions = GATE_INSTRUCTIONS[gate.role] || [];
163
+ const sections = [
164
+ `# Gate ${gateConfig.id} — ${run.id} / ${task.id}: ${task.title} (tentativa ${attempt.number})`,
165
+ `Você é o validador **${gate.role}**, independente de quem implementou. Este brief é todo o seu contexto. **Não altere nenhum arquivo**: só leia, rode comandos de verificação e reporte.`,
166
+ heading("FOCO", [gateConfig.focus || "", ...instructions.map(bullet)]),
167
+ heading("O QUE FOI ENTREGUE", [
168
+ bullet(`Resumo do worker: ${report.summary || "(sem relatório válido)"}`),
169
+ bullet(`Arquivos: ${files.map((file) => `\`${file}\``).join(", ")}`),
170
+ bullet(`Leia os arquivos inteiros. Num repositório git, veja também \`git diff -- ${files.join(" ")}\` e \`git status --porcelain\`; se não houver git, diga isso em \`summary\`.`),
171
+ bullet(`Projeto: ${config.project?.name || "ver AGENTS.md"}. Leia \`AGENTS.md\` e as regras em \`.claude/rules/\`.`),
172
+ task.doc ? bullet(`Documento da tarefa: \`${task.doc}\`.`) : null,
173
+ ]),
174
+ heading("CRITÉRIOS DE ACEITE", task.acceptance.map((item, index) => `${index + 1}. ${item}`)),
175
+ heading("CHECAGENS JÁ EXECUTADAS PELO COORDENADOR", checks.length ? checks.map((check) => bullet(`\`${check.name}\`: ${check.passed ? "passou" : "falhou"}`)) : ["Nenhuma."]),
176
+ heading("PROTOCOLO DE CONCLUSÃO", [
177
+ "Termine sua resposta final com **exatamente um** bloco `agent-kit-review` em JSON:",
178
+ "",
179
+ reviewExample(),
180
+ "",
181
+ bullet("`approved` só sem achados `blocker` ou `high`. Achados `medium`/`low` podem acompanhar uma aprovação."),
182
+ bullet("`rejected` precisa de achados concretos: arquivo, linha, o que está errado e por quê."),
183
+ bullet("Não declare nada que você não verificou."),
184
+ completionNote ? bullet(completionNote.replace("agent-kit-report", "agent-kit-review")) : null,
185
+ ]),
186
+ ];
187
+ return `${sections.filter(Boolean).join("\n\n").replace(/\n{3,}/g, "\n\n")}\n`;
188
+ }