@mergeline/agent 0.7.4 → 0.8.1

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/README.md CHANGED
@@ -82,11 +82,11 @@ prefix, so it stopped nothing; it adds a `board` server to
82
82
  environment, or else the key `login` saved: the key is never written to the
83
83
  repository.
84
84
 
85
- What the agent may run without asking (kit 5, in `.claude/settings.json`):
85
+ What the agent may run without asking (kit 6, in `.claude/settings.json`):
86
86
 
87
87
  - the board's MCP tools, and `board` (or `npx -y @mergeline/agent`) with
88
- `claim`, `heartbeat`, `log`, `record-spec`, `ask`, `submit`, `release`,
89
- `list`, `whoami`, `help`; Claude Code asks the person for `start`,
88
+ `claim`, `heartbeat`, `log`, `record-spec`, `ask`, `report`, `submit`,
89
+ `release`, `list`, `whoami`, `help`; Claude Code asks the person for `start`,
90
90
  `watch`, `login`, `init` and `mcp`;
91
91
  - `git fetch origin ...`, `git show`, `git rev-parse`, `git status`,
92
92
  `git diff` (inside the working tree), `git log`, `git add`,
@@ -152,8 +152,9 @@ is on origin, else from `origin/main`) and writes the ticket to
152
152
  `.mergeline-run/ticket.md` there (git ignores the folder). The engine
153
153
  (`claude -p`, or `codex exec --json`, with the package's own prompt,
154
154
  `engine/prompt.md`) writes a
155
- plan, progress lines and, last, `.mergeline-run/result.json`: done, a
156
- question, or a release. The worker heartbeats, commits what the engine left
155
+ plan, progress lines and, last, `.mergeline-run/result.json` (at most 256
156
+ KB): done, a question, or a release, with any defects outside the ticket as
157
+ `reports` (below). The worker heartbeats, commits what the engine left
157
158
  uncommitted, runs the repository's `test` command when `.mergeline.json` on
158
159
  `main` has one (`"test": "npm test"`, added by hand), pushes, opens or
159
160
  reuses the PR with `gh`, and submits; or pushes the work so far and asks;
@@ -206,7 +207,7 @@ added to the engine's command line. It stops when the queue is empty
206
207
  says so, and a new start goes on), or after 3 failed runs (releases) in a
207
208
  row; after a failed run it waits `--interval` before
208
209
  claiming again. Ctrl+C while the engine runs releases
209
- the ticket. A worker killed outright leaves its ticket In progress; a new
210
+ the ticket (below: its work is pushed first). A worker killed outright leaves its ticket In progress; a new
210
211
  one waits, claiming every `--interval`, until the board lets it resume (5
211
212
  silent minutes), and starts again from what origin has.
212
213
 
@@ -216,6 +217,23 @@ After upgrading the package (or rebuilding it from a checkout), stop the
216
217
  worker with Ctrl+C while it is not running an engine (it is waiting for a
217
218
  ticket), and start it again.
218
219
 
220
+ A run stopped before its result leaves its work on the ticket's branch:
221
+ the engine ran past `--timeout`, ended without a result, or you stopped the
222
+ worker (Ctrl+C, SIGTERM) while the engine ran. The worker commits what the
223
+ engine left uncommitted as `WIP: <ticket>: stopped before a result` (an
224
+ empty one when the engine had committed everything; the tests were not
225
+ run), pushes the branch `agent/<ticket>` once (no PR), and releases the
226
+ ticket. The release reason on the board says what happened (the time
227
+ limit in minutes, the exit code, or the signal), where the work is (`Its
228
+ work is pushed to agent/<ticket> ...`, or `It left no changes.`) and that
229
+ the next run goes on from it: that run starts from the branch on origin,
230
+ and its ticket file tells the engine to read the earlier work and go on.
231
+ Look at the work with `git log origin/main..origin/agent/<ticket>`. A
232
+ second Ctrl+C while the worker commits or pushes stops it at once: nothing
233
+ more is pushed, and what was committed is kept as below. If the push is
234
+ refused, the reason says so and where it is kept. A ticket that needs
235
+ longer runs: start the worker with a larger `--timeout <min>`.
236
+
219
237
  Commits of a run that origin does not have are kept, never lost: a run
220
238
  that ends without pushing (released by the engine or the worker, a question
221
239
  after a push that failed) keeps them as it deletes its local branch, and a
