@mergeline/agent 0.4.1 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -28,8 +28,11 @@ a newer kit, the claim's answer says to run
28
28
  `npx -y @mergeline/agent@latest init --claude` again. `login` checks the key with the
29
29
  board and saves it in `~/.config/mergeline/credentials.json` (readable only
30
30
  by you, outside any repository), per board and agent: `fe-1` on two boards
31
- is two saved keys. In a repository with `.mergeline.json`, `--url` can be
32
- left out. Several agents can be saved and work from the same repository:
31
+ is two saved keys. `login` takes the address typed with `--url` (or
32
+ `BOARD_URL`), never from `.mergeline.json`: in a repository someone else
33
+ controls (a clone, a fork, a PR branch) the key would go wherever its file
34
+ says, so without `--url` it refuses and prints the command with the file's
35
+ address for you to check. Several agents can be saved and work from the same repository:
33
36
  `board start qa-1` in another terminal. `board agents` lists them with their
34
37
  boards, `board logout <name>` forgets one (`--url <board>` when the name is
35
38
  saved for several). `board start <name> -- codex` starts another tool the
@@ -37,7 +40,12 @@ same way; `--agent <name>` makes any command act as a saved agent. The board
37
40
  in use is `BOARD_URL` when it is set, else the repository's
38
41
  `.mergeline.json`.
39
42
 
40
- Environment variables still work and win over saved keys:
43
+ Environment variables still work and win over saved keys. A key in
44
+ `BOARD_AGENT_KEY` (or `BOARD_AGENT_EMAIL` and `BOARD_AGENT_PASSWORD`) is used
45
+ with `BOARD_URL`: in a repository whose `.mergeline.json` names the board and
46
+ `BOARD_URL` is not set, every command and the MCP server refuse before any
47
+ request and say what to do, so a key exported in your shell never goes to
48
+ the address a repository names. `board start` and `--agent` set both.
41
49
 
