@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/dist/init.js ADDED
@@ -0,0 +1,207 @@
1
+ // `board init`: installs the agent kit (rules, pick and done) into a work
2
+ // repository without overwriting what is there.
3
+ //
4
+ // - AGENTS.md (read by Codex and many other tools) and, with --claude,
5
+ // CLAUDE.md get one section between mergeline markers; the rest of each
6
+ // file is left alone, and running init again updates only that section.
7
+ // - Command and prompt files are written only when missing or when they carry
8
+ // the kit's marker line; a file of the same name that the kit did not write
9
+ // is skipped with a note.
10
+ // - .claude/settings.json gets the kit's permissions added to its lists;
11
+ // .mcp.json gets a `board` server unless it already has one. The agent key
12
+ // is never written: .mcp.json refers to ${BOARD_URL} and ${BOARD_AGENT_KEY}.
13
+ // The permissions also allow the repository's own package manager (from its
14
+ // lockfile) to install and to run its test, lint and typecheck scripts, so an
15
+ // unattended agent does not stop at `pnpm install` in a new worktree.
16
+ // - --url <board> writes the board's address into .mergeline.json (repo.ts),
17
+ // so the board commands in this repository pick that board's saved key.
18
+ // - --codex writes the prompts into $CODEX_HOME/prompts (default
19
+ // ~/.codex/prompts) and prints the MCP snippet for ~/.codex/config.toml,
20
+ // which init does not edit. The snippet names the agent; its key stays in
21
+ // the store `board login` writes, not in config.toml.
22
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
23
+ import { homedir } from "node:os";
24
+ import { dirname, join, relative } from "node:path";
25
+ import { fileURLToPath } from "node:url";
26
+ import { readRepoBoard, REPO_FILE } from "./repo.js";
27
+ const KIT = fileURLToPath(new URL("../kit/", import.meta.url));
28
+ /** This package's npm name, for the npx commands init writes (one place to rename it). */
29
+ export const PACKAGE_NAME = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).name;
30
+ const START = "<!-- mergeline:start (managed by `board init`; edit outside these markers) -->";
31
+ /** Markers are found by these prefixes, so an edited marker line still counts. */
32
+ const START_PREFIX = "<!-- mergeline:start";
33
+ const END = "<!-- mergeline:end -->";
34
+ const MANAGED = "<!-- mergeline: written by `board init`; init updates this file while this line is here -->";
35
+ function kit(name) {
36
+ return readFileSync(join(KIT, name), "utf8").replace(/\s+$/, "") + "\n";
37
+ }
38
+ const COMMANDS = {
39
+ pick: "Take the next ticket from the board and work on it",
40
+ done: "Finish the current ticket: test, push, open a PR, submit for review",
41
+ };
42
+ /** Scripts the agent runs before a PR (done.md), when the project has them. */
43
+ const CHECK_SCRIPTS = ["test", "lint", "typecheck", "check"];
44
+ /**
45
+ * The package manager (from the lockfile) and the commands an agent needs in
46
+ * this repository: install, and the check scripts its package.json has.
47
+ */
48
+ export function projectCommands(dir) {
49
+ const has = (f) => existsSync(join(dir, f));
50
+ const manager = has("pnpm-lock.yaml") ? "pnpm" : has("yarn.lock") ? "yarn" : has("bun.lockb") || has("bun.lock") ? "bun" : "npm";
51
+ let scripts = {};
52
+ try {
53
+ scripts = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")).scripts ?? {};
54
+ }
55
+ catch {
56
+ if (!has("package.json"))
57
+ return { manager, commands: [] };
58
+ }
59
+ const run = (name) => (manager === "npm" ? (name === "test" ? "npm test" : `npm run ${name}`) : `${manager} ${name}`);
60
+ const commands = [manager === "npm" ? "npm ci" : `${manager} install`, `${manager} install`];
61
+ for (const name of CHECK_SCRIPTS)
62
+ if (typeof scripts[name] === "string")
63
+ commands.push(run(name));
64
+ return { manager, commands: [...new Set(commands)] };
65
+ }
66
+ export function init(opts) {
67
+ const actions = [];
68
+ const write = (path, content, kind) => {
69
+ if (!opts.dryRun && (kind === "create" || kind === "update")) {
70
+ mkdirSync(dirname(path), { recursive: true });
71
+ writeFileSync(path, content);
72
+ }
73
+ };
74
+ const label = (path) => {
75
+ const rel = relative(opts.dir, path);
76
+ return rel.startsWith("..") ? path : rel;
77
+ };
78
+ const record = (path, kind, note) => actions.push({ path: label(path), kind, ...(note ? { note } : {}) });
79
+ /** One marked section in a markdown file; the rest of the file stays. */
80
+ function section(path, body) {
81
+ const block = `${START}\n${body.replace(/\s+$/, "")}\n${END}\n`;
82
+ if (!existsSync(path)) {
83
+ write(path, block, "create");
84
+ return record(path, "create");
85
+ }
86
+ const current = readFileSync(path, "utf8");
87
+ const start = current.indexOf(START_PREFIX);
88
+ const end = current.indexOf(END);
89
+ if (start >= 0 !== end >= 0 || (start >= 0 && end < start)) {
90
+ return record(path, "skip", "its mergeline markers are broken; fix or remove them and run init again");
91
+ }
92
+ let next;
93
+ if (start >= 0) {
94
+ const after = current.slice(end + END.length).replace(/^\n/, "");
95
+ next = current.slice(0, start) + block + after;
96
+ }
97
+ else {
98
+ next = current.replace(/\s*$/, "") + "\n\n" + block;
99
+ }
100
+ if (next === current)
101
+ return record(path, "unchanged");
102
+ write(path, next, "update");
103
+ record(path, "update", start >= 0 ? "mergeline section replaced" : "mergeline section added at the end");
104
+ }
105
+ /** A whole file the kit owns, written only if missing or still marked as the kit's. */
106
+ function owned(path, content) {
107
+ if (!existsSync(path)) {
108
+ write(path, content, "create");
109
+ return record(path, "create");
110
+ }
111
+ const current = readFileSync(path, "utf8");
112
+ if (!current.includes(MANAGED))
113
+ return record(path, "skip", "a file of this name exists and was not written by board init");
114
+ if (current === content)
115
+ return record(path, "unchanged");
116
+ write(path, content, "update");
117
+ record(path, "update");
118
+ }
119
+ /** A JSON file changed by fn; skipped if it does not parse. */
120
+ function json(path, fn) {
121
+ let data = {};
122
+ const exists = existsSync(path);
123
+ const before = exists ? readFileSync(path, "utf8") : "";
124
+ if (exists) {
125
+ try {
126
+ data = JSON.parse(before);
127
+ }
128
+ catch {
129
+ return record(path, "skip", "not valid JSON; left as it is");
130
+ }
131
+ }
132
+ fn(data);
133
+ const next = JSON.stringify(data, null, 2) + "\n";
134
+ if (exists && JSON.stringify(JSON.parse(before)) === JSON.stringify(data))
135
+ return record(path, "unchanged");
136
+ const kind = exists ? "update" : "create";
137
+ write(path, next, kind);
138
+ record(path, kind);
139
+ }
140
+ const promptFile = (name) => `---\ndescription: ${COMMANDS[name]}\n---\n\n${MANAGED}\n\n${kit(`${name}.md`)}`;
141
+ /** .mergeline.json: the board's address, written only with --url. */
142
+ function boardFile(path, url) {
143
+ let current;
144
+ try {
145
+ current = existsSync(path) ? readRepoBoard(path) : undefined;
146
+ }
147
+ catch {
148
+ current = undefined;
149
+ }
150
+ if (!url)
151
+ return current;
152
+ const content = JSON.stringify({ board: url }, null, 2) + "\n";
153
+ if (!existsSync(path)) {
154
+ write(path, content, "create");
155
+ record(path, "create");
156
+ }
157
+ else if (current === url && readFileSync(path, "utf8") === content) {
158
+ record(path, "unchanged");
159
+ }
160
+ else {
161
+ write(path, content, "update");
162
+ record(path, "update", current && current !== url ? `board ${current} -> ${url}` : undefined);
163
+ }
164
+ return url;
165
+ }
166
+ const board = boardFile(join(opts.dir, REPO_FILE), opts.url);
167
+ let project = [];
168
+ const rules = kit("rules.md");
169
+ section(join(opts.dir, "AGENTS.md"), rules);
170
+ if (opts.claude) {
171
+ section(join(opts.dir, "CLAUDE.md"), rules);
172
+ owned(join(opts.dir, ".claude", "commands", "pick.md"), promptFile("pick"));
173
+ owned(join(opts.dir, ".claude", "commands", "done.md"), promptFile("done"));
174
+ const ours = JSON.parse(kit("claude-settings.json").replaceAll("{{package}}", PACKAGE_NAME)).permissions;
175
+ project = projectCommands(opts.dir).commands;
176
+ ours.allow = [...ours.allow, ...project.map((c) => `Bash(${c}*)`)];
177
+ json(join(opts.dir, ".claude", "settings.json"), (data) => {
178
+ data.permissions ??= {};
179
+ for (const [list, entries] of Object.entries(ours)) {
180
+ const have = Array.isArray(data.permissions[list]) ? data.permissions[list] : [];
181
+ data.permissions[list] = [...have, ...entries.filter((e) => !have.includes(e))];
182
+ }
183
+ });
184
+ json(join(opts.dir, ".mcp.json"), (data) => {
185
+ data.mcpServers ??= {};
186
+ data.mcpServers.board ??= {
187
+ command: opts.noNpx ? "board" : "npx",
188
+ args: opts.noNpx ? ["mcp"] : ["-y", PACKAGE_NAME, "mcp"],
189
+ // Empty defaults: started by `board start` these are set; otherwise
190
+ // the server uses the key `board login` saved.
191
+ env: { BOARD_URL: "${BOARD_URL:-}", BOARD_AGENT_KEY: "${BOARD_AGENT_KEY:-}", BOARD_AGENT: "${BOARD_AGENT:-}" },
192
+ };
193
+ });
194
+ }
195
+ let codexConfig;
196
+ if (opts.codex) {
197
+ const home = opts.codexHome || process.env.CODEX_HOME || join(homedir(), ".codex");
198
+ owned(join(home, "prompts", "pick.md"), promptFile("pick"));
199
+ owned(join(home, "prompts", "done.md"), promptFile("done"));
200
+ codexConfig = [
201
+ "[mcp_servers.board]",
202
+ ...(opts.noNpx ? ['command = "board"', 'args = ["mcp"]'] : ['command = "npx"', `args = ["-y", "${PACKAGE_NAME}", "mcp"]`]),
203
+ 'env = { BOARD_AGENT = "<agent name>" } # the key saved by: board login <agent name> --url <board> --key <key>',
204
+ ].join("\n");
205
+ }
206
+ return { actions, projectCommands: project, codexConfig, ...(board ? { board } : {}) };
207
+ }
package/dist/mcp.js ADDED
@@ -0,0 +1,132 @@
1
+ // MCP server for a Mergeline board (stdio). One process = one agent session.
2
+ // Started by `board mcp` (cli.ts) or `node dist/index.js`.
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
5
+ // TicketService.
6
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
7
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
8
+ import { z } from "zod";
9
+ import { agentCredentialsFromEnv } from "./pb.js";
10
+ import { BoardError, TicketService } from "./service.js";
11
+ const ticketId = z.string().min(1).describe("Ticket id, as returned by claim");
12
+ const usage = z
13
+ .object({
14
+ input_tokens: z.number().int().min(0).optional(),
15
+ output_tokens: z.number().int().min(0).optional(),
16
+ cache_read_tokens: z.number().int().min(0).optional(),
17
+ cache_write_tokens: z.number().int().min(0).optional(),
18
+ cost: z.number().min(0).optional(),
19
+ currency: z.string().length(3).optional(),
20
+ source: z.string().max(80).optional(),
21
+ })
22
+ .optional()
23
+ .describe("Optional: what this work cost, if your tool reports it (tokens, cost). Leave it out otherwise.");
24
+ async function run(fn) {
25
+ try {
26
+ const result = await fn();
27
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
28
+ }
29
+ catch (err) {
30
+ const message = err instanceof BoardError ? err.message : `board tool failed: ${err instanceof Error ? err.message : String(err)}`;
31
+ return { content: [{ type: "text", text: message }], isError: true };
32
+ }
33
+ }
34
+ export function createServer(board) {
35
+ const server = new McpServer({ name: "board", version: "0.1.0" });
36
+ server.registerTool("list_mine", {
37
+ title: "List my tickets",
38
+ description: "List the tickets assigned to you that are not done, with status, priority and block. " +
39
+ "Use it to orient yourself; it does not claim anything.",
40
+ annotations: { readOnlyHint: true },
41
+ }, () => run(() => board.listMine()));
42
+ server.registerTool("claim", {
43
+ title: "Claim my next ticket",
44
+ description: "Take your next ticket. Returns the highest-priority ready ticket assigned to you, or " +
45
+ "{ ticket: null } when there is nothing to do: then say so and stop. " +
46
+ "If you already had a ticket in progress (for example after a restart) it returns that one " +
47
+ "with resumed: true; continue it. You hold one ticket at a time. " +
48
+ "The ticket comes with spec_path, branch, answer and notes: the spec on main plus answer and " +
49
+ "notes are your only requirements. Claiming starts a lease (claimed_until); keep it alive with heartbeat. " +
50
+ "If it fails because another session of yours holds your ticket, say so and stop: do not retry and do not " +
51
+ "start other work.",
52
+ }, () => run(() => board.claim()));
53
+ server.registerTool("heartbeat", {
54
+ title: "Extend lease",
55
+ description: "Extend your lease on the ticket and optionally log a one-line progress note. " +
56
+ "Call it after every meaningful step, at least every 10 minutes. " +
57
+ "If it fails saying to claim again, stop working on the ticket and call claim. If it fails saying another " +
58
+ "session holds the ticket, stop at once: no commit, no push, no PR.",
59
+ inputSchema: {
60
+ ticket_id: ticketId,
61
+ note: z.string().max(500).optional().describe("One line on what you just finished"),
62
+ },
63
+ }, ({ ticket_id, note }) => run(() => board.heartbeat(ticket_id, note)));
64
+ server.registerTool("log_event", {
65
+ title: "Log to ticket",
66
+ description: "Add one human-readable line to the ticket's event log. kind: plan (your 3 to 6 step plan, " +
67
+ "once, after reading the spec), progress (a step done), warn (something a human should notice).",
68
+ inputSchema: {
69
+ ticket_id: ticketId,
70
+ kind: z.enum(["plan", "progress", "warn"]),
71
+ text: z.string().min(1).max(2000),
72
+ },
73
+ }, ({ ticket_id, kind, text }) => run(() => board.logEvent(ticket_id, kind, text)));
74
+ server.registerTool("record_spec", {
75
+ title: "Record spec commit",
76
+ description: "Record which commit of main you read the spec from. Call it once, right after reading the " +
77
+ "spec, with the output of `git rev-parse origin/main`.",
78
+ inputSchema: {
79
+ ticket_id: ticketId,
80
+ sha: z.string().regex(/^[0-9a-fA-F]{7,40}$/, "a git commit hash"),
81
+ },
82
+ }, ({ ticket_id, sha }) => run(() => board.recordSpec(ticket_id, sha)));
83
+ server.registerTool("ask_human", {
84
+ title: "Ask a human",
85
+ description: "Use when the spec (plus the ticket's answer and notes) does not answer a question that " +
86
+ "changes behavior. Ask exactly one concrete question. After calling it, stop working on this " +
87
+ "ticket and do not guess: no further commits, no PR. The ticket goes back to ready with a " +
88
+ "question block and comes back to you with the answer on a later claim.",
89
+ inputSchema: {
90
+ ticket_id: ticketId,
91
+ question: z.string().min(1).max(2000).describe("One concrete question a human can answer in a sentence"),
92
+ },
93
+ }, ({ ticket_id, question }) => run(() => board.askHuman(ticket_id, question)));
94
+ server.registerTool("submit_for_review", {
95
+ title: "Submit for review",
96
+ description: "Hand the ticket back for human review once its PR is open. pr_url is the URL printed by " +
97
+ "`gh pr create`; summary is 2 to 4 lines on what changed. This ends your work on the ticket. " +
98
+ "Never try to mark a ticket done: only a human does that.",
99
+ inputSchema: {
100
+ ticket_id: ticketId,
101
+ pr_url: z.string().regex(/^https?:\/\/\S+$/, "the pull request URL"),
102
+ summary: z.string().min(1).max(1500),
103
+ usage,
104
+ },
105
+ }, ({ ticket_id, pr_url, summary, usage }) => run(() => board.submitForReview(ticket_id, pr_url, summary, usage)));
106
+ server.registerTool("release", {
107
+ title: "Release ticket",
108
+ description: "Give the ticket back unfinished when you cannot continue for a reason that is not a spec " +
109
+ "question (for a spec question use ask_human). reason: one line. Stop working on it afterwards.",
110
+ inputSchema: {
111
+ ticket_id: ticketId,
112
+ reason: z.string().min(1).max(500),
113
+ usage,
114
+ },
115
+ }, ({ ticket_id, reason, usage }) => run(() => board.release(ticket_id, reason, usage)));
116
+ return server;
117
+ }
118
+ export async function runMcpServer() {
119
+ let board;
120
+ try {
121
+ board = new TicketService(agentCredentialsFromEnv());
122
+ }
123
+ catch (err) {
124
+ console.error(`board MCP: ${err instanceof Error ? err.message : String(err)}`);
125
+ process.exit(1);
126
+ }
127
+ // Log in up front so a bad config shows in the MCP logs right away. On
128
+ // failure keep serving: every tool call retries the login and returns the
129
+ // reason as a plain tool error.
130
+ 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)}`));
131
+ await createServer(board).connect(new StdioServerTransport());
132
+ }
package/dist/pb.js ADDED
@@ -0,0 +1,25 @@
1
+ // Board connection settings for an agent session: the environment first,
2
+ // else a key saved on this machine by `board login` (credentials.ts) for the
3
+ // board in use (BOARD_URL, or the repository's .mergeline.json: repo.ts).
4
+ // The PocketBase client itself lives in service.ts, the only module that
5
+ // imports the PocketBase SDK.
6
+ import { pickSaved } from "./credentials.js";
7
+ import { boardInContext } from "./repo.js";
8
+ export const DEFAULT_BOARD_URL = "http://127.0.0.1:8090";
9
+ export function agentCredentialsFromEnv(env = process.env, cwd = process.cwd()) {
10
+ const board = boardInContext(env, cwd);
11
+ const url = board?.url || DEFAULT_BOARD_URL;
12
+ const key = env.BOARD_AGENT_KEY?.trim();
13
+ if (key)
14
+ return { url, key };
15
+ const email = env.BOARD_AGENT_EMAIL?.trim();
16
+ const password = env.BOARD_AGENT_PASSWORD;
17
+ if (email && password)
18
+ return { url, email, password };
19
+ // BOARD_AGENT names a saved agent; without it, the only one saved (for the board in use, if any).
20
+ const saved = pickSaved(env.BOARD_AGENT?.trim() || undefined, board, env);
21
+ if (saved)
22
+ return { url: saved.url, key: saved.key };
23
+ throw new Error(`No agent key${board ? ` for ${board.url}` : ""}: run board login <name> --url ${board?.url ?? "<board>"} --key <key> once ` +
24
+ "(the key is shown when the agent is added on the board), or set BOARD_AGENT_KEY");
25
+ }
package/dist/repo.js ADDED
@@ -0,0 +1,67 @@
1
+ // Which board a repository works with: `board init --url <board>` writes the
2
+ // board's address into .mergeline.json at the repository's root (no secrets;
3
+ // committed), so `board start <name>` there picks that board's saved key.
4
+ //
5
+ // { "board": "https://acme.mergeline.app" }
6
+ //
7
+ // The file is looked up from the current folder upwards, up to the root of
8
+ // the git checkout (a folder with .git, which is a file in a worktree such as
9
+ // ../.wt/<ticket>). BOARD_URL, when set, wins over it.
10
+ import { existsSync, readFileSync } from "node:fs";
11
+ import { dirname, join } from "node:path";
12
+ export const REPO_FILE = ".mergeline.json";
13
+ /**
14
+ * A board address in one form, so the same board is the same string wherever
15
+ * it was typed: http(s) only, scheme and host lower-case, no default port, no
16
+ * trailing slash.
17
+ */
18
+ export function normalizeBoardUrl(raw) {
19
+ let url;
20
+ try {
21
+ url = new URL(raw.trim());
22
+ }
23
+ catch {
24
+ throw new Error(`"${raw}" is not a board address; give it as shown on the board, e.g. https://acme.mergeline.app`);
25
+ }
26
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
27
+ throw new Error(`"${raw}" is not a board address: it must start with https:// (or http://)`);
28
+ }
29
+ return (url.origin + url.pathname).replace(/\/+$/, "");
30
+ }
31
+ /** The .mergeline.json that applies in dir, or null. */
32
+ export function findRepoFile(dir) {
33
+ for (let d = dir;; d = dirname(d)) {
34
+ const file = join(d, REPO_FILE);
35
+ if (existsSync(file))
36
+ return file;
37
+ if (existsSync(join(d, ".git")) || dirname(d) === d)
38
+ return null;
39
+ }
40
+ }
41
+ /** The board a .mergeline.json names; an error that says which file when it is broken. */
42
+ export function readRepoBoard(file) {
43
+ let data;
44
+ try {
45
+ data = JSON.parse(readFileSync(file, "utf8"));
46
+ }
47
+ catch {
48
+ throw new Error(`${file} is not valid JSON; run board init --url <board> to write it again`);
49
+ }
50
+ const board = data?.board;
51
+ if (typeof board !== "string" || !board)
52
+ throw new Error(`${file} has no "board" address; run board init --url <board>`);
53
+ try {
54
+ return normalizeBoardUrl(board);
55
+ }
56
+ catch (err) {
57
+ throw new Error(`${file}: ${err instanceof Error ? err.message : String(err)}`);
58
+ }
59
+ }
60
+ /** The board in use here: BOARD_URL, else the repository's .mergeline.json, else null. */
61
+ export function boardInContext(env = process.env, cwd = process.cwd()) {
62
+ const fromEnv = env.BOARD_URL?.trim();
63
+ if (fromEnv)
64
+ return { url: normalizeBoardUrl(fromEnv), from: "BOARD_URL" };
65
+ const file = findRepoFile(cwd);
66
+ return file ? { url: readRepoBoard(file), from: file } : null;
67
+ }