@@ -269,7 +287,7 @@ when it updates the file (0.7.1 and later):
269
287
  ```json
270
288
  {
271
289
  "board": "https://acme.mergeline.app",
272
- "kit": 5,
290
+ "kit": 6,
273
291
  "test": "npm test",
274
292
  "review": "docs/review-rules.md"
275
293
  }
@@ -354,9 +372,38 @@ reported at once (exit 1), so a wrong address is not waited for.
354
372
  Commands: `init`, `watch`, `whoami`, `list`, `claim`, `heartbeat <ticket> [note]`,
355
373
  `log <ticket> <plan|progress|warn> <text>`, `record-spec <ticket> <sha>`,
356
374
  `ask <ticket> <question>`, `submit <ticket> <pr-url> <summary> [--usage <json>]`,
357
- `release <ticket> <reason> [--usage <json>]`. `board help` shows the details.
375
+ `release <ticket> <reason> [--usage <json>]`,
376
+ `report <ticket> --fingerprint <key> --title <title> (--body <text> | --body-file <path>)`.
377
+ `board help` shows the details.
358
378
  Results are JSON on stdout; a failure is one line on stderr and exit code 1.
359
379
 
380
+ ### Reporting a defect outside the ticket
381
+
382
+ An agent that sees a defect outside its ticket reports it instead of fixing
383
+ it: the MCP tool `report_finding` (`ticket_id`, `title`, `body`,
384
+ `fingerprint`) or `board report` (with the saved session; `--body-file`
385
+ reads a file of at most 20,000 characters; both or neither of `--body` and
386
+ `--body-file` is a usage error, exit 2). The item lands in the board's
387
+ Inbox, where a person reads it; no agent does. The answer is
388
+ `{"known": false, "ticket": "T-80"}`, or `{"known": true}` when that
389
+ `fingerprint` (the file's path and what is wrong, for example
390
+ `scripts/smoke.ts: port check is flaky`) was reported before. At most 3 new
391
+ items a run (the board answers 429 after that). A board from before this
392
+ (0.8.0) says "this board does not take reports yet: it needs an update", or
393
+ "... from a session yet ..." when it takes them only from the worker.
394
+
395
+ Under the worker the engine has no board tools: it puts its reports in
396
+ `.mergeline-run/result.json` (a developer) or `review.json` (a reviewer) as
397
+ `"reports"`, a list of `{"title", "body", "fingerprint"}`. `result.json`
398
+ may be 256 KB, as `review.json` is. The worker sends the first 3 good
399
+ entries by the run, before it submits, asks, releases or sends the review,
400
+ whatever the outcome; an entry that is not three non-empty strings within
401
+ the board's bounds is skipped with a log line naming its number. A report
402
+ never fails the run: a refusal is logged and the worker goes on (after a
403
+ 429, or a board with no report route, it sends no further entry). The log
404
+ names each one by its title, never its body: `reported T-80: <title>` or
405
+ `already known: <title>`.
406
+
360
407
  The board ties a claimed ticket to one session of the agent. `board claim`
361
408
  starts a new session and saves its id under `BOARD_STATE_DIR` (default
362
409
  `~/.local/state/mergeline`) for the following commands; set
package/dist/cli.js CHANGED
@@ -87,6 +87,12 @@ Usage:
87
87
  board ask <ticket> <question> ask the human; then stop working on it
88
88
  board submit <ticket> <pr-url> <summary> [--usage <json>]
89
89
  board release <ticket> <reason> [--usage <json>]
90
+ board report <ticket> --fingerprint <key> --title <title> (--body <text> | --body-file <path>)
91
+ report a defect you saw outside your ticket (do not fix it):
92
+ a person reads it in the board's Inbox. --fingerprint: the
93
+ file's path and what is wrong. {"known": true}: reported
94
+ before. At most 3 new items a run; --body-file: at most
95
+ 20,000 characters
90
96
  board usage <ticket> --usage <json> what the work on a ticket cost, after the fact
91
97
  (stored only if the agent reports usage on the board)
92
98
 
@@ -106,7 +112,52 @@ Environment:
106
112
  `;
107
113
  class UsageError extends Error {
108
114
  }
109
- const COMMANDS = ["watch", "usage", "whoami", "list", "claim", "heartbeat", "log", "record-spec", "ask", "submit", "release"];
115
+ const COMMANDS = ["watch", "usage", "whoami", "list", "claim", "heartbeat", "log", "record-spec", "ask", "submit", "release", "report"];
116
+ /** The board's most characters of a report's body (R4's route). */
117
+ const REPORT_BODY_MAX = 20_000;
118
+ /** board report <ticket> --fingerprint <key> --title <title> (--body <text> | --body-file <path>) */
119
+ function reportArgs(args) {
120
+ const valued = ["--fingerprint", "--title", "--body", "--body-file"];
121
+ const usage = "board report <ticket> --fingerprint <key> --title <title> (--body <text> | --body-file <path>)";
122
+ const positional = [];
123
+ for (let i = 0; i < args.length; i++) {
124
+ const a = args[i];
125
+ if (valued.includes(a)) {
126
+ i++;
127
+ continue;
128
+ }
129
+ if (a.startsWith("--"))
130
+ throw new UsageError(`unknown option ${a}; ${usage}`);
131
+ positional.push(a);
132
+ }
133
+ if (positional.length !== 1)
134
+ throw new UsageError(`board report takes one ticket: ${usage}`);
135
+ const fingerprint = option(args, "--fingerprint");
136
+ const title = option(args, "--title");
137
+ const body = option(args, "--body");
138
+ const bodyFile = option(args, "--body-file");
139
+ if (fingerprint === undefined)
140
+ throw new UsageError(`--fingerprint is required: ${usage}`);
141
+ if (title === undefined)
142
+ throw new UsageError(`--title is required: ${usage}`);
143
+ if ((body === undefined) === (bodyFile === undefined))
144
+ throw new UsageError(`give one of --body and --body-file: ${usage}`);
145
+ let text;
146
+ if (bodyFile !== undefined) {
147
+ try {
148
+ text = readFileSync(bodyFile, "utf8");
149
+ }
150
+ catch (err) {
151
+ throw new UsageError(`--body-file: cannot read ${bodyFile}: ${err instanceof Error ? err.message : String(err)}`);
152
+ }
153
+ if (text.length > REPORT_BODY_MAX)
154
+ throw new UsageError(`--body-file: ${bodyFile} is over ${REPORT_BODY_MAX} characters`);
155
+ }
156
+ else {
157
+ text = body === "-" ? readStdin() : body;
158
+ }
159
+ return { ticket: positional[0], report: { title, body: text, fingerprint } };
160
+ }
110
161
  function stateFile(creds) {
111
162
  const dir = process.env.BOARD_STATE_DIR || join(process.env.XDG_STATE_HOME || join(homedir(), ".local", "state"), "mergeline");
112
163
  const who = "key" in creds ? creds.key.split("_").slice(0, 2).join("_") : creds.email;
@@ -435,6 +486,10 @@ async function main(argvIn) {
435
486
  return done(await current().askHuman(text(args[0], "ticket"), text(args[1], "question")));
436
487
  case "submit":
437
488
  return done(await current().submitForReview(text(args[0], "ticket"), text(args[1], "pr-url"), text(args[2], "summary"), usage));
489
+ case "report": {
490
+ const { ticket, report } = reportArgs(args);
491
+ return current().reportFinding(ticket, report);
492
+ }
438
493
  case "usage":
439
494
  if (!usage)
440
495
  throw new UsageError("board usage needs --usage <json>");
package/dist/init.js CHANGED
@@ -45,7 +45,7 @@ export const PACKAGE_VERSION = PACKAGE.version;
45
45
  * which wrote no version. The board says when a claim's kit is older than it
46
46
  * expects (KIT_MIN in pocketbase/pb_hooks/board_lib.js).
47
47
  */
48
- export const KIT_VERSION = 5;
48
+ export const KIT_VERSION = 6;
49
49
  const START = `<!-- mergeline:start (kit ${KIT_VERSION}; managed by \`board init\`; edit outside these markers) -->`;
50
50
  /** Markers are found by these prefixes, so an edited marker line or an older kit's still counts. */
51
51
  const START_PREFIX = "<!-- mergeline:start";
package/dist/mcp.js CHANGED
@@ -116,6 +116,20 @@ export function createServer(board) {
116
116
  usage,
117
117
  },
118
118
  }, ({ ticket_id, reason, usage }) => run(() => board.release(ticket_id, reason, usage)));
