monoban 0.1.0 → 1.1.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.
Files changed (3) hide show
  1. package/README.md +24 -4
  2. package/dist/index.mjs +900 -54
  3. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { homedir, hostname, tmpdir } from "node:os";
3
3
  import path, { dirname, join } from "node:path";
4
- import { mkdir, mkdtemp, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
4
+ import { mkdir, mkdtemp, open, readFile, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
5
5
  import childProcess, { execFile, spawn, spawnSync } from "node:child_process";
6
6
  import { EventEmitter } from "node:events";
7
7
  import fs, { realpathSync } from "node:fs";
@@ -22,14 +22,14 @@ function apiUrl(env = process.env) {
22
22
  return trimSlash(env.MONOBAN_API_URL || "https://api.monoban.dev");
23
23
  }
24
24
  /**
25
- * The web app, where you approve a sign-in: $MONOBAN_WEB_URL, else the API's host without "api."
26
- * (https://api.monoban.dev → https://monoban.dev).
25
+ * The web app, where you approve a sign-in: $MONOBAN_WEB_URL, else /panel on the API's host without
26
+ * "api." (https://api.monoban.dev → https://monoban.dev/panel; monoban.dev is the landing page).
27
27
  */
28
28
  function webUrl(env = process.env) {
29
29
  if (env.MONOBAN_WEB_URL) return trimSlash(env.MONOBAN_WEB_URL);
30
30
  const url = new URL(apiUrl(env));
31
31
  url.hostname = url.hostname.replace(/^api\./, "");
32
- return trimSlash(url.origin);
32
+ return `${url.origin}/panel`;
33
33
  }
34
34
  /** What Devices & tokens calls this computer: its hostname, as printable ASCII ("mbp", not "mbp.local"). */
35
35
  function deviceName(name = hostname()) {
@@ -5367,7 +5367,7 @@ function number(params) {
5367
5367
  }
5368
5368
  //#endregion
5369
5369
  //#region ../../packages/contract/src/board.ts
5370
- /** Column and project colours. Keep in sync with the --c-* tokens (web) and the checks on columns.color and projects.color. */
5370
+ /** Column, project and tag colours. Keep in sync with the --c-* tokens (web) and the checks on columns.color, projects.color and tags.color. */
5371
5371
  const COLORS = [
5372
5372
  "grey",
5373
5373
  "blue",
@@ -5385,9 +5385,93 @@ const LIMITS = {
5385
5385
  /** Highest WIP limit the API accepts (the database only needs it positive). */
5386
5386
  wipLimit: 999,
5387
5387
  taskTitle: 200,
5388
- taskDescription: 2e4
5388
+ taskDescription: 2e4,
5389
+ tagName: 24,
5390
+ tagsPerTask: 10,
5391
+ /** A project's notes, in characters. */
5392
+ projectNotes: 1e5,
5393
+ linksPerTask: 20,
5394
+ linkUrl: 2e3,
5395
+ linkTitle: 200
5389
5396
  };
5390
5397
  //#endregion
5398
+ //#region ../../packages/contract/src/links.ts
5399
+ /** What a task's link points at. */
5400
+ const LINK_KINDS = [
5401
+ "pr",
5402
+ "issue",
5403
+ "commit",
5404
+ "url"
5405
+ ];
5406
+ /** A pull request's or an issue's state, as whoever attached it last saw it. */
5407
+ const LINK_STATES = [
5408
+ "open",
5409
+ "draft",
5410
+ "merged",
5411
+ "closed"
5412
+ ];
5413
+ const GITHUB = /^\/([A-Za-z0-9][A-Za-z0-9-]{0,38})\/([A-Za-z0-9._-]{1,100})\/(pull|issues|commit)\/([0-9A-Fa-f]+)(?:\/|$)/;
5414
+ /**
5415
+ * What a link someone gave points at, or null if it isn't a web link (http or https; "github.com/o/r/pull/54"
5416
+ * without a scheme is https). A GitHub pull request, issue or commit is stored as its canonical URL
5417
+ * (https://github.com/o/r/pull/54, without /files, a query or a #fragment); any other page as given.
5418
+ */
5419
+ function parseLink(input) {
5420
+ const given = input.trim();
5421
+ if (!given || /[\s\p{Cc}]/u.test(given)) return null;
5422
+ let url;
5423
+ try {
5424
+ url = new URL(/^[a-z][a-z0-9+.-]*:/i.test(given) ? given : `https://${given}`);
5425
+ } catch {
5426
+ return null;
5427
+ }
5428
+ if (url.protocol !== "https:" && url.protocol !== "http:" || !url.hostname.includes(".")) return null;
5429
+ const host = url.hostname.toLowerCase().replace(/^www\./, "");
5430
+ const plain = url.port === "" && url.username === "" && url.password === "";
5431
+ const match = host === "github.com" && plain ? GITHUB.exec(url.pathname) : null;
5432
+ if (match) {
5433
+ const [, owner = "", name = "", type, id = ""] = match;
5434
+ const repo = `github.com/${owner}/${name}`.toLowerCase();
5435
+ const base = `https://github.com/${owner}/${name}`;
5436
+ if (type === "commit" && /^[0-9a-f]{7,40}$/i.test(id)) return {
5437
+ url: `${base}/commit/${id.toLowerCase()}`,
5438
+ kind: "commit",
5439
+ repo,
5440
+ number: null,
5441
+ sha: id.toLowerCase()
5442
+ };
5443
+ if (type !== "commit" && /^[1-9][0-9]{0,8}$/.test(id)) {
5444
+ const kind = type === "pull" ? "pr" : "issue";
5445
+ return {
5446
+ url: `${base}/${type}/${id}`,
5447
+ kind,
5448
+ repo,
5449
+ number: Number(id),
5450
+ sha: null
5451
+ };
5452
+ }
5453
+ }
5454
+ const href = url.href;
5455
+ return href.length > LIMITS.linkUrl ? null : {
5456
+ url: href,
5457
+ kind: "url",
5458
+ repo: null,
5459
+ number: null,
5460
+ sha: null
5461
+ };
5462
+ }
5463
+ /** How a link is named in a line: "#54", "a1b2c3d", or the page's host ("figma.com"). */
5464
+ function linkLabel(link) {
5465
+ if (link.number !== null) return `#${link.number}`;
5466
+ const parsed = parseLink(link.url);
5467
+ if (parsed?.sha) return parsed.sha.slice(0, 7);
5468
+ try {
5469
+ return new URL(link.url).hostname.replace(/^www\./, "");
5470
+ } catch {
5471
+ return link.url;
5472
+ }
5473
+ }
5474
+ //#endregion
5391
5475
  //#region ../../node_modules/.pnpm/fractional-indexing@4.0.0/node_modules/fractional-indexing/src/index.js
5392
5476
  const BASE_62_DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
5393
5477
  const BASE_52_DIGITS = BASE_62_DIGITS.slice(10);
@@ -5731,7 +5815,6 @@ function parseIcon(input) {
5731
5815
  if (!value || /[\p{C}\s]/u.test(value.replace(/[\u200d\ufe0f\u{e0020}-\u{e007f}]/gu, ""))) return null;
5732
5816
  return (segmenter ? [...segmenter.segment(value)].length : [...value].length) === 1 && [...value].length <= 16 ? value : null;
5733
5817
  }
5734
- COLORS.filter((c) => c !== "grey");
5735
5818
  /** "mon-12" / "MON-12" → { key: "MON", number: 12 }; null if it isn't a task reference. */
5736
5819
  function parseTaskRef(ref) {
5737
5820
  const match = /^([A-Za-z][A-Za-z0-9]{1,4})-([1-9][0-9]{0,8})$/.exec(ref.trim());
@@ -5742,6 +5825,26 @@ function parseTaskRef(ref) {
5742
5825
  };
5743
5826
  }
5744
5827
  //#endregion
5828
+ //#region ../../packages/contract/src/tags.ts
5829
+ /** One word, not starting with - or # (the CLI and the board filter read those). Same as the check on tags.name. */
5830
+ const TAG_NAME_PATTERN = /^[^\s#-]\S*$/;
5831
+ /**
5832
+ * The tag name for what someone typed: spaces become dashes ("needs review" → "needs-review"),
5833
+ * leading - and # go, and it is cut to the limit. "" if nothing is left.
5834
+ */
5835
+ function tagName(input) {
5836
+ return [...input.trim().replace(/\s+/g, "-").replace(/^[-#]+/, "")].slice(0, LIMITS.tagName).join("");
5837
+ }
5838
+ /** The tag called `name`, in any case (with or without a leading #). */
5839
+ function findTag(tags, name) {
5840
+ const wanted = name.trim().replace(/^#/, "").toLowerCase();
5841
+ return tags.find((t) => t.name.toLowerCase() === wanted);
5842
+ }
5843
+ /** Tags in the order they're shown: by name, in any case. */
5844
+ function sortTags(tags) {
5845
+ return [...tags].sort((a, b) => a.name.localeCompare(b.name, "en", { sensitivity: "base" }) || (a.name < b.name ? -1 : 1));
5846
+ }
5847
+ //#endregion
5745
5848
  //#region ../../packages/contract/src/schemas.ts
5746
5849
  /**
5747
5850
  * The API's data shapes. The API validates requests with them and describes responses with them;
@@ -5785,6 +5888,8 @@ const ProjectSchema = object({
5785
5888
  taskCount: number$1().int().nonnegative(),
5786
5889
  /** The GitHub repository it's linked to, if any. */
5787
5890
  repo: string().nullable(),
5891
+ /** The web board opens a task after you add it, so you can write its description. */
5892
+ openNewTasks: boolean(),
5788
5893
  createdAt: Timestamp,
5789
5894
  updatedAt: Timestamp
5790
5895
  }).meta({ id: "Project" });
@@ -5811,7 +5916,9 @@ strictObject({
5811
5916
  /** New place in the project list (a key between the neighbours). */
5812
5917
  position: PositionSchema.optional(),
5813
5918
  /** Link a GitHub repository; null unlinks. One project per repository (409 if another has it). */
5814
- repo: RepoSchema.nullable().optional()
5919
+ repo: RepoSchema.nullable().optional(),
5920
+ /** Open a task on the web board after adding it. */
5921
+ openNewTasks: boolean().optional()
5815
5922
  }).refine((patch) => Object.keys(patch).length > 0, "Send at least one field to change").meta({
5816
5923
  id: "ProjectPatch",
5817
5924
  minProperties: 1
@@ -5854,11 +5961,80 @@ object({
5854
5961
  /** How many tasks moved (to the end of that column, in their order). */
5855
5962
  moved: number$1().int().nonnegative()
5856
5963
  }).meta({ id: "ColumnDeleted" });
5964
+ /** A tag's name: one word (no spaces), not starting with - or #. Unique, in any case, among the tags a board offers. */
5965
+ const TagNameSchema = text().min(1, "Required").max(LIMITS.tagName).regex(TAG_NAME_PATTERN, "One word (no spaces), not starting with - or #").refine((v) => !/[\u0000-\u001f\u007f]/.test(v), "Can't contain control characters");
5966
+ const TagSchema = object({
5967
+ id: IdSchema,
5968
+ name: string(),
5969
+ color: ColorSchema,
5970
+ /** The project it belongs to; null: shared by all your projects. */
5971
+ project: ProjectKeySchema.nullable(),
5972
+ version: Version,
5973
+ /** How many tasks have it (in every project, for a shared tag). */
5974
+ taskCount: number$1().int().nonnegative(),
5975
+ createdAt: Timestamp
5976
+ }).meta({ id: "Tag" });
5977
+ strictObject({
5978
+ /** Chosen by the client (a random uuid) so it can show and use the new tag before the answer; 409 if taken. */
5979
+ id: IdSchema.optional(),
5980
+ name: TagNameSchema,
5981
+ /** The least used colour when left out. */
5982
+ color: ColorSchema.optional(),
5983
+ /** The project it belongs to (its key), or null to share it with all your projects. */
5984
+ project: ProjectKeySchema.nullable()
5985
+ }).meta({ id: "TagCreate" });
5986
+ strictObject({
5987
+ name: TagNameSchema.optional(),
5988
+ color: ColorSchema.optional(),
5989
+ /**
5990
+ * Share it with all your projects (null), or keep it to one project (its key). A tag can move to a
5991
+ * project only if every task it is on is in that project (409 otherwise).
5992
+ */
5993
+ project: ProjectKeySchema.nullable().optional()
5994
+ }).refine((patch) => Object.keys(patch).length > 0, "Send at least one field to change").meta({
5995
+ id: "TagPatch",
5996
+ minProperties: 1
5997
+ });
5998
+ /** A task's tags: ids of its project's tags or shared ones, at most 10, each once. */
5999
+ const tagIds = array(IdSchema).max(LIMITS.tagsPerTask).refine((ids) => new Set(ids.map((id) => id.toLowerCase())).size === ids.length, "Each tag once").meta({ uniqueItems: true });
5857
6000
  const taskTitle = text().min(1, "Required").max(LIMITS.taskTitle);
5858
6001
  /** Markdown; kept as written (not trimmed). */
5859
6002
  const taskDescription = string().max(LIMITS.taskDescription).regex(/^[^\u0000]*$/, "Can't contain NUL characters");
5860
6003
  string().regex(/^[A-Za-z][A-Za-z0-9]{1,4}-[1-9][0-9]{0,8}$/, "A task reference like MON-12").meta({ example: "MON-12" });
5861
6004
  number().int().min(1).max(2147483647);
6005
+ /**
6006
+ * A web page attached to a task: a pull request, an issue, a commit, or any other page. The kind, repo and
6007
+ * number come from the URL (parseLink); the title and state are what the client that attached it knew.
6008
+ */
6009
+ const TaskLinkSchema = object({
6010
+ id: IdSchema,
6011
+ url: string(),
6012
+ kind: _enum(LINK_KINDS),
6013
+ title: string(),
6014
+ /** A pull request's or an issue's state, when it was read (`checkedAt`); null if nobody said. */
6015
+ state: _enum(LINK_STATES).nullable(),
6016
+ /** github.com/owner/repo, for GitHub links. */
6017
+ repo: string().nullable(),
6018
+ /** A pull request's or an issue's number. */
6019
+ number: number$1().int().positive().nullable(),
6020
+ checkedAt: Timestamp.nullable(),
6021
+ version: Version,
6022
+ createdAt: Timestamp
6023
+ }).meta({ id: "TaskLink" });
6024
+ const linkUrl = string().trim().min(1, "Required").max(LIMITS.linkUrl).describe("An http(s) link; github.com/o/r/pull/54 without a scheme is https");
6025
+ const linkTitle = text().max(LIMITS.linkTitle).regex(/^[^\u0000-\u001f\u007f]*$/, "One line");
6026
+ strictObject({
6027
+ /** For a new link, chosen by the client (a random uuid) so it can show and remove it before the answer. */
6028
+ id: IdSchema.optional(),
6029
+ url: linkUrl,
6030
+ /** Left out: keeps the title it has (none for a new link). */
6031
+ title: linkTitle.optional(),
6032
+ /**
6033
+ * Left out: keeps the state it has. Pull requests: open, draft, merged or closed; issues: open or
6034
+ * closed; other links have none (400).
6035
+ */
6036
+ state: _enum(LINK_STATES).nullable().optional()
6037
+ }).meta({ id: "TaskLinkCreate" });
5862
6038
  strictObject({
5863
6039
  /** Chosen by the client (a random uuid) so it can show and edit the new item before the answer; 409 if taken. */
5864
6040
  id: IdSchema.optional(),
@@ -5867,7 +6043,8 @@ strictObject({
5867
6043
  /** The project's first column when left out. */
5868
6044
  columnId: IdSchema.optional(),
5869
6045
  /** Where it goes in the column; the end when left out. */
5870
- position: PositionSchema.optional()
6046
+ position: PositionSchema.optional(),
6047
+ tagIds: tagIds.optional()
5871
6048
  }).meta({ id: "TaskCreate" });
5872
6049
  strictObject({
5873
6050
  title: taskTitle.optional(),
@@ -5875,7 +6052,9 @@ strictObject({
5875
6052
  /** Move to another column (to its end, unless you also give a position). */
5876
6053
  columnId: IdSchema.optional(),
5877
6054
  /** New place in the column. */
5878
- position: PositionSchema.optional()
6055
+ position: PositionSchema.optional(),
6056
+ /** Its tags from now on (all of them: the list replaces the old one). */
6057
+ tagIds: tagIds.optional()
5879
6058
  }).refine((patch) => Object.keys(patch).length > 0, "Send at least one field to change").meta({
5880
6059
  id: "TaskPatch",
5881
6060
  minProperties: 1
@@ -5888,6 +6067,15 @@ strictObject({
5888
6067
  title: taskTitle,
5889
6068
  description: taskDescription,
5890
6069
  position: PositionSchema,
6070
+ /** Tags deleted since are left out. */
6071
+ tagIds: tagIds.optional(),
6072
+ /** Its links, as DELETE returned them (only these fields are read). */
6073
+ links: array(object({
6074
+ url: linkUrl,
6075
+ title: linkTitle,
6076
+ state: _enum(LINK_STATES).nullable(),
6077
+ checkedAt: Timestamp.nullable().optional()
6078
+ })).max(LIMITS.linksPerTask).optional(),
5891
6079
  createdAt: datetime({ offset: true }).optional(),
5892
6080
  ref: string().optional(),
5893
6081
  version: string().optional(),
@@ -5902,6 +6090,10 @@ const TaskSchema = object({
5902
6090
  title: string(),
5903
6091
  description: string(),
5904
6092
  position: PositionSchema,
6093
+ /** Its tags' ids (see the board's `tags`), sorted. */
6094
+ tagIds: array(IdSchema),
6095
+ /** What's attached to it (pull requests, issues, pages), oldest first. They aren't part of its version. */
6096
+ links: array(TaskLinkSchema),
5905
6097
  version: Version,
5906
6098
  createdAt: Timestamp,
5907
6099
  updatedAt: Timestamp
@@ -5921,10 +6113,29 @@ strictObject({
5921
6113
  object({
5922
6114
  project: ProjectSchema,
5923
6115
  columns: array(ColumnSchema),
6116
+ /** The tags its tasks can have: the project's own and the shared ones, by name. */
6117
+ tags: array(TagSchema),
5924
6118
  tasks: array(TaskSchema),
5925
6119
  /** More tasks than the board returns at once (2,000): load the rest from the paginated task list. */
5926
6120
  truncated: boolean()
5927
6121
  }).meta({ id: "Board" });
6122
+ /** Notes text: kept as written (not trimmed). */
6123
+ const notesText = string().max(LIMITS.projectNotes).regex(/^[^\u0000]*$/, "Can't contain NUL characters");
6124
+ object({
6125
+ text: string(),
6126
+ version: Version,
6127
+ /** Null until the notes are first written. */
6128
+ updatedAt: Timestamp.nullable()
6129
+ }).meta({ id: "Notes" });
6130
+ strictObject({
6131
+ text: notesText.optional(),
6132
+ /** Added on a line of its own (after a newline, unless the notes are empty or end with one). */
6133
+ append: notesText.min(1).optional()
6134
+ }).refine((patch) => patch.text === void 0 !== (patch.append === void 0), "Send either text or append").meta({
6135
+ id: "NotesPatch",
6136
+ minProperties: 1,
6137
+ maxProperties: 1
6138
+ });
5928
6139
  /** Every error response (RFC 9457, `application/problem+json`). */
5929
6140
  const ProblemSchema = object({
5930
6141
  type: string(),
@@ -6638,7 +6849,7 @@ function matchColumn(columns, query) {
6638
6849
  //#endregion
6639
6850
  //#region src/version.ts
6640
6851
  /** This CLI's version, from package.json (set at build time by tsdown, and by vitest in tests). */
6641
- const VERSION = "0.1.0";
6852
+ const VERSION = "1.1.0";
6642
6853
  /** Sent as X-Monoban-Client, and shown in Devices & tokens. */
6643
6854
  const CLIENT = `cli/${VERSION}`;
6644
6855
  //#endregion
@@ -9980,6 +10191,74 @@ function clone(cwd = process.cwd()) {
9980
10191
  remember: async (key) => await git(cwd, "config", "--local", "monoban.project", key) !== null,
9981
10192
  forget: async () => {
9982
10193
  await git(cwd, "config", "--local", "--unset", "monoban.project");
10194
+ },
10195
+ branch: async () => {
10196
+ const name = await git(cwd, "rev-parse", "--abbrev-ref", "HEAD");
10197
+ return name && name !== "HEAD" ? name : null;
10198
+ },
10199
+ root: async () => await git(cwd, "rev-parse", "--show-toplevel") || cwd
10200
+ };
10201
+ }
10202
+ //#endregion
10203
+ //#region src/github.ts
10204
+ /** `gh` isn't installed. */
10205
+ var NoGh = class extends CliError {
10206
+ constructor() {
10207
+ super("That needs the GitHub CLI (gh), signed in: https://cli.github.com");
10208
+ this.name = "NoGh";
10209
+ }
10210
+ };
10211
+ function gh(cwd, args) {
10212
+ return new Promise((resolve, reject) => {
10213
+ execFile("gh", args, {
10214
+ cwd,
10215
+ timeout: 15e3
10216
+ }, (err, stdout, stderr) => {
10217
+ if (err?.code === "ENOENT") return reject(new NoGh());
10218
+ if (err) return reject(new CliError(`gh: ${String(stderr).trim().split("\n")[0] || err.message}`));
10219
+ try {
10220
+ resolve(JSON.parse(String(stdout)));
10221
+ } catch {
10222
+ reject(new CliError("gh answered something that isn't JSON."));
10223
+ }
10224
+ });
10225
+ });
10226
+ }
10227
+ /** OPEN, CLOSED, MERGED (and a draft pull request) → monoban's states. */
10228
+ function stateOf(state, isDraft = false) {
10229
+ if (state === "MERGED") return "merged";
10230
+ if (state === "CLOSED") return "closed";
10231
+ return isDraft ? "draft" : "open";
10232
+ }
10233
+ function github(cwd = process.cwd()) {
10234
+ return {
10235
+ pullRequest: async (ref) => {
10236
+ const pr = await gh(cwd, [
10237
+ "pr",
10238
+ "view",
10239
+ ...ref ? [ref] : [],
10240
+ "--json",
10241
+ "url,title,state,isDraft"
10242
+ ]);
10243
+ return {
10244
+ url: pr.url,
10245
+ title: pr.title,
10246
+ state: stateOf(pr.state, pr.isDraft)
10247
+ };
10248
+ },
10249
+ issue: async (ref) => {
10250
+ const issue = await gh(cwd, [
10251
+ "issue",
10252
+ "view",
10253
+ ref,
10254
+ "--json",
10255
+ "url,title,state"
10256
+ ]);
10257
+ return {
10258
+ url: issue.url,
10259
+ title: issue.title,
10260
+ state: stateOf(issue.state)
10261
+ };
9983
10262
  }
9984
10263
  };
9985
10264
  }
@@ -9999,6 +10278,16 @@ function openBrowser(url, platform = process.platform) {
9999
10278
  }
10000
10279
  //#endregion
10001
10280
  //#region src/output.ts
10281
+ /** The palette (tags, columns, projects) in the terminal's own 16 colours, so its theme decides the shade. */
10282
+ const ANSI = {
10283
+ grey: 90,
10284
+ blue: 34,
10285
+ amber: 33,
10286
+ green: 32,
10287
+ violet: 35,
10288
+ red: 31,
10289
+ cyan: 36
10290
+ };
10002
10291
  function colorEnabled(env, isTTY) {
10003
10292
  return isTTY && !env.NO_COLOR && env.TERM !== "dumb";
10004
10293
  }
@@ -10006,7 +10295,8 @@ function style(enabled) {
10006
10295
  const sgr = (on, off) => (s) => enabled ? `\x1b[${on}m${s}\x1b[${off}m` : s;
10007
10296
  return {
10008
10297
  bold: sgr(1, 22),
10009
- dim: sgr(2, 22)
10298
+ dim: sgr(2, 22),
10299
+ color: (color, s) => sgr(ANSI[color], 39)(s)
10010
10300
  };
10011
10301
  }
10012
10302
  const DAY = 864e5;
@@ -10088,7 +10378,8 @@ async function createContext(env = process.env, overrides = {}) {
10088
10378
  edit: overrides.edit ?? ((text, name) => editInEditor(text, name, env)),
10089
10379
  readStdin: overrides.readStdin ?? (() => readAll()),
10090
10380
  openUrl: overrides.openUrl ?? ((url) => openBrowser(url)),
10091
- clone: overrides.clone ?? clone()
10381
+ clone: overrides.clone ?? clone(),
10382
+ github: overrides.github ?? github()
10092
10383
  };
10093
10384
  }
10094
10385
  const apis = (ctx) => ({
@@ -10190,7 +10481,7 @@ function page(res, title, text) {
10190
10481
  //#region src/login/device.ts
10191
10482
  /**
10192
10483
  * Device sign-in (RFC 8628): for a terminal without a browser (SSH, a container). The CLI shows a
10193
- * code; you approve it on any signed-in device at monoban.dev/device while the CLI polls.
10484
+ * code; you approve it on any signed-in device at monoban.dev/panel/device while the CLI polls.
10194
10485
  */
10195
10486
  async function deviceLogin({ api, device, show, sleep = wait, now = Date.now }) {
10196
10487
  const start = await unwrap(api.POST("/v1/auth/device", { body: {
@@ -10366,6 +10657,50 @@ async function columnsOf(api, key) {
10366
10657
  })))) all.push(c);
10367
10658
  return all;
10368
10659
  }
10660
+ /** The tags a project's tasks can have (its own and the shared ones), by name. */
10661
+ async function tagsOf(api, key) {
10662
+ const all = [];
10663
+ for await (const t of pages((cursor) => unwrap(api.GET("/v1/tags", { params: { query: {
10664
+ project: key,
10665
+ cursor
10666
+ } } })).then((page) => ({
10667
+ items: page.tags,
10668
+ nextCursor: page.nextCursor
10669
+ })))) all.push(t);
10670
+ return sortTags(all);
10671
+ }
10672
+ /** A task's tags, by name (ids it has that aren't in `tags` are left out). */
10673
+ function tagsOfTask(task, tags) {
10674
+ return sortTags(tags.filter((t) => task.tagIds.includes(t.id)));
10675
+ }
10676
+ /** "#bug #ui", each in its colour. */
10677
+ const tagWords = (tags, style) => tags.map((t) => style.color(t.color, `#${t.name}`)).join(" ");
10678
+ /**
10679
+ * The tags `names` mean in project `key` (any case, a leading # or not). A name that isn't a tag yet
10680
+ * becomes one of the project's, and stderr says so. `tags` gets the new ones too.
10681
+ */
10682
+ async function resolveTags(ctx, api, key, names, tags) {
10683
+ const found = [];
10684
+ for (const given of names) {
10685
+ const name = tagName(given);
10686
+ if (!name) throw new CliError(`"${given}" isn't a tag name: use a word, like bug.`, EXIT.usage);
10687
+ let tag = findTag(tags, name);
10688
+ if (!tag) {
10689
+ tag = await unwrap(api.POST("/v1/tags", { body: {
10690
+ name,
10691
+ project: key
10692
+ } }));
10693
+ tags.push(tag);
10694
+ ctx.err(`Created tag #${tag.name} in ${key}.`);
10695
+ }
10696
+ if (!found.includes(tag)) found.push(tag);
10697
+ }
10698
+ return found;
10699
+ }
10700
+ /** A usage error before the API would refuse more than 10 tags. */
10701
+ function assertTagCount(count) {
10702
+ if (count > LIMITS.tagsPerTask) throw new CliError(`A task can have at most ${LIMITS.tagsPerTask} tags.`, EXIT.usage);
10703
+ }
10369
10704
  /** Your project linked to `repo` (github.com/o/r), if any. */
10370
10705
  async function projectForRepo(api, repo) {
10371
10706
  return (await unwrap(api.GET("/v1/projects", { params: { query: { repo } } }))).projects[0] ?? null;
@@ -10429,22 +10764,23 @@ function changedElsewhere(err, ref) {
10429
10764
  if (err instanceof ApiProblem && err.status === 412) throw new CliError(`${ref} changed elsewhere in the meantime. Run \`monoban show ${ref}\` and try again.`);
10430
10765
  throw err;
10431
10766
  }
10432
- /** A task as the CLI prints it in JSON: the API's fields plus its column's name. */
10433
- const taskJson = (task, columns) => ({
10767
+ /** A task as the CLI prints it in JSON: the API's fields plus its column's name and its tags' names. */
10768
+ const taskJson = (task, columns, tags) => ({
10434
10769
  ...task,
10435
- column: columns.find((c) => c.id === task.columnId)?.name ?? null
10770
+ column: columns.find((c) => c.id === task.columnId)?.name ?? null,
10771
+ tags: tagsOfTask(task, tags).map((t) => t.name)
10436
10772
  });
10437
10773
  /** Where the web shows a project's board, or one task on it. */
10438
10774
  const boardUrl = (ctx, key, number) => `${ctx.webUrl}/p/${key}${number === void 0 ? "" : `?task=${number}`}`;
10439
10775
  //#endregion
10440
10776
  //#region src/commands/board.ts
10441
- const printJson = (ctx, value) => ctx.out(JSON.stringify(value, null, 2));
10777
+ const printJson$1 = (ctx, value) => ctx.out(JSON.stringify(value, null, 2));
10442
10778
  /** `monoban projects`: your projects, with their keys and repositories; * marks this folder's. */
10443
10779
  async function projects(ctx, options) {
10444
10780
  const api = apis(ctx).signedIn;
10445
10781
  const all = await allProjects(api);
10446
10782
  const here = await folderProject(ctx, api);
10447
- if (options.json) return printJson(ctx, all.map((p) => ({
10783
+ if (options.json) return printJson$1(ctx, all.map((p) => ({
10448
10784
  ...p,
10449
10785
  current: p.key === here
10450
10786
  })));
@@ -10464,17 +10800,25 @@ async function projects(ctx, options) {
10464
10800
  }
10465
10801
  }
10466
10802
  const tasks = (p) => `${p.taskCount} ${p.taskCount === 1 ? "task" : "tasks"}`;
10467
- /** `monoban list [COLUMN…]`: the board, by column (every column, or the ones named). */
10803
+ /** `monoban list [COLUMN…]`: the board, by column (every column, or the ones named); `--tag` keeps a tag's tasks. */
10468
10804
  async function list(ctx, columnQueries, options) {
10469
10805
  const api = apis(ctx).signedIn;
10470
10806
  const key = await resolveProject(ctx, api, options.project);
10471
10807
  const board = await unwrap(api.GET("/v1/projects/{key}/board", { params: { path: { key } } }));
10472
- const tasks = board.truncated ? await allTasks(api, key) : board.tasks;
10808
+ let tasks = board.truncated ? await allTasks(api, key) : board.tasks;
10809
+ if (options.tag !== void 0) {
10810
+ const tag = findTag(board.tags, options.tag);
10811
+ if (!tag) {
10812
+ const names = board.tags.map((t) => t.name).join(", ");
10813
+ throw new CliError(`No tag "${options.tag}" in ${key}. ${names ? `The tags are: ${names}.` : "It has no tags yet."}`, EXIT.notFound);
10814
+ }
10815
+ tasks = tasks.filter((t) => t.tagIds.includes(tag.id));
10816
+ }
10473
10817
  const groups = (columnQueries.length ? [...new Set(columnQueries.map((q) => findColumn(board.columns, q)))] : board.columns).map((column) => ({
10474
10818
  column,
10475
10819
  tasks: tasks.filter((t) => t.columnId === column.id)
10476
10820
  }));
10477
- if (options.json) return printJson(ctx, groups.flatMap((g) => g.tasks.map((t) => taskJson(t, board.columns))));
10821
+ if (options.json) return printJson$1(ctx, groups.flatMap((g) => g.tasks.map((t) => taskJson(t, board.columns, board.tags))));
10478
10822
  const { bold, dim } = ctx.style;
10479
10823
  const repo = board.project.repo ? ` · ${board.project.repo}` : "";
10480
10824
  ctx.out(`${bold(board.project.name)} ${dim(`(${board.project.key})${repo}`)}`);
@@ -10485,19 +10829,37 @@ async function list(ctx, columnQueries, options) {
10485
10829
  return `${list ? `[${list.done}/${list.all}] ` : ""}${age(t.updatedAt).padStart(5)}`;
10486
10830
  };
10487
10831
  const metaWidth = Math.max(0, ...rows.map((t) => meta(t).length));
10488
- const titles = rows.map((t) => [...oneLine(t.title)].length);
10489
- const titleWidth = Number.isFinite(ctx.tty.width) ? Math.max(10, ctx.tty.width - (2 + refWidth + 2 + 2 + metaWidth)) : Math.max(0, ...titles);
10832
+ const cell = (t, width) => titleCell(oneLine(t.title), tagsOfTask(t, board.tags), width, ctx.style);
10833
+ const titleWidth = Number.isFinite(ctx.tty.width) ? Math.max(10, ctx.tty.width - (2 + refWidth + 2 + 2 + metaWidth)) : Math.max(0, ...rows.map((t) => visibleLength(cell(t, Number.POSITIVE_INFINITY))));
10490
10834
  for (const { column, tasks: inColumn } of groups) {
10491
10835
  const count = column.wipLimit ? `${inColumn.length}/${column.wipLimit}` : String(inColumn.length);
10492
10836
  ctx.out("");
10493
10837
  ctx.out(`${bold(column.name)} ${dim(count)}`);
10494
10838
  for (const t of inColumn) {
10495
- const title = truncate(oneLine(t.title), titleWidth);
10839
+ const title = cell(t, titleWidth);
10496
10840
  const pad = " ".repeat(Math.max(0, titleWidth - visibleLength(title)));
10497
10841
  ctx.out(` ${dim(t.ref.padEnd(refWidth))} ${title}${pad} ${dim(meta(t).padStart(metaWidth))}`.trimEnd());
10498
10842
  }
10499
10843
  }
10500
10844
  }
10845
+ /**
10846
+ * A title and its tags ("Fix login #bug #ui") in `width` characters: the title is cut first, down to
10847
+ * 10 characters; then tags that don't fit are left out and counted ("+2").
10848
+ */
10849
+ function titleCell(title, tags, width, style) {
10850
+ if (tags.length === 0) return truncate(title, width);
10851
+ const titleLength = [...title].length;
10852
+ for (let shown = tags.length; shown >= 0; shown--) {
10853
+ const hidden = tags.length - shown;
10854
+ const room = width - [...tags.slice(0, shown).map((t) => `#${t.name}`), ...hidden ? [`+${hidden}`] : []].join(" ").length - 2;
10855
+ if (room >= Math.min(titleLength, 10) || shown === 0) {
10856
+ const extra = hidden ? ` ${style.dim(`+${hidden}`)}` : "";
10857
+ const text = shown ? `${tagWords(tags.slice(0, shown), style)}${extra}` : style.dim(`+${hidden}`);
10858
+ return room > 0 ? `${truncate(title, room)} ${text}` : truncate(title, width);
10859
+ }
10860
+ }
10861
+ return truncate(title, width);
10862
+ }
10501
10863
  async function allTasks(api, key) {
10502
10864
  const all = [];
10503
10865
  for await (const t of pages((cursor) => unwrap(api.GET("/v1/projects/{key}/tasks", { params: {
@@ -10517,40 +10879,127 @@ const ago = (iso) => {
10517
10879
  async function show(ctx, ref, options) {
10518
10880
  const api = apis(ctx).signedIn;
10519
10881
  const task = await taskByRef(api, ref);
10520
- const columns = await columnsOf(api, taskRefOf(task.ref).key);
10521
- if (options.json) return printJson(ctx, taskJson(task, columns));
10882
+ const key = taskRefOf(task.ref).key;
10883
+ const [columns, tags] = await Promise.all([columnsOf(api, key), tagsFor(api, key, task)]);
10884
+ if (options.json) return printJson$1(ctx, taskJson(task, columns, tags));
10522
10885
  const { bold, dim } = ctx.style;
10523
10886
  const column = columns.find((c) => c.id === task.columnId)?.name ?? "?";
10524
10887
  const list = checklist(task.description);
10525
10888
  ctx.out(`${bold(task.ref)} ${bold(task.title)}`);
10526
10889
  ctx.out(dim(`${column} · created ${ago(task.createdAt)} · updated ${ago(task.updatedAt)}`));
10890
+ const own = tagsOfTask(task, tags);
10891
+ if (own.length) ctx.out(tagWords(own, ctx.style));
10527
10892
  if (list) ctx.out(dim(`Checklist ${list.done}/${list.all}`));
10893
+ if (task.links.length) {
10894
+ const width = Math.max(...task.links.map((l) => linkLabel(l).length));
10895
+ for (const l of task.links) {
10896
+ const state = l.state ? ` ${dim(l.state)}` : "";
10897
+ ctx.out(`${linkLabel(l).padEnd(width)} ${l.title || dim(l.url)}${state}`);
10898
+ }
10899
+ }
10528
10900
  if (task.description.trim()) {
10529
10901
  ctx.out("");
10530
10902
  ctx.out(task.description.trimEnd());
10531
10903
  }
10532
10904
  }
10533
- /** `monoban add "title"`: a new task, at the end of the first column (or of `-c column`). */
10905
+ /** The project's tags, when `task` has any to name (else none: one request fewer). */
10906
+ const tagsFor = async (api, key, task) => task.tagIds.length ? tagsOf(api, key) : [];
10907
+ /** `monoban add "title"`: a new task, at the end of the first column (or of `-c column`), with `-t` tags. */
10534
10908
  async function add(ctx, title, options) {
10535
10909
  if (options.description !== void 0 && options.edit) throw new CliError("Use -d or -e, not both.", EXIT.usage);
10910
+ const names = options.tag ?? [];
10911
+ assertTagCount(new Set(names).size);
10536
10912
  const api = apis(ctx).signedIn;
10537
10913
  const key = await resolveProject(ctx, api, options.project);
10538
- const columns = await columnsOf(api, key);
10914
+ const [columns, tags] = await Promise.all([columnsOf(api, key), names.length ? tagsOf(api, key) : []]);
10539
10915
  const column = options.column ? findColumn(columns, options.column) : columns[0];
10540
10916
  let description = options.description;
10541
10917
  if (description === "-") description = await ctx.readStdin();
10542
10918
  if (options.edit) description = await ctx.edit("", `${key}-new`);
10543
10919
  description = description?.trimEnd();
10920
+ const tagIds = (await resolveTags(ctx, api, key, names, tags)).map((t) => t.id);
10921
+ assertTagCount(tagIds.length);
10544
10922
  const task = await unwrap(api.POST("/v1/projects/{key}/tasks", {
10545
10923
  params: { path: { key } },
10546
10924
  body: {
10547
10925
  title,
10548
10926
  ...description ? { description } : {},
10549
- ...column ? { columnId: column.id } : {}
10927
+ ...column ? { columnId: column.id } : {},
10928
+ ...tagIds.length ? { tagIds } : {}
10550
10929
  }
10551
10930
  }));
10552
- if (options.json) return printJson(ctx, taskJson(task, columns));
10553
- ctx.out(`Added ${task.ref} to ${column?.name ?? "the board"}: ${task.title}`);
10931
+ if (options.json) return printJson$1(ctx, taskJson(task, columns, tags));
10932
+ const tagged = tagIds.length ? ` ${tagWords(tagsOfTask(task, tags), ctx.style)}` : "";
10933
+ ctx.out(`Added ${task.ref} to ${column?.name ?? "the board"}: ${task.title}${tagged}`);
10934
+ }
10935
+ /** `monoban tag MON-12 bug ui`: puts tags on a task (a name that isn't a tag yet becomes one). */
10936
+ async function tag(ctx, ref, names, options) {
10937
+ const api = apis(ctx).signedIn;
10938
+ const task = await taskByRef(api, ref);
10939
+ const key = taskRefOf(task.ref).key;
10940
+ const tags = await tagsOf(api, key);
10941
+ const adding = (await resolveTags(ctx, api, key, names, tags)).filter((t) => !task.tagIds.includes(t.id));
10942
+ if (adding.length === 0) {
10943
+ if (options.json) return printJson$1(ctx, taskJson(task, await columnsOf(api, key), tags));
10944
+ ctx.err(`${task.ref} already has ${names.length > 1 ? "those tags" : "that tag"}.`);
10945
+ return;
10946
+ }
10947
+ const tagIds = [...task.tagIds, ...adding.map((t) => t.id)];
10948
+ assertTagCount(tagIds.length);
10949
+ const updated = await setTags(api, task, tagIds);
10950
+ if (options.json) return printJson$1(ctx, taskJson(updated, await columnsOf(api, key), tags));
10951
+ ctx.out(`Tagged ${task.ref} ${tagWords(adding, ctx.style)}.`);
10952
+ }
10953
+ /** `monoban untag MON-12 bug`: takes tags off a task (the tags themselves stay). */
10954
+ async function untag(ctx, ref, names, options) {
10955
+ const api = apis(ctx).signedIn;
10956
+ const task = await taskByRef(api, ref);
10957
+ const key = taskRefOf(task.ref).key;
10958
+ const tags = await tagsOf(api, key);
10959
+ const own = tagsOfTask(task, tags);
10960
+ const removing = names.map((name) => {
10961
+ const found = findTag(own, name);
10962
+ if (found) return found;
10963
+ const has = own.length ? `Its tags: ${own.map((t) => t.name).join(", ")}.` : "It has no tags.";
10964
+ throw new CliError(`${task.ref} has no tag "${name}". ${has}`, EXIT.usage);
10965
+ });
10966
+ const updated = await setTags(api, task, task.tagIds.filter((id) => !removing.some((t) => t.id === id)));
10967
+ if (options.json) return printJson$1(ctx, taskJson(updated, await columnsOf(api, key), tags));
10968
+ ctx.out(`Took ${tagWords([...new Set(removing)], ctx.style)} off ${task.ref}.`);
10969
+ }
10970
+ /** A task's tags from now on, only if nobody changed the task since we read it. */
10971
+ function setTags(api, task, tagIds) {
10972
+ const { key, number } = taskRefOf(task.ref);
10973
+ return unwrap(api.PATCH("/v1/projects/{key}/tasks/{number}", {
10974
+ params: {
10975
+ path: {
10976
+ key,
10977
+ number
10978
+ },
10979
+ header: ifMatch(task.version)
10980
+ },
10981
+ body: { tagIds }
10982
+ })).catch((err) => changedElsewhere(err, task.ref));
10983
+ }
10984
+ /** `monoban tags`: the tags a project's tasks can have: its own and the shared ones. */
10985
+ async function tags(ctx, options) {
10986
+ const api = apis(ctx).signedIn;
10987
+ const key = await resolveProject(ctx, api, options.project);
10988
+ const all = await tagsOf(api, key);
10989
+ if (options.json) return printJson$1(ctx, all);
10990
+ if (all.length === 0) {
10991
+ ctx.err(`${key} has no tags yet. Add one with \`monoban tag ${key}-1 NAME\`.`);
10992
+ return;
10993
+ }
10994
+ const { dim } = ctx.style;
10995
+ const nameWidth = Math.max(...all.map((t) => [...t.name].length + 1));
10996
+ const whereWidth = Math.max(...all.map((t) => (t.project ?? "shared").length));
10997
+ for (const t of all) {
10998
+ const name = tagWords([t], ctx.style) + " ".repeat(nameWidth - [...t.name].length - 1);
10999
+ const where = (t.project ?? "shared").padEnd(whereWidth);
11000
+ const count = `${t.taskCount} ${t.taskCount === 1 ? "task" : "tasks"}`;
11001
+ ctx.out(`${name} ${dim(where)} ${dim(count)}`);
11002
+ }
10554
11003
  }
10555
11004
  /** `monoban move MON-12 done`: to the end of another column. */
10556
11005
  async function move(ctx, ref, columnQuery, options) {
@@ -10569,8 +11018,9 @@ async function done(ctx, ref, options) {
10569
11018
  await moveTo(ctx, api, task, columns, target, options);
10570
11019
  }
10571
11020
  async function moveTo(ctx, api, task, columns, target, options) {
11021
+ const json = async (t) => printJson$1(ctx, taskJson(t, columns, await tagsFor(api, taskRefOf(t.ref).key, t)));
10572
11022
  if (task.columnId === target.id) {
10573
- if (options.json) return printJson(ctx, taskJson(task, columns));
11023
+ if (options.json) return json(task);
10574
11024
  ctx.out(`${task.ref} is already in ${target.name}.`);
10575
11025
  return;
10576
11026
  }
@@ -10586,16 +11036,29 @@ async function moveTo(ctx, api, task, columns, target, options) {
10586
11036
  },
10587
11037
  body: { columnId: target.id }
10588
11038
  })).catch((err) => changedElsewhere(err, task.ref));
10589
- if (options.json) return printJson(ctx, taskJson(moved, columns));
11039
+ if (options.json) return json(moved);
10590
11040
  ctx.out(`Moved ${task.ref}${from ? ` from ${from}` : ""} to ${target.name}.`);
10591
11041
  }
10592
- /** `monoban edit MON-12`: the title (first line) and description in $EDITOR. */
11042
+ /**
11043
+ * `monoban edit MON-12`: the title (first line) and description in $EDITOR; or, without an editor
11044
+ * (scripts, agents), `--title` and `-d` (`-` reads it from stdin) replace what they name.
11045
+ */
10593
11046
  async function edit(ctx, ref, options) {
10594
11047
  const api = apis(ctx).signedIn;
10595
11048
  const task = await taskByRef(api, ref);
10596
- const text = await ctx.edit(taskText(task.title, task.description), task.ref);
10597
- const { title, description } = parseTaskText(text);
10598
- if (!title) throw new CliError("The title (the first line) is empty, so nothing changed.");
11049
+ const direct = options.title !== void 0 || options.description !== void 0;
11050
+ let text = "";
11051
+ let title;
11052
+ let description;
11053
+ if (direct) {
11054
+ title = (options.title ?? task.title).trim();
11055
+ description = options.description === void 0 ? task.description.trimEnd() : (options.description === "-" ? await ctx.readStdin() : options.description).trimEnd();
11056
+ if (!title) throw new CliError("The title can't be empty.", EXIT.usage);
11057
+ } else {
11058
+ text = await ctx.edit(taskText(task.title, task.description), task.ref);
11059
+ ({title, description} = parseTaskText(text));
11060
+ if (!title) throw new CliError("The title (the first line) is empty, so nothing changed.");
11061
+ }
10599
11062
  const patch = {
10600
11063
  ...title !== task.title ? { title } : {},
10601
11064
  ...description !== task.description.trimEnd() ? { description } : {}
@@ -10618,11 +11081,16 @@ async function edit(ctx, ref, options) {
10618
11081
  body: patch
10619
11082
  }));
10620
11083
  } catch (err) {
10621
- const draft = await keepDraft(text, task.ref);
10622
- ctx.err(`Your text is saved in ${draft}.`);
11084
+ if (!direct || options.description === "-") {
11085
+ const draft = direct ? taskText(title, description) : text;
11086
+ ctx.err(`Your text is saved in ${await keepDraft(draft, task.ref)}.`);
11087
+ }
10623
11088
  changedElsewhere(err, task.ref);
10624
11089
  }
10625
- if (options.json) return printJson(ctx, taskJson(updated, await columnsOf(api, key)));
11090
+ if (options.json) {
11091
+ const [columns, tags] = await Promise.all([columnsOf(api, key), tagsFor(api, key, updated)]);
11092
+ return printJson$1(ctx, taskJson(updated, columns, tags));
11093
+ }
10626
11094
  ctx.out(`Updated ${task.ref}.`);
10627
11095
  }
10628
11096
  /** `monoban rm MON-12`: asks first, unless -y. */
@@ -10644,7 +11112,7 @@ async function rm$1(ctx, ref, options) {
10644
11112
  },
10645
11113
  header: ifMatch(task.version)
10646
11114
  } })).catch((err) => changedElsewhere(err, task.ref));
10647
- if (options.json) return printJson(ctx, deleted);
11115
+ if (options.json) return printJson$1(ctx, deleted);
10648
11116
  ctx.out(`Deleted ${task.ref}.`);
10649
11117
  }
10650
11118
  /** `monoban open [MON-12]`: the task, or the board, in the browser (and the link on stdout). */
@@ -10657,7 +11125,7 @@ async function open$1(ctx, ref, options) {
10657
11125
  url = boardUrl(ctx, await resolveProject(ctx, apis(ctx).signedIn, options.project));
10658
11126
  } catch (err) {
10659
11127
  if (!(err instanceof CliError) || err.exitCode !== EXIT.usage || options.project) throw err;
10660
- url = `${ctx.webUrl}/`;
11128
+ url = ctx.webUrl;
10661
11129
  }
10662
11130
  ctx.out(url);
10663
11131
  if (ctx.env.MONOBAN_NO_OPEN !== "1" && canOpenBrowser(ctx.env)) ctx.openUrl(url);
@@ -10693,7 +11161,7 @@ async function link(ctx, key, options) {
10693
11161
  body: { repo }
10694
11162
  })).catch((err) => projectChanged(err, target.key));
10695
11163
  await ctx.clone.remember(linked.key);
10696
- if (options.json) return printJson(ctx, linked);
11164
+ if (options.json) return printJson$1(ctx, linked);
10697
11165
  const was = target.repo && target.repo !== repo ? ` (instead of ${target.repo})` : "";
10698
11166
  ctx.out(`Linked ${linked.key} to ${repo}${was}. Commands in this clone now use ${linked.key}.`);
10699
11167
  }
@@ -10716,7 +11184,7 @@ async function unlink(ctx, options) {
10716
11184
  body: { repo: null }
10717
11185
  })).catch((err) => projectChanged(err, linked.key));
10718
11186
  await ctx.clone.forget();
10719
- if (options.json) return printJson(ctx, project ?? null);
11187
+ if (options.json) return printJson$1(ctx, project ?? null);
10720
11188
  ctx.out(linked ? `Unlinked ${linked.key} from ${origin?.repo}.` : `This clone no longer uses ${remembered}.`);
10721
11189
  }
10722
11190
  function projectChanged(err, key) {
@@ -10724,11 +11192,369 @@ function projectChanged(err, key) {
10724
11192
  throw err;
10725
11193
  }
10726
11194
  //#endregion
11195
+ //#region src/commands/links.ts
11196
+ const printJson = (ctx, value) => ctx.out(JSON.stringify(value, null, 2));
11197
+ /** "#54 "Add invoices" (open)": a link as a message names it. */
11198
+ function linkWords(link) {
11199
+ return [
11200
+ linkLabel(link),
11201
+ link.title && `"${link.title}"`,
11202
+ link.state && `(${link.state})`
11203
+ ].filter(Boolean).join(" ");
11204
+ }
11205
+ /** The task a branch is named after: mon-12-invoices → MON-12. */
11206
+ function taskOfBranch(branch) {
11207
+ const match = branch ? /(?:^|[^A-Za-z0-9])([A-Za-z][A-Za-z0-9]{1,4}-[1-9][0-9]{0,8})(?![0-9])/.exec(branch) : null;
11208
+ const parsed = match?.[1] ? parseTaskRef(match[1]) : null;
11209
+ return parsed ? `${parsed.key}-${parsed.number}` : null;
11210
+ }
11211
+ /**
11212
+ * `monoban attach [MON-12] [URL]`: a link on a task. `--pr` is this branch's pull request, read with `gh`
11213
+ * (so its title and state come along); a GitHub pull request or issue URL is read with `gh` too, when it
11214
+ * can be. Without a task, the one the branch is named after. Attaching a link again refreshes it.
11215
+ */
11216
+ async function attach(ctx, args, options) {
11217
+ let ref;
11218
+ let url;
11219
+ for (const arg of args) if (!url && parseLink(arg)) url = arg;
11220
+ else if (!ref) ref = arg;
11221
+ else throw new CliError(`"${arg}" isn't a web link.`, EXIT.usage);
11222
+ if (url && options.pr) throw new CliError("Give a link or --pr, not both.", EXIT.usage);
11223
+ if (!url && !options.pr) throw new CliError(`${ref && !parseTaskRef(ref) ? `"${ref}" isn't a web link. ` : ""}Give a link, or --pr for this branch's pull request.`, EXIT.usage);
11224
+ ref ??= taskOfBranch(await ctx.clone.branch()) ?? void 0;
11225
+ if (!ref) throw new CliError("Which task? Name it (`monoban attach MON-12 …`), or run it on a branch named after it (mon-12-…).", EXIT.usage);
11226
+ taskRefOf(ref);
11227
+ let item = null;
11228
+ if (options.pr) {
11229
+ item = await ctx.github.pullRequest();
11230
+ url = item.url;
11231
+ }
11232
+ const parsed = parseLink(url);
11233
+ if (!parsed) throw new CliError(`"${url}" isn't a web link.`, EXIT.usage);
11234
+ if (!item && (parsed.kind === "pr" || parsed.kind === "issue")) try {
11235
+ item = await (parsed.kind === "pr" ? ctx.github.pullRequest(parsed.url) : ctx.github.issue(parsed.url));
11236
+ } catch (err) {
11237
+ if (!(err instanceof NoGh)) ctx.err(`Couldn't read it with gh (${err.message}); attaching it as it is.`);
11238
+ }
11239
+ const api = apis(ctx).signedIn;
11240
+ const task = await taskByRef(api, ref);
11241
+ const had = task.links.some((l) => l.url === parsed.url);
11242
+ const { key, number } = taskRefOf(task.ref);
11243
+ const title = options.title ?? item?.title;
11244
+ const link = await unwrap(api.POST("/v1/projects/{key}/tasks/{number}/links", {
11245
+ params: { path: {
11246
+ key,
11247
+ number
11248
+ } },
11249
+ body: {
11250
+ url: parsed.url,
11251
+ ...title !== void 0 && { title },
11252
+ ...item && { state: item.state }
11253
+ }
11254
+ }));
11255
+ if (options.json) return printJson(ctx, link);
11256
+ ctx.out(`${had ? "Updated" : "Attached"} ${linkWords(link)} ${had ? "on" : "to"} ${task.ref}.`);
11257
+ }
11258
+ /** `monoban detach MON-12 #54`: takes a link off (by its number, its URL, or where it points). */
11259
+ async function detach(ctx, ref, which, options) {
11260
+ const api = apis(ctx).signedIn;
11261
+ const task = await taskByRef(api, ref);
11262
+ const wanted = which.trim();
11263
+ const number = /^#?([1-9][0-9]*)$/.exec(wanted)?.[1];
11264
+ const url = parseLink(wanted)?.url;
11265
+ const found = task.links.filter((l) => number ? l.number === Number(number) : l.url === url || l.id === wanted || linkLabel(l) === wanted);
11266
+ if (found.length !== 1) {
11267
+ const has = task.links.length ? `Its links: ${task.links.map(linkLabel).join(", ")}.` : "It has no links.";
11268
+ throw new CliError(`${found.length ? `"${wanted}" could be ${found.map((l) => l.url).join(" or ")}: give the URL.` : `${task.ref} has no link "${wanted}".`} ${found.length ? "" : has}`.trim(), found.length ? EXIT.usage : EXIT.notFound);
11269
+ }
11270
+ const link = found[0];
11271
+ const { key, number: n } = taskRefOf(task.ref);
11272
+ const removed = await unwrap(api.DELETE("/v1/projects/{key}/tasks/{number}/links/{linkId}", { params: {
11273
+ path: {
11274
+ key,
11275
+ number: n,
11276
+ linkId: link.id
11277
+ },
11278
+ header: ifMatch(link.version)
11279
+ } })).catch((err) => changedElsewhere(err, task.ref));
11280
+ if (options.json) return printJson(ctx, removed);
11281
+ ctx.out(`Removed ${linkLabel(link)} from ${task.ref}.`);
11282
+ }
11283
+ //#endregion
11284
+ //#region src/commands/notes.ts
11285
+ const printNotes = (ctx, key, notes) => ctx.out(JSON.stringify({
11286
+ project: key,
11287
+ ...notes
11288
+ }, null, 2));
11289
+ /** `monoban notes`: the project's notes as they are, for reading, a pager or a pipe. */
11290
+ async function notesShow(ctx, options) {
11291
+ const api = apis(ctx).signedIn;
11292
+ const key = await resolveProject(ctx, api, options.project);
11293
+ const notes = await unwrap(api.GET("/v1/projects/{key}/notes", { params: { path: { key } } }));
11294
+ if (options.json) return printNotes(ctx, key, notes);
11295
+ if (!notes.text) {
11296
+ ctx.err(`${key} has no notes yet. Add a line with \`monoban notes add …\`, or write them with \`monoban notes edit\`.`);
11297
+ return;
11298
+ }
11299
+ ctx.out(notes.text.replace(/\n$/, ""));
11300
+ }
11301
+ /** `monoban notes add TEXT…`: a line at the end of the notes (`-` reads it from stdin). */
11302
+ async function notesAdd(ctx, words, options) {
11303
+ const text = words.length === 1 && words[0] === "-" ? (await ctx.readStdin()).replace(/\n$/, "") : words.join(" ");
11304
+ if (!text.trim()) throw new CliError("Nothing to add: give the text, or - to read it from stdin.", EXIT.usage);
11305
+ const api = apis(ctx).signedIn;
11306
+ const key = await resolveProject(ctx, api, options.project);
11307
+ const notes = await unwrap(api.PATCH("/v1/projects/{key}/notes", {
11308
+ params: { path: { key } },
11309
+ body: { append: text }
11310
+ }));
11311
+ if (options.json) return printNotes(ctx, key, notes);
11312
+ ctx.out(`Added to the notes of ${key}.`);
11313
+ }
11314
+ /** `monoban notes edit`: the notes in $EDITOR, saved only if nobody changed them in the meantime. */
11315
+ async function notesEdit(ctx, options) {
11316
+ const api = apis(ctx).signedIn;
11317
+ const key = await resolveProject(ctx, api, options.project);
11318
+ const notes = await unwrap(api.GET("/v1/projects/{key}/notes", { params: { path: { key } } }));
11319
+ const text = await ctx.edit(notes.text, `${key}-notes`);
11320
+ if (text === notes.text) {
11321
+ ctx.err(`No changes to the notes of ${key}.`);
11322
+ return;
11323
+ }
11324
+ let saved;
11325
+ try {
11326
+ saved = await unwrap(api.PATCH("/v1/projects/{key}/notes", {
11327
+ params: {
11328
+ path: { key },
11329
+ header: ifMatch(notes.version)
11330
+ },
11331
+ body: { text }
11332
+ }));
11333
+ } catch (err) {
11334
+ const draft = await keepDraft(text, `${key}-notes`);
11335
+ ctx.err(`Your text is saved in ${draft}.`);
11336
+ if (err instanceof ApiProblem && err.status === 412) throw new CliError(`The notes of ${key} changed elsewhere in the meantime. Run \`monoban notes edit\` again.`);
11337
+ throw err;
11338
+ }
11339
+ if (options.json) return printNotes(ctx, key, saved);
11340
+ ctx.out(`Updated the notes of ${key}.`);
11341
+ }
11342
+ //#endregion
11343
+ //#region src/skill.ts
11344
+ /** The coding agents `monoban setup` teaches monoban to. */
11345
+ const AGENTS = ["claude", "codex"];
11346
+ const AGENT_NAMES = {
11347
+ claude: "Claude Code",
11348
+ codex: "Codex"
11349
+ };
11350
+ /** Marks a SKILL.md that `monoban setup` wrote, so running it again may replace it. */
11351
+ const MARKER = "<!-- Written by `monoban setup`";
11352
+ const DESCRIPTION = "Plan and track work on the user's monoban.dev kanban board with the `monoban` CLI. Use when planning a feature or any multi-step change (offer to break the plan into board tasks, tagged by phase), when the user mentions monoban, their board or a task like MON-12, asks what to work on next, or is working on a task that is on the board.";
11353
+ /**
11354
+ * Commands Claude Code may run without asking: they only read. (`Bash(x *)` matches a bare `x` too, and
11355
+ * Claude Code checks each part of a pipe or `&&` on its own.) Anything that writes still asks.
11356
+ */
11357
+ const READ_ONLY = [
11358
+ "monoban whoami",
11359
+ "monoban projects",
11360
+ "monoban list",
11361
+ "monoban ls",
11362
+ "monoban show",
11363
+ "monoban tags",
11364
+ "monoban notes show"
11365
+ ];
11366
+ /** The skill's SKILL.md for `agent`: frontmatter for that agent, then the same instructions. */
11367
+ function skillFile(agent) {
11368
+ return `${[
11369
+ "---",
11370
+ "name: monoban",
11371
+ `description: ${JSON.stringify(DESCRIPTION)}`,
11372
+ ...agent === "claude" ? [`allowed-tools: ${READ_ONLY.map((c) => `Bash(${c} *)`).join(" ")}`] : [],
11373
+ "---"
11374
+ ].join("\n")}\n\n${MARKER} (monoban ${VERSION}). Run it again to update this file. -->\n\n${BODY}`;
11375
+ }
11376
+ const BODY = `# monoban
11377
+
11378
+ monoban.dev is the user's keyboard-first kanban board, and \`monoban\` is its command line. Use it to turn
11379
+ plans into tasks on the board and to keep those tasks current while you work.
11380
+
11381
+ - A **project** has a key (\`MON\`), columns the user named (often Backlog, In progress, In review, Done),
11382
+ tags, and one free-text **notes** file (\`notes.md\` in the web app).
11383
+ - A **task** is \`MON-12\`: a title, a Markdown description, tags, links (pull requests, pages), and a column. \`- [ ]\` / \`- [x]\` lines in
11384
+ the description are its checklist; the board shows the progress (\`[2/5]\`).
11385
+
11386
+ ## First
11387
+
11388
+ 1. \`monoban whoami\`. Exit code 4 means not signed in: ask the user to run \`monoban login\` themselves (it
11389
+ opens a browser). Never sign in for them, and never read, print or ask for tokens.
11390
+ 2. Which project: in a repository linked with \`monoban link\` (or with \`MONOBAN_PROJECT\` set) commands use
11391
+ that project. Otherwise \`monoban projects\` lists the keys; pass \`-p KEY\` to project commands. If it's
11392
+ unclear which project the work belongs to, ask. Suggest \`monoban link KEY\` to the user rather than
11393
+ running it (it changes the project).
11394
+ 3. Read with \`--json\`: \`monoban list --json\` (every task, with its \`column\` and \`tags\`),
11395
+ \`monoban show MON-12 --json\`, \`monoban tags --json\`, and \`monoban notes show\` for the notes.
11396
+
11397
+ If a command can't reach the API (a sandbox without network), ask the user to allow it; don't work around it.
11398
+
11399
+ ## When you make a plan: offer tasks
11400
+
11401
+ When you plan work with several steps (a feature, a migration, a refactor), offer to put it on the board.
11402
+
11403
+ 1. Read the board first (\`monoban list --json\`, \`monoban tags\`), so you reuse existing tasks and tags
11404
+ instead of adding duplicates.
11405
+ 2. **Propose, don't create.** Show the breakdown, grouped by phase, and ask before writing anything:
11406
+
11407
+ \`\`\`
11408
+ Add these 5 tasks to MON?
11409
+ phase-1 Add the invoices table and its API route
11410
+ phase-1 Show invoices on the account page
11411
+ phase-2 Email a receipt when an invoice is paid
11412
+ phase-2 Let users download an invoice as a PDF
11413
+ phase-3 Remove the old billing page
11414
+ \`\`\`
11415
+
11416
+ The user may change, drop or reorder tasks. Create them only after they agree.
11417
+ 3. Create them in order (each goes to the end of the first column, or of \`-c COLUMN\`):
11418
+
11419
+ \`\`\`sh
11420
+ monoban add "Add the invoices table and its API route" -t phase-1 -d - <<'EOF'
11421
+ Why: invoices live in Stripe only, so the account page can't list them.
11422
+
11423
+ - [ ] migration for invoices
11424
+ - [ ] GET /v1/invoices, with tests
11425
+ EOF
11426
+ \`\`\`
11427
+
11428
+ 4. Say which refs you created (\`MON-31\`…\`MON-35\`). If the user wants it, keep a short summary of the plan
11429
+ in the project's notes: \`monoban notes add -\` appends stdin as the last lines.
11430
+
11431
+ Good tasks:
11432
+ - One reviewable change each (about a commit or a pull request), not every small step: small steps go in
11433
+ the task's checklist.
11434
+ - Titles are short and imperative ("Add…", "Fix…", "Remove…"), at most ${LIMITS.taskTitle} characters.
11435
+ - The description says why, and ends with a checklist of what "done" means.
11436
+
11437
+ ## Phases are tags
11438
+
11439
+ Tag each task with its phase: \`phase-1\`, \`phase-2\`, … in the order the work should happen, one phase tag
11440
+ per task. A tag that doesn't exist yet is created in the project on first use. \`monoban list --tag phase-2\`
11441
+ shows one phase.
11442
+
11443
+ - If \`monoban tags\` shows phase tags still on unfinished tasks from an earlier plan, say so in your
11444
+ proposal and ask whether to continue the numbering or reuse them.
11445
+ - Other tags are fine alongside (\`bug\`, \`api\`); reuse the project's existing ones. A tag is one word
11446
+ (no spaces, not starting with \`-\` or \`#\`), at most ${LIMITS.tagName} characters; a task has at most
11447
+ ${LIMITS.tagsPerTask} tags.
11448
+
11449
+ ## While you work
11450
+
11451
+ Ask once before you start updating the board in a session ("Shall I keep MON-31…MON-35 up to date as I
11452
+ go?"). Once the user agrees:
11453
+
11454
+ - Starting a task: \`monoban move MON-31 "in progress"\` (columns match in any case, or by a unique prefix;
11455
+ use the names \`monoban list\` shows).
11456
+ - Ticking the checklist: read the description (\`monoban show MON-31 --json\`), change \`- [ ]\` to \`- [x]\`,
11457
+ and write the whole description back with \`monoban edit MON-31 -d -\` (stdin, a heredoc as above).
11458
+ - Opened a pull request for it: \`monoban attach MON-31 --pr\` right after \`gh pr create\` (on a branch named
11459
+ after the task, like \`mon-31-invoices\`, \`monoban attach --pr\` finds the task itself). The card shows it.
11460
+ - Finished: \`monoban done MON-31\`, when the work is really done by the user's standard (tests pass, merged,
11461
+ or whatever they said). If unsure, ask. After a merge, attach the pull request again
11462
+ (\`monoban attach MON-31 <its URL>\`) so the board shows it merged.
11463
+ - New work you discover: propose a task; don't add it silently.
11464
+
11465
+ "changed elsewhere" means someone edited the task since you read it: read it again, then retry once.
11466
+
11467
+ ## Rules
11468
+
11469
+ - Never delete a task (\`monoban rm\`) unless the user asked to delete that task.
11470
+ - Avoid interactive commands: \`monoban edit\` without \`--title\`/\`-d\` and \`monoban notes edit\` open an
11471
+ editor, \`monoban login\` a browser, and \`monoban rm\` asks for confirmation. Use flags and stdin.
11472
+ - Results are on stdout, messages on stderr. Exit codes: 0 ok, 1 error, 2 usage, 4 not signed in,
11473
+ 5 not found.
11474
+
11475
+ ## Commands
11476
+
11477
+ | Command | Does |
11478
+ | --- | --- |
11479
+ | \`monoban projects\` | the projects and their keys |
11480
+ | \`monoban list [COLUMN…] [--tag TAG]\` | tasks by column |
11481
+ | \`monoban show MON-12\` | one task in full |
11482
+ | \`monoban tags\` | the tags the project's tasks can have |
11483
+ | \`monoban notes show\` | the project's notes |
11484
+ | \`monoban add "TITLE" [-c COLUMN] [-t TAG]… [-d TEXT \\| -d -]\` | add a task |
11485
+ | \`monoban edit MON-12 [--title TEXT] [-d TEXT \\| -d -]\` | replace its title or description |
11486
+ | \`monoban move MON-12 COLUMN\` | move it to the end of a column |
11487
+ | \`monoban done MON-12\` | move it to Done |
11488
+ | \`monoban tag MON-12 TAG…\` / \`monoban untag MON-12 TAG…\` | put tags on it / take them off |
11489
+ | \`monoban attach MON-12 --pr\` or \`monoban attach MON-12 URL\` | attach this branch's pull request, or any link |
11490
+ | \`monoban notes add TEXT\` (or \`-\` for stdin) | add lines at the end of the notes |
11491
+
11492
+ Every command takes \`--json\`; project commands take \`-p KEY\`. \`monoban COMMAND --help\` has the rest.
11493
+ `;
11494
+ //#endregion
11495
+ //#region src/commands/setup.ts
11496
+ /** Where each agent looks for skills: in your home folder, or in a repository (`--project`). */
11497
+ const FOLDER = {
11498
+ claude: ".claude",
11499
+ codex: ".agents"
11500
+ };
11501
+ /**
11502
+ * The skill's file: ~/.claude/skills/monoban/SKILL.md (or ~/.agents/… for Codex), or with --project the
11503
+ * same at the top of the repository; and how to show it ("~/.claude/…", or ".claude/…" in the repository).
11504
+ */
11505
+ async function skillPath(ctx, agent, project = false) {
11506
+ const base = project ? await ctx.clone.root() : ctx.env.HOME || homedir();
11507
+ const inside = join(FOLDER[agent], "skills", "monoban", "SKILL.md");
11508
+ return {
11509
+ path: join(base, inside),
11510
+ shown: project ? inside : join("~", inside)
11511
+ };
11512
+ }
11513
+ const read = (path) => readFile(path, "utf8").catch((err) => {
11514
+ if (err.code === "ENOENT") return null;
11515
+ throw err;
11516
+ });
11517
+ /**
11518
+ * `monoban setup claude|codex`: installs the monoban skill, which teaches the agent the CLI, to offer a
11519
+ * plan as board tasks (phases as tags) and to keep them current. Running it again updates the skill;
11520
+ * a SKILL.md it didn't write is replaced only with --force.
11521
+ */
11522
+ async function setup(ctx, agent, options) {
11523
+ const name = AGENT_NAMES[agent];
11524
+ const content = skillFile(agent);
11525
+ if (options.print) return ctx.out(content.trimEnd());
11526
+ const { path, shown } = await skillPath(ctx, agent, options.project);
11527
+ const existing = await read(path);
11528
+ const ours = existing?.includes("<!-- Written by `monoban setup`") ?? false;
11529
+ const report = (action, message) => options.json ? ctx.out(JSON.stringify({
11530
+ agent,
11531
+ path,
11532
+ action
11533
+ }, null, 2)) : ctx.out(message);
11534
+ if (existing !== null && !ours && !options.force) throw new CliError(`${shown} is a monoban skill that \`monoban setup\` didn't write. Pass --force to ${options.remove ? "remove" : "replace"} it.`);
11535
+ if (options.remove) {
11536
+ if (existing === null) {
11537
+ if (options.json) return report("none", "");
11538
+ return ctx.err(`The monoban skill isn't installed for ${name} at ${shown}.`);
11539
+ }
11540
+ await rm(path);
11541
+ await rmdir(dirname(path)).catch(() => {});
11542
+ return report("removed", `Removed the monoban skill for ${name}: ${shown}.`);
11543
+ }
11544
+ if (existing === content) return report("unchanged", `The monoban skill for ${name} is up to date: ${shown}.`);
11545
+ await mkdir(dirname(path), { recursive: true });
11546
+ await writeFile(path, content);
11547
+ report(existing === null ? "installed" : "updated", `${existing === null ? "Installed" : "Updated"} the monoban skill for ${name}: ${shown}.`);
11548
+ if (options.json) return;
11549
+ if (agent === "claude") ctx.err(`It lets Claude run commands that only read (${READ_ONLY.map((c) => c.slice(8)).join(", ")}) without asking.`);
11550
+ ctx.err(options.project ? `Commit it so everyone working in this repository gets it. New ${name} sessions use it.` : `New ${name} sessions use it, in any repository. Ask one to plan something, or say "put it on monoban".`);
11551
+ }
11552
+ //#endregion
10727
11553
  //#region src/complete.ts
10728
11554
  /**
10729
11555
  * Shell completion (`monoban completion bash|zsh|fish`). The scripts are thin: on Tab they run
10730
11556
  * `monoban __complete -- WORD… CURRENT`, which prints one `value<TAB>description` per line. Commands and
10731
- * options come from the command tree; project keys, columns and tasks from the API (when signed in).
11557
+ * options come from the command tree; project keys, columns, tasks and tags from the API (when signed in).
10732
11558
  */
10733
11559
  const SHELLS = [
10734
11560
  "bash",
@@ -10741,7 +11567,9 @@ const VALUES = {
10741
11567
  key: "projects",
10742
11568
  column: "columns",
10743
11569
  columns: "columns",
10744
- task: "tasks"
11570
+ task: "tasks",
11571
+ tag: "tags",
11572
+ tags: "tags"
10745
11573
  };
10746
11574
  const takesValue = (option) => option.required || option.optional;
10747
11575
  /** What can come next, for `words` (everything after `monoban`, the last one being the word being typed). */
@@ -10797,6 +11625,7 @@ function values(name, choices, lookup, project, current) {
10797
11625
  case "projects": return lookup.projects();
10798
11626
  case "columns": return lookup.columns(project);
10799
11627
  case "tasks": return lookup.tasks(/^([^-\s]+)-/.exec(current)?.[1] ?? project);
11628
+ case "tags": return lookup.tags(project);
10800
11629
  default: return [];
10801
11630
  }
10802
11631
  }
@@ -10835,7 +11664,11 @@ function apiLookup(ctx, deadlineMs = 2e3) {
10835
11664
  value: t.ref,
10836
11665
  description: `${t.title} (${columns.get(t.columnId)})`
10837
11666
  }));
10838
- }
11667
+ },
11668
+ tags: async (project) => (await tagsOf(api, await resolveProject(ctx, api, project))).map((t) => ({
11669
+ value: t.name,
11670
+ description: t.project ? `${t.project} only` : "shared"
11671
+ }))
10839
11672
  };
10840
11673
  }
10841
11674
  /** `monoban __complete`: the lines for the shell. Quiet on any error (not signed in, offline…). */
@@ -10966,7 +11799,7 @@ async function latestVersion(ctx) {
10966
11799
  async function upgrade(ctx, options, kind = thisInstall()) {
10967
11800
  const latest = await latestVersion(ctx);
10968
11801
  const { how, command } = UPGRADE[kind];
10969
- const outdated = latest !== null && newer(latest, "0.1.0");
11802
+ const outdated = latest !== null && newer(latest, "1.1.0");
10970
11803
  if (options.json) {
10971
11804
  ctx.out(JSON.stringify({
10972
11805
  version: VERSION,
@@ -10988,22 +11821,35 @@ function program(ctx) {
10988
11821
  const cli = new Command("monoban").description("monoban.dev from your terminal: a keyboard-first kanban board.").version(VERSION, "-v, --version").showHelpAfterError("(run `monoban --help` for usage)").exitOverride();
10989
11822
  const json = () => new Option("--json", "print JSON");
10990
11823
  const project = () => new Option("-p, --project <key>", "the project (else $MONOBAN_PROJECT, or your only project)");
11824
+ const collect = (value, previous = []) => [...previous, value];
10991
11825
  cli.command("login").description("Sign in: approve in your browser, with --device a code on any other device, or --with-token (CI)").option("--device", "sign in with a code (for SSH, containers, or no browser)").option("--browser", "open the browser even over SSH").option("--with-token", "use a personal access token (for CI), read from stdin").action(async (options) => login(await ctx(), options));
10992
11826
  cli.command("logout").description("Sign out, here and on the server").action(async () => logout(await ctx()));
10993
11827
  cli.command("whoami").description("Show who you're signed in as").addOption(json()).action(async (options) => whoami(await ctx(), options));
10994
11828
  cli.command("projects").description("List your projects and their keys").addOption(json()).action(async (options) => projects(await ctx(), options));
10995
11829
  cli.command("link").argument("[key]", "the project (else the one already linked, or your only one)").description("Link a project to this clone's GitHub repository, so commands here use it").addOption(json()).action(async (key, options) => link(await ctx(), key, options));
10996
11830
  cli.command("unlink").description("Undo `monoban link` for this clone's repository").addOption(json()).action(async (options) => unlink(await ctx(), options));
10997
- cli.command("list").alias("ls").argument("[columns...]", "only these columns (any case; a prefix works: `back`, `inp`)").description("Show the board's tasks by column").addOption(project()).addOption(json()).action(async (columns, options) => list(await ctx(), columns, options));
10998
- cli.command("show").argument("<task>", "like MON-12").description("Show a task: title, column, checklist and description").addOption(json()).action(async (ref, options) => show(await ctx(), ref, options));
10999
- cli.command("add").argument("<title>").description("Add a task (to the end of the first column, or of -c)").option("-c, --column <column>", "the column to add it to").option("-d, --description <text>", "its description (- reads it from stdin)").option("-e, --edit", "write the description in $EDITOR").addOption(project()).addOption(json()).action(async (title, options) => add(await ctx(), title, options));
11831
+ cli.command("list").alias("ls").argument("[columns...]", "only these columns (any case; a prefix works: `back`, `inp`)").description("Show the board's tasks by column").option("-t, --tag <tag>", "only tasks with this tag").addOption(project()).addOption(json()).action(async (columns, options) => list(await ctx(), columns, options));
11832
+ cli.command("show").argument("<task>", "like MON-12").description("Show a task: title, column, tags, checklist and description").addOption(json()).action(async (ref, options) => show(await ctx(), ref, options));
11833
+ cli.command("add").argument("<title>").description("Add a task (to the end of the first column, or of -c)").option("-c, --column <column>", "the column to add it to").option("-d, --description <text>", "its description (- reads it from stdin)").option("-e, --edit", "write the description in $EDITOR").option("-t, --tag <tag>", "a tag (repeat for more; a new name makes a tag)", collect).addOption(project()).addOption(json()).action(async (title, options) => add(await ctx(), title, options));
11000
11834
  cli.command("move").argument("<task>", "like MON-12").argument("<column>", "where to (any case; a prefix works)").description("Move a task to the end of another column").addOption(json()).action(async (ref, column, options) => move(await ctx(), ref, column, options));
11001
11835
  cli.command("done").argument("<task>", "like MON-12").description("Move a task to Done (or the last column)").addOption(json()).action(async (ref, options) => done(await ctx(), ref, options));
11002
- cli.command("edit").argument("<task>", "like MON-12").description("Edit a task's title (the first line) and description in $EDITOR").addOption(json()).action(async (ref, options) => edit(await ctx(), ref, options));
11836
+ cli.command("edit").argument("<task>", "like MON-12").description("Edit a task's title (the first line) and description in $EDITOR, or set them with --title and -d").option("--title <text>", "a new title (no editor)").option("-d, --description <text>", "a new description, replacing it (- reads it from stdin; no editor)").addOption(json()).action(async (ref, options) => edit(await ctx(), ref, options));
11003
11837
  cli.command("rm").argument("<task>", "like MON-12").description("Delete a task (asks first)").option("-y, --yes", "don't ask").addOption(json()).action(async (ref, options) => rm$1(await ctx(), ref, options));
11838
+ cli.command("tag").argument("<task>", "like MON-12").argument("<tags...>", "tag names (a new name makes a tag in the task's project)").description("Put tags on a task").addOption(json()).action(async (ref, names, options) => tag(await ctx(), ref, names, options));
11839
+ cli.command("untag").argument("<task>", "like MON-12").argument("<tags...>", "tag names").description("Take tags off a task").addOption(json()).action(async (ref, names, options) => untag(await ctx(), ref, names, options));
11840
+ cli.command("attach").argument("[task]", "like MON-12 (else the one this branch is named after: mon-12-…)").argument("[link]", "a pull request, an issue, a commit, or any page").description("Attach a link to a task (again: refresh it); --pr attaches this branch's pull request").option("--pr", "this branch's pull request, with its title and state (needs gh)").option("--title <text>", "its title (a pull request's or an issue's comes from gh)").addOption(json()).action(async (task, link, options) => attach(await ctx(), [task, link].filter((a) => a !== void 0), options));
11841
+ cli.command("detach").argument("<task>", "like MON-12").argument("<link>", "#54, or its URL").description("Take a link off a task").addOption(json()).action(async (ref, link, options) => detach(await ctx(), ref, link, options));
11842
+ cli.command("tags").description("List the tags a project's tasks can have: its own and the shared ones").addOption(project()).addOption(json()).action(async (options) => tags(await ctx(), options));
11843
+ const notes = cli.command("notes").description("A project's notes: print them, add a line, or edit them in $EDITOR");
11844
+ notes.command("show", { isDefault: true }).description("Print the notes (the default)").addOption(project()).addOption(json()).action(async (options) => notesShow(await ctx(), options));
11845
+ notes.command("add").argument("<text...>", "the line to add (- reads it from stdin)").description("Add a line at the end of the notes").addOption(project()).addOption(json()).action(async (words, options) => notesAdd(await ctx(), words, options));
11846
+ notes.command("edit").description("Edit the notes in $EDITOR").addOption(project()).addOption(json()).action(async (options) => notesEdit(await ctx(), options));
11004
11847
  cli.command("open").argument("[task]", "like MON-12").description("Open the board, or a task, in the browser").addOption(project()).action(async (ref, options) => open$1(await ctx(), ref, options));
11848
+ cli.command("setup").addArgument(new Argument("<agent>", "which agent: claude (Claude Code) or codex").choices(AGENTS)).description("Teach a coding agent monoban: a skill to plan work as tasks (phases as tags) and keep them current").option("--project", "install it in this repository (to commit), not for you in every one").option("--print", "print the skill instead of installing it").option("--remove", "remove the skill").option("-f, --force", "replace (or remove) a skill monoban didn't write").addOption(json()).addHelpText("after", `
11849
+ It goes in ~/.claude/skills/monoban (Claude Code) or ~/.agents/skills/monoban (Codex); with --project,
11850
+ in .claude/skills or .agents/skills at the top of this repository. Run it again after upgrading monoban.`).action(async (agent, options) => setup(await ctx(), agent, options));
11005
11851
  cli.command("upgrade").description("Check for a newer version, and say how to install it (Homebrew, npm…)").addOption(json()).action(async (options) => upgrade(await ctx(), options));
11006
- cli.command("completion").addArgument(new Argument("<shell>", "bash, zsh or fish").choices(SHELLS)).description("Print the script that makes Tab complete commands, projects, columns and tasks").addHelpText("after", `
11852
+ cli.command("completion").addArgument(new Argument("<shell>", "bash, zsh or fish").choices(SHELLS)).description("Print the script that makes Tab complete commands, projects, columns, tasks and tags").addHelpText("after", `
11007
11853
  Load it in your shell:
11008
11854
  bash in ~/.bashrc: eval "$(monoban completion bash)"
11009
11855
  zsh in ~/.zshrc: eval "$(monoban completion zsh)" (after compinit)