42
50
  ```sh
43
51
  export BOARD_URL=https://board.example.com
@@ -107,7 +115,11 @@ stalls the agent at its first push.
107
115
 
108
116
  It stops when the queue is empty (unless `--follow`), after `--max-runs`
109
117
  (default 10), after 2 runs that changed nothing in the queue, or after 3
110
- failed runs in a row. One watcher per agent and machine.
118
+ failed runs in a row. One watcher per agent and machine. When the runs that
119
+ changed nothing all failed, the stop says so and points at the agent's
120
+ output; with `--usage-from claude-json`, a run Claude Code reports as failed
121
+ (`"is_error": true`, such as an expired login) is logged as `the agent
122
+ failed: <its message>`.
111
123
 
112
124
  A board that is paused (asleep until a person opens it; it answers HTTP 503
113
125
  with `{"code": "board_paused"}`) is not a failure: tools and commands say
package/dist/cli.js CHANGED
@@ -5,7 +5,8 @@
5
5
  // board <command> [args] the same calls as the MCP tools, one per run
6
6
  //
7
7
  // Connection: BOARD_URL and BOARD_AGENT_KEY (or BOARD_AGENT_EMAIL and
8
- // BOARD_AGENT_PASSWORD), as for the MCP server; without them, a key saved by
8
+ // BOARD_AGENT_PASSWORD), as for the MCP server (a key from the environment
9
+ // is never sent to the board a .mergeline.json names: pb.ts); without them, a key saved by
9
10
  // `board login <name>` (credentials.ts) for the board in use (BOARD_URL, or
10
11
  // the repository's .mergeline.json written by `board init --url`: repo.ts),
11
12
  // picked with --agent <name> or BOARD_AGENT, or the only one saved. `board start <name>` runs the agent's
@@ -43,11 +44,12 @@ Usage:
43
44
  so the commands below pick that board in this repository.
44
45
  Never overwrites what it did not write. --no-npx: MCP
45
46
  configs run "board mcp" (package installed globally).
46
- board login <name> [--url <board>] --key <key>
47
+ board login <name> --url <board> --key <key>
47
48
  check the key with the board and save it on this machine
48
49
  (~/.config/mergeline, outside any repository), per board and
49
- agent; --url defaults to the repository's board. Key "-"
50
- reads it from stdin. Once per agent and machine
50
+ agent; --url is required (or BOARD_URL), never taken from
51
+ the repository. Key "-" reads it from stdin. Once per agent
52
+ and machine
51
53
  board start [<name>] [-- <command...>] start the agent's tool (default: claude) with that agent's
52
54
  board address and key; then /pick. Name optional when
53
55
  only one agent is saved for the board in use
@@ -80,7 +82,8 @@ A text argument of "-" is read from stdin (for a multi-line plan).
80
82
 
81
83
  Environment:
82
84
  BOARD_URL the board (default: the repository's .mergeline.json, else http://127.0.0.1:8090)
83
- BOARD_AGENT_KEY the agent key shown when a human added the agent
85
+ BOARD_AGENT_KEY the agent key shown when a human added the agent; used only with BOARD_URL
86
+ (never sent to a board a repository's .mergeline.json names)
84
87
  BOARD_AGENT a saved agent's name, used when BOARD_AGENT_KEY is not set
85
88
  BOARD_CONFIG_DIR where board login saves keys (default ~/.config/mergeline)
86
89
  BOARD_SESSION optional session id; otherwise claim saves one in BOARD_STATE_DIR
@@ -172,8 +175,7 @@ function runInit(args) {
172
175
  out.write(result.codexConfig + "\n");
173
176
  }
174
177
  out.write("\nThen, once per agent and machine, save its key (shown when the agent was added on the board):\n" +
175
- ` board login <agent name> ${result.board ? "" : "--url <board address> "}--key <key>` +
176
- (result.board ? ` (the board: ${result.board}, from ${REPO_FILE})` : "") + "\n" +
178
+ ` board login <agent name> --url ${result.board ?? "<board address>"} --key <key>\n` +
177
179
  "and start each session with: board start <agent name>" + (args.includes("--codex") ? " -- codex" : "") + "\n" +
178
180
  "Commit AGENTS.md" + (args.includes("--claude") ? ", CLAUDE.md, .claude/, .mcp.json" : "") + `, ${REPO_FILE}` +
179
181
  " so every checkout has the kit; the key is not in any of them.\n");
@@ -212,16 +214,24 @@ async function runLogin(args) {
212
214
  if (!name || name.startsWith("-"))
213
215
  throw new UsageError("board login needs the agent's name: board login <name> --url <board> --key <key>");
214
216
  const given = option(args, "--url");
217
+ // The address is typed (or in BOARD_URL), never taken from a .mergeline.json:
218
+ // the repository may be someone else's, and the key would go where it says.
215
219
  let url;
220
+ let board = null;
216
221
  try {
217
- url = given === undefined ? boardInContext()?.url : normalizeBoardUrl(given);
222
+ board = given === undefined ? boardInContext() : null;
223
+ url = given !== undefined ? normalizeBoardUrl(given) : board?.from === "BOARD_URL" ? board.url : undefined;
218
224
  }
219
225
  catch (err) {
220
226
  throw new UsageError(err instanceof Error ? err.message : String(err));
221
227
  }
222
228
  let key = option(args, "--key");
229
+ if (!url && board) {
230
+ throw new BoardError(`board login needs the board's address typed; ${board.from} names ${board.url}. If that is your board, run: ` +
231
+ `board login ${name} --url ${board.url} --key <key>`);
232
+ }
223
233
  if (!url)
224
- throw new UsageError(`--url is required: the board's address, as shown on the board (or run it in a repository with ${REPO_FILE}: board init --url <board>)`);
234
+ throw new UsageError("--url is required: the board's address, as shown on the board");
225
235
  if (!key)
226
236
  throw new UsageError("--key is required: the key shown when the agent was added (or - to read it from stdin)");
227
237
  if (key === "-")
package/dist/init.js CHANGED
@@ -22,9 +22,13 @@
22
22
  // ~/.codex/prompts) and prints the MCP snippet for ~/.codex/config.toml,