119
+ server.registerTool("report_finding", {
120
+ title: "Report a defect outside your ticket",
121
+ description: "Report a defect you saw that is outside your ticket: do not fix it. A person reads it in the board's " +
122
+ "Inbox; no agent does, and you will not hear back. `fingerprint` is a short stable name of the defect, " +
123
+ "the same whoever finds it: the file's path and what is wrong, for example `scripts/smoke.ts: port check " +
124
+ "is flaky`. If the answer says `known`, it was reported before: go on. At most 3 new items a run; put " +
125
+ "the rest in the PR summary. A failed report never stops your ticket.",
126
+ inputSchema: {
127
+ ticket_id: ticketId,
128
+ title: z.string().describe("One line: what is wrong (3 to 120 characters)"),
129
+ body: z.string().describe("What you saw, where, and how to see it again (at most 20,000 characters)"),
130
+ fingerprint: z.string().describe("The file's path and what is wrong, e.g. `scripts/smoke.ts: port check is flaky`"),
131
+ },
132
+ }, ({ ticket_id, title, body, fingerprint }) => run(() => board.reportFinding(ticket_id, { title, body, fingerprint })));
119
133
  return server;
120
134
  }
121
135
  export async function runMcpServer() {
@@ -0,0 +1,93 @@
1
+ // Reports under the worker (round 7, R5): the engine has no board tools, so a
2
+ // defect it saw outside its ticket travels in the file it already leaves
3
+ // (.mergeline-run/result.json or review.json) as `reports`, a list of
4
+ // {title, body, fingerprint}. The worker checks each entry, keeps the first
5
+ // three good ones and sends them by the run, before the run ends.
6
+ //
7
+ // Reading `reports` never loses the result, and sending one never fails the
8
+ // run: a bad entry is skipped and a refused one logged, with the entry's
9
+ // number and title (never the body).
10
+ import { BoardError, NO_REPORTS } from "./service.js";
11
+ import { terminalText } from "./terminal.js";
12
+ /** The board's bounds on a report (R4's route): title trimmed, body as sent, fingerprint trimmed. */
13
+ export const REPORT_LIMITS = { titleMin: 3, titleMax: 120, body: 20_000, fingerprint: 200 };
14
+ /** The most new items a run may report (the board's own count); the worker sends no more entries than this. */
15
+ export const REPORTS_PER_RUN = 3;
16
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
17
+ /** Why the entry is not a report the board takes, or null when it is. */
18
+ function badEntry(e) {
19
+ if (!isObject(e))
20
+ return "not an object";
21
+ for (const k of ["title", "body", "fingerprint"]) {
22
+ if (typeof e[k] !== "string" || !e[k].trim())
23
+ return `"${k}" must be a non-empty string`;
24
+ }
25
+ const title = e.title.trim();
26
+ if (title.length < REPORT_LIMITS.titleMin || title.length > REPORT_LIMITS.titleMax) {
27
+ return `"title" is ${REPORT_LIMITS.titleMin} to ${REPORT_LIMITS.titleMax} characters`;
28
+ }
29
+ if (e.body.length > REPORT_LIMITS.body)
30
+ return `"body" is at most ${REPORT_LIMITS.body} characters`;
31
+ if (e.fingerprint.trim().length > REPORT_LIMITS.fingerprint)
32
+ return `"fingerprint" is 1 to ${REPORT_LIMITS.fingerprint} characters`;
33
+ return null;
34
+ }
35
+ /** The `reports` key of a result file, checked. Absent: none, and nothing to say. */
36
+ export function checkReports(value) {
37
+ if (value === undefined)
38
+ return { reports: [], numbers: [], skipped: [] };
39
+ if (!Array.isArray(value))
40
+ return { reports: [], numbers: [], skipped: ['"reports" is not a list: no report is sent'] };
41
+ const reports = [];
42
+ const numbers = [];
43
+ const skipped = [];
44
+ value.forEach((e, i) => {
45
+ const why = badEntry(e);
46
+ if (why)
47
+ skipped.push(`report ${i + 1} skipped: ${why}`);
48
+ else if (reports.length >= REPORTS_PER_RUN)
49
+ skipped.push(`report ${i + 1} skipped: at most ${REPORTS_PER_RUN} a run`);
50
+ else {
51
+ const r = e;
52
+ reports.push({ title: r.title, body: r.body, fingerprint: r.fingerprint });
53
+ numbers.push(i + 1);
54
+ }
55
+ });
56
+ return { reports, numbers, skipped };
57
+ }
58
+ /**
59
+ * Sends the reports by the run, one call each in order, and logs each outcome. Never throws: a refusal or a
60
+ * network error is logged and the next entry is sent; after a 429 (the run's count is reached) or a board with
61
+ * no report route, none further.
62
+ */
63
+ export async function sendReports(board, runId, read, say) {
64
+ for (const line of read.skipped)
65
+ say(line);
66
+ if (!read.reports.length)
67
+ return;
68
+ if (!runId) {
69
+ say(`${NO_REPORTS}: ${read.reports.length} report(s) not sent`);
70
+ return;
71
+ }
72
+ for (const [i, r] of read.reports.entries()) {
73
+ const title = terminalText(r.title.trim());
74
+ try {
75
+ const answer = await board.reportFromRun(runId, r);
76
+ say(answer.known ? `already known: ${title}` : `reported ${terminalText(answer.ticket)}: ${title}`);
77
+ }
78
+ catch (err) {
79
+ const message = terminalText(err instanceof Error ? err.message : String(err));
80
+ const status = err instanceof BoardError ? err.status : 0;
81
+ if (status === 404 && message === NO_REPORTS) {
82
+ say(`${NO_REPORTS}: no report is sent`);
83
+ return;
84
+ }
85
+ say(`report ${read.numbers[i] ?? i + 1} not sent (${title}): ${message}`);
86
+ if (status === 429) {
87
+ if (i + 1 < read.reports.length)
88
+ say(`the rest (${read.reports.length - i - 1}) not sent`);
89
+ return;
90
+ }
91
+ }
92
+ }
93
+ }
package/dist/review.js CHANGED
@@ -6,6 +6,7 @@
6
6
  // read like result.json, checked field by field, and cut to the board's
7
7
  // limits with the worker's own mark before anything is sent.
8
8
  import { lstatSync, readFileSync } from "node:fs";
9
+ import { checkReports } from "./reports.js";
9
10
  export const REVIEW_MAX = 256 * 1024;
10
11
  /** The board's limits on a review (R5's route): what is over them is cut, never refused. */
11
12
  export const LIMITS = {
@@ -140,7 +141,8 @@ export function checkReview(data) {
140
141
  proof: typeof f.proof === "string" ? f.proof : "",
141
142
  });
142
143
  }
