@mergeline/agent 0.0.0-stage → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +122 -2
- package/dist/cli.js +396 -0
- package/dist/credentials.js +96 -0
- package/dist/index.js +5 -0
- package/dist/init.js +207 -0
- package/dist/mcp.js +132 -0
- package/dist/pb.js +25 -0
- package/dist/repo.js +67 -0
- package/dist/service.js +312 -0
- package/dist/watch.js +243 -0
- package/kit/claude-settings.json +39 -0
- package/kit/done.md +19 -0
- package/kit/pick.md +34 -0
- package/kit/rules.md +29 -0
- package/package.json +51 -4
package/dist/service.js
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
// TicketService: the only place that talks to PocketBase.
|
|
2
|
+
//
|
|
3
|
+
// The MCP server, the `board` CLI, the seed script and the tests call these
|
|
4
|
+
// classes; nothing else in the agent package imports the PocketBase SDK. Swapping the backend later means
|
|
5
|
+
// reimplementing this file only.
|
|
6
|
+
import { randomUUID } from "node:crypto";
|
|
7
|
+
import PocketBase, { ClientResponseError } from "pocketbase";
|
|
8
|
+
/** An error whose message is safe to show to an agent or a human as is. */
|
|
9
|
+
export class BoardError extends Error {
|
|
10
|
+
status;
|
|
11
|
+
constructor(message, status = 0) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.status = status;
|
|
14
|
+
this.name = "BoardError";
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* The board is asleep (HTTP 503, code board_paused): nothing can be done on it
|
|
19
|
+
* until a person opens it. Tools say so; `board watch` waits.
|
|
20
|
+
*/
|
|
21
|
+
export class BoardPaused extends BoardError {
|
|
22
|
+
constructor(message) {
|
|
23
|
+
super(message, 503);
|
|
24
|
+
this.name = "BoardPaused";
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
const SUMMARY_FIELDS = "id,title,status,priority,spec_path,branch,pr_url,claimed_until,attempts,block_kind,block_text";
|
|
28
|
+
function toBoardError(err, url, action) {
|
|
29
|
+
if (err instanceof BoardError)
|
|
30
|
+
return err;
|
|
31
|
+
if (err instanceof ClientResponseError) {
|
|
32
|
+
if (err.status === 0) {
|
|
33
|
+
return new BoardError(`board is not reachable at ${url}; is PocketBase running?`);
|
|
34
|
+
}
|
|
35
|
+
const response = (err.response ?? {});
|
|
36
|
+
if (err.status === 503 && response.code === "board_paused") {
|
|
37
|
+
return new BoardPaused(`board paused: ${response.message || `${url} is asleep until a person opens it`}`);
|
|
38
|
+
}
|
|
39
|
+
const fields = Object.entries(response.data ?? {})
|
|
40
|
+
.map(([field, detail]) => `${field}: ${detail?.message ?? "invalid"}`)
|
|
41
|
+
.join("; ");
|
|
42
|
+
const message = response.message || `${action} failed (HTTP ${err.status})`;
|
|
43
|
+
return new BoardError(fields ? `${message} (${fields})` : message, err.status);
|
|
44
|
+
}
|
|
45
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
46
|
+
return new BoardError(`${action} failed: ${reason}`);
|
|
47
|
+
}
|
|
48
|
+
function newClient(url) {
|
|
49
|
+
const pb = new PocketBase(url);
|
|
50
|
+
// The SDK cancels duplicate in-flight requests by default; board calls must
|
|
51
|
+
// never be dropped silently.
|
|
52
|
+
pb.autoCancellation(false);
|
|
53
|
+
return pb;
|
|
54
|
+
}
|
|
55
|
+
/** Board access for one agent session. Every method acts as that agent. */
|
|
56
|
+
export class TicketService {
|
|
57
|
+
creds;
|
|
58
|
+
/** Id of this session; the server uses it to tell restarts from double claims. Random unless given. */
|
|
59
|
+
session;
|
|
60
|
+
pb;
|
|
61
|
+
constructor(creds, session) {
|
|
62
|
+
this.creds = creds;
|
|
63
|
+
this.session = session || randomUUID();
|
|
64
|
+
this.pb = newClient(creds.url);
|
|
65
|
+
}
|
|
66
|
+
get agentId() {
|
|
67
|
+
return this.pb.authStore.record?.id ?? "";
|
|
68
|
+
}
|
|
69
|
+
get agentName() {
|
|
70
|
+
return String(this.pb.authStore.record?.name ?? "");
|
|
71
|
+
}
|
|
72
|
+
async login() {
|
|
73
|
+
const creds = this.creds;
|
|
74
|
+
try {
|
|
75
|
+
if ("key" in creds) {
|
|
76
|
+
// Answers like auth-with-password: {token, record}.
|
|
77
|
+
const res = await this.pb.send("/api/board/agent-login", {
|
|
78
|
+
method: "POST",
|
|
79
|
+
body: { key: creds.key },
|
|
80
|
+
});
|
|
81
|
+
this.pb.authStore.save(res.token, res.record);
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
await this.pb.collection("agents").authWithPassword(creds.email, creds.password);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
catch (err) {
|
|
88
|
+
if (!("key" in creds) && err instanceof ClientResponseError && err.status === 400) {
|
|
89
|
+
throw new BoardError(`agent login failed for ${creds.email}: check BOARD_AGENT_EMAIL and BOARD_AGENT_PASSWORD`);
|
|
90
|
+
}
|
|
91
|
+
// The agents collection's auth rule refuses disabled agents.
|
|
92
|
+
if (!("key" in creds) && err instanceof ClientResponseError && err.status === 403) {
|
|
93
|
+
throw new BoardError(`agent ${creds.email} is disabled on the board; ask a human to enable it`, 403);
|
|
94
|
+
}
|
|
95
|
+
throw toBoardError(err, creds.url, "agent login");
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/** Runs fn with a valid token: logs in when needed and once more on a 401. */
|
|
99
|
+
async call(action, fn) {
|
|
100
|
+
if (!this.pb.authStore.isValid)
|
|
101
|
+
await this.login();
|
|
102
|
+
try {
|
|
103
|
+
return await fn();
|
|
104
|
+
}
|
|
105
|
+
catch (err) {
|
|
106
|
+
if (err instanceof ClientResponseError && err.status === 401) {
|
|
107
|
+
await this.login();
|
|
108
|
+
try {
|
|
109
|
+
return await fn();
|
|
110
|
+
}
|
|
111
|
+
catch (retryErr) {
|
|
112
|
+
throw toBoardError(retryErr, this.creds.url, action);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
throw toBoardError(err, this.creds.url, action);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
/** Board route call; every call carries this session's id so the server can refuse a session that no longer holds the ticket. */
|
|
119
|
+
post(route, body) {
|
|
120
|
+
return this.call(route, () => this.pb.send(`/api/board/${route}`, { method: "POST", body: { ...body, session: this.session } }));
|
|
121
|
+
}
|
|
122
|
+
/** Tickets assigned to this agent, any status except done. */
|
|
123
|
+
async listMine() {
|
|
124
|
+
return this.call("list tickets", async () => {
|
|
125
|
+
const records = await this.pb.collection("tickets").getFullList({
|
|
126
|
+
filter: 'status != "done"',
|
|
127
|
+
sort: "-priority,created",
|
|
128
|
+
fields: SUMMARY_FIELDS,
|
|
129
|
+
});
|
|
130
|
+
return records;
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
claim() {
|
|
134
|
+
return this.post("claim", {});
|
|
135
|
+
}
|
|
136
|
+
heartbeat(ticketId, note) {
|
|
137
|
+
return this.post("heartbeat", { ticket_id: ticketId, note: note ?? "" });
|
|
138
|
+
}
|
|
139
|
+
async logEvent(ticketId, kind, text) {
|
|
140
|
+
return this.call("log event", async () => {
|
|
141
|
+
try {
|
|
142
|
+
await this.pb.collection("events").create({ ticket: ticketId, agent: this.agentId, kind, text, session: this.session });
|
|
143
|
+
}
|
|
144
|
+
catch (err) {
|
|
145
|
+
// The create rule rejects events on tickets that are not ours with a
|
|
146
|
+
// bare 400 and no field errors.
|
|
147
|
+
const data = err instanceof ClientResponseError ? err.response?.data : undefined;
|
|
148
|
+
if (err instanceof ClientResponseError && err.status === 400 && !Object.keys(data ?? {}).length) {
|
|
149
|
+
throw new BoardError("cannot log on this ticket: not found or not yours", 404);
|
|
150
|
+
}
|
|
151
|
+
throw err;
|
|
152
|
+
}
|
|
153
|
+
return { ok: true };
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
recordSpec(ticketId, sha) {
|
|
157
|
+
return this.post("record-spec", { ticket_id: ticketId, sha });
|
|
158
|
+
}
|
|
159
|
+
askHuman(ticketId, question) {
|
|
160
|
+
return this.post("ask", { ticket_id: ticketId, question });
|
|
161
|
+
}
|
|
162
|
+
submitForReview(ticketId, prUrl, summary, usage) {
|
|
163
|
+
return this.post("submit", { ticket_id: ticketId, pr_url: prUrl, summary, ...(usage ? { usage } : {}) });
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Usage for one of this agent's tickets after the work, in any status (for
|
|
167
|
+
* example from Claude Code's final JSON). `stored` is false when the agent
|
|
168
|
+
* does not report usage on the board: the server dropped it.
|
|
169
|
+
*/
|
|
170
|
+
reportUsage(ticketId, usage) {
|
|
171
|
+
return this.post("usage", { ticket_id: ticketId, usage });
|
|
172
|
+
}
|
|
173
|
+
release(ticketId, reason, usage) {
|
|
174
|
+
return this.post("release", { ticket_id: ticketId, reason, ...(usage ? { usage } : {}) });
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
export class BoardAdmin {
|
|
178
|
+
url;
|
|
179
|
+
email;
|
|
180
|
+
password;
|
|
181
|
+
pb;
|
|
182
|
+
constructor(url, email, password) {
|
|
183
|
+
this.url = url;
|
|
184
|
+
this.email = email;
|
|
185
|
+
this.password = password;
|
|
186
|
+
this.pb = newClient(url);
|
|
187
|
+
}
|
|
188
|
+
async call(action, fn) {
|
|
189
|
+
try {
|
|
190
|
+
if (!this.pb.authStore.isValid) {
|
|
191
|
+
await this.pb.collection("_superusers").authWithPassword(this.email, this.password);
|
|
192
|
+
}
|
|
193
|
+
return await fn();
|
|
194
|
+
}
|
|
195
|
+
catch (err) {
|
|
196
|
+
throw toBoardError(err, this.url, action);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
/** Creates the agent, or resets its profile and password if it exists. */
|
|
200
|
+
upsertAgent(agent) {
|
|
201
|
+
return this.call(`upsert agent ${agent.name}`, async () => {
|
|
202
|
+
const data = {
|
|
203
|
+
name: agent.name,
|
|
204
|
+
email: agent.email,
|
|
205
|
+
password: agent.password,
|
|
206
|
+
passwordConfirm: agent.password,
|
|
207
|
+
role: agent.role,
|
|
208
|
+
model: agent.model ?? "",
|
|
209
|
+
effort: agent.effort ?? "",
|
|
210
|
+
runtime: agent.runtime ?? "",
|
|
211
|
+
report_usage: agent.report_usage ?? false,
|
|
212
|
+
key_hint: agent.password.slice(-4),
|
|
213
|
+
verified: true,
|
|
214
|
+
};
|
|
215
|
+
const existing = await this.pb
|
|
216
|
+
.collection("agents")
|
|
217
|
+
.getFirstListItem(this.pb.filter("email = {:email}", { email: agent.email }))
|
|
218
|
+
.catch((err) => {
|
|
219
|
+
if (err instanceof ClientResponseError && err.status === 404)
|
|
220
|
+
return null;
|
|
221
|
+
throw err;
|
|
222
|
+
});
|
|
223
|
+
const record = existing
|
|
224
|
+
? await this.pb.collection("agents").update(existing.id, data)
|
|
225
|
+
: await this.pb.collection("agents").create(data);
|
|
226
|
+
return { id: record.id };
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
/** Creates the board's human (a `users` record), or resets their name and password if they exist. */
|
|
230
|
+
upsertUser(user) {
|
|
231
|
+
return this.call(`upsert user ${user.email}`, async () => {
|
|
232
|
+
const data = {
|
|
233
|
+
name: user.name,
|
|
234
|
+
email: user.email,
|
|
235
|
+
password: user.password,
|
|
236
|
+
passwordConfirm: user.password,
|
|
237
|
+
verified: true,
|
|
238
|
+
};
|
|
239
|
+
const existing = await this.pb
|
|
240
|
+
.collection("users")
|
|
241
|
+
.getFirstListItem(this.pb.filter("email = {:email}", { email: user.email }))
|
|
242
|
+
.catch((err) => {
|
|
243
|
+
if (err instanceof ClientResponseError && err.status === 404)
|
|
244
|
+
return null;
|
|
245
|
+
throw err;
|
|
246
|
+
});
|
|
247
|
+
const record = existing
|
|
248
|
+
? await this.pb.collection("users").update(existing.id, data)
|
|
249
|
+
: await this.pb.collection("users").create(data);
|
|
250
|
+
return { id: record.id };
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
findTicketByTitle(title) {
|
|
254
|
+
return this.call("find ticket", () => this.pb
|
|
255
|
+
.collection("tickets")
|
|
256
|
+
.getFirstListItem(this.pb.filter("title = {:title}", { title }))
|
|
257
|
+
.catch((err) => {
|
|
258
|
+
if (err instanceof ClientResponseError && err.status === 404)
|
|
259
|
+
return null;
|
|
260
|
+
throw err;
|
|
261
|
+
}));
|
|
262
|
+
}
|
|
263
|
+
/** Finds a ticket by record id or by its label, e.g. "T-1" for a title starting with "T-1:". */
|
|
264
|
+
findTicket(idOrLabel) {
|
|
265
|
+
return this.call("find ticket", async () => {
|
|
266
|
+
const filter = this.pb.filter("id = {:id} || title ~ {:prefix}", { id: idOrLabel, prefix: `${idOrLabel}:%` });
|
|
267
|
+
const found = await this.pb.collection("tickets").getList(1, 2, { filter });
|
|
268
|
+
return found.items.length === 1 ? found.items[0] : null;
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
createTicket(ticket) {
|
|
272
|
+
return this.call("create ticket", () => this.pb.collection("tickets").create(ticket));
|
|
273
|
+
}
|
|
274
|
+
updateTicket(id, data) {
|
|
275
|
+
return this.call("update ticket", () => this.pb.collection("tickets").update(id, data));
|
|
276
|
+
}
|
|
277
|
+
getTicket(id) {
|
|
278
|
+
return this.call("get ticket", () => this.pb.collection("tickets").getOne(id));
|
|
279
|
+
}
|
|
280
|
+
listTickets() {
|
|
281
|
+
return this.call("list tickets", () => this.pb.collection("tickets").getFullList({ sort: "created" }));
|
|
282
|
+
}
|
|
283
|
+
/** Agent id → agent name. */
|
|
284
|
+
async agentNames() {
|
|
285
|
+
return this.call("list agents", async () => {
|
|
286
|
+
const agents = await this.pb.collection("agents").getFullList({ fields: "id,name" });
|
|
287
|
+
return new Map(agents.map((a) => [a.id, a.name]));
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
listEvents(ticketId) {
|
|
291
|
+
return this.call("list events", () => this.pb.collection("events").getFullList({
|
|
292
|
+
filter: this.pb.filter("ticket = {:id}", { id: ticketId }),
|
|
293
|
+
sort: "created",
|
|
294
|
+
}));
|
|
295
|
+
}
|
|
296
|
+
/** Deletes every ticket (events cascade). */
|
|
297
|
+
deleteAllTickets() {
|
|
298
|
+
return this.call("delete tickets", async () => {
|
|
299
|
+
const all = await this.pb.collection("tickets").getFullList({ fields: "id" });
|
|
300
|
+
for (const t of all)
|
|
301
|
+
await this.pb.collection("tickets").delete(t.id);
|
|
302
|
+
return all.length;
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
/** Runs the lease sweeper now (same logic as the cron job) and returns the swept ticket ids. */
|
|
306
|
+
runSweeper() {
|
|
307
|
+
return this.call("run sweeper", async () => {
|
|
308
|
+
const res = await this.pb.send("/api/board/sweep", { method: "POST" });
|
|
309
|
+
return res.swept;
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
}
|
package/dist/watch.js
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
// `board watch -- <agent command>`: runs the agent whenever its own queue has
|
|
2
|
+
// work, one run at a time, on the client's machine and AI account. The board
|
|
3
|
+
// is only asked what is in the queue; the command is whatever starts the
|
|
4
|
+
// client's agent for one ticket (Claude Code, Codex, a script).
|
|
5
|
+
//
|
|
6
|
+
// Work means a ticket in progress (resume it) or a ready ticket without a
|
|
7
|
+
// block. The watcher stops when:
|
|
8
|
+
// - the queue is empty (unless --follow, which then polls every --interval),
|
|
9
|
+
// - --max-runs runs have happened,
|
|
10
|
+
// - two runs in a row changed nothing in the queue (for example another
|
|
11
|
+
// session of the agent holds its ticket), or
|
|
12
|
+
// - the command failed three times in a row.
|
|
13
|
+
// A paused board (asleep until a person opens it) is not a failure: the
|
|
14
|
+
// watcher waits, checking every --interval, and goes on when it is back.
|
|
15
|
+
// One watcher per agent and machine: a lock file in the state directory.
|
|
16
|
+
import { spawn } from "node:child_process";
|
|
17
|
+
import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
18
|
+
import { dirname } from "node:path";
|
|
19
|
+
import { BoardError, BoardPaused } from "./service.js";
|
|
20
|
+
/** Usage from Claude Code's final JSON (`claude -p --output-format json`), or null. */
|
|
21
|
+
export function usageFromClaudeJson(output) {
|
|
22
|
+
const candidates = [output.trim(), ...output.trim().split("\n").reverse()];
|
|
23
|
+
for (const text of candidates) {
|
|
24
|
+
let run;
|
|
25
|
+
try {
|
|
26
|
+
run = JSON.parse(text);
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
if (!run || typeof run !== "object" || (run.total_cost_usd === undefined && !run.usage))
|
|
32
|
+
continue;
|
|
33
|
+
const u = run.usage ?? {};
|
|
34
|
+
const usage = { source: "claude-code" };
|
|
35
|
+
if (Number.isInteger(u.input_tokens))
|
|
36
|
+
usage.input_tokens = u.input_tokens;
|
|
37
|
+
if (Number.isInteger(u.output_tokens))
|
|
38
|
+
usage.output_tokens = u.output_tokens;
|
|
39
|
+
if (Number.isInteger(u.cache_read_input_tokens))
|
|
40
|
+
usage.cache_read_tokens = u.cache_read_input_tokens;
|
|
41
|
+
if (Number.isInteger(u.cache_creation_input_tokens))
|
|
42
|
+
usage.cache_write_tokens = u.cache_creation_input_tokens;
|
|
43
|
+
if (typeof run.total_cost_usd === "number") {
|
|
44
|
+
usage.cost = Math.round(run.total_cost_usd * 10000) / 10000;
|
|
45
|
+
usage.currency = "USD";
|
|
46
|
+
}
|
|
47
|
+
return usage;
|
|
48
|
+
}
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
/** The ticket a run worked on: the one whose state it changed, else the one it resumed. */
|
|
52
|
+
/**
|
|
53
|
+
* The ticket a run worked on, for its usage. Only a ticket the agent could
|
|
54
|
+
* take when the run started counts (ready or in progress then): what a human
|
|
55
|
+
* did meanwhile, such as approving a ticket in review or adding a new one,
|
|
56
|
+
* also changes the queue but is not the run's work.
|
|
57
|
+
*/
|
|
58
|
+
export function workedOn(before, after) {
|
|
59
|
+
const now = new Map(after.map((t) => [t.id, t]));
|
|
60
|
+
const takeable = before.filter((t) => t.status === "ready" || t.status === "in_progress");
|
|
61
|
+
const changed = takeable.filter((t) => snapshot([t]) !== (now.has(t.id) ? snapshot([now.get(t.id)]) : undefined));
|
|
62
|
+
if (changed.length === 1)
|
|
63
|
+
return now.get(changed[0].id) ?? changed[0];
|
|
64
|
+
if (changed.length === 0)
|
|
65
|
+
return before.find((t) => t.status === "in_progress") ?? null;
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
const label = (t) => /^T-\d+/.exec(t.title)?.[0] ?? t.id;
|
|
69
|
+
const NO_PROGRESS_STOP = 2;
|
|
70
|
+
const FAILURE_STOP = 3;
|
|
71
|
+
export function hasWork(mine) {
|
|
72
|
+
return mine.some((t) => t.status === "in_progress" || (t.status === "ready" && t.block_kind === "none" && !!t.spec_path));
|
|
73
|
+
}
|
|
74
|
+
/** What a run can change in the queue: status, block, lease, PR, attempts. */
|
|
75
|
+
function snapshot(mine) {
|
|
76
|
+
return mine
|
|
77
|
+
.map((t) => [t.id, t.status, t.block_kind, t.claimed_until, t.pr_url, t.attempts].join(":"))
|
|
78
|
+
.sort()
|
|
79
|
+
.join("|");
|
|
80
|
+
}
|
|
81
|
+
function alive(pid) {
|
|
82
|
+
try {
|
|
83
|
+
process.kill(pid, 0);
|
|
84
|
+
return true;
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
function takeLock(file) {
|
|
91
|
+
try {
|
|
92
|
+
const pid = Number(JSON.parse(readFileSync(file, "utf8")).pid);
|
|
93
|
+
if (pid && pid !== process.pid && alive(pid)) {
|
|
94
|
+
throw new BoardError(`another board watch for this agent is running here (pid ${pid}); stop it first`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
catch (err) {
|
|
98
|
+
if (err instanceof BoardError)
|
|
99
|
+
throw err;
|
|
100
|
+
}
|
|
101
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
102
|
+
writeFileSync(file, JSON.stringify({ pid: process.pid, at: new Date().toISOString() }) + "\n", { mode: 0o600 });
|
|
103
|
+
}
|
|
104
|
+
function sleep(ms, stop) {
|
|
105
|
+
return new Promise((resolve) => {
|
|
106
|
+
const step = 250;
|
|
107
|
+
let left = ms;
|
|
108
|
+
const tick = () => {
|
|
109
|
+
if (stop.stopped || left <= 0)
|
|
110
|
+
return resolve();
|
|
111
|
+
left -= step;
|
|
112
|
+
setTimeout(tick, step);
|
|
113
|
+
};
|
|
114
|
+
tick();
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
/** Runs the watcher until a stop condition; returns the exit code for the CLI. */
|
|
118
|
+
export async function watch(opts) {
|
|
119
|
+
const { board, command, log } = opts;
|
|
120
|
+
// The lock first: two watchers waiting on a paused board must not both run when it is back.
|
|
121
|
+
takeLock(opts.lockFile);
|
|
122
|
+
const state = { stopped: false };
|
|
123
|
+
let child = null;
|
|
124
|
+
const onSignal = (signal) => {
|
|
125
|
+
state.stopped = true;
|
|
126
|
+
log(`${signal}: stopping${child ? " after the current run" : ""}`);
|
|
127
|
+
child?.kill(signal);
|
|
128
|
+
};
|
|
129
|
+
process.on("SIGINT", onSignal);
|
|
130
|
+
process.on("SIGTERM", onSignal);
|
|
131
|
+
/** fn's result once the board answers; null when stopped while it was paused. */
|
|
132
|
+
const whenAwake = async (fn) => {
|
|
133
|
+
let paused = false;
|
|
134
|
+
while (!state.stopped) {
|
|
135
|
+
try {
|
|
136
|
+
const result = await fn();
|
|
137
|
+
if (paused)
|
|
138
|
+
log("the board is back");
|
|
139
|
+
return result;
|
|
140
|
+
}
|
|
141
|
+
catch (err) {
|
|
142
|
+
if (!(err instanceof BoardPaused))
|
|
143
|
+
throw err;
|
|
144
|
+
if (!paused)
|
|
145
|
+
log(`${err.message}; waiting, checking every ${opts.intervalSec}s (Ctrl+C to stop)`);
|
|
146
|
+
paused = true;
|
|
147
|
+
await sleep(opts.intervalSec * 1000, state);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return null;
|
|
151
|
+
};
|
|
152
|
+
let runs = 0;
|
|
153
|
+
let noProgress = 0;
|
|
154
|
+
let failures = 0;
|
|
155
|
+
let waitingLogged = false;
|
|
156
|
+
try {
|
|
157
|
+
if ((await whenAwake(() => board.login())) === null)
|
|
158
|
+
return 0;
|
|
159
|
+
log(`watching ${board.agentName}'s queue; command: ${command.join(" ")}`);
|
|
160
|
+
while (!state.stopped) {
|
|
161
|
+
const before = await whenAwake(() => board.listMine());
|
|
162
|
+
if (before === null)
|
|
163
|
+
break;
|
|
164
|
+
if (!hasWork(before)) {
|
|
165
|
+
if (!opts.follow) {
|
|
166
|
+
log(`queue empty after ${runs} run(s); stopping`);
|
|
167
|
+
return 0;
|
|
168
|
+
}
|
|
169
|
+
if (!waitingLogged)
|
|
170
|
+
log(`queue empty; checking every ${opts.intervalSec}s (Ctrl+C to stop)`);
|
|
171
|
+
waitingLogged = true;
|
|
172
|
+
await sleep(opts.intervalSec * 1000, state);
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
waitingLogged = false;
|
|
176
|
+
if (runs >= opts.maxRuns) {
|
|
177
|
+
log(`stopping after ${runs} runs (--max-runs) with work still in the queue`);
|
|
178
|
+
return 1;
|
|
179
|
+
}
|
|
180
|
+
runs++;
|
|
181
|
+
const started = Date.now();
|
|
182
|
+
log(`run ${runs}: starting the agent`);
|
|
183
|
+
let output = "";
|
|
184
|
+
const code = await new Promise((resolve) => {
|
|
185
|
+
child = spawn(command[0], command.slice(1), {
|
|
186
|
+
stdio: ["inherit", opts.usageFrom ? "pipe" : "inherit", "inherit"],
|
|
187
|
+
env: process.env,
|
|
188
|
+
});
|
|
189
|
+
child.stdout?.on("data", (d) => {
|
|
190
|
+
output += d;
|
|
191
|
+
process.stdout.write(d);
|
|
192
|
+
});
|
|
193
|
+
child.on("error", (err) => {
|
|
194
|
+
log(`run ${runs}: could not start ${command[0]}: ${err.message}`);
|
|
195
|
+
resolve(127);
|
|
196
|
+
});
|
|
197
|
+
child.on("exit", (exitCode, signal) => resolve(exitCode ?? (signal ? 128 : 1)));
|
|
198
|
+
});
|
|
199
|
+
child = null;
|
|
200
|
+
const secs = Math.round((Date.now() - started) / 1000);
|
|
201
|
+
log(`run ${runs}: exit ${code} after ${secs}s`);
|
|
202
|
+
failures = code === 0 ? 0 : failures + 1;
|
|
203
|
+
if (failures >= FAILURE_STOP) {
|
|
204
|
+
log(`the command failed ${failures} times in a row; stopping`);
|
|
205
|
+
return 1;
|
|
206
|
+
}
|
|
207
|
+
const after = await whenAwake(() => board.listMine());
|
|
208
|
+
if (after === null)
|
|
209
|
+
break;
|
|
210
|
+
if (opts.usageFrom)
|
|
211
|
+
await reportRunUsage(board, before, after, output, runs, log);
|
|
212
|
+
noProgress = snapshot(after) === snapshot(before) ? noProgress + 1 : 0;
|
|
213
|
+
if (noProgress >= NO_PROGRESS_STOP) {
|
|
214
|
+
log(`${noProgress} runs in a row changed nothing in the queue; stopping. ` +
|
|
215
|
+
"Is another session of this agent holding its ticket? See the board.");
|
|
216
|
+
return 1;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
return 0;
|
|
220
|
+
}
|
|
221
|
+
finally {
|
|
222
|
+
process.off("SIGINT", onSignal);
|
|
223
|
+
process.off("SIGTERM", onSignal);
|
|
224
|
+
rmSync(opts.lockFile, { force: true });
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
async function reportRunUsage(board, before, after, output, run, log) {
|
|
228
|
+
const usage = usageFromClaudeJson(output);
|
|
229
|
+
if (!usage)
|
|
230
|
+
return log(`run ${run}: no Claude Code JSON result in the output; no usage reported`);
|
|
231
|
+
const ticket = workedOn(before, after);
|
|
232
|
+
if (!ticket)
|
|
233
|
+
return log(`run ${run}: could not tell which ticket the run worked on; usage not reported`);
|
|
234
|
+
try {
|
|
235
|
+
const res = await board.reportUsage(ticket.id, usage);
|
|
236
|
+
log(res.stored
|
|
237
|
+
? `run ${run}: usage reported on ${label(ticket)}${usage.cost !== undefined ? ` (${usage.cost} USD)` : ""}`
|
|
238
|
+
: `run ${run}: usage not stored: this agent does not report usage on the board`);
|
|
239
|
+
}
|
|
240
|
+
catch (err) {
|
|
241
|
+
log(`run ${run}: usage not reported: ${err instanceof Error ? err.message : String(err)}`);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
{
|
|
2
|
+
"permissions": {
|
|
3
|
+
"additionalDirectories": [
|
|
4
|
+
"../.wt"
|
|
5
|
+
],
|
|
6
|
+
"allow": [
|
|
7
|
+
"mcp__board__*",
|
|
8
|
+
"Bash(board *)",
|
|
9
|
+
"Bash(npx -y {{package}} *)",
|
|
10
|
+
"Bash(git fetch *)",
|
|
11
|
+
"Bash(git show *)",
|
|
12
|
+
"Bash(git rev-parse *)",
|
|
13
|
+
"Bash(git worktree *)",
|
|
14
|
+
"Bash(git status *)",
|
|
15
|
+
"Bash(git diff *)",
|
|
16
|
+
"Bash(git log *)",
|
|
17
|
+
"Bash(git add *)",
|
|
18
|
+
"Bash(git commit *)",
|
|
19
|
+
"Bash(git push *)",
|
|
20
|
+
"Bash(gh pr create *)",
|
|
21
|
+
"Bash(gh pr view *)",
|
|
22
|
+
"Bash(npm test)",
|
|
23
|
+
"Bash(npm run lint)"
|
|
24
|
+
],
|
|
25
|
+
"deny": [
|
|
26
|
+
"Bash(curl *)",
|
|
27
|
+
"Bash(gh pr merge *)",
|
|
28
|
+
"Bash(gh api *)",
|
|
29
|
+
"Bash(gh repo *)",
|
|
30
|
+
"Bash(git push origin main*)",
|
|
31
|
+
"Bash(git push -u origin main*)",
|
|
32
|
+
"Bash(git push origin HEAD:main*)",
|
|
33
|
+
"Bash(git push --force*)",
|
|
34
|
+
"Bash(git push -f *)",
|
|
35
|
+
"Bash(git push * --force*)",
|
|
36
|
+
"Bash(git push * -f*)"
|
|
37
|
+
]
|
|
38
|
+
}
|
|
39
|
+
}
|
package/kit/done.md
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Finish the ticket you are working on. Run everything inside its worktree
|
|
2
|
+
`../.wt/<ticket id>`. Board calls are named by their MCP tool; in a shell use
|
|
3
|
+
the `board` command of the same name (`submit_for_review` is `board submit`).
|
|
4
|
+
|
|
5
|
+
1. Run the project's tests and linter (for example `npm test`,
|
|
6
|
+
`npm run lint`; use what the project has). If they fail, fix them. If you
|
|
7
|
+
cannot, call `log_event` kind `warn` with what fails, then `ask_human`,
|
|
8
|
+
and stop.
|
|
9
|
+
2. Commit with a clear message and push the branch:
|
|
10
|
+
`git push -u origin <branch>`.
|
|
11
|
+
3. Open a PR against `main` with `gh pr create`. Title: the ticket title.
|
|
12
|
+
The body names the ticket id, the spec path and the spec commit
|
|
13
|
+
(`record_spec`). If a PR for the branch already exists
|
|
14
|
+
(`gh pr view <branch>`), the push updates it; use its URL.
|
|
15
|
+
4. Call `heartbeat`, then `submit_for_review` with the PR URL and a 2 to 4
|
|
16
|
+
line summary of what changed. If your tool tells you what this work cost
|
|
17
|
+
(tokens, cost), pass it as `usage`; otherwise leave it out.
|
|
18
|
+
5. Do not mark the ticket done and do not merge the PR. A human does that.
|
|
19
|
+
Stop here.
|
package/kit/pick.md
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
Take the next ticket from the board and work on it. Board calls below are
|
|
2
|
+
named by their MCP tool; in a shell use the `board` command of the same name
|
|
3
|
+
(`claim` is `board claim`, `ask_human` is `board ask`).
|
|
4
|
+
|
|
5
|
+
1. Call `claim`.
|
|
6
|
+
- If `ticket` is null, say there is nothing to do and stop.
|
|
7
|
+
- If `resumed` is true, you are continuing your own ticket after a restart:
|
|
8
|
+
reuse its worktree (step 4) and pick up where the work stopped.
|
|
9
|
+
- If `claim` fails because another session of yours holds the ticket, say
|
|
10
|
+
so and stop. Do not retry and do not touch its worktree.
|
|
11
|
+
2. Read `answer` and `notes` on the ticket. They are additions to the spec:
|
|
12
|
+
answers to earlier questions and review feedback. They override the spec
|
|
13
|
+
where they conflict with it.
|
|
14
|
+
3. Read the spec from `main` only, never from the working tree:
|
|
15
|
+
```
|
|
16
|
+
git fetch origin main
|
|
17
|
+
git show origin/main:<spec_path>/spec.md
|
|
18
|
+
```
|
|
19
|
+
Then call `record_spec` with the output of `git rev-parse origin/main`.
|
|
20
|
+
4. Set up the worktree `../.wt/<ticket id>` and work only inside it:
|
|
21
|
+
- If `../.wt/<ticket id>` already exists, use it as is.
|
|
22
|
+
- Else, if the branch already exists on origin (a review round), run
|
|
23
|
+
`git fetch origin <branch>` and
|
|
24
|
+
`git worktree add ../.wt/<ticket id> -B <branch> origin/<branch>`.
|
|
25
|
+
- Else run `git worktree add ../.wt/<ticket id> -b <branch> origin/main`.
|
|
26
|
+
- A new worktree has no dependencies: install them with the project's
|
|
27
|
+
package manager (`npm ci`, `pnpm install`, …) before running anything.
|
|
28
|
+
5. Write a short plan (3 to 6 steps) and log it with `log_event`, kind `plan`.
|
|
29
|
+
6. Implement step by step. After each step call `heartbeat` with a one-line
|
|
30
|
+
note.
|
|
31
|
+
7. If the spec, `answer` and `notes` do not answer something that changes
|
|
32
|
+
behavior, call `ask_human` with one concrete question and stop. Do not
|
|
33
|
+
guess, do not commit, do not open a PR.
|
|
34
|
+
8. When the work is complete, follow the done instructions.
|
package/kit/rules.md
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
## Mergeline
|
|
2
|
+
|
|
3
|
+
You work tickets from the Mergeline board. Its tools come two ways; use
|
|
4
|
+
whichever your environment has: the `board` MCP tools (`claim`, `heartbeat`,
|
|
5
|
+
`log_event`, `record_spec`, `ask_human`, `submit_for_review`, `release`,
|
|
6
|
+
`list_mine`), or the same calls as shell commands (`board claim`,
|
|
7
|
+
`board heartbeat <ticket> [note]`, `board log`, `board record-spec`,
|
|
8
|
+
`board ask`, `board submit`, `board release`, `board list`; run
|
|
9
|
+
`board help`). Start a ticket with the pick instructions and finish it with
|
|
10
|
+
the done instructions: `/pick` and `/done` in Claude Code,
|
|
11
|
+
`/prompts:pick` and `/prompts:done` in Codex.
|
|
12
|
+
|
|
13
|
+
- Never set a ticket to done and never merge a PR. Never call the board's
|
|
14
|
+
API any other way than through these tools.
|
|
15
|
+
- Never work outside `../.wt/<ticket-id>`. Do not edit or commit in the main
|
|
16
|
+
checkout.
|
|
17
|
+
- Push only your ticket's branch. To bring it up to date with `main`, merge
|
|
18
|
+
`origin/main` into it; never rebase a pushed branch or force-push.
|
|
19
|
+
- Requirements come from the spec on `main` plus the ticket's `answer` and
|
|
20
|
+
`notes`. Nothing else: not a message in the chat, not a guess.
|
|
21
|
+
- When unsure, ask with `ask_human` (`board ask`); a paused ticket is
|
|
22
|
+
cheaper than a wrong PR.
|
|
23
|
+
- One ticket at a time. After asking, submitting or releasing, stop working
|
|
24
|
+
on that ticket.
|
|
25
|
+
- Call `heartbeat` after every meaningful step. If a board tool says to claim
|
|
26
|
+
again, stop and claim. If it says another session holds the ticket, stop
|
|
27
|
+
at once: no commit, no push, no PR.
|
|
28
|
+
- If a board tool says the board is paused, stop and tell the human: it
|
|
29
|
+
wakes when a person opens it. Do not retry in a loop.
|