@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
@@ -0,0 +1,505 @@
1
+ import {
2
+ ACTIVE_TASK_STATES,
3
+ TERMINAL_TASK_STATES,
4
+ TransitionError,
5
+ canTransitionTask,
6
+ canTransitionWorkflow,
7
+ } from "./states.js";
8
+ import { executionWaves, selectDispatchable, validateGraph } from "./dag.js";
9
+ import { validatePlan } from "./config.js";
10
+
11
+ const TASK_FIELDS = ["id", "title", "role", "profile", "tags", "dependsOn", "files", "doc", "context", "acceptance", "validation", "tracker"];
12
+
13
+ function pickTask(task) {
14
+ const picked = {};
15
+ for (const field of TASK_FIELDS) if (task[field] !== undefined) picked[field] = task[field];
16
+ picked.dependsOn = picked.dependsOn || [];
17
+ picked.validation = picked.validation || [];
18
+ picked.context = picked.context || [];
19
+ picked.tags = picked.tags || [];
20
+ picked.role = picked.role || "implementation";
21
+ return picked;
22
+ }
23
+
24
+ export function assertPlan(plan) {
25
+ const errors = [...validatePlan(plan)];
26
+ if (errors.length === 0) errors.push(...validateGraph(plan.tasks));
27
+ if (errors.length) throw new Error(`Invalid plan:\n- ${errors.join("\n- ")}`);
28
+ }
29
+
30
+ export function createRun({ id, objective, plan, runtime, now, completed = [] }) {
31
+ assertPlan(plan);
32
+ const run = {
33
+ id,
34
+ objective: objective || plan.objective || "",
35
+ feature: plan.feature || null,
36
+ runtime,
37
+ state: "planning",
38
+ createdAt: now,
39
+ updatedAt: now,
40
+ tasks: {},
41
+ order: plan.tasks.map((task) => task.id),
42
+ waves: executionWaves(plan.tasks),
43
+ finalChecks: null,
44
+ tracker: plan.tracker || null,
45
+ history: [],
46
+ events: [],
47
+ };
48
+ for (const task of plan.tasks) {
49
+ run.tasks[task.id] = { ...pickTask(task), state: "pending", attempts: [], fixCycles: 0, budgetBase: 0, fix: null, notes: [] };
50
+ }
51
+ for (const taskId of completed) {
52
+ const task = getTask(run, taskId);
53
+ task.state = "completed";
54
+ task.imported = true;
55
+ log(run, { at: now, scope: "task", id: taskId, from: "pending", to: "completed", reason: "already completed in the tracker" });
56
+ }
57
+ setWorkflowState(run, "running", "plan accepted", now);
58
+ refreshReadiness(run, now);
59
+ return run;
60
+ }
61
+
62
+ function log(run, entry) {
63
+ run.history.push(entry);
64
+ run.events.push({ ...entry, synced: false });
65
+ run.updatedAt = entry.at;
66
+ }
67
+
68
+ export function setTaskState(run, taskId, to, reason, now) {
69
+ const task = getTask(run, taskId);
70
+ if (task.state === to) return task;
71
+ if (!canTransitionTask(task.state, to)) throw new TransitionError("task", taskId, task.state, to);
72
+ log(run, { at: now, scope: "task", id: taskId, from: task.state, to, reason });
73
+ task.state = to;
74
+ return task;
75
+ }
76
+
77
+ export function setWorkflowState(run, to, reason, now) {
78
+ if (run.state === to) return;
79
+ if (!canTransitionWorkflow(run.state, to)) throw new TransitionError("workflow", run.id, run.state, to);
80
+ log(run, { at: now, scope: "workflow", id: run.id, from: run.state, to, reason });
81
+ run.state = to;
82
+ }
83
+
84
+ export function getTask(run, taskId) {
85
+ const task = run.tasks[taskId];
86
+ if (!task) throw new Error(`Unknown task "${taskId}" in run ${run.id}`);
87
+ return task;
88
+ }
89
+
90
+ function orderedTasks(run) {
91
+ return run.order.map((id) => run.tasks[id]).filter(Boolean);
92
+ }
93
+
94
+ export function refreshReadiness(run, now) {
95
+ for (const task of orderedTasks(run)) {
96
+ if (task.state !== "pending" && task.state !== "ready") continue;
97
+ const deps = task.dependsOn.map((id) => run.tasks[id]);
98
+ const dead = deps.find((dep) => dep.state === "cancelled" || dep.state === "failed");
99
+ if (dead) {
100
+ setTaskState(run, task.id, "blocked", `dependency ${dead.id} is ${dead.state}`, now);
101
+ } else if (deps.every((dep) => dep.state === "completed")) {
102
+ setTaskState(run, task.id, "ready", "dependencies completed", now);
103
+ } else if (task.state === "ready") {
104
+ setTaskState(run, task.id, "pending", "dependency reopened", now);
105
+ }
106
+ }
107
+ }
108
+
109
+ function minutesSince(iso, now) {
110
+ return (Date.parse(now) - Date.parse(iso)) / 60000;
111
+ }
112
+
113
+ export function nextActions(run, autonomy, now) {
114
+ refreshReadiness(run, now);
115
+ const tasks = orderedTasks(run);
116
+ const running = tasks.filter((task) => task.state === "running");
117
+ const holders = tasks.filter((task) => ACTIVE_TASK_STATES.includes(task.state));
118
+ const slots = Math.max(0, autonomy.maxWorkers - running.length);
119
+ const ready = tasks.filter((task) => task.state === "ready");
120
+ const dispatch = selectDispatchable(ready, holders, slots).map((task) => task.id);
121
+ const waitingForFiles = ready.filter((task) => !dispatch.includes(task.id) && slots > dispatch.length).map((task) => task.id);
122
+ const overdue = running
123
+ .map((task) => ({ task, attempt: currentAttempt(task) }))
124
+ .filter(({ attempt }) => attempt && minutesSince(attempt.lastProgressAt || attempt.dispatchedAt, now) > autonomy.taskTimeoutMinutes)
125
+ .map(({ task, attempt }) => ({ id: task.id, runtimeRef: attempt.runtimeRef, runtime: attempt.runtime, since: attempt.dispatchedAt }));
126
+ const unconfirmed = running
127
+ .filter((task) => !currentAttempt(task)?.runtimeRef && currentAttempt(task)?.executor !== "coordinator")
128
+ .map((task) => ({ id: task.id, clientRequestId: currentAttempt(task)?.clientRequestId }));
129
+ return {
130
+ workflow: run.state,
131
+ dispatch,
132
+ waitingForFiles,
133
+ running: running.map((task) => ({ id: task.id, runtimeRef: currentAttempt(task)?.runtimeRef || null })),
134
+ overdue,
135
+ unconfirmed,
136
+ awaitingChecks: tasks.filter((task) => task.state === "testing").map((task) => task.id),
137
+ awaitingReview: tasks.filter((task) => task.state === "review").map((task) => reviewSummary(task)),
138
+ blocked: tasks.filter((task) => task.state === "blocked").map((task) => ({ id: task.id, reason: lastReason(run, task.id) })),
139
+ failed: tasks.filter((task) => task.state === "failed").map((task) => ({ id: task.id, reason: lastReason(run, task.id) })),
140
+ allTasksDone: tasks.every((task) => TERMINAL_TASK_STATES.includes(task.state)),
141
+ };
142
+ }
143
+
144
+ function reviewSummary(task) {
145
+ const gates = currentAttempt(task).gates || {};
146
+ const ids = Object.keys(gates);
147
+ return {
148
+ id: task.id,
149
+ ready: ids.filter((id) => gateReady(gates, id) && !gates[id].dispatchedAt),
150
+ inProgress: ids.filter((id) => gates[id].status === "pending" && gates[id].dispatchedAt).map((id) => ({ gate: id, runtimeRef: gates[id].runtimeRef })),
151
+ waiting: ids.filter((id) => gates[id].status === "pending" && !gateReady(gates, id)),
152
+ approved: ids.filter((id) => gates[id].status === "approved"),
153
+ };
154
+ }
155
+
156
+ function lastReason(run, taskId) {
157
+ const entry = [...run.history].reverse().find((item) => item.scope === "task" && item.id === taskId);
158
+ return entry?.reason || null;
159
+ }
160
+
161
+ export function currentAttempt(task) {
162
+ return task.attempts[task.attempts.length - 1] || null;
163
+ }
164
+
165
+ export function attemptsInBudget(task) {
166
+ return task.attempts.length - task.budgetBase;
167
+ }
168
+
169
+ export function startAttempt(run, taskId, { profile, executor, runtime, briefPath, briefHash, now }) {
170
+ const task = getTask(run, taskId);
171
+ if (task.state !== "ready") throw new Error(`Task ${taskId} is ${task.state}, not ready`);
172
+ const number = task.attempts.length + 1;
173
+ task.attempts.push({
174
+ number,
175
+ profile,
176
+ executor,
177
+ runtime,
178
+ clientRequestId: `agent-kit:${run.id}:${taskId}:${number}`,
179
+ briefPath,
180
+ briefHash,
181
+ fix: task.fix,
182
+ dispatchedAt: now,
183
+ lastProgressAt: now,
184
+ runtimeRef: null,
185
+ report: null,
186
+ checks: null,
187
+ gates: null,
188
+ outcome: null,
189
+ finishedAt: null,
190
+ });
191
+ setTaskState(run, taskId, "running", `attempt ${number} dispatched (${profile})`, now);
192
+ if (run.state === "blocked") setWorkflowState(run, "running", `task ${taskId} dispatched`, now);
193
+ return task.attempts[number - 1];
194
+ }
195
+
196
+ export function bindRuntimeRef(run, taskId, runtimeRef, now, gateId) {
197
+ const attempt = requireAttempt(run, taskId);
198
+ if (gateId) {
199
+ const gate = attempt.gates?.[gateId];
200
+ if (!gate?.dispatchedAt) throw new Error(`Gate "${gateId}" of ${taskId} was not started`);
201
+ gate.runtimeRef = runtimeRef;
202
+ log(run, { at: now, scope: "attempt", id: taskId, from: null, to: "bound", reason: `gate ${gateId} runtime ref ${runtimeRef}` });
203
+ return gate;
204
+ }
205
+ attempt.runtimeRef = runtimeRef;
206
+ attempt.lastProgressAt = now;
207
+ log(run, { at: now, scope: "attempt", id: taskId, from: null, to: "bound", reason: `runtime ref ${runtimeRef}` });
208
+ return attempt;
209
+ }
210
+
211
+ export function touch(run, taskId, note, now) {
212
+ const attempt = requireAttempt(run, taskId);
213
+ attempt.lastProgressAt = now;
214
+ getTask(run, taskId).notes.push({ at: now, note });
215
+ return attempt;
216
+ }
217
+
218
+ function requireAttempt(run, taskId) {
219
+ const attempt = currentAttempt(getTask(run, taskId));
220
+ if (!attempt) throw new Error(`Task ${taskId} has no attempt`);
221
+ return attempt;
222
+ }
223
+
224
+ export function recordReport(run, taskId, parsed, autonomy, now) {
225
+ const task = getTask(run, taskId);
226
+ if (task.state !== "running") throw new Error(`Task ${taskId} is ${task.state}; a report is only accepted while running`);
227
+ const attempt = currentAttempt(task);
228
+ attempt.report = parsed.report || { outcome: "unreported", errors: parsed.errors };
229
+ attempt.finishedAt = now;
230
+ if (!parsed.valid) {
231
+ setTaskState(run, taskId, "testing", `report invalid (${parsed.errors.join("; ")}); verifying independently`, now);
232
+ return { next: "verify" };
233
+ }
234
+ const { outcome } = parsed.report;
235
+ if (outcome === "succeeded") {
236
+ setTaskState(run, taskId, "testing", "worker reported success; awaiting independent checks", now);
237
+ return { next: "verify" };
238
+ }
239
+ if (outcome === "blocked") {
240
+ attempt.outcome = "blocked";
241
+ setTaskState(run, taskId, "blocked", `worker blocked: ${parsed.report.blockers.join("; ")}`, now);
242
+ syncWorkflow(run, now);
243
+ return { next: "resolve-blocker", blockers: parsed.report.blockers };
244
+ }
245
+ return applyFailure(run, taskId, { kind: "worker", details: parsed.report.summary }, autonomy, now);
246
+ }
247
+
248
+ export function applicableGates(task, workflow) {
249
+ const gates = workflow?.gates?.length ? workflow.gates : [{ id: "review", role: "review", when: "always" }];
250
+ const chosen = gates.filter((gate) => {
251
+ const when = gate.when || "always";
252
+ return when === "always" || (when.startsWith("tag:") && task.tags.includes(when.slice(4)));
253
+ });
254
+ const ids = new Set(chosen.map((gate) => gate.id));
255
+ const result = {};
256
+ for (const gate of chosen) {
257
+ result[gate.id] = { role: gate.role, after: (gate.after || []).filter((id) => ids.has(id)), status: "pending", runtimeRef: null, dispatchedAt: null, profile: null, executor: null, review: null };
258
+ }
259
+ return result;
260
+ }
261
+
262
+ function gateReady(gates, id) {
263
+ return gates[id].status === "pending" && gates[id].after.every((dep) => gates[dep].status === "approved");
264
+ }
265
+
266
+ export function recordChecks(run, taskId, checks, autonomy, now, workflow) {
267
+ const task = getTask(run, taskId);
268
+ if (task.state !== "testing") throw new Error(`Task ${taskId} is ${task.state}, not testing`);
269
+ const attempt = currentAttempt(task);
270
+ attempt.checks = { at: now, ...checks };
271
+ if (checks.skipped && autonomy.completion.requireTaskChecks) {
272
+ return applyFailure(run, taskId, { kind: "checks", details: "task has no validation commands and requireTaskChecks is on" }, autonomy, now);
273
+ }
274
+ if (checks.passed) {
275
+ attempt.gates = applicableGates(task, workflow);
276
+ setTaskState(run, taskId, "review", checks.skipped ? "no task checks defined; review must cover behaviour" : "checks passed", now);
277
+ return { next: "review" };
278
+ }
279
+ const failing = checks.results.filter((result) => !result.passed && result.required).map((result) => result.name);
280
+ return applyFailure(run, taskId, { kind: "checks", details: `failing: ${failing.join(", ")}`, results: checks.results }, autonomy, now);
281
+ }
282
+
283
+ export function startGate(run, taskId, gateId, { profile, executor, now }) {
284
+ const attempt = reviewAttempt(run, taskId);
285
+ const gate = attempt.gates[gateId];
286
+ if (!gate) throw new Error(`Gate "${gateId}" does not apply to task ${taskId}`);
287
+ if (!gateReady(attempt.gates, gateId)) throw new Error(`Gate "${gateId}" of ${taskId} is not ready (status ${gate.status}; after: ${gate.after.join(", ") || "none"})`);
288
+ Object.assign(gate, { profile, executor, dispatchedAt: now, runtimeRef: null });
289
+ log(run, { at: now, scope: "attempt", id: taskId, from: null, to: `gate:${gateId}`, reason: `gate ${gateId} started (${profile})` });
290
+ return gate;
291
+ }
292
+
293
+ function reviewAttempt(run, taskId) {
294
+ const task = getTask(run, taskId);
295
+ if (task.state !== "review") throw new Error(`Task ${taskId} is ${task.state}, not in review`);
296
+ const attempt = currentAttempt(task);
297
+ if (!attempt.gates) attempt.gates = applicableGates(task, null);
298
+ return attempt;
299
+ }
300
+
301
+ export function recordReview(run, taskId, { gate: gateId, verdict, reviewer, findings = [], criteria = [] }, autonomy, now) {
302
+ const task = getTask(run, taskId);
303
+ const attempt = reviewAttempt(run, taskId);
304
+ const pending = Object.keys(attempt.gates).filter((id) => attempt.gates[id].status === "pending");
305
+ const id = gateId || (pending.length === 1 ? pending[0] : null);
306
+ if (!id) throw new Error(`Task ${taskId} has several pending gates (${pending.join(", ")}); pass --gate`);
307
+ const gate = attempt.gates[id];
308
+ if (!gate) throw new Error(`Gate "${id}" does not apply to task ${taskId}`);
309
+ if (!gateReady(attempt.gates, id)) throw new Error(`Gate "${id}" of ${taskId} must wait for: ${gate.after.join(", ")}`);
310
+ if (autonomy.completion.requireIndependentReview && reviewer === attempt.executor) {
311
+ throw new Error(`Gate "${id}" of ${taskId} must be independent: reviewer "${reviewer}" implemented it`);
312
+ }
313
+ if (verdict !== "approved" && verdict !== "rejected") throw new Error('verdict must be "approved" or "rejected"');
314
+ gate.status = verdict;
315
+ gate.review = { at: now, verdict, reviewer, findings, criteria };
316
+ log(run, { at: now, scope: "attempt", id: taskId, from: `gate:${id}`, to: verdict, reason: `gate ${id} ${verdict} by ${reviewer}${findings.length ? `: ${findings.length} finding(s)` : ""}` });
317
+ if (verdict === "rejected") {
318
+ const labelled = findings.map((finding) => `[${id}] ${finding}`);
319
+ return applyFailure(run, taskId, { kind: "review", details: `gate ${id} rejected the work`, findings: labelled }, autonomy, now);
320
+ }
321
+ const remaining = Object.keys(attempt.gates).filter((key) => attempt.gates[key].status !== "approved");
322
+ if (remaining.length) return { next: "gates", remaining, ready: remaining.filter((key) => gateReady(attempt.gates, key)) };
323
+ attempt.outcome = "succeeded";
324
+ task.fix = null;
325
+ setTaskState(run, taskId, "completed", `all gates approved (${Object.keys(attempt.gates).join(", ")})`, now);
326
+ refreshReadiness(run, now);
327
+ syncWorkflow(run, now);
328
+ return { next: "continue" };
329
+ }
330
+
331
+ export function retryDecision(task, autonomy, kind) {
332
+ const attempts = attemptsInBudget(task);
333
+ const fixCycles = task.fixCycles + (kind === "checks" || kind === "review" ? 1 : 0);
334
+ if (attempts >= autonomy.maxAttemptsPerTask || fixCycles > autonomy.maxFixCycles) {
335
+ const takenOver = currentAttempt(task)?.executor === "coordinator";
336
+ const to = takenOver && autonomy.escalation.onBudgetExhausted === "coordinator-takeover" ? "ask-user" : autonomy.escalation.onBudgetExhausted;
337
+ return { action: "escalate", to, attempts, fixCycles };
338
+ }
339
+ const last = currentAttempt(task)?.profile;
340
+ let profile = last;
341
+ if (autonomy.retry.strategy === "escalate-profile") {
342
+ const ladder = autonomy.retry.ladder;
343
+ const index = ladder.indexOf(last);
344
+ if (index >= 0 && index < ladder.length - 1) profile = ladder[index + 1];
345
+ }
346
+ return { action: "retry", profile, attempts, fixCycles };
347
+ }
348
+
349
+ function applyFailure(run, taskId, failure, autonomy, now) {
350
+ const task = getTask(run, taskId);
351
+ const attempt = currentAttempt(task);
352
+ attempt.outcome = "failed";
353
+ attempt.finishedAt = attempt.finishedAt || now;
354
+ const decision = retryDecision(task, autonomy, failure.kind);
355
+ task.fixCycles = decision.fixCycles;
356
+ if (decision.action === "retry") {
357
+ task.fix = { kind: failure.kind, details: failure.details, findings: failure.findings || [], fromAttempt: attempt.number, profile: decision.profile };
358
+ setTaskState(run, taskId, "ready", `${failure.kind} failed; retry ${decision.attempts + 1} with profile ${decision.profile}`, now);
359
+ return { next: "redispatch", decision };
360
+ }
361
+ setTaskState(run, taskId, "failed", `${failure.kind} failed; budget exhausted (${decision.attempts} attempts, ${decision.fixCycles} fix cycles) -> ${decision.to}`, now);
362
+ task.fix = { kind: failure.kind, details: failure.details, findings: failure.findings || [], fromAttempt: attempt.number, profile: null };
363
+ if (decision.to === "fail") setWorkflowState(run, "failed", `task ${taskId} exhausted its budget and the policy is "fail"`, now);
364
+ else syncWorkflow(run, now);
365
+ return { next: decision.to, decision };
366
+ }
367
+
368
+ export function markLost(run, taskId, reason, autonomy, now) {
369
+ const task = getTask(run, taskId);
370
+ if (task.state !== "running") throw new Error(`Task ${taskId} is ${task.state}, not running`);
371
+ return applyFailure(run, taskId, { kind: "lost", details: reason }, autonomy, now);
372
+ }
373
+
374
+ export function unblock(run, taskId, resolution, now) {
375
+ const task = getTask(run, taskId);
376
+ if (task.state !== "blocked") throw new Error(`Task ${taskId} is ${task.state}, not blocked`);
377
+ task.notes.push({ at: now, note: `unblocked: ${resolution}` });
378
+ task.fix = { kind: "blocker", details: resolution, findings: [], fromAttempt: currentAttempt(task)?.number || 0, profile: currentAttempt(task)?.profile || null };
379
+ setTaskState(run, taskId, "pending", `unblocked: ${resolution}`, now);
380
+ refreshReadiness(run, now);
381
+ syncWorkflow(run, now);
382
+ }
383
+
384
+ export function reopenForTakeover(run, taskId, now) {
385
+ const task = getTask(run, taskId);
386
+ if (task.state !== "failed" && task.state !== "blocked") throw new Error(`Task ${taskId} is ${task.state}; takeover is for failed or blocked tasks`);
387
+ setTaskState(run, taskId, "ready", "coordinator takes the task over", now);
388
+ if (run.state === "blocked") setWorkflowState(run, "running", `coordinator took over ${taskId}`, now);
389
+ return task;
390
+ }
391
+
392
+ export function cancelTask(run, taskId, reason, now) {
393
+ setTaskState(run, taskId, "cancelled", reason, now);
394
+ refreshReadiness(run, now);
395
+ syncWorkflow(run, now);
396
+ }
397
+
398
+ function syncWorkflow(run, now) {
399
+ if (!["running", "blocked"].includes(run.state)) return;
400
+ const tasks = orderedTasks(run);
401
+ const stuck = tasks.some((task) => task.state === "failed" || task.state === "blocked");
402
+ const moving = tasks.some((task) => ["ready", "running", "testing", "review"].includes(task.state));
403
+ if (stuck && !moving) setWorkflowState(run, "blocked", "no task can progress without coordinator action", now);
404
+ else if (run.state === "blocked" && moving) setWorkflowState(run, "running", "work can progress again", now);
405
+ }
406
+
407
+ export function recordFinalChecks(run, checks, now) {
408
+ const active = orderedTasks(run).filter((task) => task.state === "running");
409
+ if (active.length) throw new Error(`Final checks need a quiet checkout; still running: ${active.map((task) => task.id).join(", ")}`);
410
+ run.finalChecks = { at: now, ...checks };
411
+ log(run, { at: now, scope: "workflow", id: run.id, from: null, to: "final-checks", reason: checks.passed ? "final checks passed" : "final checks failed" });
412
+ }
413
+
414
+ export function completionStatus(run, autonomy, config) {
415
+ const missing = [];
416
+ const tasks = orderedTasks(run);
417
+ const rules = autonomy.completion;
418
+ if (rules.requireAllTasks) {
419
+ const open = tasks.filter((task) => task.state !== "completed" && task.state !== "cancelled");
420
+ if (open.length) missing.push(`tasks not completed: ${open.map((task) => `${task.id} (${task.state})`).join(", ")}`);
421
+ }
422
+ if (rules.requireFinalChecks) {
423
+ if (!(config.checks || []).length) missing.push("no project checks configured in .agent-kit/config.json (checks)");
424
+ else if (!run.finalChecks) missing.push("final checks have not run (agent-kit wf verify <run> --final)");
425
+ else if (!run.finalChecks.passed) missing.push("final checks failed");
426
+ else if (lastTaskChange(run) > run.finalChecks.at) missing.push("final checks are older than the last task change");
427
+ }
428
+ if (rules.requireIndependentReview) {
429
+ const unreviewed = tasks.filter((task) => {
430
+ if (task.state !== "completed" || task.imported) return false;
431
+ const gates = currentAttempt(task)?.gates;
432
+ return !gates || Object.values(gates).some((gate) => gate.status !== "approved");
433
+ });
434
+ if (unreviewed.length) missing.push(`completed without review: ${unreviewed.map((task) => task.id).join(", ")}`);
435
+ }
436
+ return { complete: missing.length === 0, missing };
437
+ }
438
+
439
+ function lastTaskChange(run) {
440
+ const entries = run.history.filter((entry) => entry.scope === "task");
441
+ return entries.length ? entries[entries.length - 1].at : "";
442
+ }
443
+
444
+ export function completeRun(run, autonomy, config, now) {
445
+ const status = completionStatus(run, autonomy, config);
446
+ if (!status.complete) return status;
447
+ setWorkflowState(run, "completed", "all completion criteria met", now);
448
+ return status;
449
+ }
450
+
451
+ export function resumePlan(run, autonomy, now, runtime) {
452
+ const tasks = orderedTasks(run);
453
+ const reconcile = [];
454
+ const redispatchSameKey = [];
455
+ const foreign = [];
456
+ const coordinatorOwned = [];
457
+ for (const task of tasks.filter((item) => item.state === "running")) {
458
+ const attempt = currentAttempt(task);
459
+ if (attempt.executor === "coordinator") {
460
+ coordinatorOwned.push({ id: task.id, briefPath: attempt.briefPath });
461
+ } else if (attempt.runtime && runtime && attempt.runtime !== runtime) {
462
+ foreign.push({ id: task.id, runtime: attempt.runtime, runtimeRef: attempt.runtimeRef });
463
+ } else if (attempt.runtimeRef) {
464
+ reconcile.push({ id: task.id, runtimeRef: attempt.runtimeRef });
465
+ } else {
466
+ redispatchSameKey.push({ id: task.id, clientRequestId: attempt.clientRequestId, briefPath: attempt.briefPath });
467
+ }
468
+ }
469
+ return { workflow: run.state, reconcile, redispatchSameKey, foreign, coordinatorOwned, next: nextActions(run, autonomy, now) };
470
+ }
471
+
472
+ export function replan(run, plan, now) {
473
+ assertPlan(plan);
474
+ const incoming = new Map(plan.tasks.map((task) => [task.id, task]));
475
+ for (const task of orderedTasks(run)) {
476
+ if (!incoming.has(task.id) && !TERMINAL_TASK_STATES.includes(task.state)) {
477
+ if (ACTIVE_TASK_STATES.includes(task.state)) throw new Error(`Cannot drop ${task.id} while it is ${task.state}; cancel it first`);
478
+ setTaskState(run, task.id, "cancelled", "removed by replan", now);
479
+ }
480
+ }
481
+ for (const spec of plan.tasks) {
482
+ const existing = run.tasks[spec.id];
483
+ if (!existing) {
484
+ run.tasks[spec.id] = { ...pickTask(spec), state: "pending", attempts: [], fixCycles: 0, budgetBase: 0, fix: null, notes: [] };
485
+ log(run, { at: now, scope: "task", id: spec.id, from: null, to: "pending", reason: "added by replan" });
486
+ continue;
487
+ }
488
+ if (existing.state === "completed" || ACTIVE_TASK_STATES.includes(existing.state)) continue;
489
+ Object.assign(existing, pickTask(spec));
490
+ if (existing.state === "failed" || existing.state === "blocked") {
491
+ existing.budgetBase = existing.attempts.length;
492
+ existing.fixCycles = 0;
493
+ setTaskState(run, spec.id, "pending", "reset by replan", now);
494
+ }
495
+ }
496
+ run.order = [...new Set([...plan.tasks.map((task) => task.id), ...run.order])];
497
+ const live = run.order.map((id) => run.tasks[id]);
498
+ const errors = validateGraph(live);
499
+ if (errors.length) throw new Error(`Replan produced an invalid graph:\n- ${errors.join("\n- ")}`);
500
+ run.waves = executionWaves(live);
501
+ if (run.state === "blocked" || run.state === "failed") setWorkflowState(run, run.state === "failed" ? "planning" : "running", "replanned", now);
502
+ if (run.state === "planning") setWorkflowState(run, "running", "replanned", now);
503
+ refreshReadiness(run, now);
504
+ syncWorkflow(run, now);
505
+ }
@@ -0,0 +1,145 @@
1
+ // Self-contained on purpose: this module is copied verbatim into generated projects
2
+ // (.agent-kit/hooks/policy.mjs) so the approval hook runs without the package installed.
3
+
4
+ export const DEFAULT_PROTECTED_ACTIONS = [
5
+ {
6
+ id: "production-deploy",
7
+ description: "Deploy to production",
8
+ patterns: [
9
+ "\\b(vercel|netlify)\\b.*--prod\\b",
10
+ "\\bfly(ctl)?\\s+deploy\\b",
11
+ "\\bheroku\\s+.*(deploy|releases:rollback|container:release)\\b",
12
+ "\\b(gcloud|aws|az)\\s+.*\\bdeploy\\b",
13
+ "\\bkubectl\\s+.*\\b(prod|production)\\b",
14
+ "\\bgit\\s+push\\b.*\\b(prod|production|release)\\b",
15
+ ],
16
+ },
17
+ {
18
+ id: "production-infra",
19
+ description: "Change production infrastructure",
20
+ patterns: [
21
+ "\\bterraform\\s+(apply|destroy|import|state\\s+rm)\\b",
22
+ "\\bpulumi\\s+(up|destroy)\\b",
23
+ "\\bhelm\\s+(install|upgrade|uninstall|rollback)\\b",
24
+ "\\bkubectl\\s+(apply|delete|scale|rollout|drain|cordon)\\b",
25
+ ],
26
+ },
27
+ {
28
+ id: "data-destruction",
29
+ description: "Irreversible data deletion",
30
+ patterns: [
31
+ "\\bdrop\\s+(database|schema|table)\\b",
32
+ "\\btruncate\\s+(table\\s+)?\\w",
33
+ "\\bdelete\\s+from\\s+\\w+\\s*(;|$|\")",
34
+ "\\bdropdb\\b",
35
+ "\\b(prisma\\s+migrate\\s+reset|db:drop|rake\\s+db:reset)\\b",
36
+ "\\brm\\s+-[a-z]*r[a-z]*\\s+(-[a-z]+\\s+)*(/|~|\\$HOME|\\*|\\.\\.?)(\\s|/?$)",
37
+ "\\bredis-cli\\b.*\\bflush(all|db)\\b",
38
+ ],
39
+ },
40
+ {
41
+ id: "external-destructive",
42
+ description: "Destructive operation on an external service",
43
+ patterns: [
44
+ "\\bgit\\s+push\\b.*(--force\\b|--force-with-lease\\b|\\s-f\\b|--delete\\b|\\s:\\S)",
45
+ "\\bgh\\s+(repo|release)\\s+delete\\b",
46
+ "\\bgh\\s+pr\\s+merge\\b",
47
+ "\\baws\\s+s3\\s+(rm|rb)\\b",
48
+ "\\bgsutil\\s+(rm|rb)\\b",
49
+ "\\bdocker\\s+push\\b",
50
+ ],
51
+ },
52
+ {
53
+ id: "package-publish",
54
+ description: "Publish a package or release (cannot be unpublished safely)",
55
+ patterns: [
56
+ "\\b(npm|pnpm|bun)\\s+publish\\b",
57
+ "\\byarn\\s+(npm\\s+)?publish\\b",
58
+ "\\bcargo\\s+publish\\b",
59
+ "\\btwine\\s+upload\\b",
60
+ "\\bgem\\s+push\\b",
61
+ "\\bgh\\s+release\\s+create\\b",
62
+ ],
63
+ },
64
+ {
65
+ id: "financial",
66
+ description: "Charges, payouts or other financial changes",
67
+ patterns: ["\\bstripe\\s+\\S*(charges|payment_intents|refunds|payouts|transfers|subscriptions)\\b.*\\b(create|update|cancel|delete)\\b"],
68
+ },
69
+ {
70
+ id: "credential-exposure",
71
+ description: "Printing or exporting credentials",
72
+ patterns: [
73
+ "\\b(cat|type|less|more|head|tail|bat)\\s+[^|;&]*\\.env(\\.[\\w-]+)?\\b",
74
+ "\\b(cat|type)\\s+[^|;&]*(id_rsa|id_ed25519|\\.pem|credentials(\\.json)?)\\b",
75
+ "\\bprintenv\\b",
76
+ "\\becho\\s+[^|;&]*\\$\\{?\\w*(token|secret|password|api_?key)\\w*",
77
+ "\\bgh\\s+auth\\s+token\\b",
78
+ "\\baws\\s+configure\\s+get\\b",
79
+ ],
80
+ },
81
+ ];
82
+
83
+ const GIT_PUSH = /\bgit\s+push\b/i;
84
+ const GIT_COMMIT = /\bgit\s+commit\b/i;
85
+
86
+ function compile(pattern) {
87
+ return new RegExp(pattern, "i");
88
+ }
89
+
90
+ export function protectedCategories(autonomy = {}) {
91
+ const configured = autonomy.protectedActions?.categories;
92
+ return Array.isArray(configured) ? configured : DEFAULT_PROTECTED_ACTIONS;
93
+ }
94
+
95
+ export function classifyCommand(command, autonomy = {}) {
96
+ const text = String(command || "");
97
+ const decision = autonomy.protectedActions?.decision || "ask";
98
+ const allowed = new Set(autonomy.protectedActions?.allow || []);
99
+ for (const category of protectedCategories(autonomy)) {
100
+ if (allowed.has(category.id)) continue;
101
+ const hit = (category.patterns || []).find((pattern) => compile(pattern).test(text));
102
+ if (hit) return { decision, category: category.id, reason: category.description };
103
+ }
104
+ const permissions = autonomy.permissions || {};
105
+ if (GIT_PUSH.test(text) && !permissions.push) {
106
+ return { decision, category: "git-push", reason: "Pushing is not enabled in autonomy.permissions.push" };
107
+ }
108
+ if (GIT_COMMIT.test(text) && !permissions.localCommits) {
109
+ return {
110
+ decision,
111
+ category: "git-commit",
112
+ reason: "Local commits are not enabled in autonomy.permissions.localCommits",
113
+ };
114
+ }
115
+ return { decision: "allow", category: null, reason: null };
116
+ }
117
+
118
+ function globToRegExp(glob) {
119
+ const normalized = glob.replace(/\\/g, "/");
120
+ let source = "";
121
+ for (let index = 0; index < normalized.length; index += 1) {
122
+ const char = normalized[index];
123
+ if (char === "*" && normalized[index + 1] === "*") {
124
+ source += ".*";
125
+ index += normalized[index + 2] === "/" ? 2 : 1;
126
+ } else if (char === "*") source += "[^/]*";
127
+ else if (char === "?") source += "[^/]";
128
+ else source += char.replace(/[.+^${}()|[\]\\]/g, "\\$&");
129
+ }
130
+ return new RegExp(`^${source}$`, "i");
131
+ }
132
+
133
+ export function matchesAny(path, globs = []) {
134
+ const normalized = String(path).replace(/\\/g, "/").replace(/^\.\//, "");
135
+ return globs.some((glob) => globToRegExp(glob).test(normalized));
136
+ }
137
+
138
+ export function classifyWrite(path, autonomy = {}) {
139
+ const permissions = autonomy.permissions || {};
140
+ const decision = autonomy.protectedActions?.decision || "ask";
141
+ if (matchesAny(path, permissions.denyWrite || [])) {
142
+ return { decision, category: "protected-path", reason: `Writing ${path} is protected` };
143
+ }
144
+ return { decision: "allow", category: null, reason: null };
145
+ }