kanbo-cli 0.1.2 → 0.2.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.
@@ -3,18 +3,20 @@ import { c as getBoardMigrationsPath, i as BOARD_PERSON_ROLE, l as createPostgre
3
3
  import { a as openBoardDatabase, c as createSqliteBoardStore, i as markBoardFileOwnedByKanbo, n as migrateBoardFile, o as readBoardFileContents, r as assertBoardSchema$1 } from "./migrate-BhYi9cXw.mjs";
4
4
  import { Command } from "commander";
5
5
  import { z } from "zod";
6
- import { hostname, userInfo } from "node:os";
6
+ import { homedir, hostname, userInfo } from "node:os";
7
7
  import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
8
8
  import { sql } from "drizzle-orm";
9
- import { chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
10
- import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
9
+ import { accessSync, chmodSync, constants, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
10
+ import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
11
11
  import { drizzle } from "drizzle-orm/postgres-js";
12
12
  import { migrate } from "drizzle-orm/postgres-js/migrator";
13
13
  import postgres from "postgres";
14
14
  import { fileURLToPath } from "node:url";
15
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
16
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
17
+ import { spawn, spawnSync } from "node:child_process";
15
18
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
16
19
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
17
- import { spawn } from "node:child_process";
18
20
  import { createServer } from "node:http";
19
21
  /**
20
22
  * Every exit code this tool promises, and what it means — the capabilities
@@ -1901,15 +1903,12 @@ async function approve(store, issueId, input, actor, scope) {
1901
1903
  * leaves even says "returned by you".
1902
1904
  */
1903
1905
  async function returnCard(store, issueId, input, actor, scope) {
1904
- if (actor.kind !== "user") throw new BoardError("board_return_requires_user", {
1905
- issueId,
1906
- actorKind: actor.kind
1907
- });
1908
1906
  return await runBoardWrite(store, async ({ tx }) => {
1907
+ await ensureDefaultColumns(tx, (await requireCard$1(tx, issueId)).workspaceId, { tx });
1908
+ const target = await assertReturnable(tx, issueId, input, actor);
1909
1909
  const card = await requireCard$1(tx, issueId);
1910
- const columns = await ensureDefaultColumns(tx, card.workspaceId, { tx });
1911
1910
  const updates = {
1912
- statusId: (input.toStatusName ? await requireColumn(tx, card.workspaceId, input.toStatusName) : previousColumn(columns, card)).id,
1911
+ statusId: target.id,
1913
1912
  waitingFor: null,
1914
1913
  updatedAt: currentUnixSeconds()
1915
1914
  };
@@ -1930,6 +1929,27 @@ async function returnCard(store, issueId, input, actor, scope) {
1930
1929
  };
1931
1930
  }, scope);
1932
1931
  }
1932
+ /**
1933
+ * Every reason `returnCard` would refuse, asked on reads alone, and the column
1934
+ * the card would go back to when none applies.
1935
+ *
1936
+ * `returnCard` asks exactly this inside its write. A caller that has to undo
1937
+ * something of its own before the return — stop listening for the approval the
1938
+ * card is waiting on, say — asks it first, so a return the board refuses leaves
1939
+ * that untouched. The refusals are the same `BoardError` codes: an actor who is
1940
+ * not a person (`board_return_requires_user`), a card that is not there
1941
+ * (`issue_not_found`), a named column the workspace does not hold
1942
+ * (`issue_status_not_found`), and a card already in the first column with no
1943
+ * column named (`board_return_no_previous_column`).
1944
+ */
1945
+ async function assertReturnable(store, issueId, input, actor) {
1946
+ if (actor.kind !== "user") throw new BoardError("board_return_requires_user", {
1947
+ issueId,
1948
+ actorKind: actor.kind
1949
+ });
1950
+ const card = await requireCard$1(store, issueId);
1951
+ return input.toStatusName ? await requireColumn(store, card.workspaceId, input.toStatusName) : previousColumn(await listColumns(store, card.workspaceId), card);
1952
+ }
1933
1953
  /** Write a comment on the card, as the actor unless the caller names another author. */
1934
1954
  async function addComment(store, input, actor, scope) {
1935
1955
  return await runBoardWrite(store, async ({ tx }) => {
@@ -2807,6 +2827,7 @@ function createBoardOps(store) {
2807
2827
  waitApproval: async (issueId, input, actor, scope) => await waitApproval(store, issueId, input, actor, scope),
2808
2828
  approve: async (issueId, input, actor, scope) => await approve(store, issueId, input, actor, scope),
2809
2829
  returnCard: async (issueId, input, actor, scope) => await returnCard(store, issueId, input, actor, scope),
2830
+ assertReturnable: async (issueId, input, actor) => await assertReturnable(store, issueId, input, actor),
2810
2831
  readApproval: async (issueId) => await readApproval(store, issueId),
2811
2832
  linkPullRequest: async (issueId, urlOrRef, actor, scope) => await linkPullRequest(store, issueId, urlOrRef, actor, scope),
2812
2833
  unlinkPullRequest: async (issueId, linkId, actor, scope) => await unlinkPullRequest(store, issueId, linkId, actor, scope),
@@ -4293,21 +4314,1043 @@ function registerColumnsCommands(program) {
4293
4314
  });
4294
4315
  });
4295
4316
  }
4296
- /** The rules `--require` names, or `null` for `--clear` — exactly one of the two. */
4297
- function readRequestedRules(options) {
4298
- if (options.clear && options.require !== void 0) throw new CliError(1, "Pass --require or --clear, not both.");
4299
- if (options.clear) return null;
4300
- if (options.require === void 0) throw new CliError(1, `Pass --require ${ENTRY_RULES.join(",")} (any of them) or --clear.`);
4301
- return options.require.split(",").map((rule) => rule.trim()).filter(Boolean);
4317
+ /** The rules `--require` names, or `null` for `--clear` — exactly one of the two. */
4318
+ function readRequestedRules(options) {
4319
+ if (options.clear && options.require !== void 0) throw new CliError(1, "Pass --require or --clear, not both.");
4320
+ if (options.clear) return null;
4321
+ if (options.require === void 0) throw new CliError(1, `Pass --require ${ENTRY_RULES.join(",")} (any of them) or --clear.`);
4322
+ return options.require.split(",").map((rule) => rule.trim()).filter(Boolean);
4323
+ }
4324
+ //#endregion
4325
+ //#region src/package-version.ts
4326
+ dirname(fileURLToPath(import.meta.url));
4327
+ /**
4328
+ * This build's own version, one source for the CLI's `--version`, the MCP
4329
+ * server's reported version and the capabilities manifest's
4330
+ * `package.version`. A build carries it as a literal; running from source
4331
+ * (tests, `tsx`) reads the package's own `package.json` instead.
4332
+ */
4333
+ const KANBO_PACKAGE_VERSION = "0.2.0";
4334
+ //#endregion
4335
+ //#region src/cli/failure.ts
4336
+ /**
4337
+ * What a failed command says, and what it leaves with.
4338
+ *
4339
+ * One place, because a failure is output as much as a result is: the exit code
4340
+ * a caller may branch on, the sentence a person reads, and the chain underneath
4341
+ * it that says what actually went wrong.
4342
+ */
4343
+ /** How far down a chain of causes is still worth reading. */
4344
+ const CAUSE_DEPTH_LIMIT = 5;
4345
+ /**
4346
+ * What to say about a failure, and what to leave with.
4347
+ *
4348
+ * A `CliError` already carries both. A `BoardError` is a rule of the board the
4349
+ * caller broke: its code is the honest name of what happened, and its details
4350
+ * say which value did it, so both are printed rather than translated into a
4351
+ * sentence that could drift away from the rule. The one exception is a card
4352
+ * held at a column's door: its details are a list, and a person reads it as
4353
+ * one line per rule the card does not meet yet (`describeColumnRefusal`).
4354
+ *
4355
+ * Whatever it is, its causes are printed under it. A driver's failure arrives
4356
+ * wrapped — `Failed query: create schema …` with the connection refused
4357
+ * underneath — and the wrapper alone tells a person nothing they can act on.
4358
+ * Every line goes through the masking on its way out, because a message this
4359
+ * tool did not write is free to carry the whole connection string in it.
4360
+ */
4361
+ function describeFailure(error) {
4362
+ const { message, exitCode } = readFailure(error);
4363
+ return {
4364
+ message: maskDatabaseUrls([message, ...describeCauses(error, 1)].join("\n")),
4365
+ exitCode
4366
+ };
4367
+ }
4368
+ function readFailure(error) {
4369
+ if (error instanceof CliError) return {
4370
+ message: error.message,
4371
+ exitCode: error.exitCode
4372
+ };
4373
+ if (error instanceof BoardError && error.code === "board_column_rules_unmet") return {
4374
+ message: describeColumnRefusal(error.details),
4375
+ exitCode: 1
4376
+ };
4377
+ if (error instanceof BoardError) {
4378
+ const details = error.details ? ` ${JSON.stringify(error.details)}` : "";
4379
+ return {
4380
+ message: `${error.code}${details}`,
4381
+ exitCode: 1
4382
+ };
4383
+ }
4384
+ return {
4385
+ message: error instanceof Error ? error.message : String(error),
4386
+ exitCode: 1
4387
+ };
4388
+ }
4389
+ /**
4390
+ * The chain under a failure, one indented line per link.
4391
+ *
4392
+ * Bounded, because `cause` is an ordinary property and nothing stops it
4393
+ * pointing back at the error it came from; a chain longer than this has stopped
4394
+ * explaining anything anyway.
4395
+ */
4396
+ function describeCauses(error, depth) {
4397
+ const cause = error instanceof Error ? error.cause : void 0;
4398
+ if (cause === void 0 || cause === null || depth > CAUSE_DEPTH_LIMIT) return [];
4399
+ const message = cause instanceof Error ? cause.message : String(cause);
4400
+ return [`${" ".repeat(depth)}Caused by: ${message}`, ...describeCauses(cause, depth + 1)];
4401
+ }
4402
+ //#endregion
4403
+ //#region src/cli/setup/instructions.ts
4404
+ /**
4405
+ * The instruction block kanbo writes into an agent's standing instructions,
4406
+ * and the three things done to it: written, found again, taken out.
4407
+ *
4408
+ * Two versions of the block exist. The project block says "this project is on
4409
+ * a board"; the global one, for a person's user-level file, says "a project
4410
+ * with `.kanbo/` is on a board" and binds nothing — one user file serves every
4411
+ * project, and most of them have no board.
4412
+ */
4413
+ /** The markers that make the block something this tool can find again. */
4414
+ const INSTRUCTION_START = "<!-- KANBO_START -->";
4415
+ const INSTRUCTION_END = "<!-- KANBO_END -->";
4416
+ /**
4417
+ * What to run and when, and nothing about how to do the work: the method is
4418
+ * the person's own instructions to their agent. The rules are the sentences
4419
+ * `ops/agent-rules.ts` holds for every surface, with the command beside each.
4420
+ */
4421
+ const RULE_LINES = [
4422
+ "- Take a card from `kanbo ready`.",
4423
+ `- ${MOVE_CARD_RULE} (\`kanbo card move <id> <column>\`)`,
4424
+ `- ${STATUS_LINE_RULE} (\`kanbo card status-line <id> --text "..."\`)`,
4425
+ `- ${SUBTASK_RULE} (\`kanbo card create --description "..." --parent <id>\`)`,
4426
+ `- ${COMMENT_RULE} (\`kanbo card comment <id> --content "..."\`)`,
4427
+ `- ${WAIT_FOR_PERSON_RULE} (\`kanbo card wait-approval <id>\`)`,
4428
+ `- ${PERSON_ONLY_RULE}`,
4429
+ `- ${OWN_SESSION_RULE} (\`kanbo run start <id> --agent <name> --session <ref>\`)`,
4430
+ "- Run `kanbo capabilities` for the full list of tools, commands and rules."
4431
+ ];
4432
+ /** The block `kanbo init --instructions …` writes into a project's own file. */
4433
+ const INSTRUCTION_BLOCK = [
4434
+ INSTRUCTION_START,
4435
+ "## Kanbo board",
4436
+ "",
4437
+ "Work on this project is tracked on a kanbo board. Before starting a task run `kanbo prime` — it prints the board's columns and what each one means.",
4438
+ "",
4439
+ ...RULE_LINES,
4440
+ INSTRUCTION_END
4441
+ ].join("\n");
4442
+ /** The block `kanbo init --global` writes into a person's user-level file. */
4443
+ const GLOBAL_INSTRUCTION_BLOCK = [
4444
+ INSTRUCTION_START,
4445
+ "## Kanbo boards",
4446
+ "",
4447
+ "A project with a `.kanbo/` directory tracks its work on a kanbo board. In such a project, before starting a task run `kanbo prime` (or call the `kanbo_prime` tool) — it prints the board's columns and what each one means. A project without `.kanbo/` has no board: ignore this section there, and do not create one — a person sets a board up with `kanbo init`.",
4448
+ "",
4449
+ ...RULE_LINES,
4450
+ INSTRUCTION_END
4451
+ ].join("\n");
4452
+ /**
4453
+ * The block in that file, once.
4454
+ *
4455
+ * A file that already carries the markers has its block replaced rather than
4456
+ * appended to, so a current block changes nothing at all and an outdated one is
4457
+ * brought forward. Everything outside the markers is the person's own writing
4458
+ * and is never touched.
4459
+ */
4460
+ function planInstructionBlock(path, block) {
4461
+ const existing = readText(path);
4462
+ const next = withBlock(existing, block);
4463
+ return {
4464
+ path,
4465
+ next: existing === next ? null : next
4466
+ };
4467
+ }
4468
+ /**
4469
+ * The file without the block, or no change when it carries none. The file
4470
+ * itself stays even when nothing is left in it: kanbo does not record which
4471
+ * files it created, and a person's file is not this tool's to delete.
4472
+ */
4473
+ function planInstructionBlockRemoval(path) {
4474
+ const existing = readText(path);
4475
+ const bounds = existing === null ? null : findBlock(existing);
4476
+ if (existing === null || bounds === null) return {
4477
+ path,
4478
+ next: null
4479
+ };
4480
+ const joined = [existing.slice(0, bounds.start).replace(/\s*$/, ""), existing.slice(bounds.end).trim()].filter((part) => part.length > 0).join("\n\n");
4481
+ return {
4482
+ path,
4483
+ next: joined ? `${joined}\n` : ""
4484
+ };
4485
+ }
4486
+ /** The block a file carries, markers included, or `null` when it carries none. */
4487
+ function readInstructionBlock(path) {
4488
+ const existing = readText(path);
4489
+ const bounds = existing === null ? null : findBlock(existing);
4490
+ return existing === null || bounds === null ? null : existing.slice(bounds.start, bounds.end);
4491
+ }
4492
+ function withBlock(existing, block) {
4493
+ if (existing === null || !existing.trim()) return `${block}\n`;
4494
+ const bounds = findBlock(existing);
4495
+ if (bounds) return existing.slice(0, bounds.start) + block + existing.slice(bounds.end);
4496
+ return `${existing.replace(/\s*$/, "")}\n\n${block}\n`;
4497
+ }
4498
+ function findBlock(text) {
4499
+ const start = text.indexOf(INSTRUCTION_START);
4500
+ const end = text.indexOf(INSTRUCTION_END);
4501
+ return start >= 0 && end > start ? {
4502
+ start,
4503
+ end: end + 18
4504
+ } : null;
4505
+ }
4506
+ function readText(path) {
4507
+ return existsSync(path) ? readFileSync(path, "utf8") : null;
4508
+ }
4509
+ //#endregion
4510
+ //#region src/cli/setup/paths.ts
4511
+ /**
4512
+ * Where each agent tool keeps the files kanbo writes into, for one project and
4513
+ * for the person's whole machine.
4514
+ *
4515
+ * Resolved on every call rather than at import, so `HOME` and `CODEX_HOME` set
4516
+ * by a test (or a person) are the ones obeyed. Each path was checked against
4517
+ * the tool's own documentation; `docs/agents.md` lists the pages.
4518
+ */
4519
+ /** The tools whose user-level instruction file `kanbo init --global` can write. */
4520
+ const GLOBAL_INSTRUCTION_CLIENTS = [
4521
+ "claude",
4522
+ "codex",
4523
+ "gemini"
4524
+ ];
4525
+ /** The files a project's agents read their standing instructions from. */
4526
+ const PROJECT_INSTRUCTION_FILES = {
4527
+ claude: "CLAUDE.md",
4528
+ agents: "AGENTS.md"
4529
+ };
4530
+ /** The tools that can be told about the board's MCP server. */
4531
+ const MCP_CLIENTS = [
4532
+ "claude",
4533
+ "codex",
4534
+ "cursor"
4535
+ ];
4536
+ /** Where Codex keeps its global files: `$CODEX_HOME`, else `~/.codex`. */
4537
+ function codexHome() {
4538
+ return process.env.CODEX_HOME?.trim() || join(homedir(), ".codex");
4539
+ }
4540
+ /** The user-level instruction file of each tool. */
4541
+ function globalInstructionPath(client) {
4542
+ switch (client) {
4543
+ case "claude": return join(homedir(), ".claude", "CLAUDE.md");
4544
+ case "codex": return join(codexHome(), "AGENTS.md");
4545
+ case "gemini": return join(homedir(), ".gemini", "GEMINI.md");
4546
+ }
4547
+ }
4548
+ /**
4549
+ * The user-level MCP configuration of each tool. Claude Code's is
4550
+ * `~/.claude.json`, its own state file: kanbo reads it but never writes it —
4551
+ * `claude mcp add` and `claude mcp remove` do.
4552
+ */
4553
+ function globalMcpConfigPath(client) {
4554
+ switch (client) {
4555
+ case "claude": return join(homedir(), ".claude.json");
4556
+ case "codex": return join(codexHome(), "config.toml");
4557
+ case "cursor": return join(homedir(), ".cursor", "mcp.json");
4558
+ }
4559
+ }
4560
+ /** The project-level MCP configuration of each tool. */
4561
+ function projectMcpConfigPath(projectDir, client) {
4562
+ switch (client) {
4563
+ case "claude": return join(projectDir, ".mcp.json");
4564
+ case "codex": return join(projectDir, ".codex", "config.toml");
4565
+ case "cursor": return join(projectDir, ".cursor", "mcp.json");
4566
+ }
4567
+ }
4568
+ /**
4569
+ * Every executable of that name on `PATH`, in the order a shell would find
4570
+ * them. A path with a separator in it is looked at directly, as a shell does.
4571
+ */
4572
+ function findAllOnPath(command) {
4573
+ if (isAbsolute(command) || command.includes("/")) return isExecutableFile(command) ? [command] : [];
4574
+ const extensions = process.platform === "win32" ? ["", ...(process.env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";")] : [""];
4575
+ const found = [];
4576
+ for (const directory of (process.env.PATH ?? "").split(delimiter).filter(Boolean)) for (const extension of extensions) {
4577
+ const candidate = join(directory, command + extension);
4578
+ if (isExecutableFile(candidate) && !found.includes(candidate)) found.push(candidate);
4579
+ }
4580
+ return found;
4581
+ }
4582
+ /** The executable a shell would start for that command, or `null` when there is none. */
4583
+ function findOnPath(command) {
4584
+ return findAllOnPath(command)[0] ?? null;
4585
+ }
4586
+ function isExecutableFile(path) {
4587
+ try {
4588
+ if (!statSync(path).isFile()) return false;
4589
+ accessSync(path, constants.X_OK);
4590
+ return true;
4591
+ } catch {
4592
+ return false;
4593
+ }
4594
+ }
4595
+ //#endregion
4596
+ //#region src/cli/setup/mcp-config.ts
4597
+ /**
4598
+ * The board's MCP server entry, in the two formats the tools keep it in: the
4599
+ * `mcpServers` JSON map Claude Code (`.mcp.json`) and Cursor (`mcp.json`) read,
4600
+ * and the `[mcp_servers.<name>]` TOML table Codex reads (`config.toml`). Each
4601
+ * is planned before anything is written, found again by the doctor, and taken
4602
+ * out by `kanbo uninstall` without touching any other server.
4603
+ */
4604
+ /** The name the board's MCP server is registered under, in every tool. */
4605
+ const MCP_SERVER_NAME = "kanbo";
4606
+ /** How every registration kanbo writes starts the server. */
4607
+ const MCP_COMMAND = "kanbo";
4608
+ const MCP_ARGS = ["mcp"];
4609
+ /** The line that registers the server with Claude Code for every project of this user. */
4610
+ const CLAUDE_USER_ADD = [
4611
+ "claude",
4612
+ "mcp",
4613
+ "add",
4614
+ "--scope",
4615
+ "user",
4616
+ MCP_SERVER_NAME,
4617
+ "--",
4618
+ MCP_COMMAND,
4619
+ ...MCP_ARGS
4620
+ ];
4621
+ /** The line that takes that registration out again. */
4622
+ const CLAUDE_USER_REMOVE = [
4623
+ "claude",
4624
+ "mcp",
4625
+ "remove",
4626
+ MCP_SERVER_NAME,
4627
+ "--scope",
4628
+ "user"
4629
+ ];
4630
+ /**
4631
+ * A Codex table header naming this server or one of its subtables
4632
+ * (`[mcp_servers.kanbo.env]`), in every spelling TOML allows for the key: bare,
4633
+ * double-quoted and single-quoted all name the same server, and a check that
4634
+ * only knew the bare one would write a second table beside a registration the
4635
+ * person already has.
4636
+ */
4637
+ const CODEX_HEADER_PATTERN = new RegExp(String.raw`^\s*\[\s*mcp_servers\s*\.\s*(?:${MCP_SERVER_NAME}|"${MCP_SERVER_NAME}"|'${MCP_SERVER_NAME}')\s*(\.[^\]]*)?\]`);
4638
+ /** Any table header, which is where a table's keys end. */
4639
+ const TOML_HEADER_PATTERN = /^\s*\[/;
4640
+ /** A `command = "..."` line, either string spelling. */
4641
+ const TOML_COMMAND_PATTERN = /^\s*command\s*=\s*(?:"([^"]*)"|'([^']*)')/m;
4642
+ /**
4643
+ * The `mcpServers` map, merged rather than replaced: the file may already
4644
+ * describe servers that have nothing to do with this board. A `kanbo` entry
4645
+ * that is already there belongs to the person — it may point at a different
4646
+ * binary or carry arguments of its own — and is left as it is.
4647
+ */
4648
+ function planJsonMcpServer(path) {
4649
+ const existing = readJsonConfig(path);
4650
+ if (existing.mcpServers && "kanbo" in existing.mcpServers) return {
4651
+ path,
4652
+ next: null
4653
+ };
4654
+ const next = {
4655
+ ...existing,
4656
+ mcpServers: {
4657
+ ...existing.mcpServers,
4658
+ [MCP_SERVER_NAME]: {
4659
+ type: "stdio",
4660
+ command: MCP_COMMAND,
4661
+ args: [...MCP_ARGS]
4662
+ }
4663
+ }
4664
+ };
4665
+ return {
4666
+ path,
4667
+ next: `${JSON.stringify(next, null, 2)}\n`
4668
+ };
4669
+ }
4670
+ /**
4671
+ * The same file without the `kanbo` entry. Everything else stays, the
4672
+ * `mcpServers` object included when nothing else is left in it: kanbo does not
4673
+ * record which files it created, so it leaves the structure rather than guess.
4674
+ * A file it cannot read as a JSON object is not touched at all.
4675
+ */
4676
+ function planJsonMcpServerRemoval(path) {
4677
+ const existing = readJsonIfObject(path);
4678
+ if (!existing || !isPlainObject(existing.mcpServers) || !("kanbo" in existing.mcpServers)) return {
4679
+ path,
4680
+ next: null
4681
+ };
4682
+ const { [MCP_SERVER_NAME]: _removed, ...others } = existing.mcpServers;
4683
+ return {
4684
+ path,
4685
+ next: `${JSON.stringify({
4686
+ ...existing,
4687
+ mcpServers: others
4688
+ }, null, 2)}\n`
4689
+ };
4690
+ }
4691
+ /**
4692
+ * The command a JSON registration starts the server with: `undefined` when the
4693
+ * file registers no `kanbo` server, `null` when it does but names no command
4694
+ * (a URL server, say).
4695
+ */
4696
+ function readJsonMcpCommand(path) {
4697
+ const servers = readJsonIfObject(path)?.mcpServers;
4698
+ if (!isPlainObject(servers) || !isPlainObject(servers["kanbo"])) return;
4699
+ const command = servers[MCP_SERVER_NAME].command;
4700
+ return typeof command === "string" && command.trim() ? command.trim() : null;
4701
+ }
4702
+ /** Codex keeps its servers in TOML tables, so the table is appended rather than merged. */
4703
+ function planCodexMcpServer(path) {
4704
+ const existing = existsSync(path) ? readFileSync(path, "utf8") : "";
4705
+ if (findCodexSections(existing).length > 0) return {
4706
+ path,
4707
+ next: null
4708
+ };
4709
+ const table = `[mcp_servers.${MCP_SERVER_NAME}]\ncommand = "${MCP_COMMAND}"\nargs = ${JSON.stringify(MCP_ARGS)}\n`;
4710
+ return {
4711
+ path,
4712
+ next: existing.trim() ? `${existing.replace(/\s*$/, "")}\n\n${table}` : table
4713
+ };
4714
+ }
4715
+ /**
4716
+ * The same file without the `kanbo` table and its subtables. A table runs from
4717
+ * its header to the next header, so every other table — and every line before
4718
+ * the first — is kept byte for byte.
4719
+ */
4720
+ function planCodexMcpServerRemoval(path) {
4721
+ if (!existsSync(path)) return {
4722
+ path,
4723
+ next: null
4724
+ };
4725
+ const existing = readFileSync(path, "utf8");
4726
+ const sections = findCodexSections(existing);
4727
+ if (sections.length === 0) return {
4728
+ path,
4729
+ next: null
4730
+ };
4731
+ const lines = existing.split("\n");
4732
+ const removed = new Set(sections.flatMap(({ start, end }) => range(start, end)));
4733
+ const next = lines.filter((_, index) => !removed.has(index)).join("\n").replace(/^\n+/, "");
4734
+ return {
4735
+ path,
4736
+ next: next.trim() ? `${next.replace(/\s*$/, "")}\n` : ""
4737
+ };
4738
+ }
4739
+ /** The command the Codex table starts the server with, with the same `undefined`/`null` meaning as the JSON one. */
4740
+ function readCodexMcpCommand(path) {
4741
+ if (!existsSync(path)) return;
4742
+ const text = readFileSync(path, "utf8");
4743
+ const main = findCodexSections(text).find((section) => section.main);
4744
+ if (!main) return;
4745
+ const body = text.split("\n").slice(main.start, main.end).join("\n");
4746
+ const match = TOML_COMMAND_PATTERN.exec(body);
4747
+ return match ? match[1] ?? match[2] ?? null : null;
4748
+ }
4749
+ /** Is the server registered with Claude Code for every project of this user (`~/.claude.json`, read only)? */
4750
+ function readClaudeUserMcpCommand() {
4751
+ return readJsonMcpCommand(globalMcpConfigPath("claude"));
4752
+ }
4753
+ /**
4754
+ * Run `claude mcp …` when Claude Code is here to run it, and hand the line to
4755
+ * the person when it is not — or when it failed, with the first line it said.
4756
+ * `~/.claude.json` is Claude Code's own state file and is never edited by hand.
4757
+ */
4758
+ function runClaudeMcp(argv) {
4759
+ const command = argv.join(" ");
4760
+ const executable = findOnPath(argv[0]);
4761
+ if (!executable) return {
4762
+ state: "manual",
4763
+ command,
4764
+ reason: `${argv[0]} is not on PATH`
4765
+ };
4766
+ const result = spawnSync(executable, argv.slice(1), {
4767
+ encoding: "utf8",
4768
+ timeout: 6e4
4769
+ });
4770
+ if (result.status === 0) return {
4771
+ state: "ran",
4772
+ command
4773
+ };
4774
+ const said = `${result.stderr ?? ""}${result.stdout ?? ""}`.trim().split("\n")[0];
4775
+ return {
4776
+ state: "manual",
4777
+ command,
4778
+ reason: result.error ? result.error.message : `${argv[0]} exited ${result.status ?? "on a signal"}${said ? `: ${said}` : ""}`
4779
+ };
4780
+ }
4781
+ /** The line ranges (`end` exclusive) of the `kanbo` table and its subtables. */
4782
+ function findCodexSections(text) {
4783
+ const lines = text.split("\n");
4784
+ const sections = [];
4785
+ for (let index = 0; index < lines.length; index += 1) {
4786
+ const match = CODEX_HEADER_PATTERN.exec(lines[index]);
4787
+ if (!match) continue;
4788
+ let end = index + 1;
4789
+ while (end < lines.length && !TOML_HEADER_PATTERN.test(lines[end])) end += 1;
4790
+ sections.push({
4791
+ start: index,
4792
+ end,
4793
+ main: match[1] === void 0
4794
+ });
4795
+ index = end - 1;
4796
+ }
4797
+ return sections;
4798
+ }
4799
+ function range(start, end) {
4800
+ return Array.from({ length: end - start }, (_, offset) => start + offset);
4801
+ }
4802
+ /**
4803
+ * The tool's configuration file as an object to merge into — or a refusal.
4804
+ *
4805
+ * A file that is valid JSON but not an object (a list, a string, `null`) is
4806
+ * something this command has no idea how to merge into, and spreading it would
4807
+ * quietly throw the person's file away. The file is left exactly as it is and
4808
+ * they are told which one to look at.
4809
+ */
4810
+ function readJsonConfig(path) {
4811
+ if (!existsSync(path)) return {};
4812
+ let parsed;
4813
+ try {
4814
+ parsed = JSON.parse(readFileSync(path, "utf8"));
4815
+ } catch {
4816
+ throw new CliError(1, `${path} is not valid JSON. Fix or remove it, then run kanbo init again.`);
4817
+ }
4818
+ if (!isPlainObject(parsed)) throw new CliError(1, `${path} does not hold a JSON object. Fix or remove it, then run kanbo init again.`);
4819
+ if (parsed.mcpServers !== void 0 && !isPlainObject(parsed.mcpServers)) throw new CliError(1, `${path} has an "mcpServers" that is not an object. Fix it, then run kanbo init again.`);
4820
+ return parsed;
4821
+ }
4822
+ /** The file as a JSON object, or `null` when it is missing or anything else — for reading and removal, which never refuse. */
4823
+ function readJsonIfObject(path) {
4824
+ if (!existsSync(path)) return null;
4825
+ try {
4826
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
4827
+ return isPlainObject(parsed) ? parsed : null;
4828
+ } catch {
4829
+ return null;
4830
+ }
4831
+ }
4832
+ function isPlainObject(value) {
4833
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4834
+ }
4835
+ //#endregion
4836
+ //#region src/cli/doctor.ts
4837
+ /** How long an external board may take to answer before the doctor gives up on it. */
4838
+ const POSTGRES_TIMEOUT_MS = 5e3;
4839
+ async function collectDoctorFindings(input) {
4840
+ const findings = [{
4841
+ check: "version",
4842
+ status: "ok",
4843
+ detail: `kanbo ${KANBO_PACKAGE_VERSION}${input.self ? ` (${input.self})` : ""}`
4844
+ }, checkPath(input.self)];
4845
+ const project = findKanboProject(input.cwd);
4846
+ findings.push(checkProject(project));
4847
+ const target = project?.binding ? resolveTarget(project.root) : null;
4848
+ if (project?.binding && !project.binding.databaseUrl) findings.push(await checkSqlite());
4849
+ if (project?.binding && findings.every((finding) => finding.check !== "sqlite" || finding.status === "ok")) findings.push(...await checkBoard(target));
4850
+ findings.push(...checkInstructions(project?.root ?? null));
4851
+ const registrations = findRegistrations(project?.root ?? null);
4852
+ findings.push(...checkRegistrations(registrations));
4853
+ if (project?.binding && !(target instanceof Error)) findings.push(await checkHandshake(registrations, project.root, input.handshakeTimeoutMs));
4854
+ findings.push(checkActor());
4855
+ return findings;
4856
+ }
4857
+ /** Is the `kanbo` a client would start this one? */
4858
+ function checkPath(self) {
4859
+ const all = findAllOnPath(MCP_COMMAND);
4860
+ if (all.length === 0) return {
4861
+ check: "path",
4862
+ status: "warn",
4863
+ detail: "No kanbo on PATH: a shell or MCP client that runs `kanbo` will not find it.",
4864
+ fix: "Install kanbo globally (see docs/installation.md), or put the directory that holds it on PATH."
4865
+ };
4866
+ const first = all[0];
4867
+ if (self && realPath(first) !== realPath(self)) return {
4868
+ check: "path",
4869
+ status: "warn",
4870
+ detail: `${first} comes first on PATH and is not this kanbo (${self}): agents and MCP clients start that one.`,
4871
+ fix: "Remove the other install, or put this one first on PATH."
4872
+ };
4873
+ return {
4874
+ check: "path",
4875
+ status: "ok",
4876
+ detail: `kanbo on PATH: ${first}`
4877
+ };
4878
+ }
4879
+ /** The nearest folder at or above `cwd` with a `.kanbo/` directory, and its binding. */
4880
+ function findKanboProject(cwd) {
4881
+ let directory = resolve(cwd);
4882
+ while (true) {
4883
+ const kanboDirectory = join(directory, dirname(BINDING_FILE_PATH));
4884
+ if (existsSync(kanboDirectory) && statSync(kanboDirectory).isDirectory()) return {
4885
+ root: directory,
4886
+ binding: readBinding(join(directory, BINDING_FILE_PATH))
4887
+ };
4888
+ const parent = dirname(directory);
4889
+ if (parent === directory) return null;
4890
+ directory = parent;
4891
+ }
4892
+ }
4893
+ function checkProject(project) {
4894
+ if (!project) return {
4895
+ check: "binding",
4896
+ status: "warn",
4897
+ detail: "Not inside a kanbo project (no .kanbo/ here or above); board checks are skipped.",
4898
+ fix: "Run kanbo init --file in a project to give it a board."
4899
+ };
4900
+ const path = join(project.root, BINDING_FILE_PATH);
4901
+ if (!project.binding) return {
4902
+ check: "binding",
4903
+ status: "fail",
4904
+ detail: existsSync(path) ? `${path} is not a binding this build can read.` : `${join(project.root, dirname(BINDING_FILE_PATH))} has no ${BINDING_FILE_PATH.split(/[\\/]/).pop()}: nothing says which board this project is on.`,
4905
+ fix: `Run kanbo init (with --file, or the --database-url you used) in ${project.root} to bind it again.`
4906
+ };
4907
+ return {
4908
+ check: "binding",
4909
+ status: "ok",
4910
+ detail: `${path}: workspace ${project.binding.workspaceId}`
4911
+ };
4912
+ }
4913
+ function resolveTarget(root) {
4914
+ try {
4915
+ return resolveDbTarget({ cwd: root });
4916
+ } catch (error) {
4917
+ return error instanceof Error ? error : new Error(String(error));
4918
+ }
4919
+ }
4920
+ /** The native module a board file needs, loaded on a database of its own in memory. */
4921
+ async function checkSqlite() {
4922
+ try {
4923
+ (await openBoardDatabase(":memory:")).close();
4924
+ return {
4925
+ check: "sqlite",
4926
+ status: "ok",
4927
+ detail: "better-sqlite3 loads."
4928
+ };
4929
+ } catch (error) {
4930
+ return {
4931
+ check: "sqlite",
4932
+ status: "fail",
4933
+ detail: `better-sqlite3 cannot be loaded: ${describeFailure(error).message}`,
4934
+ fix: "Install better-sqlite3 next to kanbo (npm install -g better-sqlite3 for a global kanbo)."
4935
+ };
4936
+ }
4937
+ }
4938
+ /** The board itself: it opens, and its schema is this build's. */
4939
+ async function checkBoard(target) {
4940
+ if (target === null) return [];
4941
+ if (target instanceof Error) return [{
4942
+ check: "board",
4943
+ status: "fail",
4944
+ detail: describeFailure(target).message,
4945
+ fix: "Run kanbo init in the project to bind it to a board."
4946
+ }];
4947
+ if (target.kind === "postgres") return [await checkPostgresBoard(target.url)];
4948
+ const board = await openBoardDatabase(target.path);
4949
+ try {
4950
+ assertBoardSchema$1(board.database);
4951
+ return [{
4952
+ check: "board",
4953
+ status: "ok",
4954
+ detail: `${target.path} opens; its schema is current.`
4955
+ }];
4956
+ } catch (error) {
4957
+ const outdated = error instanceof BoardError && error.code === "board_schema_outdated";
4958
+ const ownFile = target.owner === "kanbo";
4959
+ return [{
4960
+ check: "board",
4961
+ status: "fail",
4962
+ detail: outdated ? `${target.path}: ${ownFile ? FILE_SCHEMA_OUTDATED_MESSAGE : SCHEMA_OUTDATED_MESSAGE}` : `${target.path}: ${describeFailure(error).message}`,
4963
+ fix: ownFile ? "Run kanbo migrate." : "Start the app this database belongs to, so it applies its migrations."
4964
+ }];
4965
+ } finally {
4966
+ board.close();
4967
+ }
4968
+ }
4969
+ async function checkPostgresBoard(url) {
4970
+ const where = maskDatabaseUrl(url);
4971
+ let timer;
4972
+ const timeout = new Promise((_, reject) => {
4973
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`no answer within ${POSTGRES_TIMEOUT_MS / 1e3}s`)), POSTGRES_TIMEOUT_MS);
4974
+ });
4975
+ try {
4976
+ const board = await Promise.race([openPostgresBoard(url), timeout]);
4977
+ try {
4978
+ await Promise.race([assertInstalledBoard(board.database), timeout]);
4979
+ } finally {
4980
+ board.close();
4981
+ }
4982
+ return {
4983
+ check: "board",
4984
+ status: "ok",
4985
+ detail: `${where} answers; its schema is current.`
4986
+ };
4987
+ } catch (error) {
4988
+ return {
4989
+ check: "board",
4990
+ status: "fail",
4991
+ detail: `${where}: ${describeFailure(error).message}`,
4992
+ fix: "Check the connection string, then run kanbo migrate."
4993
+ };
4994
+ } finally {
4995
+ clearTimeout(timer);
4996
+ }
4997
+ }
4998
+ /**
4999
+ * Every instruction block kanbo could have written, compared with the one this
5000
+ * build writes. Only files that carry a block are reported: a file without one
5001
+ * is not a fault, but having no block anywhere is worth a warning.
5002
+ */
5003
+ function checkInstructions(root) {
5004
+ const findings = [];
5005
+ if (root) for (const [target, name] of Object.entries(PROJECT_INSTRUCTION_FILES)) {
5006
+ const path = join(root, name);
5007
+ const block = readInstructionBlock(path);
5008
+ if (block !== null) findings.push(blockFinding(path, block === INSTRUCTION_BLOCK, `cd ${root} && kanbo init --instructions ${target} --yes`));
5009
+ }
5010
+ for (const client of GLOBAL_INSTRUCTION_CLIENTS) {
5011
+ const path = globalInstructionPath(client);
5012
+ const block = readInstructionBlock(path);
5013
+ if (block !== null) findings.push(blockFinding(path, block === GLOBAL_INSTRUCTION_BLOCK, `kanbo init --global --instructions ${client}`));
5014
+ }
5015
+ if (findings.length === 0) findings.push({
5016
+ check: "instructions",
5017
+ status: "warn",
5018
+ detail: "No kanbo instruction block in this project's or your own agent files: agents learn the rules only from the MCP server.",
5019
+ fix: "Run kanbo init --instructions claude in the project, or kanbo init --global."
5020
+ });
5021
+ return findings;
5022
+ }
5023
+ function blockFinding(path, current, fix) {
5024
+ return current ? {
5025
+ check: "instructions",
5026
+ status: "ok",
5027
+ detail: `${path}: block is current.`
5028
+ } : {
5029
+ check: "instructions",
5030
+ status: "fail",
5031
+ detail: `${path}: block differs from the one this kanbo writes (stale).`,
5032
+ fix: `Run ${fix} to rewrite it.`
5033
+ };
5034
+ }
5035
+ /** Every `kanbo` registration in the project's and the person's own tool configuration. */
5036
+ function findRegistrations(root) {
5037
+ const found = [];
5038
+ for (const client of MCP_CLIENTS) {
5039
+ const paths = [...root ? [projectMcpConfigPath(root, client)] : [], globalMcpConfigPath(client)];
5040
+ for (const path of paths) {
5041
+ const command = client === "codex" ? readCodexMcpCommand(path) : readJsonMcpCommand(path);
5042
+ if (command !== void 0) found.push({
5043
+ client,
5044
+ path,
5045
+ command
5046
+ });
5047
+ }
5048
+ }
5049
+ return found;
5050
+ }
5051
+ function checkRegistrations(registrations) {
5052
+ if (registrations.length === 0) return [{
5053
+ check: "mcp",
5054
+ status: "warn",
5055
+ detail: "No MCP client has the kanbo server registered.",
5056
+ fix: "Run kanbo init --mcp claude,codex,cursor in the project, or kanbo init --global."
5057
+ }];
5058
+ return registrations.map(({ client, path, command }) => {
5059
+ const check = `mcp:${client}`;
5060
+ if (command === null) return {
5061
+ check,
5062
+ status: "warn",
5063
+ detail: `${path}: the kanbo entry names no command.`,
5064
+ fix: `Set "command" to kanbo in ${path}.`
5065
+ };
5066
+ const resolved = findOnPath(command);
5067
+ return resolved ? {
5068
+ check,
5069
+ status: "ok",
5070
+ detail: `${path}: starts ${command} (${resolved}).`
5071
+ } : {
5072
+ check,
5073
+ status: "fail",
5074
+ detail: `${path}: starts ${command}, which is not on PATH — the client cannot start the server.`,
5075
+ fix: `Install kanbo globally, or change the command in ${path} to a path that exists.`
5076
+ };
5077
+ });
5078
+ }
5079
+ /**
5080
+ * Start the server a client would start, from the project folder, and ask it
5081
+ * `initialize`. It has to call itself `kanbo` and send its instructions.
5082
+ */
5083
+ async function checkHandshake(registrations, root, timeoutMs) {
5084
+ const command = registrations.map((entry) => entry.command && findOnPath(entry.command)).find(Boolean) ?? findOnPath("kanbo");
5085
+ if (!command) return {
5086
+ check: "mcp:handshake",
5087
+ status: "warn",
5088
+ detail: "No kanbo to start, so the MCP server was not tried.",
5089
+ fix: "Put kanbo on PATH."
5090
+ };
5091
+ const transport = new StdioClientTransport({
5092
+ command,
5093
+ args: ["mcp"],
5094
+ cwd: root,
5095
+ env: stringEnvironment(),
5096
+ stderr: "pipe"
5097
+ });
5098
+ let stderr = "";
5099
+ transport.stderr?.on("data", (chunk) => {
5100
+ stderr += chunk.toString();
5101
+ });
5102
+ const client = new Client({
5103
+ name: "kanbo-doctor",
5104
+ version: KANBO_PACKAGE_VERSION
5105
+ });
5106
+ try {
5107
+ await client.connect(transport, { timeout: timeoutMs });
5108
+ const name = client.getServerVersion()?.name;
5109
+ const instructions = client.getInstructions();
5110
+ if (name !== "kanbo" || !instructions?.trim()) return {
5111
+ check: "mcp:handshake",
5112
+ status: "fail",
5113
+ detail: `${command} mcp answered as ${name ?? "nothing"}${instructions?.trim() ? "" : ", without instructions"}.`,
5114
+ fix: "Put a current kanbo first on PATH."
5115
+ };
5116
+ return {
5117
+ check: "mcp:handshake",
5118
+ status: "ok",
5119
+ detail: `${command} mcp answers initialize as kanbo, with instructions.`
5120
+ };
5121
+ } catch (error) {
5122
+ return {
5123
+ check: "mcp:handshake",
5124
+ status: "fail",
5125
+ detail: `${command} mcp did not answer initialize: ${stderr.trim().split("\n")[0] || describeFailure(error).message}`,
5126
+ fix: "Run kanbo mcp in the project yourself to see why it does not start."
5127
+ };
5128
+ } finally {
5129
+ await client.close().catch(() => {});
5130
+ }
5131
+ }
5132
+ function checkActor() {
5133
+ if (isAgentShell()) return {
5134
+ check: "actor",
5135
+ status: "warn",
5136
+ detail: "This shell says it belongs to an agent (KANBO_ACTOR_KIND=agent): approve and return refuse here.",
5137
+ fix: "If this is your own terminal, remove KANBO_ACTOR_KIND from your shell profile."
5138
+ };
5139
+ return {
5140
+ check: "actor",
5141
+ status: "ok",
5142
+ detail: "This shell is a person's."
5143
+ };
5144
+ }
5145
+ /** The environment as the SDK wants it: every value a string, so `KANBO_*` reaches the server as it would from a client. */
5146
+ function stringEnvironment() {
5147
+ return Object.fromEntries(Object.entries(process.env).filter((entry) => entry[1] !== void 0));
5148
+ }
5149
+ function realPath(path) {
5150
+ try {
5151
+ return realpathSync(path);
5152
+ } catch {
5153
+ return path;
5154
+ }
5155
+ }
5156
+ //#endregion
5157
+ //#region src/cli/commands/doctor.ts
5158
+ /** How long `kanbo mcp` may take to answer `initialize`. */
5159
+ const HANDSHAKE_TIMEOUT_MS = 1e4;
5160
+ const MARKS = {
5161
+ ok: "ok ",
5162
+ warn: "warn",
5163
+ fail: "FAIL"
5164
+ };
5165
+ function registerDoctorCommand(program) {
5166
+ program.command("doctor").description("check this install, this project's binding and board, instruction blocks and MCP registrations").option("--json", "print the findings as JSON").action(async (options) => {
5167
+ const findings = await collectDoctorFindings({
5168
+ cwd: process.cwd(),
5169
+ self: process.argv[1] ?? null,
5170
+ handshakeTimeoutMs: HANDSHAKE_TIMEOUT_MS
5171
+ });
5172
+ if (options.json) console.log(JSON.stringify({
5173
+ version: KANBO_PACKAGE_VERSION,
5174
+ findings
5175
+ }, null, 2));
5176
+ else for (const finding of findings) {
5177
+ console.log(`${MARKS[finding.status]} ${finding.check.padEnd(14)} ${finding.detail}`);
5178
+ if (finding.fix) console.log(`${" ".repeat(21)}fix: ${finding.fix}`);
5179
+ }
5180
+ const failed = findings.filter((finding) => finding.status === "fail").length;
5181
+ if (failed > 0) throw new CliError(1, `kanbo doctor: ${failed} check${failed === 1 ? "" : "s"} failed.`);
5182
+ });
5183
+ }
5184
+ //#endregion
5185
+ //#region src/default-board-file-path.ts
5186
+ /**
5187
+ * Where a board file of a project's own goes when nobody names a path —
5188
+ * `kanbo init --file` writes it here, and an app that attaches a project's
5189
+ * board file can import the same constant rather than spelling it again.
5190
+ */
5191
+ const DEFAULT_BOARD_FILE_PATH = join(".kanbo", "board.db");
5192
+ //#endregion
5193
+ //#region src/cli/setup/confirm.ts
5194
+ /**
5195
+ * Show a plan of file changes and ask before carrying it out.
5196
+ *
5197
+ * `--yes` is the answer given in advance. A shell with nobody at its terminal
5198
+ * cannot be asked, so it is refused rather than taken as a yes: these commands
5199
+ * write into a person's own configuration, which is the kind of thing a person
5200
+ * says yes to. When the caller asked for machine output, stdout belongs to the
5201
+ * result and the plan goes to stderr.
5202
+ */
5203
+ async function confirmPlan(input) {
5204
+ (input.machineOutput ? console.error : console.log)(input.preview);
5205
+ if (input.yes) return true;
5206
+ if (!isInteractive()) throw new CliError(1, `Nothing was changed. Run ${input.command} again with --yes to do this without being asked.`);
5207
+ return await (await import("@clack/prompts")).confirm({ message: input.question }) === true;
5208
+ }
5209
+ /** Is there a person on the other end of this shell to ask? */
5210
+ function isInteractive() {
5211
+ return Boolean(process.stdin.isTTY && process.stdout.isTTY);
5212
+ }
5213
+ //#endregion
5214
+ //#region src/cli/setup/file-change.ts
5215
+ /** Write the change, creating the directory it lives in, and say what happened. */
5216
+ function applyFileChange(change) {
5217
+ if (change.next === null) return {
5218
+ path: change.path,
5219
+ state: "unchanged"
5220
+ };
5221
+ mkdirSync(dirname(change.path), { recursive: true });
5222
+ writeFileSync(change.path, change.next);
5223
+ return {
5224
+ path: change.path,
5225
+ state: "written"
5226
+ };
5227
+ }
5228
+ //#endregion
5229
+ //#region src/cli/commands/init-global.ts
5230
+ /**
5231
+ * `kanbo init --global` — this person's own agent tools, told about kanbo once
5232
+ * for every project.
5233
+ *
5234
+ * It binds no board and creates none: the block it writes says "a project with
5235
+ * `.kanbo/` is on a board", and a project becomes one with a plain `kanbo init`.
5236
+ * The MCP registrations are the same `kanbo mcp` every project registration
5237
+ * starts, which resolves the board from the folder the client starts it in.
5238
+ *
5239
+ * Every change is worked out first and shown; nothing is written until the
5240
+ * person says yes (or said `--yes`), and a file that already says it is
5241
+ * reported `unchanged`.
5242
+ */
5243
+ /** Written when `--instructions` is not given. Gemini is asked for by name. */
5244
+ const DEFAULT_INSTRUCTION_CLIENTS = ["claude", "codex"];
5245
+ /** The flags that are about binding a project, which `--global` does not do. */
5246
+ const PROJECT_ONLY_FLAGS = [
5247
+ ["file", "--file"],
5248
+ ["db", "--db"],
5249
+ ["databaseUrl", "--database-url"],
5250
+ ["workspace", "--workspace"],
5251
+ ["board", "--board"],
5252
+ ["identifier", "--identifier"],
5253
+ ["agentUrl", "--agent-url"]
5254
+ ];
5255
+ async function initGlobal(options) {
5256
+ const format = readFormat(options);
5257
+ const given = PROJECT_ONLY_FLAGS.filter(([key]) => options[key] !== void 0).map(([, flag]) => flag);
5258
+ if (given.length > 0) throw new CliError(1, `--global binds no board; ${given.join(", ")} ${given.length === 1 ? "is" : "are"} for a project. Run kanbo init in the project for that.`);
5259
+ const instructionClients = parseGlobalInstructions(options.instructions);
5260
+ const mcpClients = options.mcp ?? [...MCP_CLIENTS];
5261
+ const instructionChanges = instructionClients.map((client) => ({
5262
+ client,
5263
+ change: planInstructionBlock(globalInstructionPath(client), GLOBAL_INSTRUCTION_BLOCK)
5264
+ }));
5265
+ const fileMcpChanges = mcpClients.filter((client) => client !== "claude").map((client) => ({
5266
+ client,
5267
+ change: planGlobalMcpFile(client)
5268
+ }));
5269
+ const claudeNeeded = mcpClients.includes("claude") && readClaudeUserMcpCommand() === void 0;
5270
+ const pending = [...instructionChanges, ...fileMcpChanges].filter(({ change }) => change.next !== null);
5271
+ let confirmed = true;
5272
+ if (pending.length > 0 || claudeNeeded) confirmed = await confirmPlan({
5273
+ preview: describePlan$1(pending.map(({ change }) => change), claudeNeeded),
5274
+ question: "Make these changes?",
5275
+ yes: options.yes,
5276
+ machineOutput: Boolean(options.json || format),
5277
+ command: "kanbo init --global"
5278
+ });
5279
+ if (!confirmed) throw new CliError(1, "Nothing was changed.");
5280
+ printResult(describeResult(instructionChanges.map(({ client, change }) => ({
5281
+ client,
5282
+ ...applyFileChange(change)
5283
+ })), mcpClients.map((client) => {
5284
+ if (client === "claude") return registerWithClaude(claudeNeeded);
5285
+ return {
5286
+ client,
5287
+ ...applyFileChange(fileMcpChanges.find((entry) => entry.client === client).change)
5288
+ };
5289
+ })), options);
5290
+ }
5291
+ function planGlobalMcpFile(client) {
5292
+ const path = globalMcpConfigPath(client);
5293
+ return client === "codex" ? planCodexMcpServer(path) : planJsonMcpServer(path);
5294
+ }
5295
+ /** Claude Code's user-scope registration goes through its own command, never an edit of `~/.claude.json`. */
5296
+ function registerWithClaude(needed) {
5297
+ const path = globalMcpConfigPath("claude");
5298
+ if (!needed) return {
5299
+ client: "claude",
5300
+ path,
5301
+ state: "unchanged"
5302
+ };
5303
+ const outcome = runClaudeMcp(CLAUDE_USER_ADD);
5304
+ return outcome.state === "ran" ? {
5305
+ client: "claude",
5306
+ path,
5307
+ state: "written",
5308
+ command: outcome.command
5309
+ } : {
5310
+ client: "claude",
5311
+ path,
5312
+ state: "manual",
5313
+ command: outcome.command,
5314
+ reason: outcome.reason
5315
+ };
5316
+ }
5317
+ function describePlan$1(changes, claudeNeeded) {
5318
+ const lines = ["kanbo init --global will:"];
5319
+ for (const change of changes) lines.push(` write ${change.path}`);
5320
+ if (claudeNeeded) lines.push(` run ${CLAUDE_USER_ADD.join(" ")}`);
5321
+ lines.push("No board is created. Narrow this with --instructions and --mcp.");
5322
+ return lines.join("\n");
5323
+ }
5324
+ function describeResult(instructions, mcp) {
5325
+ const lines = [];
5326
+ for (const outcome of instructions) lines.push(`Instructions: ${outcome.path} (${outcome.state})`);
5327
+ for (const outcome of mcp) if (outcome.state === "manual") lines.push(`MCP: ${outcome.client} — run this yourself: ${outcome.command} (${outcome.reason})`);
5328
+ else lines.push(`MCP: ${outcome.path} (${outcome.state})`);
5329
+ lines.push("A project uses the board once it has run kanbo init. Check everything with kanbo doctor.");
5330
+ return {
5331
+ value: {
5332
+ scope: "global",
5333
+ instructions,
5334
+ mcp
5335
+ },
5336
+ text: lines.join("\n"),
5337
+ fields: [
5338
+ "scope",
5339
+ "instructions",
5340
+ "mcp"
5341
+ ]
5342
+ };
5343
+ }
5344
+ function parseGlobalInstructions(value) {
5345
+ if (value === void 0) return DEFAULT_INSTRUCTION_CLIENTS;
5346
+ const names = value.split(",").map((name) => name.trim()).filter((name) => name.length > 0);
5347
+ if (names.length === 1 && names[0] === "none") return [];
5348
+ return names.map((name) => {
5349
+ const client = GLOBAL_INSTRUCTION_CLIENTS.find((candidate) => candidate === name);
5350
+ if (!client) throw new CliError(1, `Unknown instructions target "${name}" for --global. Use one or more of ${GLOBAL_INSTRUCTION_CLIENTS.join(", ")}, or none.`);
5351
+ return client;
5352
+ });
4302
5353
  }
4303
- //#endregion
4304
- //#region src/default-board-file-path.ts
4305
- /**
4306
- * Where a board file of a project's own goes when nobody names a path —
4307
- * `kanbo init --file` writes it here, and an app that attaches a project's
4308
- * board file can import the same constant rather than spelling it again.
4309
- */
4310
- const DEFAULT_BOARD_FILE_PATH = join(".kanbo", "board.db");
4311
5354
  //#endregion
4312
5355
  //#region src/cli/commands/init.ts
4313
5356
  /**
@@ -4321,22 +5364,6 @@ const DEFAULT_BOARD_FILE_PATH = join(".kanbo", "board.db");
4321
5364
  * whichever tools the person actually uses. Nothing is written to a file the
4322
5365
  * person did not ask for, and nothing is written twice.
4323
5366
  */
4324
- /** The markers that make the instruction block something this tool can find again. */
4325
- const INSTRUCTION_START = "<!-- KANBO_START -->";
4326
- const INSTRUCTION_END = "<!-- KANBO_END -->";
4327
- /** The files an agent reads its standing instructions from. */
4328
- const INSTRUCTION_FILES = {
4329
- claude: "CLAUDE.md",
4330
- agents: "AGENTS.md"
4331
- };
4332
- /** The tools that can be told about the board's MCP server. */
4333
- const MCP_CLIENTS = [
4334
- "claude",
4335
- "codex",
4336
- "cursor"
4337
- ];
4338
- /** The name the board's MCP server is registered under, in every tool. */
4339
- const MCP_SERVER_NAME = "kanbo";
4340
5367
  /**
4341
5368
  * What a person is told when an external board is named and nothing says which
4342
5369
  * workspace it is about. There is no table to look the answer up in, and a card
@@ -4351,40 +5378,13 @@ const FILE_AND_DATABASE_URL_MESSAGE = "One board at a time: pass --file for a bo
4351
5378
  * rule an agent is missing is one the database keeps, not this command.
4352
5379
  */
4353
5380
  const AGENT_URL_MISSING_WARNING = "kanbo: agents in this project will reach the board with the connection string you gave, which owns it. Until you run \"kanbo roles apply\" and record the agent role's own string with --agent-url, an agent here can approve its own work.";
4354
- /**
4355
- * The Codex table this command writes, in every spelling TOML allows for the
4356
- * key: bare, double-quoted and single-quoted all name the same server, and a
4357
- * check that only knew the bare one would write a second table beside a
4358
- * registration the person already has.
4359
- */
4360
- const CODEX_TABLE_PATTERN = new RegExp(String.raw`^\s*\[\s*mcp_servers\s*\.\s*(?:${MCP_SERVER_NAME}|"${MCP_SERVER_NAME}"|'${MCP_SERVER_NAME}')\s*\]`, "m");
4361
- /**
4362
- * What an agent working in this project is told about the board.
4363
- *
4364
- * It says what to run and when, and nothing about how to do the work: the
4365
- * method is the person's own instructions to their agent, and the board only
4366
- * insists on the part that keeps the card honest. The rules are the sentences
4367
- * `ops/agent-rules.ts` holds for every surface, with the command beside each.
4368
- */
4369
- const INSTRUCTION_BLOCK = [
4370
- INSTRUCTION_START,
4371
- "## Kanbo board",
4372
- "",
4373
- "Work on this project is tracked on a kanbo board. Before starting a task run `kanbo prime` — it prints the board's columns and what each one means.",
4374
- "",
4375
- "- Take a card from `kanbo ready`.",
4376
- `- ${MOVE_CARD_RULE} (\`kanbo card move <id> <column>\`)`,
4377
- `- ${STATUS_LINE_RULE} (\`kanbo card status-line <id> --text "..."\`)`,
4378
- `- ${SUBTASK_RULE} (\`kanbo card create --description "..." --parent <id>\`)`,
4379
- `- ${COMMENT_RULE} (\`kanbo card comment <id> --content "..."\`)`,
4380
- `- ${WAIT_FOR_PERSON_RULE} (\`kanbo card wait-approval <id>\`)`,
4381
- `- ${PERSON_ONLY_RULE}`,
4382
- `- ${OWN_SESSION_RULE} (\`kanbo run start <id> --agent <name> --session <ref>\`)`,
4383
- "- Run `kanbo capabilities` for the full list of tools, commands and rules.",
4384
- INSTRUCTION_END
4385
- ].join("\n");
4386
5381
  function registerInitCommand(program) {
4387
- program.command("init").description("bind this project to a board, and tell its agents about it").option("--db <path>", "host database file to read this project's workspace from").option("--database-url <url>", "external Postgres board to bind this project to").option("--file [path]", `use a board file of this project's own instead of a host database or an external board (default ${DEFAULT_BOARD_FILE_PATH})`).option("--workspace <nameOrId>", "workspace this project is").option("--json <fields>", "print only these comma-separated fields, as JSON").option("--format <format>", "output format: json or pretty").option("--board <id>", "the board inside the workspace, when it has more than one").option("--identifier <key>", "what this workspace's card keys start with, for an external board").option("--agent-url <url>", "the connection string agents get, when it is not the one above").option("--instructions <file>", "where to write the instruction block: claude, agents or none", parseInstructions).option("--mcp <clients>", `register the board's MCP server with ${MCP_CLIENTS.join(", ")}`, parseMcpClients).option("--yes", "take the defaults instead of asking").action(async (options) => {
5382
+ program.command("init").description("bind this project to a board, and tell its agents about it").option("--db <path>", "host database file to read this project's workspace from").option("--database-url <url>", "external Postgres board to bind this project to").option("--file [path]", `use a board file of this project's own instead of a host database or an external board (default ${DEFAULT_BOARD_FILE_PATH})`).option("--workspace <nameOrId>", "workspace this project is").option("--json <fields>", "print only these comma-separated fields, as JSON").option("--format <format>", "output format: json or pretty").option("--board <id>", "the board inside the workspace, when it has more than one").option("--identifier <key>", "what this workspace's card keys start with, for an external board").option("--agent-url <url>", "the connection string agents get, when it is not the one above").option("--instructions <file>", "where to write the instruction block: claude, agents or none; with --global, a comma-separated list of claude, codex, gemini, or none").option("--mcp <clients>", `register the board's MCP server with ${MCP_CLIENTS.join(", ")}`, parseMcpClients).option("--global", "set up your own agent tools for every project instead of binding this one; binds no board").option("--yes", "take the defaults instead of asking").action(async (options) => {
5383
+ if (options.global) {
5384
+ await initGlobal(options);
5385
+ return;
5386
+ }
5387
+ if (options.instructions !== void 0) parseInstructions(options.instructions);
4388
5388
  const projectDir = process.cwd();
4389
5389
  if (options.file !== void 0) {
4390
5390
  await initOwnFile(projectDir, options);
@@ -4717,9 +5717,9 @@ function warnAboutOwnerAccess(target, options) {
4717
5717
  * instructions is the kind of thing a person says yes to.
4718
5718
  */
4719
5719
  async function writeInstructions(projectDir, options) {
4720
- const target = options.instructions ?? await askInstructionTarget(options);
5720
+ const target = options.instructions === void 0 ? await askInstructionTarget(options) : parseInstructions(options.instructions);
4721
5721
  if (target === "none") return null;
4722
- return writeInstructionBlock(join(projectDir, INSTRUCTION_FILES[target]));
5722
+ return applyFileChange(planInstructionBlock(join(projectDir, PROJECT_INSTRUCTION_FILES[target]), INSTRUCTION_BLOCK));
4723
5723
  }
4724
5724
  async function askInstructionTarget(options) {
4725
5725
  showBlock(options);
@@ -4753,35 +5753,6 @@ function showBlock(options) {
4753
5753
  if (!options.json && !options.format) console.log(`${INSTRUCTION_BLOCK}\n`);
4754
5754
  }
4755
5755
  /**
4756
- * The block, in that file, once.
4757
- *
4758
- * A file that already carries the markers has its block replaced rather than
4759
- * appended to, so running `init` again on a project whose block is current
4760
- * changes nothing at all, and running it after an upgrade brings the block
4761
- * forward. Everything outside the markers is the person's own writing and is
4762
- * never touched.
4763
- */
4764
- function writeInstructionBlock(path) {
4765
- const existing = existsSync(path) ? readFileSync(path, "utf8") : null;
4766
- const next = buildInstructionFile(existing);
4767
- if (existing === next) return {
4768
- path,
4769
- state: "unchanged"
4770
- };
4771
- writeFileSync(path, next);
4772
- return {
4773
- path,
4774
- state: "written"
4775
- };
4776
- }
4777
- function buildInstructionFile(existing) {
4778
- if (existing === null) return `${INSTRUCTION_BLOCK}\n`;
4779
- const start = existing.indexOf(INSTRUCTION_START);
4780
- const end = existing.indexOf(INSTRUCTION_END);
4781
- if (start >= 0 && end > start) return existing.slice(0, start) + INSTRUCTION_BLOCK + existing.slice(end + 18);
4782
- return `${existing.replace(/\s*$/, "")}\n\n${INSTRUCTION_BLOCK}\n`;
4783
- }
4784
- /**
4785
5756
  * Tell the tools the person uses about the board's MCP server.
4786
5757
  *
4787
5758
  * Only the ones they named, and only when the tool does not already know: a
@@ -4816,81 +5787,8 @@ async function askMcpClients(options) {
4816
5787
  return prompts.isCancel(answer) ? [] : answer;
4817
5788
  }
4818
5789
  function registerMcpServer(projectDir, client) {
4819
- if (client === "codex") return writeCodexMcpServer(join(projectDir, ".codex", "config.toml"));
4820
- return writeJsonMcpServer(join(projectDir, ...client === "claude" ? [".mcp.json"] : [".cursor", "mcp.json"]));
4821
- }
4822
- /**
4823
- * The `mcpServers` map Claude Code and Cursor both read, merged rather than
4824
- * replaced: the file is the project's, and it may already describe servers that
4825
- * have nothing to do with this board.
4826
- */
4827
- function writeJsonMcpServer(path) {
4828
- const existing = readJsonFile(path);
4829
- if (existing.mcpServers && MCP_SERVER_NAME in existing.mcpServers) return {
4830
- path,
4831
- state: "unchanged"
4832
- };
4833
- const next = {
4834
- ...existing,
4835
- mcpServers: {
4836
- ...existing.mcpServers,
4837
- [MCP_SERVER_NAME]: {
4838
- type: "stdio",
4839
- command: "kanbo",
4840
- args: ["mcp"]
4841
- }
4842
- }
4843
- };
4844
- mkdirSync(dirname(path), { recursive: true });
4845
- writeFileSync(path, `${JSON.stringify(next, null, 2)}\n`);
4846
- return {
4847
- path,
4848
- state: "written"
4849
- };
4850
- }
4851
- /**
4852
- * The tool's configuration file as an object to merge into — or a refusal.
4853
- *
4854
- * A file that is valid JSON but not an object (a list, a string, `null`) is
4855
- * something this command has no idea how to merge into, and spreading it would
4856
- * quietly throw the person's file away. The file is left exactly as it is and
4857
- * they are told which one to look at.
4858
- */
4859
- function readJsonFile(path) {
4860
- if (!existsSync(path)) return {};
4861
- const parsed = parseJsonFile(path);
4862
- if (!isPlainObject(parsed)) throw new CliError(1, `${path} does not hold a JSON object. Fix or remove it, then run kanbo init again.`);
4863
- if (parsed.mcpServers !== void 0 && !isPlainObject(parsed.mcpServers)) throw new CliError(1, `${path} has an "mcpServers" that is not an object. Fix it, then run kanbo init again.`);
4864
- return parsed;
4865
- }
4866
- function parseJsonFile(path) {
4867
- try {
4868
- return JSON.parse(readFileSync(path, "utf8"));
4869
- } catch {
4870
- throw new CliError(1, `${path} is not valid JSON. Fix or remove it, then run kanbo init again.`);
4871
- }
4872
- }
4873
- function isPlainObject(value) {
4874
- return typeof value === "object" && value !== null && !Array.isArray(value);
4875
- }
4876
- /** Codex keeps its servers in TOML tables, so the table is appended rather than merged. */
4877
- function writeCodexMcpServer(path) {
4878
- const existing = existsSync(path) ? readFileSync(path, "utf8") : "";
4879
- const table = `[mcp_servers.${MCP_SERVER_NAME}]\ncommand = "kanbo"\nargs = ["mcp"]\n`;
4880
- if (CODEX_TABLE_PATTERN.test(existing)) return {
4881
- path,
4882
- state: "unchanged"
4883
- };
4884
- mkdirSync(dirname(path), { recursive: true });
4885
- writeFileSync(path, existing.trim() ? `${existing.replace(/\s*$/, "")}\n\n${table}` : table);
4886
- return {
4887
- path,
4888
- state: "written"
4889
- };
4890
- }
4891
- /** Is there a person on the other end of this shell to ask? */
4892
- function isInteractive() {
4893
- return Boolean(process.stdin.isTTY && process.stdout.isTTY);
5790
+ const path = projectMcpConfigPath(projectDir, client);
5791
+ return applyFileChange(client === "codex" ? planCodexMcpServer(path) : planJsonMcpServer(path));
4894
5792
  }
4895
5793
  function describeInit(workspace, target, bindingPath, instructions, mcp) {
4896
5794
  const lines = [`Bound this project to ${workspace.name} — ${bindingPath}`];
@@ -5163,16 +6061,6 @@ async function createDbTransport(input) {
5163
6061
  };
5164
6062
  }
5165
6063
  //#endregion
5166
- //#region src/package-version.ts
5167
- dirname(fileURLToPath(import.meta.url));
5168
- /**
5169
- * This build's own version, one source for the CLI's `--version`, the MCP
5170
- * server's reported version and the capabilities manifest's
5171
- * `package.version`. A build carries it as a literal; running from source
5172
- * (tests, `tsx`) reads the package's own `package.json` instead.
5173
- */
5174
- const KANBO_PACKAGE_VERSION = "0.1.2";
5175
- //#endregion
5176
6064
  //#region src/mcp/resources.ts
5177
6065
  /** The URI a client reads the manifest as JSON from. */
5178
6066
  const KANBO_CAPABILITIES_RESOURCE_URI = "kanbo://capabilities";
@@ -5625,74 +6513,6 @@ function createKanboMcpServer(transport, options) {
5625
6513
  return server;
5626
6514
  }
5627
6515
  //#endregion
5628
- //#region src/cli/failure.ts
5629
- /**
5630
- * What a failed command says, and what it leaves with.
5631
- *
5632
- * One place, because a failure is output as much as a result is: the exit code
5633
- * a caller may branch on, the sentence a person reads, and the chain underneath
5634
- * it that says what actually went wrong.
5635
- */
5636
- /** How far down a chain of causes is still worth reading. */
5637
- const CAUSE_DEPTH_LIMIT = 5;
5638
- /**
5639
- * What to say about a failure, and what to leave with.
5640
- *
5641
- * A `CliError` already carries both. A `BoardError` is a rule of the board the
5642
- * caller broke: its code is the honest name of what happened, and its details
5643
- * say which value did it, so both are printed rather than translated into a
5644
- * sentence that could drift away from the rule. The one exception is a card
5645
- * held at a column's door: its details are a list, and a person reads it as
5646
- * one line per rule the card does not meet yet (`describeColumnRefusal`).
5647
- *
5648
- * Whatever it is, its causes are printed under it. A driver's failure arrives
5649
- * wrapped — `Failed query: create schema …` with the connection refused
5650
- * underneath — and the wrapper alone tells a person nothing they can act on.
5651
- * Every line goes through the masking on its way out, because a message this
5652
- * tool did not write is free to carry the whole connection string in it.
5653
- */
5654
- function describeFailure(error) {
5655
- const { message, exitCode } = readFailure(error);
5656
- return {
5657
- message: maskDatabaseUrls([message, ...describeCauses(error, 1)].join("\n")),
5658
- exitCode
5659
- };
5660
- }
5661
- function readFailure(error) {
5662
- if (error instanceof CliError) return {
5663
- message: error.message,
5664
- exitCode: error.exitCode
5665
- };
5666
- if (error instanceof BoardError && error.code === "board_column_rules_unmet") return {
5667
- message: describeColumnRefusal(error.details),
5668
- exitCode: 1
5669
- };
5670
- if (error instanceof BoardError) {
5671
- const details = error.details ? ` ${JSON.stringify(error.details)}` : "";
5672
- return {
5673
- message: `${error.code}${details}`,
5674
- exitCode: 1
5675
- };
5676
- }
5677
- return {
5678
- message: error instanceof Error ? error.message : String(error),
5679
- exitCode: 1
5680
- };
5681
- }
5682
- /**
5683
- * The chain under a failure, one indented line per link.
5684
- *
5685
- * Bounded, because `cause` is an ordinary property and nothing stops it
5686
- * pointing back at the error it came from; a chain longer than this has stopped
5687
- * explaining anything anyway.
5688
- */
5689
- function describeCauses(error, depth) {
5690
- const cause = error instanceof Error ? error.cause : void 0;
5691
- if (cause === void 0 || cause === null || depth > CAUSE_DEPTH_LIMIT) return [];
5692
- const message = cause instanceof Error ? cause.message : String(cause);
5693
- return [`${" ".repeat(depth)}Caused by: ${message}`, ...describeCauses(cause, depth + 1)];
5694
- }
5695
- //#endregion
5696
6516
  //#region src/cli/commands/mcp.ts
5697
6517
  function registerMcpCommand(program) {
5698
6518
  program.command("mcp").description("serve this board to an MCP client over stdio").option("--db <path>", "board database file to open").option("--database-url <url>", "external Postgres board to serve instead of a board file").option("--workspace <nameOrId>", "workspace the board tools are about").action(async (options) => {
@@ -6196,21 +7016,6 @@ function sendBoardPage(response, pathname, assets) {
6196
7016
  * reason turned around: the answer will be yes once the card meets them, and
6197
7017
  * `details.unmet` says what is missing.
6198
7018
  *
6199
- * The five failures about where a board is kept read the same rule. A database
6200
- * that holds no board this build can speak for is 409 — the setting is there,
6201
- * the board behind it is not yet, and `board-storage prepare` is what settles
6202
- * that — and one nobody could reach at all is 503, because nothing about the
6203
- * request was wrong. A workspace naming no board at all is 404: the caller
6204
- * asked about a setting that is not there. A board still holding cards when
6205
- * somebody asks to point the workspace elsewhere is 409, because the answer
6206
- * would have been yes on an empty board and `board-storage migrate` is what
6207
- * makes it one. An operation naming cards from two different boards is 400: no
6208
- * transaction reaches both, so the caller asked for something that cannot be
6209
- * done. A copy that would land on a card number or a column name the target
6210
- * already holds under a different id is 409 for the same reason the others
6211
- * are: the answer would have been yes on a target that did not hold that
6212
- * board, and `details.conflicts` names every value that clashed.
6213
- *
6214
7019
  * A failure may also be renamed here: the package names its codes after the
6215
7020
  * board, while every error the `/issues` routes answer with is named after the
6216
7021
  * issue, and a client matching on `issue_*` should not have to learn a second
@@ -6232,10 +7037,6 @@ const BOARD_ERROR_RESPONSES = {
6232
7037
  message: "The card does not meet what that column asks for yet",
6233
7038
  code: "issue_column_rules_unmet"
6234
7039
  },
6235
- board_copy_conflict: {
6236
- status: 409,
6237
- message: "That board already holds cards or columns of this workspace under the same numbers or names; nothing was copied"
6238
- },
6239
7040
  board_entry_rule_invalid: {
6240
7041
  status: 400,
6241
7042
  message: "Unknown column entry rule"
@@ -6244,10 +7045,6 @@ const BOARD_ERROR_RESPONSES = {
6244
7045
  status: 400,
6245
7046
  message: "Execution mode cannot change once the card has been launched"
6246
7047
  },
6247
- board_mixed_workspaces: {
6248
- status: 400,
6249
- message: "Those cards are not all on the same board"
6250
- },
6251
7048
  board_pull_request_invalid: {
6252
7049
  status: 400,
6253
7050
  message: "Not a GitHub pull request: give its URL or owner/repo#number"
@@ -6307,22 +7104,6 @@ const BOARD_ERROR_RESPONSES = {
6307
7104
  status: 400,
6308
7105
  message: "A sprint cannot start after it is due"
6309
7106
  },
6310
- board_storage_not_configured: {
6311
- status: 404,
6312
- message: "This workspace names no board storage"
6313
- },
6314
- board_storage_not_empty: {
6315
- status: 409,
6316
- message: "That board still holds cards of this workspace; move them with migrate before changing where the board is kept"
6317
- },
6318
- board_storage_not_prepared: {
6319
- status: 409,
6320
- message: "That board has not been prepared yet"
6321
- },
6322
- board_storage_unavailable: {
6323
- status: 503,
6324
- message: "That board could not be reached"
6325
- },
6326
7107
  issue_comment_delete_requires_user: {
6327
7108
  status: 403,
6328
7109
  message: "Only a person can delete a comment the board wrote"
@@ -7784,6 +8565,143 @@ function registerSprintCommands(program) {
7784
8565
  });
7785
8566
  }
7786
8567
  //#endregion
8568
+ //#region src/cli/commands/uninstall.ts
8569
+ function registerUninstallCommand(program) {
8570
+ program.command("uninstall").description("remove what kanbo init wrote: instruction blocks and kanbo MCP entries; boards stay unless --purge").option("--project", "only this project's files").option("--global", "only your own user-level files").option("--purge", "also remove this project's .kanbo/binding.json, and its board file after a confirmation naming it").option("--yes", "do it without asking (never deletes a board file)").option("--json", "print what was done as JSON").action(async (options) => {
8571
+ await uninstall(options);
8572
+ });
8573
+ }
8574
+ async function uninstall(options) {
8575
+ const both = !options.project && !options.global;
8576
+ const withProject = both || Boolean(options.project);
8577
+ const withGlobal = both || Boolean(options.global);
8578
+ if (options.purge && !withProject) throw new CliError(1, "--purge removes a project's binding and board; run it without --global, in the project.");
8579
+ const projectRoot = withProject ? findKanboProject(process.cwd())?.root ?? process.cwd() : null;
8580
+ const edits = [...projectRoot ? planProjectEdits(projectRoot) : [], ...withGlobal ? planGlobalEdits() : []].filter((edit) => edit.change.next !== null);
8581
+ const claudeUser = withGlobal && readClaudeUserMcpCommand() !== void 0;
8582
+ const bindingPath = projectRoot && options.purge ? join(projectRoot, BINDING_FILE_PATH) : null;
8583
+ const purgeBinding = bindingPath !== null && existsSync(bindingPath);
8584
+ const boardFile = projectRoot && options.purge ? findOwnBoardFile(projectRoot) : null;
8585
+ const actions = [];
8586
+ if (edits.length > 0 || claudeUser || purgeBinding || boardFile) {
8587
+ if (!await confirmPlan({
8588
+ preview: describePlan(edits, claudeUser, purgeBinding ? bindingPath : null, boardFile),
8589
+ question: "Remove these?",
8590
+ yes: options.yes,
8591
+ machineOutput: Boolean(options.json),
8592
+ command: "kanbo uninstall"
8593
+ })) throw new CliError(1, "Nothing was changed.");
8594
+ for (const edit of edits) {
8595
+ applyFileChange(edit.change);
8596
+ actions.push({
8597
+ path: edit.change.path,
8598
+ action: "edited",
8599
+ note: edit.what
8600
+ });
8601
+ }
8602
+ if (claudeUser) {
8603
+ const outcome = runClaudeMcp(CLAUDE_USER_REMOVE);
8604
+ actions.push({
8605
+ path: globalMcpConfigPath("claude"),
8606
+ action: outcome.state,
8607
+ note: outcome.state === "ran" ? outcome.command : `run this yourself: ${outcome.command} (${outcome.reason})`
8608
+ });
8609
+ }
8610
+ if (purgeBinding) {
8611
+ rmSync(bindingPath);
8612
+ actions.push({
8613
+ path: bindingPath,
8614
+ action: "deleted",
8615
+ note: "project binding"
8616
+ });
8617
+ }
8618
+ if (boardFile) actions.push(await purgeBoardFile(boardFile));
8619
+ }
8620
+ printActions(actions, options);
8621
+ }
8622
+ function planProjectEdits(root) {
8623
+ return [...Object.values(PROJECT_INSTRUCTION_FILES).map((name) => ({
8624
+ change: planInstructionBlockRemoval(join(root, name)),
8625
+ what: "kanbo instruction block"
8626
+ })), ...[
8627
+ "claude",
8628
+ "codex",
8629
+ "cursor"
8630
+ ].map((client) => ({
8631
+ change: planMcpRemoval(projectMcpConfigPath(root, client), client),
8632
+ what: "kanbo MCP server"
8633
+ }))];
8634
+ }
8635
+ function planGlobalEdits() {
8636
+ return [...GLOBAL_INSTRUCTION_CLIENTS.map((client) => ({
8637
+ change: planInstructionBlockRemoval(globalInstructionPath(client)),
8638
+ what: "kanbo instruction block"
8639
+ })), ...["codex", "cursor"].map((client) => ({
8640
+ change: planMcpRemoval(globalMcpConfigPath(client), client),
8641
+ what: "kanbo MCP server"
8642
+ }))];
8643
+ }
8644
+ function planMcpRemoval(path, client) {
8645
+ return client === "codex" ? planCodexMcpServerRemoval(path) : planJsonMcpServerRemoval(path);
8646
+ }
8647
+ /**
8648
+ * The board file `kanbo init --file` made for this project — the only board
8649
+ * `--purge` may offer to delete. A host app's database or an external board is
8650
+ * not kanbo's to delete, and a binding that names none offers nothing.
8651
+ */
8652
+ function findOwnBoardFile(root) {
8653
+ const binding = findKanboProject(root)?.binding;
8654
+ if (!binding?.dbPath) return null;
8655
+ const path = resolve(root, binding.dbPath);
8656
+ return existsSync(path) ? path : null;
8657
+ }
8658
+ /** Delete the board file only on a yes to a question that names it; `--yes` is not that answer. */
8659
+ async function purgeBoardFile(path) {
8660
+ if (!isInteractive()) return {
8661
+ path,
8662
+ action: "kept",
8663
+ note: "board file: deleting it needs a confirmation in a terminal; delete it yourself if you mean to"
8664
+ };
8665
+ if (await (await import("@clack/prompts")).confirm({
8666
+ message: `Delete the board file ${path} and every card in it? This cannot be undone.`,
8667
+ initialValue: false
8668
+ }) !== true) return {
8669
+ path,
8670
+ action: "kept",
8671
+ note: "board file"
8672
+ };
8673
+ for (const file of [
8674
+ path,
8675
+ `${path}-wal`,
8676
+ `${path}-shm`
8677
+ ]) rmSync(file, { force: true });
8678
+ return {
8679
+ path,
8680
+ action: "deleted",
8681
+ note: "board file"
8682
+ };
8683
+ }
8684
+ function describePlan(edits, claudeUser, bindingPath, boardFile) {
8685
+ const lines = ["kanbo uninstall will:"];
8686
+ for (const edit of edits) lines.push(` edit ${edit.change.path} (remove the ${edit.what})`);
8687
+ if (claudeUser) lines.push(` run ${CLAUDE_USER_REMOVE.join(" ")}`);
8688
+ if (bindingPath) lines.push(` delete ${bindingPath}`);
8689
+ if (boardFile) lines.push(` ask whether to delete the board file ${boardFile} (only in a terminal; --yes does not answer this)`);
8690
+ lines.push("Files stay even when nothing is left in them. Boards stay unless you confirm deleting one.");
8691
+ return lines.join("\n");
8692
+ }
8693
+ function printActions(actions, options) {
8694
+ if (options.json) {
8695
+ console.log(JSON.stringify({ actions }, null, 2));
8696
+ return;
8697
+ }
8698
+ if (actions.length === 0) {
8699
+ console.log("Nothing to remove: no kanbo block or MCP entry in the files kanbo writes.");
8700
+ return;
8701
+ }
8702
+ for (const action of actions) console.log(`${action.action.padEnd(8)} ${action.path}${action.note ? ` (${action.note})` : ""}`);
8703
+ }
8704
+ //#endregion
7787
8705
  //#region src/cli/commands/index.ts
7788
8706
  /**
7789
8707
  * Every command the `kanbo` binary answers to, put on one program.
@@ -7797,6 +8715,8 @@ function registerSprintCommands(program) {
7797
8715
  */
7798
8716
  function registerKanboCommands(program) {
7799
8717
  registerInitCommand(program);
8718
+ registerDoctorCommand(program);
8719
+ registerUninstallCommand(program);
7800
8720
  registerCapabilitiesCommand(program);
7801
8721
  registerPrimeCommand(program);
7802
8722
  registerReadyCommand(program);
@@ -8010,4 +8930,4 @@ function buildCapabilitiesManifest() {
8010
8930
  //#endregion
8011
8931
  export { commentAuthorReference as $, maskDatabaseUrls as A, readEntryRules as B, cardDisplayTitle as C, readProjectBinding as D, readBinding as E, ENTRY_RULES as F, normalizeStatusName as G, readChangeSeq as H, ENTRY_RULE_DESCRIPTIONS as I, BOARD_ACTOR as J, TRACKED_FIELDS as K, UNMET_ENTRY_RULE_REASONS as L, formatExternalSessionRef as M, parseExternalSessionRef as N, writeBinding as O, pullRequestFactKeys as P, activityToken as Q, evaluateEntryRules as R, renderCapabilitiesMarkdown as S, ignoreBoardFile as T, runBoardWrite as U, serializeEntryRules as V, DEFAULT_STATUSES as W, activityKindOrder as X, currentUnixSeconds as Y, activityText as Z, projectKanboPullRequest as _, BOARD_ERROR_RESPONSES as a, isOutsideWriter as at, projectKanboSubCard as b, registerKanboTools as c, formatIssueId as ct, KANBO_MCP_INSTRUCTIONS as d, nextIssueOrder as dt, formatActivityIssueReference as et, KANBO_CAPABILITIES_MARKDOWN_RESOURCE_URI as f, readIssuePrefix as ft, projectKanboColumn as g, projectKanboCard as h, KANBO_TOOL_NAMES as i, readSystemCommentKind as it, createBoardOps as j, maskDatabaseUrl as k, KANBO_TOOLS as l, nextIssueIdentity as lt, registerKanboCapabilitiesResources as m, buildCapabilitiesManifest as n, isEmptyActivityValue as nt, KANBO_MCP_SERVER_NAME as o, normalizeCommentAuthorKind as ot, KANBO_CAPABILITIES_RESOURCE_URI as p, diffFieldChanges as q, KANBO_TOOL_CLI_EQUIVALENTS as r, parseActivityStringArray as rt, createKanboMcpServer as s, toIssueView as st, CAPABILITIES_MANIFEST_VERSION as t, formatPlainActivityValue as tt, buildKanboTools as u, nextIssueNumber as ut, projectKanboRun as v, BINDING_FILE_PATH as w, DEFAULT_BOARD_FILE_PATH as x, projectKanboSprint as y, readChecklist as z };
8012
8932
 
8013
- //# sourceMappingURL=manifest-NRhhhOkC.mjs.map
8933
+ //# sourceMappingURL=manifest-BwpC-4BO.mjs.map