143
- return { ok: true, review: { verdict: verdict, summary: data.summary, ...(risk ? { risk } : {}), findings } };
144
+ const reports = "reports" in data ? { reports: checkReports(data.reports) } : {};
145
+ return { ok: true, review: { verdict: verdict, summary: data.summary, ...(risk ? { risk } : {}), findings, ...reports } };
144
146
  }
145
147
  /** The title of the finding the worker adds for a failing `test` command (D7: a red gate blocks). */
146
148
  export const TEST_FINDING = "The test command fails";
package/dist/service.js CHANGED
@@ -36,6 +36,14 @@ export class BoardUnreachable extends BoardError {
36
36
  this.name = "BoardUnreachable";
37
37
  }
38
38
  }
39
+ /** What a client says when the board has no report route (a board from before R4). */
40
+ export const NO_REPORTS = "this board does not take reports yet: it needs an update";
41
+ /** What a person's session says when the board takes reports by run_id only (R4 deployed, R5 not yet). */
42
+ export const NO_SESSION_REPORTS = "this board does not take reports from a session yet: it needs an update";
43
+ /** A 404 of the route itself (PocketBase's own answer), not the board's "not found or not yours". */
44
+ function noRoute(err) {
45
+ return err instanceof BoardError && err.status === 404 && !/not yours/.test(err.message);
46
+ }
39
47
  const SUMMARY_FIELDS = "id,title,status,priority,spec_path,branch,pr_url,claimed_until,attempts,block_kind,block_text";