23
23
  // which init does not edit. The snippet names the agent; its key stays in
24
24
  // the store `board login` writes, not in config.toml.
25
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
25
+ // - Init writes only real files inside the repository: when a file it would
26
+ // touch, or a folder between --dir and it, is a symbolic link (a cloned
27
+ // repository's CLAUDE.md linking to ~/.zshrc), it writes nothing and fails
28
+ // (realFilesOnly). --dir itself may be reached through a link.
29
+ import { existsSync, lstatSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
26
30
  import { homedir } from "node:os";
27
- import { dirname, join, relative } from "node:path";
31
+ import { dirname, join, relative, sep } from "node:path";
28
32
  import { fileURLToPath } from "node:url";
29
33
  import { readRepoFile, REPO_FILE } from "./repo.js";
30
34
  const KIT = fileURLToPath(new URL("../kit/", import.meta.url));
@@ -77,7 +81,40 @@ export function projectCommands(dir) {
77
81
  commands.push(run(name));
78
82
  return { manager, commands: [...new Set(commands)] };
79
83
  }
84
+ /** The files init touches under dir, relative to it. */
85
+ function repoPaths(opts) {
86
+ const paths = [REPO_FILE, "AGENTS.md"];
87
+ if (opts.claude) {
88
+ paths.push("CLAUDE.md", join(".claude", "commands", "pick.md"), join(".claude", "commands", "done.md"), join(".claude", "settings.json"), ".mcp.json");
89
+ }
90
+ return paths;
91
+ }
92
+ /**
93
+ * Throws, before anything is written, when one of the files init touches, or
94
+ * a folder between opts.dir and it, is a symbolic link: writing through it
95
+ * would change a file outside the repository.
96
+ */
97
+ function realFilesOnly(opts) {
98
+ for (const path of repoPaths(opts)) {
99
+ const parts = path.split(sep);
100
+ for (let i = 1; i <= parts.length; i++) {
101
+ const rel = parts.slice(0, i).join(sep);
102
+ let link = false;
103
+ try {
104
+ link = lstatSync(join(opts.dir, rel)).isSymbolicLink();
105
+ }
106
+ catch {
107
+ break; // missing: init creates it, and everything below it, as real files and folders
108
+ }
109
+ if (link) {
110
+ throw new Error(`${rel} is a symbolic link; board init writes only real files inside the repository. ` +
111
+ `Replace it with a ${i < parts.length ? "folder" : "file"} and run init again.`);
112
+ }
113
+ }
114
+ }
115
+ }
80
116
  export function init(opts) {
117
+ realFilesOnly(opts);
81
118
  const actions = [];
82
119
  const write = (path, content, kind) => {
83
120
  if (!opts.dryRun && (kind === "create" || kind === "update")) {
package/dist/mcp.js CHANGED
@@ -1,7 +1,8 @@
1
1
  // MCP server for a Mergeline board (stdio). One process = one agent session.
2
2
  // Started by `board mcp` (cli.ts) or `node dist/index.js`.
3
3
  // Credentials come from BOARD_AGENT_KEY (or BOARD_AGENT_EMAIL / BOARD_AGENT_PASSWORD); BOARD_URL
4
- // defaults to http://127.0.0.1:8090. All board access goes through
4
+ // defaults to http://127.0.0.1:8090 (pb.ts: a key from the environment is used
5
+ // only with BOARD_URL). All board access goes through
5
6
  // TicketService.
6
7
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
7
8
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
@@ -122,8 +123,13 @@ export async function runMcpServer() {
122
123
  board = new TicketService(agentCredentialsFromEnv());
123
124
  }
124
125
  catch (err) {
125
- console.error(`board MCP: ${err instanceof Error ? err.message : String(err)}`);
126
- process.exit(1);
126
+ // No usable credentials (none, or a key from the environment the board
127
+ // here may not get): serve anyway, so the agent sees why on its first
128
+ // tool call, and send nothing to any board.
129
+ const message = err instanceof Error ? err.message : String(err);
130
+ console.error(`board MCP: ${message}`);
131
+ await createServer(refusingBoard(message)).connect(new StdioServerTransport());
132
+ return;
127
133
  }
128
134
  // Log in up front so a bad config shows in the MCP logs right away. On
129
135
  // failure keep serving: every tool call retries the login and returns the
@@ -131,3 +137,9 @@ export async function runMcpServer() {
131
137
  await board.login().then(() => console.error(`board MCP: logged in as ${board.agentName}`), (err) => console.error(`board MCP: ${err instanceof Error ? err.message : String(err)}`));
132
138
  await createServer(board).connect(new StdioServerTransport());
133
139
  }
140
+ /** A stand-in for TicketService whose every call fails with message, before any request. */
141
+ function refusingBoard(message) {
142
+ return new Proxy({}, {
143
+ get: (_target, prop) => (prop === "then" ? undefined : () => Promise.reject(new BoardError(message))),
144
+ });
145
+ }
package/dist/pb.js CHANGED
@@ -1,21 +1,40 @@
1
1
  // Board connection settings for an agent session: the environment first,
2
2
  // else a key saved on this machine by `board login` (credentials.ts) for the
3
3
  // board in use (BOARD_URL, or the repository's .mergeline.json: repo.ts).
4
+ // A key from the environment is used only with BOARD_URL (envKeyRefusal).
4
5
  // The PocketBase client itself lives in service.ts, the only module that
5
6
  // imports the PocketBase SDK.
6
7
  import { pickSaved } from "./credentials.js";
7
8
  import { boardInContext } from "./repo.js";
8
9
  export const DEFAULT_BOARD_URL = "http://127.0.0.1:8090";
10
+ /**
11
+ * A key from the environment goes only to BOARD_URL (or the default address
12
+ * when nothing names a board): never to an address a repository's
13
+ * .mergeline.json names, since the repository may be someone else's (a
14
+ * clone, a fork, a PR branch checked out to review). Saved keys are safe
15
+ * already: each goes only to the board it was saved for.
16
+ */
17
+ function envKeyRefusal(what, board) {
18
+ return new Error(`${what}, and the board here is ${board.url} (from ${board.from}): ` +
19
+ `set BOARD_URL=${board.url} to use that key there, or save it with board login <name> --url ${board.url} --key <key>`);
20
+ }
9
21
  export function agentCredentialsFromEnv(env = process.env, cwd = process.cwd()) {
10
22
  const board = boardInContext(env, cwd);
11
23
  const url = board?.url || DEFAULT_BOARD_URL;
24
+ const fromFile = board && board.from !== "BOARD_URL" ? board : null;
12
25
  const key = env.BOARD_AGENT_KEY?.trim();
13
- if (key)
26
+ if (key) {
27
+ if (fromFile)
28
+ throw envKeyRefusal("BOARD_AGENT_KEY is set", fromFile);
14
29
  return { url, key };
30
+ }
15
31
  const email = env.BOARD_AGENT_EMAIL?.trim();
16
32
  const password = env.BOARD_AGENT_PASSWORD;
17
- if (email && password)
33
+ if (email && password) {
34
+ if (fromFile)
35
+ throw envKeyRefusal("BOARD_AGENT_EMAIL and BOARD_AGENT_PASSWORD are set", fromFile);
18
36
  return { url, email, password };
37
+ }
19
38
  // BOARD_AGENT names a saved agent; without it, the only one saved (for the board in use, if any).
20
39
  const saved = pickSaved(env.BOARD_AGENT?.trim() || undefined, board, env);
21
40
  if (saved)
package/dist/watch.js CHANGED
@@ -8,7 +8,8 @@
8
8
  // - the queue is empty (unless --follow, which then polls every --interval),
9
9
  // - --max-runs runs have happened,
10
10
  // - two runs in a row changed nothing in the queue (for example another
11
- // session of the agent holds its ticket), or
11
+ // session of the agent holds its ticket; when those runs all exited
12
+ // non-zero the stop says they failed instead), or
12
13
  // - the command failed three times in a row.
13
14
  // A paused board (asleep until a person opens it) is not a failure: the
14
15
  // watcher waits, checking every --interval, and goes on when it is back.
@@ -48,7 +49,29 @@ export function usageFromClaudeJson(output) {
48
49
  }
49
50
  return null;
50
51
  }
51
- /** The ticket a run worked on: the one whose state it changed, else the one it resumed. */
52
+ /**
53
+ * The error text of Claude Code's final JSON when it says the run failed
54
+ * (`"is_error": true`), on one line and cut short; else null.
55
+ */
56
+ export function errorFromClaudeJson(output) {
57
+ const candidates = [output.trim(), ...output.trim().split("\n").reverse()];
58
+ for (const text of candidates) {
59
+ let run;
60
+ try {
61
+ run = JSON.parse(text);
62
+ }
63
+ catch {
64
+ continue;
65
+ }
66
+ if (!run || typeof run !== "object" || run.is_error !== true)
67
+ continue;
68
+ const said = typeof run.result === "string" && run.result.trim() ? run.result : `no result text (subtype ${run.subtype ?? "unknown"})`;
69
+ const line = said.replace(/\s+/g, " ").trim();
70
+ return line.length > ERROR_CHARS ? `${line.slice(0, ERROR_CHARS)}...` : line;
71
+ }
72
+ return null;
73
+ }
74
+ const ERROR_CHARS = 300;
52
75
  /**
53
76
  * The ticket a run worked on, for its usage. Only a ticket the agent could
54
77
  * take when the run started counts (ready or in progress then): what a human
@@ -151,6 +174,8 @@ export async function watch(opts) {
151
174
  };
152
175
  let runs = 0;
153
176
  let noProgress = 0;
177
+ /** Exit codes of the runs counted in noProgress. */
178
+ let noProgressCodes = [];
154
179
  let failures = 0;
155
180
  let waitingLogged = false;
156
181
  try {
@@ -209,10 +234,18 @@ export async function watch(opts) {
209
234
  break;
210
235
  if (opts.usageFrom)
211
236
  await reportRunUsage(board, before, after, output, runs, log);
212
- noProgress = snapshot(after) === snapshot(before) ? noProgress + 1 : 0;
237
+ const unchanged = snapshot(after) === snapshot(before);
238
+ noProgress = unchanged ? noProgress + 1 : 0;
239
+ noProgressCodes = unchanged ? [...noProgressCodes, code] : [];
213
240
  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.");
241
+ if (noProgressCodes.every((c) => c !== 0)) {
242
+ const codes = [...new Set(noProgressCodes)].map((c) => `exit ${c}`).join(", ");
243
+ log(`${noProgress} runs in a row failed (${codes}) and changed nothing in the queue; stopping. The agent's error is above.`);
244
+ }
245
+ else {
246
+ log(`${noProgress} runs in a row changed nothing in the queue; stopping. ` +
247
+ "Is another session of this agent holding its ticket? See the board.");
248
+ }
216
249
  return 1;
217
250
  }
218
251
  }
@@ -225,12 +258,15 @@ export async function watch(opts) {
225
258
  }
226
259
  }
227
260
  async function reportRunUsage(board, before, after, output, run, log) {
261
+ const failed = errorFromClaudeJson(output);
262
+ if (failed)
263
+ log(`run ${run}: the agent failed: ${failed}`);
228
264
  const usage = usageFromClaudeJson(output);
229
265
  if (!usage)
230
- return log(`run ${run}: no Claude Code JSON result in the output; no usage reported`);
266
+ return failed ? undefined : log(`run ${run}: no Claude Code JSON result in the output; no usage reported`);
231
267
  const ticket = workedOn(before, after);
232
268
  if (!ticket)
233
- return log(`run ${run}: could not tell which ticket the run worked on; usage not reported`);
269
+ return failed ? undefined : log(`run ${run}: could not tell which ticket the run worked on; usage not reported`);
234
270
  try {
235
271
  const res = await board.reportUsage(ticket.id, usage);
236
272
  log(res.stored
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mergeline/agent",
3
- "version": "0.4.1",
3
+ "version": "0.4.2",
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",