40
48
  function toBoardError(err, url, action) {
41
49
  if (err instanceof BoardError)
@@ -208,6 +216,35 @@ export class TicketService {
208
216
  release(ticketId, reason, usage) {
209
217
  return this.post("release", { ticket_id: ticketId, reason, ...(usage ? { usage } : {}) });
210
218
  }
219
+ /** Reports a defect outside the ticket this session holds (R5): the MCP tool and `board report`. */
220
+ async reportFinding(ticketId, report) {
221
+ try {
222
+ return await this.post("report", { ticket_id: ticketId, ...fields(report) });
223
+ }
224
+ catch (err) {
225
+ if (err instanceof BoardError && err.status === 400 && /^run_id is required/.test(err.message)) {
226
+ throw new BoardError(NO_SESSION_REPORTS, 400);
227
+ }
228
+ if (noRoute(err))
229
+ throw new BoardError(NO_REPORTS, 404);
230
+ throw err;
231
+ }
232
+ }
233
+ /** Reports a defect outside the run's ticket by the run (the worker, R5). */
234
+ async reportFromRun(runId, report) {
235
+ try {
236
+ return await this.post("report", { run_id: runId, ...fields(report) });
237
+ }
238
+ catch (err) {
239
+ if (noRoute(err))
240
+ throw new BoardError(NO_REPORTS, 404);
241
+ throw err;
242
+ }
243
+ }
244
+ }
245
+ /** Only these three go to the board, whatever else the caller's object has. */
246
+ function fields(r) {
247
+ return { title: r.title, body: r.body, fingerprint: r.fingerprint };
211
248
  }
212
249
  export class BoardAdmin {
213
250
  url;
package/dist/worker.js CHANGED
@@ -36,9 +36,11 @@ import { reviewPrompt } from "./engines.js";
36
36
  import { badPath, boardNumbers, ciGates, diffHunks, findingMarkdown, fitFindings, fitGate, ghFailure, githubBody, githubPr, inHunks, LIMITS, newRefs, readReview, reviewTicketFile, rulesFile, tail, tailWithin, testOutputWithin, TEST_FINDING, withTestFinding, } from "./review.js";
37
37
  import { BoardError, BoardPaused, } from "./service.js";
38
38
  import { hasWork, isUnreachable, label, sleep, takeLock, untilAnswered } from "./watch.js";
39
+ import { checkReports, sendReports } from "./reports.js";
39
40
  const FAILURE_STOP = 3;
40
41
  const RUN_DIR = ".mergeline-run";
41
- const RESULT_MAX = 64 * 1024;
42
+ /** As review.json's (R5): three report bodies of 20,000 characters fit. */
43
+ const RESULT_MAX = 256 * 1024;
42
44
  const POLL_MS = 5000;
43
45
  const NOTE_GAP_MS = 30_000;
44
46
  const NOTE_CHARS = 500;
@@ -82,7 +84,7 @@ export function readResult(file) {
82
84
  if (!st.isFile())
83
85
  return { outcome: "none", why: "result.json is not a regular file" };
84
86
  if (st.size > RESULT_MAX)
85
- return { outcome: "none", why: "result.json is over 64 KB" };
87
+ return { outcome: "none", why: "result.json is over 256 KB" };
86
88
  let data;
87
89
  try {
88
90
  data = JSON.parse(readFileSync(file, "utf8"));
@@ -104,11 +106,13 @@ export function readResult(file) {
104
106
  if (typeof text !== "string" || !text.trim())
105
107
  return { outcome: "none", why: `"${field[o]}" must be a non-empty string` };
106
108
  const value = cut(text.trim(), max[o]);
109
+ // The optional reports (R5): what is wrong with them is skipped, never the result.
110
+ const reports = "reports" in r ? { reports: checkReports(r.reports) } : {};
107
111
  if (o === "done")
108
- return { outcome: "done", summary: value };
112
+ return { outcome: "done", summary: value, ...reports };
109
113
  if (o === "ask")
110
- return { outcome: "ask", question: value };
111
- return { outcome: "release", reason: value };
114
+ return { outcome: "ask", question: value, ...reports };
115
+ return { outcome: "release", reason: value, ...reports };
112
116
  }
113
117
  /** A subject's most characters, the ticket's label included. */
114
118
  const SUBJECT_MAX = 72;
@@ -387,12 +391,26 @@ export async function work(opts) {
387
391
  let engineChild = null;
388
392
  /** The signal that stopped the worker while an engine ran: that run is released. */
389
393
  let engineStopped = null;
394
+ /** A builder's engine runs: a run it stops has its work pushed (R6.3). */
395
+ let builderEngine = false;
396
+ /** The steps after a stopped builder run (R6.3), while they run; and their push: a second signal kills it. */
397
+ let stopSteps = false;
398
+ let stopPush = null;
390
399
  const onSignal = (signal) => {
391
400
  if (state.stopped)
392
401
  hard.stopped = true;
393
402
  state.stopped = true;
394
403
  stopSignal ??= signal;
395
- log(`${signal}: stopping${engineChild ? " the engine" : " after the current step"}`);
404
+ if (hard.stopped && stopSteps) {
405
+ log(`${signal}: stopping at once; nothing more is pushed`);
406
+ if (stopPush)
407
+ killGroup(stopPush);
408
+ return;
409
+ }
410
+ const what = engineChild
411
+ ? ` the engine${builderEngine ? "; its work will be pushed (again to stop at once)" : ""}`
412
+ : " after the current step";
413
+ log(`${signal}: stopping${what}`);
396
414
  if (engineChild) {
397
415
  engineStopped ??= signal;
398
416
  killGroup(engineChild);
@@ -503,9 +521,10 @@ export async function work(opts) {
503
521
  * as it was.
504
522
  */
505
523
  const gitEnv = withoutBoard(process.env);
506
- const git = async (cwd, ...args) => {
524
+ const git = async (cwd, ...args) => gitTracked(cwd, undefined, ...args);
525
+ const gitTracked = async (cwd, track, ...args) => {
507
526
  checkConfig();
508
- return exec("git", ["-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false", ...args], { cwd, env: gitEnv, group: true });
527
+ return exec("git", ["-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false", ...args], { cwd, env: gitEnv, group: true, track });
509
528
  };
510
529
  const removeWorktree = async (path, branch) => {
511
530
  await git(repo, "worktree", "remove", "--force", path);
@@ -546,7 +565,7 @@ export async function work(opts) {
546
565
  return { error: `could not keep the unpushed commits on ${ticket.branch}: ${last}` };
547
566
  };
548
567
  /** One claimed ticket, from its spec to its cleanup. Returns whether it was a failed run. */
549
- const runTicket = async (n, ticket, resumed) => {
568
+ const runTicket = async (n, ticket, runId, resumed) => {
550
569
  const lbl = label(ticket);
551
570
  const say = (line) => log(`run ${n}: ${lbl}: ${line}`);
552
571
  log(`run ${n}: ${resumed ? "resumed" : "claimed"} ${lbl} (${ticket.branch})`);
@@ -686,7 +705,9 @@ export async function work(opts) {
686
705
  const runDir = join(path, RUN_DIR);
687
706
  mkdirSync(runDir, { recursive: true });
688
707
  writeFileSync(join(runDir, ".gitignore"), "*\n");
689
- writeFileSync(join(runDir, "ticket.md"), ticketFile(ticket, lbl, onOrigin, sha, spec.stdout));
708
+ // An earlier run stopped before its result left its work on the branch (R6.3): told from the branch alone.
709
+ const wipTip = onOrigin && (await git(repo, "log", "-1", "--format=%s", `origin/${ticket.branch}`)).stdout.startsWith("WIP: ");
710
+ writeFileSync(join(runDir, "ticket.md"), ticketFile(ticket, lbl, onOrigin, sha, spec.stdout, wipTip));
690
711
  // The engine.
691
712
  const originUrl = (await git(repo, "remote", "get-url", "origin")).stdout.trim();
692
713
  const deadline = Date.now() + opts.timeoutSec * 1000;
@@ -758,6 +779,7 @@ export async function work(opts) {
758
779
  track: (c) => {
759
780
  current = c;
760
781
  engineChild = c;
782
+ builderEngine = c !== null;
761
783
  },
762
784
  }).finally(() => clearInterval(poll));
763
785
  while (polling)
@@ -768,16 +790,118 @@ export async function work(opts) {
768
790
  await readFolder(true);
769
791
  held();
770
792
  usage = engine.usage(ran.stdout);
771
- if (engineStopped)
772
- return await release(`board watch was stopped (${engineStopped})`);
793
+ if (engineStopped) {
794
+ try {
795
+ checkConfig();
796
+ }
797
+ catch (err) {
798
+ // A changed git config: released as before R6.3, and nothing more of git (the finally stops the worker).
799
+ if (err instanceof ConfigChanged)
800
+ return await release(`board watch was stopped (${engineStopped})`);
801
+ throw err;
802
+ }
803
+ }
773
804
  checkConfig();
805
+ /**
806
+ * A run the worker stopped, or that ended without a result (R6.3): what the engine left is committed as WIP,
807
+ * pushed once to the ticket's branch, and the release says what happened, where the work is and what is next.
808
+ */
809
+ const stopped = async (what, why) => {
810
+ stopSteps = true;
811
+ try {
812
+ return await stoppedSteps(what, why);
813
+ }
814
+ finally {
815
+ stopSteps = false;
816
+ }
817
+ };
818
+ const stoppedSteps = async (what, why) => {
819
+ const problems = [];
820
+ let wip = 0;
821
+ const status = await git(path, "status", "--porcelain");
822
+ const dirty = status.code === 0 && status.stdout.trim() !== "";
823
+ if (status.code !== 0)
824
+ problems.push(`could not read the worktree's status (${oneLine(status.stderr)})`);
825
+ const count = async () => Number((await git(path, "rev-list", "--count", `${base}..HEAD`)).stdout.trim()) || 0;
826
+ if (!hard.stopped && (dirty || (await count()) > 0)) {
827
+ const added = dirty ? await git(path, "add", "-A") : null;
828
+ const body = [
829
+ why,
830
+ "The tests were not run.",
831
+ dirty ? `Committed by the worker: ${engine.name} left this uncommitted.` : "Committed by the worker, empty: it marks where the run stopped.",
832
+ ].join("\n\n");
833
+ const c = added && added.code !== 0 ? added : await git(path, "commit", ...(dirty ? [] : ["--allow-empty"]), "-m", `WIP: ${lbl}: stopped before a result`, "-m", body);
834
+ if (c.code === 0)
835
+ wip = 1;
836
+ else
837
+ problems.push(`could not commit what the engine left (${oneLine(c.stderr || c.stdout)})`);
838
+ }
839
+ const k = await count();
840
+ let where;
841
+ if (!k) {
842
+ where = dirty ? "Its uncommitted changes are not pushed." : "It left no changes.";
843
+ }
844
+ else {
845
+ let failure = "";
846
+ if (hard.stopped)
847
+ failure = "a second signal stopped the worker before the push";
848
+ else {
849
+ held();
850
+ await beat();
851
+ held();
852
+ const pushed = await gitTracked(path, (c) => (stopPush = c), "push", originUrl, `HEAD:refs/heads/${ticket.branch}`);
853
+ if (pushed.code === 0)
854
+ pushedOk = true;
855
+ else
856
+ failure = hard.stopped ? "a second signal stopped the push" : oneLine(pushed.stderr || pushed.stdout) || `exit ${pushed.code}`;
857
+ }
858
+ if (pushedOk) {
859
+ // The open PR of a rework run, told apart with gh pr view; a call that fails leaves the part out.
860
+ let pr = null;
861
+ if (!hard.stopped) {
862
+ checkConfig();
863
+ const view = await exec("gh", ["pr", "view", ticket.branch, "--json", "url,state"], { cwd: repo, env: withoutBoard(process.env), group: true });
864
+ if (view.code === 0) {
865
+ try {
866
+ const state = JSON.parse(view.stdout).state;
867
+ pr = state === "OPEN" ? "; its PR is still open, with unfinished work on it." : "; no PR.";
868
+ }
869
+ catch {
870
+ // not gh's JSON: left out
871
+ }
872
+ }
873
+ else if (/no (open )?pull requests? found/i.test(view.stderr)) {
874
+ pr = "; no PR.";
875
+ }
876
+ }
877
+ where = `Its work is pushed to ${ticket.branch} (${k} commit(s), ${wip} of them the worker's WIP commit)${pr ?? "."} The next run goes on from it.`;
878
+ }
879
+ else {
880
+ where = `Its work is not pushed (${failure}); it is kept on the worker's machine under refs/mergeline/kept/${ticket.id}/.`;
881
+ }
882
+ }
883
+ const problem = problems.length ? ` The worker ${problems.join("; ")}.` : "";
884
+ return await release(`${/[.!?]$/.test(what) ? what : `${what}.`}${problem} ${where}`);
885
+ };
886
+ if (engineStopped) {
887
+ const signal = engineStopped;
888
+ return await stopped(`board watch was stopped (${signal})`, `The worker was stopped (${signal}) while the engine ran, and stopped the engine.`);
889
+ }
774
890
  let result = ran.killed
775
- ? { outcome: "none", why: `the engine ran past the timeout (${opts.timeoutSec}s) and was stopped` }
891
+ ? { outcome: "none", why: `the engine ran past the time limit (${limitText(opts.timeoutSec)}) and was stopped` }
776
892
  : readResult(join(runDir, "result.json"));
777
893
  if (result.outcome === "none") {
778
894
  say(`no result from the engine: ${result.why}`);
895
+ if (ran.killed)
896
+ return await stopped(result.why, `The worker stopped the engine at the time limit (${limitText(opts.timeoutSec)}).`);
779
897
  const error = engine.error(ran.stdout);
780
- return await release(`the engine ended without a result (exit ${ran.code})${error ? `: ${error}` : ""}`);
898
+ const what = `the engine ended without a result (exit ${ran.code})${error ? `: ${error}` : ""}`;
899
+ return await stopped(what, `The engine ended without a result (exit ${ran.code}): ${result.why}.`);
900
+ }
901
+ // The engine's reports (R5), while the run is still open: before submit, ask or release, whatever the outcome.
902
+ if (result.reports) {
903
+ held();
904
+ await sendReports(board, runId, result.reports, say);
781
905
  }
782
906
  if (result.outcome === "release")
783
907
  return await release(result.reason);
@@ -1120,6 +1244,11 @@ export async function work(opts) {
1120
1244
  return await release(`the engine ended without a review (exit ${ran.code}): ${read.why}${error ? `; ${error}` : ""}`);
1121
1245
  }
1122
1246
  const result = read.review;
1247
+ // The engine's reports (R5), before the review is sent, whatever its verdict.
1248
+ if (result.reports) {
1249
+ held();
1250
+ await sendReports(board, runId, result.reports, say);
1251
+ }
1123
1252
  // The gates: the repository's test command, then the PR's checks.
1124
1253
  const gates = [];
1125
1254
  let findings = result.findings;
@@ -1420,7 +1549,7 @@ export async function work(opts) {
1420
1549
  // The run's kind says the mode: a review run is reviewed, a rework run is worked as an implement run.
1421
1550
  const outcome = claimed.run?.kind === "review"
1422
1551
  ? await runReview(runs, claimed.ticket, claimed.run.id, claimed.review, !!claimed.resumed)
1423
- : await runTicket(runs, claimed.ticket, !!claimed.resumed);
1552
+ : await runTicket(runs, claimed.ticket, claimed.run?.id, !!claimed.resumed);
1424
1553
  if (configStop) {
1425
1554
  const { file, what, path, branch, id, pushed, review } = configStop;
1426
1555
  log(`stopping: ${file} changed while run ${runs} was going on (${what}), so the worker ran no more git for it.`);
@@ -1474,6 +1603,8 @@ function killGroup(child) {
1474
1603
  kill("SIGTERM");
1475
1604
  setTimeout(() => kill("SIGKILL"), KILL_GRACE_MS).unref();
1476
1605
  }
1606
+ /** A time limit as the worker names it (R6.3): whole minutes, else seconds. */
1607
+ export const limitText = (sec) => (sec % 60 === 0 ? `${sec / 60} min` : `${sec} s`);
1477
1608
  const oneLine = (s) => clip(s.replace(/\s+/g, " ").trim(), 500);
1478
1609
  /** A question for a run that could not push, after what the engine itself asked (if it asked). */
1479
1610
  export function withBefore(result, what, lost) {
@@ -1528,7 +1659,9 @@ async function repoTest(git, repo) {
1528
1659
  return null;
1529
1660
  }
1530
1661
  }
1531
- function ticketFile(t, lbl, onOrigin, sha, spec) {
1662
+ /** The line under Branch: when the branch's tip is an earlier run's WIP commit (R6.3). */
1663
+ export const WIP_LINE = "The branch holds an earlier run's work that was stopped before it finished: not tested, not reviewed. Read it (git log origin/main..HEAD) and go on from it; do not start over.";
1664
+ function ticketFile(t, lbl, onOrigin, sha, spec, wipTip = false) {
1532
1665
  const notes = t.notes ?? [];
1533
1666
  const round = 1 + notes.filter((n) => n.kind === "review").length;
1534
1667
  return [
@@ -1536,6 +1669,7 @@ function ticketFile(t, lbl, onOrigin, sha, spec) {
1536
1669
  "",
1537
1670
  `Ticket: ${lbl} (${t.id})`,
1538
1671
  `Branch: ${t.branch}, ${onOrigin ? `from origin/${t.branch}` : "new, from origin/main"}`,
1672
+ ...(wipTip ? [WIP_LINE] : []),
1539
1673
  `Review round: ${round}`,
1540
1674
  `Spec: ${t.spec_path}/spec.md at ${sha}`,
1541
1675
  "",
package/engine/prompt.md CHANGED
@@ -26,6 +26,8 @@ on the ticket's branch. Stay in it: do not read or write outside it.
26
26
  `package.json` lists dependencies: with none, there is nothing to install.
27
27
  - A lockfile the run did not mean to add is not part of the change: do not
28
28
  leave one behind.
29
+ - A defect you see outside this ticket is reported, not fixed: put it in
30
+ `reports` in the result file (below). Then go on with your ticket.
29
31
 
30
32
  ## Steps
31
33
 
@@ -45,7 +47,7 @@ on the ticket's branch. Stay in it: do not read or write outside it.
45
47
  check:
46
48
  - Run it again. If it passes now, it failed by chance. Leave it, and
47
49
  name it in the summary: the check, and that it passed when run
48
- again.
50
+ again. Put it in `reports` too (below).
49
51
  - If it fails again, end with `ask`, naming the check and the end of
50
52
  its output. Do not change code outside the ticket to make it pass.
51
53
  5. Commit with `git commit -m "<message>"`. To bring the branch up to date
@@ -77,4 +79,20 @@ End by writing `.mergeline-run/result.json`, one of:
77
79
  - `release` when something in your environment stops you (a command you
78
80
  need is denied, a tool is missing), with what and why.
79
81
 
82
+ Any of the three may also carry `"reports"`: defects you saw outside this
83
+ ticket, which you did not fix. Leave it out when there are none.
84
+
85
+ ```json
86
+ "reports": [{"title": "<one line, 3 to 120 characters>", "body": "<what you saw, where, and how to see it again>", "fingerprint": "<path: what is wrong>"}]
87
+ ```
88
+
89
+ - A person reads each one in the board's Inbox; no agent does, and you
90
+ will not hear back.
91
+ - `fingerprint` is a short stable name of the defect, the same whoever
92
+ finds it: the file's path and what is wrong, for example
93
+ `scripts/smoke.ts: port check is flaky`. One reported before is not
94
+ added again.
95
+ - At most 3; put the rest in the summary. A report that is not sent never
96
+ changes your outcome.
97
+
80
98
  Then stop.
package/engine/review.md CHANGED
@@ -53,9 +53,11 @@ A finding is `blocking` only when both hold:
53
53
  shows the gap.
54
54
 
55
55
  Anything else is `non_blocking`: a risk, a smell, a better way, a problem
56
- that was there before this PR. A blocking finding with no proof is stored
57
- as non-blocking. Nitpicks are not findings: style with no rule behind it is
58
- not reported at all. A review with nothing to say is a good review.
56
+ that was there before this PR in code the PR touches. A defect in code the
57
+ PR does not touch is not a finding of this review: put it in `reports`
58
+ (below). A blocking finding with no proof is stored as non-blocking.
59
+ Nitpicks are not findings: style with no rule behind it is not reported at
60
+ all. A review with nothing to say is a good review.
59
61
 
60
62
  ## Never
61
63
 
@@ -94,4 +96,19 @@ End by writing `.mergeline-run/review.json`, one JSON object:
94
96
  when only non-blocking ones are open; `approve` when none is.
95
97
  - `findings` is `[]` when there are none.
96
98
 
99
+ `review.json` may also carry `"reports"`: defects you saw in code the PR
100
+ does not touch. Leave it out when there are none.
101
+
102
+ ```json
103
+ "reports": [{"title": "<one line, 3 to 120 characters>", "body": "<what you saw, where, and how to see it again>", "fingerprint": "<path: what is wrong>"}]
104
+ ```
105
+
106
+ - A person reads each one in the board's Inbox; no agent does, and you
107
+ will not hear back. A report is not part of the review.
108
+ - `fingerprint` is a short stable name of the defect, the same whoever
109
+ finds it: the file's path and what is wrong, for example
110
+ `scripts/smoke.ts: port check is flaky`. One reported before is not
111
+ added again.
112
+ - At most 3. A report that is not sent never changes the review.
113
+
97
114
  Then stop.
@@ -15,6 +15,8 @@
15
15
  "Bash(board record-spec *)",
16
16
  "Bash(board ask)",
17
17
  "Bash(board ask *)",
18
+ "Bash(board report)",
19
+ "Bash(board report *)",
18
20
  "Bash(board submit)",
19
21
  "Bash(board submit *)",
20
22
  "Bash(board release)",
@@ -35,6 +37,8 @@
35
37
  "Bash(npx -y {{package}} record-spec *)",
36
38
  "Bash(npx -y {{package}} ask)",
37
39
  "Bash(npx -y {{package}} ask *)",
40
+ "Bash(npx -y {{package}} report)",
41
+ "Bash(npx -y {{package}} report *)",
38
42
  "Bash(npx -y {{package}} submit)",
39
43
  "Bash(npx -y {{package}} submit *)",
40
44
  "Bash(npx -y {{package}} release)",
package/kit/done.md CHANGED
@@ -3,9 +3,14 @@ Finish the ticket you are working on. Run everything inside its worktree
3
3
  the `board` command of the same name (`submit_for_review` is `board submit`).
4
4
 
5
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.
6
+ `npm run lint`; use what the project has), and fix what this ticket's
7
+ change broke. A check that fails in code the change does not touch
8
+ (the files in `git diff origin/main...HEAD` and the code that uses
9
+ them) is not this ticket's to fix: run it again. If it passes now,
10
+ report it with `report_finding` and name it in the summary. If it
11
+ fails again, call `log_event` kind `warn` with what fails, then
12
+ `ask_human`, and stop. Do not change code outside the ticket to make
13
+ it pass.
9
14
  2. Call `heartbeat` before you push. If it says another session holds the
10
15
  ticket, stop at once: do not commit, push or open a PR. If it says to
11
16
  claim again, stop and claim.
package/kit/rules.md CHANGED
@@ -3,10 +3,10 @@
3
3
  You work tickets from the Mergeline board. Its tools come two ways; use
4
4
  whichever your environment has: the `board` MCP tools (`claim`, `heartbeat`,
5
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
6
+ `list_mine`, `report_finding`), or the same calls as shell commands
7
+ (`board claim`, `board heartbeat <ticket> [note]`, `board log`,
8
+ `board record-spec`, `board ask`, `board submit`, `board release`,
9
+ `board list`, `board report`; run `board help`). Start a ticket with the pick instructions and finish it with
10
10
  the done instructions: `/pick` and `/done` in Claude Code,
11
11
  `/prompts:pick` and `/prompts:done` in Codex.
12
12
 
@@ -20,6 +20,8 @@ the done instructions: `/pick` and `/done` in Claude Code,
20
20
  `notes`. Nothing else: not a message in the chat, not a guess.
21
21
  - When unsure, ask with `ask_human` (`board ask`); a paused ticket is
22
22
  cheaper than a wrong PR.
23
+ - A defect outside your ticket is reported, not fixed: `report_finding`
24
+ (`board report`). Then go on with your ticket.
23
25
  - One ticket at a time. After asking, submitting or releasing, stop working
24
26
  on that ticket.
25
27
  - Call `heartbeat` after every meaningful step. If a board tool says to claim
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mergeline/agent",
3
- "version": "0.7.4",
3
+ "version": "0.8.1",
4
4
  "description": "The agent's side of a Mergeline board: an MCP server and the `board` CLI. Works with any agent tool that runs MCP servers or shell commands.",
5
5
  "license": "MIT",
6
6
  "author": "frontender-ua",